The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(desktop): handle snapshot state transitions correctly
Steven Enamakel43e20c6927aa
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rsnew file mode 100644index 0000000000..7d5bef62d2--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs@@ -0,0 +1,574 @@+//! [`EventListener`] implementation for [`OpenhumanEventBridge`] — projects+//! each `tinyagents` [`AgentEvent`] onto an [`AgentProgress`] update (or a+//! grep-friendly trace line for events with no UI surface), plus the+//! prompt-cache layout diagnostic helper drained after a run.++use std::sync::atomic::Ordering;++use tinyagents_harness::cache::CacheLayoutEvent;+use tinyagents_harness::events::{AgentEvent, EventListener, EventRecord};++use crate::agent::progress::AgentProgress;+use crate::tools::traits::humanize_tool_name;++use super::event_bridge::OpenhumanEventBridge;++impl EventListener for OpenhumanEventBridge {+ fn on_event(&self, record: &EventRecord) {+ match &record.event {+ AgentEvent::ModelStarted { .. } => {+ let iteration = self.cursor.fetch_add(1, Ordering::SeqCst) + 1;+ match &self.scope {+ None => self.send(AgentProgress::IterationStarted {+ iteration,+ max_iterations: self.max_iterations,+ }),+ Some(s) => self.send(AgentProgress::SubagentIterationStarted {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ iteration,+ max_iterations: self.max_iterations,+ extended_policy: s.extended_policy,+ }),+ }+ }+ AgentEvent::ModelDelta { delta, .. } => {+ let iteration = self.iteration();+ if !delta.text.is_empty() {+ match &self.scope {+ None => self.send(AgentProgress::TextDelta {+ delta: delta.text.clone(),+ iteration,+ }),+ Some(s) => self.send(AgentProgress::SubagentTextDelta {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ delta: delta.text.clone(),+ iteration,+ }),+ }+ }+ if !delta.reasoning.is_empty() {+ match &self.scope {+ None => self.send(AgentProgress::ThinkingDelta {+ delta: delta.reasoning.clone(),+ iteration,+ }),+ Some(s) => self.send(AgentProgress::SubagentThinkingDelta {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ delta: delta.reasoning.clone(),+ iteration,+ }),+ }+ }+ // Tool-call **start** + **argument** fragments both ride the crate+ // stream (`MessageDelta.tool_call`) now — the out-of-band+ // `ThinkingForwarder` is gone. The call-opening delta carries the+ // tool name (crate `ToolDelta::tool_name`, G2) with empty content;+ // argument fragments carry content with no name. We record the+ // name on the opening delta so subsequent fragments can be+ // labelled, and project both onto the `ToolCallArgsDelta` the UI+ // timeline consumes so the model can be shown composing the call+ // before it executes.+ if let Some(tool_call) = &delta.tool_call {+ // Record the tool name as soon as the call opens (matching the+ // legacy forwarder's `note_tool_call`), and emit the start+ // marker — an empty-delta `ToolCallArgsDelta` — top-level+ // regardless of scope, exactly as the forwarder did.+ if let Some(name) = tool_call.tool_name.as_deref().filter(|n| !n.is_empty()) {+ self.tool_names+ .lock()+ .unwrap()+ .insert(tool_call.call_id.clone(), name.to_string());+ if tool_call.content.is_empty() {+ self.send(AgentProgress::ToolCallArgsDelta {+ call_id: tool_call.call_id.clone(),+ tool_name: name.to_string(),+ delta: String::new(),+ iteration,+ });+ }+ }+ // Argument fragments are parent-only: there is no `Subagent*`+ // tool-arg variant, and an UNSCOPED top-level `ToolCallArgsDelta`+ // emitted from a child run would render the child's argument+ // composition as the *parent's* own timeline activity (#4467,+ // item 6; v0.58.7 dropped child arg fragments). A child run's+ // Started/Completed rows already carry the final arguments+ // under the `Subagent*` scope.+ if self.scope.is_none() && !tool_call.content.is_empty() {+ let tool_name = tool_call+ .tool_name+ .as_deref()+ .filter(|n| !n.is_empty())+ .map(str::to_string)+ .unwrap_or_else(|| {+ self.tool_names+ .lock()+ .unwrap()+ .get(&tool_call.call_id)+ .cloned()+ .unwrap_or_default()+ });+ tracing::trace!(+ call_id = tool_call.call_id.as_str(),+ tool_name = tool_name.as_str(),+ len = tool_call.content.len(),+ "[stream] projecting crate tool-arg fragment onto ToolCallArgsDelta"+ );+ self.send(AgentProgress::ToolCallArgsDelta {+ call_id: tool_call.call_id.clone(),+ tool_name,+ delta: tool_call.content.clone(),+ iteration,+ });+ }+ }+ }+ // `UsageRecorded` carries the authoritative per-call usage and fires+ // exactly once per model call; prefer it over `ModelCompleted`'s+ // optional usage to avoid double counting.+ AgentEvent::UsageRecorded { usage } => self.record_usage(usage),+ // Per-call generation telemetry. `ModelCompleted` fires exactly once+ // per model call, after `UsageRecorded`, and is the only event+ // carrying the captured request messages (incl. the system prompt)+ // + completion (`RunPolicy.capture.model_io`, enabled in+ // `run_policy_for`). Emitted for parent AND child scopes — the+ // child call carries its owning `subagent_task_id` so the trace+ // exporter nests the generation under the subagent span (this is+ // what makes the Context Scout's model calls visible in Langfuse).+ AgentEvent::ModelCompleted {+ usage,+ input,+ output,+ ..+ } => {+ let iteration = self.iteration();+ let usage = usage.unwrap_or_default();+ // Prefer the figures `record_usage` resolved for this call+ // (charged>estimate cost + carried cache/reasoning breakdown —+ // `UsageRecorded` fires before `ModelCompleted`), so the+ // generation telemetry matches the wallet accounting exactly;+ // fall back to a bare tier-aware estimate when absent.+ let resolved = self+ .resolved_calls+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .remove(&iteration);+ let call_cost = resolved+ .as_ref()+ .map(|r| r.cost_usd)+ .unwrap_or_else(|| Self::estimate_call_cost(&self.model, &usage));+ let cache_creation_tokens = resolved+ .as_ref()+ .map(|r| r.cache_creation_tokens)+ .unwrap_or(usage.cache_creation_tokens);+ let reasoning_tokens = resolved+ .as_ref()+ .map(|r| r.reasoning_tokens)+ .unwrap_or(usage.reasoning_tokens);+ log::debug!(+ "[tinyagents][usage] model_call_completed model={} provider={} iteration={} \+ child={} in={} out={} cache_read={} cache_write={} reasoning={} \+ cost_usd={:.6} input_captured={} output_captured={}",+ self.model,+ self.provider_id,+ iteration,+ self.scope.is_some(),+ usage.input_tokens,+ usage.output_tokens,+ usage.cache_read_tokens,+ cache_creation_tokens,+ reasoning_tokens,+ call_cost,+ input.is_some(),+ output.is_some(),+ );+ self.send(AgentProgress::ModelCallCompleted {+ model: self.model.clone(),+ provider_id: self.provider_id.clone(),+ subagent_task_id: self.scope.as_ref().map(|s| s.task_id.clone()),+ input: input.clone(),+ output: output.clone(),+ iteration,+ input_tokens: usage.input_tokens,+ output_tokens: usage.output_tokens,+ cached_input_tokens: usage.cache_read_tokens,+ cache_creation_tokens,+ reasoning_tokens,+ cost_usd: call_cost,+ });+ }+ AgentEvent::CostRecorded { cost } => {+ tracing::debug!(+ cost = ?cost,+ "[tinyagents] cost event observed without OpenHuman accounting side effect"+ );+ }+ AgentEvent::BudgetReserved {+ estimated_input_tokens,+ } => {+ tracing::debug!(+ estimated_input_tokens,+ "[tinyagents] budget reserved estimated input tokens"+ );+ }+ AgentEvent::BudgetReconciled {+ estimated_input_tokens,+ actual_input_tokens,+ } => {+ tracing::debug!(+ estimated_input_tokens,+ actual_input_tokens,+ "[tinyagents] budget reservation reconciled"+ );+ }+ AgentEvent::BudgetWarning { reason } => {+ tracing::debug!(+ reason,+ "[tinyagents] budget warning observed without run interruption"+ );+ }+ AgentEvent::BudgetExceeded { reason, blocked } => {+ tracing::debug!(+ reason,+ blocked,+ "[tinyagents] budget exceeded event observed"+ );+ }+ AgentEvent::Steered {+ command_kind,+ accepted,+ } => {+ // Grep-friendly `[steering]` projection of every drained steering+ // command (issue #4249, 07.3). A rejected command means the run's+ // `SteeringPolicy` refused the kind and the crate is aborting the+ // run with `TinyAgentsError::Steering`, so surface it louder. The+ // bespoke ack plumbing in `harness/run_queue/` stays live (gated:+ // web-channel followup/parallel still need a local owner); UI+ // projection of this event remains pending.+ if *accepted {+ tracing::debug!(+ command_kind = command_kind.as_str(),+ accepted,+ "[steering] command applied at safe boundary"+ );+ } else {+ tracing::warn!(+ command_kind = command_kind.as_str(),+ accepted,+ "[steering] command rejected by run policy"+ );+ }+ }+ AgentEvent::ToolsFiltered {+ by,+ excluded,+ remaining,+ } => {+ tracing::debug!(+ policy = by.as_str(),+ excluded_tools = ?excluded,+ remaining,+ "[tinyagents] model-visible tools filtered"+ );+ }+ AgentEvent::Compressed {+ from_tokens,+ to_tokens,+ } => {+ tracing::debug!(+ from_tokens,+ to_tokens,+ saved_tokens = from_tokens.saturating_sub(*to_tokens),+ "[tinyagents] context compressed before model call"+ );+ }+ AgentEvent::UnknownToolCall {+ call_id,+ requested_name,+ arguments,+ recovery,+ } => {+ tracing::debug!(+ call_id = call_id.as_str(),+ requested_tool = requested_name.as_str(),+ recovery = recovery.as_str(),+ arguments = %arguments,+ "[tinyagents] recovered unknown tool call without executing a tool"+ );+ // #4118: surface the *attempted* unavailable tool on the timeline+ // as a failed call so the UI shows what the agent tried (and+ // recovered from) rather than silently dropping it — the crate+ // recovers the call without ever emitting Started/Completed for it,+ // so nothing else in this bridge projects it. Two rows (start ++ // failed-complete) keyed by the same call_id, mirroring a real+ // tool call. Classified `Unknown` (recoverable) — the model got the+ // "valid tools: [...]" corrective and can retry a real tool.+ let iteration = self.iteration();+ let failure = Some(crate::tools::status::describe(+ crate::tools::status::ToolFailureClass::Unknown,+ ));+ let label = format!("{} (unavailable)", humanize_tool_name(requested_name));+ match &self.scope {+ None => {+ self.send(AgentProgress::ToolCallStarted {+ call_id: call_id.as_str().to_string(),+ tool_name: requested_name.clone(),+ arguments: arguments.clone(),+ iteration,+ display_label: Some(label),+ display_detail: Some("tool not available".to_string()),+ });+ self.send(AgentProgress::ToolCallCompleted {+ call_id: call_id.as_str().to_string(),+ tool_name: requested_name.clone(),+ success: false,+ output_chars: 0,+ output: String::new(),+ arguments: Some(arguments.clone()),+ elapsed_ms: 0,+ iteration,+ failure,+ });+ }+ Some(s) => {+ self.send(AgentProgress::SubagentToolCallStarted {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ call_id: call_id.as_str().to_string(),+ tool_name: requested_name.clone(),+ arguments: arguments.clone(),+ iteration,+ display_label: Some(label),+ display_detail: Some("tool not available".to_string()),+ });+ self.send(AgentProgress::SubagentToolCallCompleted {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ call_id: call_id.as_str().to_string(),+ tool_name: requested_name.clone(),+ success: false,+ output_chars: 0,+ output: String::new(),+ arguments: Some(arguments.clone()),+ elapsed_ms: 0,+ iteration,+ failure,+ });+ }+ }+ }+ AgentEvent::ToolStarted { call_id, tool_name } => {+ // Unknown/invisible tool calls no longer produce a sentinel-named+ // Started event: the migration replaced `UNKNOWN_TOOL_SENTINEL` ++ // `UnknownToolRewriteMiddleware` with the crate+ // `UnknownToolPolicy::ReturnToolError` path (01.2), which recovers+ // the call and emits `AgentEvent::UnknownToolCall` (handled above)+ // instead of a rewritten ToolStarted. So this arm fires only for+ // real, model-visible tools and needs no sentinel guard.+ let iteration = self.iteration();+ // Stamp the start instant so the completion event carries a real+ // elapsed_ms (the crate's ToolCompleted has no timing payload).+ self.tool_started_at+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .insert(call_id.as_str().to_string(), std::time::Instant::now());+ match &self.scope {+ None => self.send(AgentProgress::ToolCallStarted {+ call_id: call_id.as_str().to_string(),+ tool_name: tool_name.clone(),+ arguments: serde_json::Value::Null,+ iteration,+ display_label: Some(humanize_tool_name(tool_name)),+ display_detail: None,+ }),+ Some(s) => self.send(AgentProgress::SubagentToolCallStarted {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ call_id: call_id.as_str().to_string(),+ tool_name: tool_name.clone(),+ arguments: serde_json::Value::Null,+ iteration,+ display_label: Some(humanize_tool_name(tool_name)),+ display_detail: None,+ }),+ }+ }+ AgentEvent::ToolCompleted {+ call_id,+ tool_name,+ input,+ output,+ // `started_at_ms`/`duration_ms`/`output_bytes`/`error` now ride+ // the crate event (tinyagents 1.7 / tinyagents#18). The bridge+ // still reads its richer side channels below to preserve current+ // success/duration/size behavior; adopting crate fields directly+ // is C4 slice S1.+ ..+ } => {+ let iteration = self.iteration();+ // The crate event carries no success/error, so read what the+ // outcome-capture middleware classified for this call. Absent →+ // the event was projected before the middleware ran; assume+ // success (never worse than the previous hardcoded `true`).+ let outcome = self+ .failure_map+ .lock()+ .ok()+ .and_then(|mut m| m.remove(call_id.as_str()));+ let success = outcome.as_ref().map(|(ok, ..)| *ok).unwrap_or(true);+ // Real execution duration + output size the capture middleware+ // recorded off the `ToolResult` (#4467, item 4). Fall back to+ // the bridge's own ToolStarted stamp for duration, and to the+ // captured payload for size, when the middleware ran late.+ let stamped_elapsed = self+ .tool_started_at+ .lock()+ .unwrap_or_else(|p| p.into_inner())+ .remove(call_id.as_str())+ .map(|t| t.elapsed().as_millis() as u64)+ .unwrap_or(0);+ let elapsed_ms = outcome+ .as_ref()+ .map(|(_, _, e, _)| *e)+ .filter(|e| *e > 0)+ .unwrap_or(stamped_elapsed);+ // Tool result text, captured by the harness when+ // `RunPolicy.capture.tool_io` is on (the loop emits it as a+ // JSON string). Empty when capture is off.+ let output_text = match output {+ Some(serde_json::Value::String(s)) => s.clone(),+ Some(v) => v.to_string(),+ None => String::new(),+ };+ let output_chars = outcome+ .as_ref()+ .map(|(_, _, _, c)| *c)+ .filter(|c| *c > 0)+ .unwrap_or_else(|| output_text.chars().count());+ // Carry the classified failure onto whichever completion event+ // this projects — main-agent OR sub-agent (#4459). Previously+ // the sub-agent branch dropped it on the floor.+ let failure = outcome.and_then(|(_, f, _, _)| f);+ match &self.scope {+ None => self.send(AgentProgress::ToolCallCompleted {+ call_id: call_id.as_str().to_string(),+ tool_name: tool_name.clone(),+ success,+ output_chars,+ output: output_text,+ arguments: input.clone(),+ elapsed_ms,+ iteration,+ failure,+ }),+ Some(s) => self.send(AgentProgress::SubagentToolCallCompleted {+ agent_id: s.agent_id.clone(),+ task_id: s.task_id.clone(),+ call_id: call_id.as_str().to_string(),+ tool_name: tool_name.clone(),+ success,+ output_chars,+ output: output_text,+ arguments: input.clone(),+ elapsed_ms,+ iteration,+ failure,+ }),+ }+ }+ // Response-cache accounting (issue #4249, 03.2). A hit means the+ // harness served this model call from its local `ResponseCache`+ // without invoking the provider (deterministic internal runs only —+ // interactive chat never attaches a cache). Counters are additive; the+ // cost-footer DTO wiring is a follow-up (workstream 06).+ AgentEvent::CacheHit { call_id, key } => {+ {+ let mut s = self.state.lock().unwrap();+ s.cache_hits += 1;+ }+ tracing::debug!(+ model = %self.model,+ call_id = call_id.as_str(),+ key = key.as_str(),+ "[cache] response-cache hit — provider call skipped"+ );+ }+ AgentEvent::CacheMiss { call_id, key } => {+ {+ let mut s = self.state.lock().unwrap();+ s.cache_misses += 1;+ }+ tracing::debug!(+ model = %self.model,+ call_id = call_id.as_str(),+ key = key.as_str(),+ "[cache] response-cache miss — invoking provider and storing result"+ );+ }+ // Retry/fallback parity (issue #4249, Workstream 02.2). These surface the+ // SDK-owned reliability decisions on the observability bridge so they are+ // no longer silently dropped by the catch-all below. `RetryScheduled` is+ // emitted by the crate's model-retry loop; with the retry pin at a single+ // attempt (`RunPolicy.retry.max_attempts = 1`, pending `ReliableProvider`+ // removal) it will not fire on the live path yet, but the bridge is wired+ // for when it does. `FallbackSelected` is emitted by+ // [`FallbackObserverMiddleware`](super::routes::FallbackObserverMiddleware)+ // whenever the harness fails over to a sibling workload-tier route.+ AgentEvent::RetryScheduled { call_id, attempt } => {+ tracing::info!(+ model = %self.model,+ call_id = call_id.as_str(),+ attempt,+ "[models] SDK scheduled a model-call retry after a retryable provider error"+ );+ }+ AgentEvent::FallbackSelected { from, to } => {+ tracing::info!(+ model = %self.model,+ from = from.as_str(),+ to = to.as_str(),+ "[fallback] SDK failed over to a cross-route fallback model"+ );+ }+ other => {+ // Not projected into `AgentProgress` (run lifecycle, sub-agent+ // boundaries — reconstructed from the orchestration tools'+ // manual emits — middleware, workspace, memory, limits). Trace+ // the kind so a dropped-event hypothesis is checkable from+ // logs instead of reading this match.+ tracing::trace!(+ model = %self.model,+ kind = ?std::mem::discriminant(other),+ "[tinyagents:bridge] event observed but not forwarded to UI progress"+ );+ }+ }+ }+}++/// Surface the crate `PromptCacheGuardMiddleware`'s recorded+/// [`CacheLayoutEvent`]s as structured `[cache]` warnings (issue #4249, 03.2).+///+/// The guard records a layout event whenever the cacheable prompt prefix changes+/// between turns (volatile content — a timestamp, uuid, injected memory, etc. —+/// silently busting the provider KV-cache prefix). This is the crate-native+/// replacement for the deleted `CacheAlignMiddleware` free-text warn-log:+/// instead of a token-pattern heuristic it reports the exact before/after+/// cacheable segment ids. Drained by the turn loop after the run and logged+/// here. The warn-only `CacheAlignMiddleware` shadow was deleted in C3; this+/// guard is now the sole owner of KV-cache-prefix drift detection.+pub(crate) fn surface_cache_layout_events(model: &str, events: &[CacheLayoutEvent]) {+ for event in events {+ tracing::warn!(+ model,+ changed_prefix = event.changed_prefix,+ volatile_only = event.volatile_only,+ segments_before = ?event.segment_ids_before,+ segments_after = ?event.segment_ids_after,+ "[cache] prompt-cache prefix changed across turns — KV-cache prefix may not hit; keep dynamic content out of the system prompt / stable tool set"+ );+ }+}diff --git a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rsindex d16c246ade..0c85a73cc9 100644--- a/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs+++ b/crates/openhuman-core/src/desktop/app_state/ops/snapshot.rs@@ -33,10 +33,10 @@ use std::sync::atomic::{AtomicU64, Ordering};use std::time::Instant;/// Correlates a snapshot call's own timing/debug log lines across the poll.-static SNAPSHOT_REQ_COUNTER: AtomicU64 = AtomicU64::new(0);+pub(super) static SNAPSHOT_REQ_COUNTER: AtomicU64 = AtomicU64::new(0);#[derive(Debug, Clone)]-enum SnapshotCurrentUser {+pub(super) enum SnapshotCurrentUser {User(Option<Value>),DeferredSessionRejected,}@@ -47,9 +47,9 @@ impl SnapshotCurrentUser {}}-type SnapshotCurrentUserResult = (SnapshotCurrentUser, Option<Box<Config>>);+pub(super) type SnapshotCurrentUserResult = (SnapshotCurrentUser, Option<Box<Config>>);-fn snapshot_current_user_result(user: Option<Value>) -> SnapshotCurrentUserResult {+pub(super) fn snapshot_current_user_result(user: Option<Value>) -> SnapshotCurrentUserResult {(SnapshotCurrentUser::user(user), None)}diff --git a/crates/openhuman-core/src/integrations/composio/schemas/util.rs b/crates/openhuman-core/src/integrations/composio/schemas/util.rsnew file mode 100644index 0000000000..388fde02ae--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/schemas/util.rs@@ -0,0 +1,49 @@+//! Small param-decoding and response-shaping helpers shared by every+//! handler in `schemas/handlers_*.rs`.++use serde::de::DeserializeOwned;+use serde_json::{Map, Value};++use crate::rpc::RpcOutcome;++pub(super) fn read_required<T: DeserializeOwned>(+ params: &Map<String, Value>,+ key: &str,+) -> Result<T, String> {+ let value = params+ .get(key)+ .cloned()+ .ok_or_else(|| format!("missing required param '{key}'"))?;+ serde_json::from_value(value).map_err(|e| format!("invalid '{key}': {e}"))+}++/// Read a required `String` parameter and reject blank / whitespace-only+/// input at the RPC boundary instead of letting it reach the backend.+/// Returns the trimmed value.+pub(super) fn read_required_non_empty(+ params: &Map<String, Value>,+ key: &str,+) -> Result<String, String> {+ let raw = read_required::<String>(params, key)?;+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return Err(format!("'{key}' must not be empty"));+ }+ Ok(trimmed.to_string())+}++pub(super) fn read_optional<T: DeserializeOwned>(+ params: &Map<String, Value>,+ key: &str,+) -> Result<Option<T>, String> {+ match params.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(value) => serde_json::from_value(value.clone())+ .map(Some)+ .map_err(|e| format!("invalid '{key}': {e}")),+ }+}++pub(super) fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {+ outcome.into_cli_compatible_json()+}diff --git a/crates/openhuman-core/src/memory/tree/tree/rpc/ingest.rs b/crates/openhuman-core/src/memory/tree/tree/rpc/ingest.rsnew file mode 100644index 0000000000..f7e76ada9d--- /dev/null+++ b/crates/openhuman-core/src/memory/tree/tree/rpc/ingest.rs@@ -0,0 +1,468 @@+//! The unified `memory_tree_ingest` RPC: canonicalises a chat/email/document+//! payload into contract items and hands them to the bound driver's `Ingest`+//! family.++use crate::config::Config;+use crate::rpc::RpcOutcome;+use tinymemory_api::chunks::{DataSource, SourceKind, SourceRef};+use tinymemory_api::provider::types::{IngestItem, IngestOutcome};+use tinymemory_api::types::MemoryTaint;++// The canonical payload shapes (and `invalid_payload_message`) live in+// `canonicalize_types.rs`, split for the file-layout gate; re-exported here so+// every existing path keeps resolving.+pub use crate::memory::tree::tree::canonicalize_types::*;++/// Returns `true` when `message` is an ingest-payload schema-validation+/// failure produced by `invalid_payload_message`.+///+/// Such a failure is a **caller** error — the submitted JSON does not match+/// the canonicaliser's shape — not a core defect. The handler already returns+/// a precise, actionable JSON-RPC error naming the offending field, and no+/// core-side change can fix a producer that sends the wrong shape. Reporting+/// it at Sentry *error* severity therefore pages on someone else's payload+/// bug: #5169 (`CORE-RUST-1P0`) was 14 such events for a chat batch whose+/// messages omitted `timestamp`.+///+/// The transport layer demotes these to a warn-level capture — still recorded+/// for triage, because a spike genuinely means a producer regressed, but not+/// an error event. See `core::jsonrpc::rpc_handler`.+///+/// Anchored on the exact `invalid <kind> payload: ` prefix rather than a+/// loose `"invalid"` substring so unrelated failures keep paging.+pub fn is_invalid_ingest_payload_message(message: &str) -> bool {+ let Some(rest) = message.strip_prefix("invalid ") else {+ return false;+ };+ // Enumerated rather than parsed so a new `SourceKind` that forgets to+ // update this list stays *loud* (keeps paging) instead of silently+ // inheriting the demotion. The `all_source_kinds_are_recognised_*` test+ // below pins that every variant reachable from `ingest_rpc` is covered.+ [SourceKind::Chat, SourceKind::Email, SourceKind::Document]+ .iter()+ .any(|k| rest.starts_with(&format!("{} payload: ", k.as_str())))+}++/// Which `Ingest` member a canonicalised request lands on.+///+/// One type rather than two resolve sites, so the family lookup and its+/// refusal wording exist once: the arms differ only in which member they call.+enum DriverIngest {+ Chat(Vec<IngestItem>),+ Email(Vec<IngestItem>),+ Document(IngestItem),+}++/// Hand canonicalised items to the bound driver's `Ingest` family.+///+/// A missing family is **refused**, not degraded. The read handlers below+/// answer empty for one because "this driver stores no chunks" is a true+/// answer to what they were asked; this is a write, and the only empty answer+/// available to it — zero written, zero dropped — is byte-identical to a+/// successful ingest of nothing, so the content would go on the floor while+/// the caller was told it landed.+///+/// Resolved on `provider()`, the same seam [`super::backfill::store_stats`]+/// and [`super::backfill::queue_stats`] use, and deliberately not on+/// `binding.guard()`: the guard's `Ingest` decorator re-stamps `taint`, and+/// `ExternalSync` — what it stamps whenever a source scope is active — is+/// exactly what the driver's own `validate_ingest_item` refuses for the chunk+/// tier, so routing this path through the guard would fail every ingest+/// issued during a sync.+async fn ingest_through_driver(+ config: &Config,+ call: DriverIngest,+) -> Result<IngestOutcome, String> {+ let binding = crate::memory::binding::for_config(config)?;+ let Some(ingest) = binding.provider().as_ingest() else {+ return Err(format!(+ "ingest: driver '{}' does not serve Ingest",+ binding.driver_id()+ ));+ };+ match call {+ DriverIngest::Chat(messages) => ingest.ingest_chat(messages).await,+ DriverIngest::Email(messages) => ingest.ingest_email(messages).await,+ DriverIngest::Document(item) => ingest.ingest_document(item).await,+ }+ .map_err(|e| format!("ingest: {e}"))+}++/// The [`DataSource`] a chat payload's `platform` string names.+///+/// The verbatim string still crosses as `IngestItem::platform`, which is what+/// the driver rebuilds `ChatBatch::platform` from, so this enum only has to+/// agree with the arm it came from. An unrecognised platform is `Conversation`+/// — the generic chat member — rather than a rejection: this RPC has always+/// taken any platform string, and a new integration must not start failing at+/// the seam because its name is not in an enum here.+fn chat_data_source(platform: &str) -> DataSource {+ match DataSource::parse(platform) {+ Ok(source) if source.kind() == SourceKind::Chat => source,+ _ => DataSource::Conversation,+ }+}++/// As [`chat_data_source`], for a mail payload's `provider`.+///+/// `OtherEmail` is the fallback because it is the mail member that means "an+/// email provider this enum does not name", which is the honest reading of a+/// provider string that did not parse. Demoting to a non-mail member would put+/// the thread under the wrong `SourceKind` entirely.+fn email_data_source(provider: &str) -> DataSource {+ match DataSource::parse(provider) {+ Ok(source) if source.kind() == SourceKind::Email => source,+ _ => DataSource::OtherEmail,+ }+}++/// Canonicalise a mail thread into contract items.+///+/// **This is the exact inverse of the driver's reconstruction**, and it has to+/// be: the driver rebuilds an `EmailThread` from these fields and then calls+/// the same `ingest_pipeline::ingest_email` this arm used to call directly, so+/// any field that does not round-trip changes what is stored rather than+/// failing. Every one it reads through `unwrap_or` is therefore sent as+/// `Some`, so no fallback on the far side can substitute a different value:+///+/// | driver reads | sent here |+/// | --- | --- |+/// | `platform.unwrap_or(source)` | `platform: Some(provider)` |+/// | `channel_label.unwrap_or(source_id)` | `channel_label: Some(thread_subject)` |+/// | `author.unwrap_or(owner)` | `author: Some(from)` |+/// | `subject.unwrap_or(thread_subject)` | `subject: Some(subject)` |+/// | `timestamp.unwrap_or(now)` | `timestamp: Some(sent_at)` |+///+/// `to`, `cc` and `list_unsubscribe` cross verbatim. The unsubscribe header+/// matters more than it looks: an unsubscribe flow reads it back out of stored+/// mail, so dropping it makes that flow impossible rather than merely poorer.+///+/// # Empty bodies are filtered, not refused+///+/// `validate_ingest_item` answers `Invalid` for empty content, and the driver+/// validates every item before ingesting any — so one body-less message would+/// fail the whole thread, where the in-process pipeline wrote the rest of it.+/// A header-only message is entirely plausible in mail, so filtering first+/// (exactly as [`chat_items`] does) keeps the old behaviour instead of turning+/// a survivable thread into a rejected one.+fn email_items(+ source_id: &str,+ owner: &str,+ tags: &[String],+ thread: EmailThread,+) -> Vec<IngestItem> {+ let EmailThread {+ provider,+ thread_subject,+ messages,+ } = thread;+ let source = email_data_source(&provider);+ messages+ .into_iter()+ .filter(|message| !message.body.trim().is_empty())+ .map(|message| IngestItem {+ namespace: None,+ source,+ source_id: source_id.to_string(),+ owner: owner.to_string(),+ source_ref: message.source_ref.map(SourceRef::new),+ content: message.body,+ mime: None,+ timestamp: Some(message.sent_at),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ path_scope: None,+ author: Some(message.from),+ channel_label: Some(thread_subject.clone()),+ to: message.to,+ cc: message.cc,+ subject: Some(message.subject),+ list_unsubscribe: message.list_unsubscribe,+ platform: Some(provider.clone()),+ })+ .collect()+}++/// As [`chat_data_source`], for a document payload's `provider`.+///+/// `Upload` is the fallback because it is the member that means "handed to the+/// memory layer directly, with no upstream to re-read it from", which is what+/// a document arriving over this RPC is.+fn document_data_source(provider: &str) -> DataSource {+ match DataSource::parse(provider) {+ Ok(source) if source.kind() == SourceKind::Document => source,+ _ => DataSource::Upload,+ }+}++/// Canonicalise a chat batch into the contract's items.+///+/// The attribution trio is what keeps the stored rows identical to the ones+/// the in-process pipeline wrote. The driver rebuilds a `ChatBatch` from the+/// **first** item's `platform` and `channel_label` and from each item's+/// `author`, falling back to values that are not this payload's (the+/// `DataSource` name and the `source_id`), so all three are set on every item+/// rather than only where they differ.+///+/// Messages whose text trims to empty are dropped before the call.+/// `validate_ingest_item` answers `Invalid` for empty content and the driver+/// checks every item before ingesting any, so one attachment-only message+/// would fail the whole batch where the in-process pipeline wrote the rest of+/// it. What the filter costs is that message's bare `## <ts> — <author>`+/// header, which carried no content. Same filter, for the same reason, as+/// `agent::harness::archivist::tree_ingest`.+fn chat_items(source_id: &str, owner: &str, tags: &[String], batch: ChatBatch) -> Vec<IngestItem> {+ let ChatBatch {+ platform,+ channel_label,+ messages,+ } = batch;+ let source = chat_data_source(&platform);+ messages+ .into_iter()+ .filter(|message| !message.text.trim().is_empty())+ .map(|message| IngestItem {+ namespace: None,+ source,+ source_id: source_id.to_string(),+ owner: owner.to_string(),+ source_ref: message.source_ref.map(SourceRef::new),+ content: message.text,+ // The payload carries no MIME. `None` is the honest answer — the+ // driver validates what it is told, and naming a type here would+ // be asserting one the caller never claimed.+ mime: None,+ timestamp: Some(message.timestamp),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ path_scope: None,+ author: Some(message.author),+ channel_label: Some(channel_label.clone()),+ // Mail-only fields; this source is not mail, and the contract+ // documents empty/absent as the same statement as "not mail".+ to: Vec::new(),+ cc: Vec::new(),+ subject: None,+ list_unsubscribe: None,+ platform: Some(platform.clone()),+ })+ .collect()+}++/// Canonicalise a document payload into the contract's single item.+///+/// `title` does not cross, and the contract's `ingest_document` hard-codes an+/// empty one on the way back in. Nothing is lost by that: the document+/// canonicaliser writes the body alone into the stored markdown and carries+/// the title nowhere else — it reads it only to decide whether the payload was+/// wholly empty, which [`ingest_rpc`] now answers before the call.+///+/// `pub(super)` — reused verbatim by tests declared directly under `rpc`.+pub(super) fn document_item(+ source_id: &str,+ owner: &str,+ tags: &[String],+ doc: DocumentInput,+) -> IngestItem {+ IngestItem {+ namespace: None,+ source: document_data_source(&doc.provider),+ source_id: source_id.to_string(),+ owner: owner.to_string(),+ source_ref: doc.source_ref.map(SourceRef::new),+ content: doc.body,+ mime: None,+ timestamp: Some(doc.modified_at),+ tags: tags.to_vec(),+ taint: MemoryTaint::Internal,+ // This handler called `ingest_document_with_scope(.., None)`, so the+ // scope stays unset rather than falling back to `source_id`.+ path_scope: None,+ author: None,+ channel_label: None,+ // Mail-only fields; this source is not mail, and the contract+ // documents empty/absent as the same statement as "not mail".+ to: Vec::new(),+ cc: Vec::new(),+ subject: None,+ list_unsubscribe: None,+ platform: None,+ }+}++/// Map the driver's outcome onto the wire body.+///+/// `source_id` comes from the request, not from the outcome echoing it back:+/// the caller supplied it, and reading it off the producer is what would let a+/// reply be paired with the wrong request if a producer ever normalised it.+///+/// `written` / `skipped` are the contract's names for the two counts this wire+/// calls `chunks_written` / `chunks_dropped`, and they carry the same two+/// facts: `skipped` counts dropped units only, a refused call being+/// `already_ingested` instead, which is what `chunks_dropped` has always meant+/// here.+fn response_from_outcome(source_id: String, outcome: IngestOutcome) -> IngestResponse {+ IngestResponse {+ source_id,+ chunks_written: outcome.written as usize,+ chunks_dropped: outcome.skipped as usize,+ chunk_ids: outcome.ids,+ extract_jobs_enqueued: outcome.extract_jobs_enqueued as usize,+ already_ingested: outcome.already_ingested,+ }+}++/// Unified ingest RPC handler. Dispatches on `source_kind`.+///+/// Chat and document go to the bound driver's `Ingest` family. At the v1.3.0+/// module pin they could not: the contract's `IngestOutcome` carried neither+/// `already_ingested` nor `extract_jobs_enqueued` (both would have decoded to+/// their serde defaults, reporting every duplicate submission as a plain empty+/// write, forever) and its `skipped` counted duplicate-refusals rather than+/// dropped units, so `chunks_dropped` would have carried a different fact+/// under the same name. v1.4.0 closes all three, which is why the swap is a+/// swap and not a wire change —+/// `the_response_body_serialises_exactly_as_the_engine_summary` still holds.+///+/// **Mail is still on the in-process pipeline, and it is the last thing in this+/// file that is** (#5560). This paragraph used to list two blockers, and+/// **both are closed** — re-checked 2026-08-25 rather than inherited, because+/// leaving them stated is what would stop the next reader from finishing it:+///+/// 1. *"`IngestItem` carries no recipient list, no per-message subject and no+/// `List-Unsubscribe`."* It carries all of them now, plus `platform`, and+/// the contract's own field docs are written for this path — they say+/// dropping the unsubscribe header makes the unsubscribe flow impossible+/// rather than merely less complete. `chat_items` and `document_item`+/// already spell the five mail fields as their not-mail values.+/// 2. *"`ModuleMemoryProvider` does not forward `IngestEmail`."* It does —+/// `modules::memory` implements `ingest_email` beside `ingest_document` and+/// `ingest_chat`, and the module declares the member.+///+/// The driver's mapping is a lossless inverse: it rebuilds `EmailThread` with+/// `provider` from `platform`, `thread_subject` from `channel_label`, `from`+/// from `author`, and `to` / `cc` / `subject` / `list_unsubscribe` verbatim,+/// then calls the same `ingest_pipeline::ingest_email` this arm calls now.+///+/// So what is left is host work plus one verification, and neither is a+/// contract change:+///+/// - An `email_items(source_id, owner, tags, EmailThread)` mapper that is the+/// **exact** inverse of that reconstruction (`platform: Some(provider)`,+/// `channel_label: Some(thread_subject)`, `author: Some(from)`,+/// `subject: Some(msg.subject)` — always `Some`, so no `unwrap_or` fallback+/// on the far side can substitute a different value), a `DataSource` chooser+/// in the shape of `chat_data_source`, and a `DriverIngest::Email` arm.+/// - A decision on empty bodies, which is a real behaviour delta and wants its+/// own test: `validate_ingest_item` answers `Invalid` for empty content and+/// the driver validates every item before ingesting any, so one body-less+/// message fails the whole thread where the in-process pipeline writes the+/// rest of it. The chat arm answers this by filtering first; mail has to+/// choose the same, and a header-only message is more plausible in mail.+/// - **Check the released artifact, not the submodule.** The five mail fields+/// are `#[serde(default)]`, so a pinned module that predates them decodes+/// every one to its default and mail loses its headers **silently** — the+/// capability check stays green because the family and the member both+/// exist. `vendor/tinymemory` is currently *behind* the pinned release, so+/// grep the tag.+pub async fn ingest_rpc(+ config: &Config,+ req: IngestRequest,+) -> Result<RpcOutcome<IngestResponse>, String> {+ let IngestRequest {+ source_kind,+ source_id,+ owner,+ tags,+ payload,+ } = req;++ log::debug!(+ "[memory::rpc] ingest kind={} source_id={}",+ source_kind.as_str(),+ source_id+ );++ let response = match source_kind {+ SourceKind::Chat => {+ let batch: ChatBatch = serde_json::from_value(payload).map_err(|e| {+ let msg = invalid_payload_message(SourceKind::Chat, &e);+ log::warn!("[memory::rpc] invalid payload for chat");+ msg+ })?;+ let messages = chat_items(&source_id, &owner, &tags, batch);+ if messages.is_empty() {+ // Answered here rather than handed over. The in-process+ // pipeline returned an empty summary for a batch it could not+ // canonicalise, and "the driver returns zeros for zero items"+ // is a behaviour of the one driver we ship, not something the+ // contract promises of the next one.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Chat(messages))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] chat ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }+ }+ SourceKind::Email => {+ let thread: EmailThread = serde_json::from_value(payload).map_err(|e| {+ let msg = invalid_payload_message(SourceKind::Email, &e);+ log::warn!("[memory::rpc] invalid payload for email");+ msg+ })?;+ let messages = email_items(&source_id, &owner, &tags, thread);+ if messages.is_empty() {+ // The chat arm's answer, for the same reason: a thread whose+ // every message was body-less canonicalises to nothing, and+ // "the driver returns zeros for zero items" is a behaviour of+ // the one driver we ship rather than a contract promise.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Email(messages))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] email ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }+ }+ SourceKind::Document => {+ let doc: DocumentInput = serde_json::from_value(payload).map_err(|e| {+ let msg = invalid_payload_message(SourceKind::Document, &e);+ log::warn!("[memory::rpc] invalid payload for document");+ msg+ })?;+ let item = document_item(&source_id, &owner, &tags, doc);+ if item.content.trim().is_empty() {+ // The chat arm's filter, on this arm's single item. Empty+ // content is `Invalid` at the driver, so a body-less document+ // would arrive as a failed call; the in-process pipeline+ // instead canonicalised it to a lone whitespace chunk. Neither+ // is worth keeping — "nothing to ingest" is. What it gives up+ // is that a body-less payload under an already-claimed+ // `source_id` used to answer `already_ingested`, and there is+ // nothing behind that gate to go and clear when the body was+ // empty.+ response_from_outcome(source_id.clone(), IngestOutcome::default())+ } else {+ let outcome = ingest_through_driver(config, DriverIngest::Document(item))+ .await+ .inspect_err(|_| {+ log::warn!("[memory::rpc] document ingestion failed");+ })?;+ response_from_outcome(source_id.clone(), outcome)+ }+ }+ };++ Ok(RpcOutcome::single_log(+ response,+ format!(+ "memory_tree: ingest kind={} source_id={source_id}",+ source_kind.as_str()+ ),+ ))+}