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
refactor(triage): use shared lenient JSON parser for triage decisions
Steven Enamakel5c4591434dd0
diff --git a/crates/openhuman-core/src/triage/decision.rs b/crates/openhuman-core/src/triage/decision.rsindex 13c7ca6a16..6c63dc844b 100644--- a/crates/openhuman-core/src/triage/decision.rs+++ b/crates/openhuman-core/src/triage/decision.rs@@ -27,7 +27,7 @@use serde::Deserialize;use thiserror::Error;-use tinytools_agent::repair::json::strip_trailing_commas;+use tinyagents_harness::structured::parse_lenient_last_object;/// The four outcomes the triage agent is allowed to choose.#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]@@ -114,9 +114,8 @@ pub enum ParseError {/// 4. Parse as JSON, lowercasing the `action` string in flight./// 5. Reject if React / Escalate but `target_agent`/`prompt` missing.pub fn parse_triage_decision(llm_text: &str) -> Result<TriageDecision, ParseError> {- let slice = extract_json_slice(llm_text).ok_or(ParseError::NoJsonObject)?;- let cleaned = strip_trailing_commas(&slice);- let normalized = lowercase_action_value(&cleaned);+ let (value, _) = parse_lenient_last_object(llm_text).ok_or(ParseError::NoJsonObject)?;+ let normalized = lowercase_action_value(&value.to_string());let decision: TriageDecision =serde_json::from_str(&normalized).map_err(ParseError::InvalidJson)?;@@ -139,93 +138,6 @@ pub fn parse_triage_decision(llm_text: &str) -> Result<TriageDecision, ParseErroOk(decision)}-// ─────────────────────────────────────────────────────────────────────────────-// Extraction helpers — all private, all exhaustively unit-tested below.-// ─────────────────────────────────────────────────────────────────────────────--/// Return the content of the **last** JSON object in `text`, preferring-/// fenced blocks over raw braces so we don't accidentally pick up a-/// half-written object inside a code fence's preamble.-fn extract_json_slice(text: &str) -> Option<String> {- if let Some(fenced) = last_fenced_json_block(text) {- return Some(fenced);- }- last_balanced_brace_object(text)-}--/// Find the last ```json … ``` fenced block in `text`, if any.-/// Accepts `` ```json ``, `` ```JSON ``, and plain `` ``` `` fences-/// since small models are inconsistent about the language tag.-fn last_fenced_json_block(text: &str) -> Option<String> {- // Walk fence starts from the end so we naturally find the last one.- let mut last: Option<String> = None;- let mut search_from = 0;- while let Some(rel) = text[search_from..].find("```") {- let start = search_from + rel + 3;- // Skip an optional language tag on the same line.- let body_start = match text[start..].find('\n') {- Some(nl) => {- let tag = &text[start..start + nl];- // Accept "json", "JSON", or empty tags. If the tag is- // something else (e.g. "python") we still try to parse- // the block — small models mislabel fences all the- // time and the content may still be JSON.- let _ = tag;- start + nl + 1- }- None => return last,- };- let close = text[body_start..].find("```")?;- let body = &text[body_start..body_start + close];- last = Some(body.trim().to_string());- search_from = body_start + close + 3;- }- last-}--/// Brace-match the last balanced `{ … }` object in `text`, ignoring-/// braces inside string literals. Returns the substring including the-/// outer braces. O(n) single pass.-fn last_balanced_brace_object(text: &str) -> Option<String> {- let bytes = text.as_bytes();- let mut best: Option<(usize, usize)> = None;- let mut depth = 0usize;- let mut start: Option<usize> = None;- let mut in_string = false;- let mut escape = false;- for (i, &b) in bytes.iter().enumerate() {- if in_string {- if escape {- escape = false;- } else if b == b'\\' {- escape = true;- } else if b == b'"' {- in_string = false;- }- continue;- }- match b {- b'"' => in_string = true,- b'{' => {- if depth == 0 {- start = Some(i);- }- depth += 1;- }- b'}' if depth > 0 => {- depth -= 1;- if depth == 0 {- if let Some(s) = start.take() {- best = Some((s, i + 1));- }- }- }- _ => {}- }- }- best.map(|(s, e)| text[s..e].to_string())-}-/// Rewrite `"action": "Drop"` / `"action": "ESCALATE"` as/// `"action": "drop"` / `"action": "escalate"` so serde's/// `rename_all = "lowercase"` attribute accepts whatever casing thediff --git a/crates/openhuman-core/src/triage/decision_tests.rs b/crates/openhuman-core/src/triage/decision_tests.rsindex 446db7d693..ce190a32d7 100644--- a/crates/openhuman-core/src/triage/decision_tests.rs+++ b/crates/openhuman-core/src/triage/decision_tests.rs@@ -1,53 +1,5 @@use super::*;-// ── extract / cleanup helpers ───────────────────────────────────────--#[test]-fn fenced_block_is_preferred_over_raw_braces() {- let text = "preamble { \"other\": 1 } middle\n```json\n{\n \"action\": \"drop\",\n \"reason\": \"test\"\n}\n```\ntrailing notes";- let slice = extract_json_slice(text).unwrap();- assert!(slice.contains("\"action\""));- assert!(slice.contains("\"reason\": \"test\""));- assert!(!slice.contains("middle"));-}--#[test]-fn bare_brace_object_is_extracted_when_no_fence() {- let text = "Here is my verdict: { \"action\": \"drop\", \"reason\": \"test\" } — thanks!";- let slice = extract_json_slice(text).unwrap();- assert!(slice.contains("\"action\""));-}--#[test]-fn last_of_multiple_braces_wins() {- let text = "{ \"action\": \"escalate\", \"reason\": \"first\" } and then { \"action\": \"drop\", \"reason\": \"second\" }";- let slice = extract_json_slice(text).unwrap();- assert!(slice.contains("\"second\""));- assert!(!slice.contains("\"first\""));-}--#[test]-fn brace_inside_string_does_not_break_matching() {- let text = "{ \"action\": \"drop\", \"reason\": \"has } and { chars\" }";- let slice = extract_json_slice(text).unwrap();- assert!(slice.contains("has } and { chars"));-}--#[test]-fn action_value_is_lowercased() {- let src = "{\"action\": \"Drop\", \"reason\": \"x\"}";- let out = lowercase_action_value(src);- assert!(out.contains("\"action\": \"drop\""));-}--#[test]-fn other_string_values_are_not_lowercased() {- let src = "{\"action\": \"DROP\", \"reason\": \"X Y Z\"}";- let out = lowercase_action_value(src);- assert!(out.contains("\"action\": \"drop\""));- assert!(out.contains("\"reason\": \"X Y Z\""));-}-// ── full parse_triage_decision ──────────────────────────────────────#[test]@@ -126,3 +78,11 @@ fn prefers_last_fenced_block() {assert_eq!(d.action, TriageAction::Drop);assert_eq!(d.reason, "never mind");}++#[test]+fn corrected_unfenced_object_after_fence_is_selected() {+ let reply = "```json\n{\"action\":\"drop\",\"reason\":\"old\"}\n```\nCorrection: {\"action\":\"acknowledge\",\"reason\":\"corrected\"}";+ let decision = parse_triage_decision(reply).unwrap();+ assert_eq!(decision.action, TriageAction::Acknowledge);+ assert_eq!(decision.reason, "corrected");+}