nitpicker_agent/
session.rs1use eyre::{Result, WrapErr};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::{SystemTime, UNIX_EPOCH};
7use tokio::fs::OpenOptions;
8use tokio::io::AsyncWriteExt;
9use tokio::sync::Mutex;
10
11#[derive(Clone)]
12pub struct SessionLogger {
13 root: Arc<PathBuf>,
14 write_lock: Arc<Mutex<()>>,
16}
17
18#[derive(Debug, Serialize, Deserialize)]
19pub struct AggregationRecord {
20 pub kind: String,
21 pub model: String,
22 pub text: String,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub rounds: Option<usize>,
25 #[serde(skip_serializing_if = "Option::is_none")]
26 pub converged: Option<bool>,
27}
28
29#[derive(Debug, Serialize, Deserialize)]
30pub struct ToolCallRecord {
31 pub ts_unix_ms: u128,
32 pub agent: String,
33 pub depth: usize,
34 pub turn: usize,
35 pub tool: String,
36 pub args: Value,
37 pub status: String,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub spawned_agent: Option<String>,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub result: Option<String>,
42}
43
44impl SessionLogger {
45 pub fn maybe_new(enabled: bool) -> Result<Option<Self>> {
46 if !enabled {
47 return Ok(None);
48 }
49
50 let home =
51 dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
52 let ts = now_unix_ms();
53 let pid = std::process::id();
54 let root = home
55 .join(".nitpicker")
56 .join("sessions")
57 .join(format!("session-{ts}-{pid}"));
58 std::fs::create_dir_all(&root)
59 .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
60 Ok(Some(Self {
61 root: Arc::new(root),
62 write_lock: Arc::new(Mutex::new(())),
63 }))
64 }
65
66 pub fn root(&self) -> &Path {
67 self.root.as_ref()
68 }
69
70 pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
71 SessionWriter {
72 root: Arc::clone(&self.root),
73 relative_path: relative_path.as_ref().to_path_buf(),
74 write_lock: Arc::clone(&self.write_lock),
75 }
76 }
77
78 pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
79 let path = self.root.join("aggregation.json");
80 let body = serde_json::to_vec_pretty(record)?;
81 tokio::fs::write(&path, body)
82 .await
83 .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
84 Ok(())
85 }
86}
87
88#[derive(Clone)]
89pub struct SessionWriter {
90 root: Arc<PathBuf>,
91 relative_path: PathBuf,
92 write_lock: Arc<Mutex<()>>,
93}
94
95impl SessionWriter {
96 pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
97 let path = self.root.join(&self.relative_path);
98 if let Some(parent) = path.parent() {
99 tokio::fs::create_dir_all(parent).await.wrap_err_with(|| {
100 format!("failed to create session log dir {}", parent.display())
101 })?;
102 }
103 let mut buf = serde_json::to_vec(record)?;
104 buf.push(b'\n');
105 let _guard = self.write_lock.lock().await;
107 let mut file = OpenOptions::new()
108 .create(true)
109 .append(true)
110 .open(&path)
111 .await
112 .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
113 file.write_all(&buf).await?;
114 Ok(())
115 }
116}
117
118pub fn now_unix_ms() -> u128 {
119 SystemTime::now()
120 .duration_since(UNIX_EPOCH)
121 .map(|d| d.as_millis())
122 .unwrap_or(0)
123}
124
125pub fn sanitize_path_component(value: &str) -> String {
126 let sanitized: String = value
127 .chars()
128 .map(|ch| match ch {
129 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
130 _ => '-',
131 })
132 .collect();
133 let trimmed = sanitized.trim_matches('-');
134 if trimmed.is_empty() {
135 "agent".to_string()
136 } else {
137 trimmed.to_string()
138 }
139}