Skip to main content

agent_trace/commands/
write_cmd.rs

1use crate::data_plane::{self, WriteDocumentError};
2use crate::observability::{format_permission_denied, CliOutput};
3use crate::session::{session_id_for_actor, touch_session, AgentState};
4use anyhow::Result;
5use std::io::{self, Read};
6use std::path::Path;
7
8pub fn run(
9    root: &Path,
10    file: &Path,
11    content: Option<String>,
12    cli_agent: Option<String>,
13    output: &dyn CliOutput,
14) -> Result<()> {
15    let body = match content {
16        Some(c) => c,
17        None => {
18            let mut buf = String::new();
19            io::stdin().read_to_string(&mut buf)?;
20            buf
21        }
22    };
23
24    let agent_state = AgentState::new(cli_agent);
25    let actor = agent_state.current_actor(root);
26    let session_id = session_id_for_actor(root, &actor);
27    if let Some(name) = actor.agent_name() {
28        let _ = touch_session(root, name);
29    }
30
31    let rel = match data_plane::write_document(
32        root,
33        file,
34        &body,
35        &actor,
36        "agent write",
37        session_id.as_deref(),
38    ) {
39        Ok(path) => path,
40        Err(WriteDocumentError::PermissionDenied { path, reason }) => {
41            output.error(&format_permission_denied(&path, &reason))?;
42            std::process::exit(1);
43        }
44        Err(WriteDocumentError::Other(e)) => return Err(e),
45    };
46
47    output.line(&format!("OK: {} written", rel.display()))?;
48    Ok(())
49}