use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use serde_json::{Value, json};
use super::adapter::{self, Agent};
use super::capture::Captured;
use super::events::{FIELD_BYTES, head};
use super::link::{self, Naming};
use super::plan::Checked;
use super::recorder::{Failure, call};
use super::text::say;
use crate::memory::mounts::Mount;
use crate::record::payload::{PROMPT_EVENT, RESPONSE_EVENT, STOP_EVENT, TOOL_EVENT};
use crate::remote::selection::Selection;
pub const RECORD_LINE: &str = "neosian-harness-record";
pub const BEGUN_LINE: &str = "neosian-harness-filing";
const REFUSED: [&str; 3] = ["capture_paused", "capture_off", "capture_off_pending"];
fn outcome(disposition: &str) -> Value {
json!({"disposition": disposition})
}
fn failed(error: &str) -> Value {
json!({"disposition": "error", "error": head(error, FIELD_BYTES)})
}
pub fn identity(
agent: Agent,
resume: Option<&str>,
new_session: &str,
announced: Option<&str>,
) -> Result<String, &'static str> {
let Some(announced) = announced.filter(|session| adapter::session_ok(session)) else {
return Err("session");
};
let expected = match resume {
Some(session) => Some(session),
None => agent.names_session().then_some(new_session),
};
if expected.is_some_and(|session| session != announced) {
return Err("session");
}
Ok(announced.to_string())
}
fn existed(plan: &Checked, native: &str) -> Result<bool, String> {
let flag = |name: &str| {
plan.selection
.chunks(2)
.find(|pair| pair[0] == name)
.map(|pair| pair[1].as_str())
};
let selection = Selection::resolve_profile(
flag("--root").map(Path::new),
flag("--url"),
flag("--schema"),
flag("--profile"),
&plan.directory,
!plan.mounts.is_empty(),
)?;
let text = |error| crate::conversation::Error::from(error).text();
let store = selection.open().map_err(text)?;
let mounts = match selection.mounts() {
Some(mounts) => mounts?,
None => plan
.mounts
.iter()
.filter_map(|token| Mount::parse(token).ok())
.collect(),
};
let scopes: Vec<String> = mounts.into_iter().map(|mount| mount.scope).collect();
let conversation = Naming::of_store(store.as_ref()).conversation(plan.agent.kind(), native);
link::last_turn(store.as_ref(), &conversation)?;
Ok(link::existed(&store, &scopes, &conversation))
}
pub fn file(plan: &Checked, prompt: &[u8], captured: Option<Captured>, code: u8) -> Value {
let Some(captured) = captured else {
return outcome("gap");
};
if captured.over {
return outcome("bound");
}
if let Some(error) = &captured.error {
return failed(error);
}
if !captured.completed || code != 0 {
return outcome("gap");
}
let drift =
super::selection::drifted(&plan.selection, plan.identity.as_deref(), &plan.directory);
if let Err(sentence) = drift {
return failed(&sentence);
}
let resume = plan.resume.as_deref();
let announced = captured.session.as_deref();
let native = match identity(plan.agent, resume, &plan.new_session, announced) {
Ok(native) => native,
Err(reason) => return outcome(reason),
};
if resume.is_none() {
match existed(plan, &native) {
Ok(false) => {}
Ok(true) => return outcome("existing"),
Err(error) => return failed(&error),
}
}
let prompt = String::from_utf8_lossy(prompt);
let asked = json!({"prompt": prompt});
match call(plan, &native, PROMPT_EVENT, asked) {
Ok(envelope) => {
if let Some(refused) = envelope["disposition"]
.as_str()
.filter(|disposition| REFUSED.contains(disposition))
{
return outcome(refused);
}
}
Err(Failure::Slow(error)) => return failed(&error),
Err(Failure::Failed(_)) => {}
}
for line in captured
.tools
.into_iter()
.flat_map(|file| BufReader::new(file).lines())
{
let Some(tool) = line
.ok()
.and_then(|line| serde_json::from_str::<Value>(&line).ok())
else {
return failed(&say("record_spool_unreadable", &[]));
};
if let Err(Failure::Slow(error)) = call(plan, &native, TOOL_EVENT, tool) {
return failed(&error);
}
}
let mut answer = json!({"last_assistant_message": captured.answer});
if plan.agent == Agent::Cursor {
let said = json!({"text": captured.answer});
if let Err(Failure::Slow(error)) = call(plan, &native, RESPONSE_EVENT, said) {
return failed(&error);
}
answer = json!({"status": "completed"});
}
match call(plan, &native, STOP_EVENT, answer) {
Ok(envelope) => json!({
"disposition": envelope["disposition"],
"conversation": envelope["conversation_id"],
"turn": envelope["turn"],
}),
Err(failure) => failed(failure.text()),
}
}
pub fn begun(nonce: &str) {
let _ = writeln!(super::ending::raw(2), "\n{BEGUN_LINE} {nonce}");
}
pub fn began(text: &str, nonce: &str) -> Option<String> {
let marker = format!("{BEGUN_LINE} {nonce}");
text.contains(&marker).then(|| {
text.replace(&format!("\n{marker}\n"), "\n")
.replace(&marker, "")
})
}
pub fn report(nonce: &str, filed: &Value) {
let _ = writeln!(super::ending::raw(2), "\n{RECORD_LINE} {nonce} {filed}");
}
pub fn taken(text: &str, nonce: &str) -> (String, Option<Value>) {
let marker = format!("{RECORD_LINE} {nonce} ");
let Some(at) = text.rfind(&marker) else {
return (text.to_string(), None);
};
let rest = &text[at + marker.len()..];
let end = rest.find('\n').unwrap_or(rest.len());
let filed = serde_json::from_str::<Value>(&rest[..end]).ok();
let mut kept = text[..at].trim_end().to_string();
let after = rest[end..].trim();
if !after.is_empty() {
kept.push('\n');
kept.push_str(after);
}
(kept, filed)
}
#[cfg(test)]
mod tests;