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 = dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
51 let ts = now_unix_ms();
52 let pid = std::process::id();
53 let root = home
54 .join(".nitpicker")
55 .join("sessions")
56 .join(format!("session-{ts}-{pid}"));
57 std::fs::create_dir_all(&root)
58 .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
59 Ok(Some(Self {
60 root: Arc::new(root),
61 write_lock: Arc::new(Mutex::new(())),
62 }))
63 }
64
65 pub fn root(&self) -> &Path {
66 self.root.as_ref()
67 }
68
69 pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
70 SessionWriter {
71 root: Arc::clone(&self.root),
72 relative_path: relative_path.as_ref().to_path_buf(),
73 write_lock: Arc::clone(&self.write_lock),
74 }
75 }
76
77 pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
78 let path = self.root.join("aggregation.json");
79 let body = serde_json::to_vec_pretty(record)?;
80 tokio::fs::write(&path, body)
81 .await
82 .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
83 Ok(())
84 }
85}
86
87#[derive(Clone)]
88pub struct SessionWriter {
89 root: Arc<PathBuf>,
90 relative_path: PathBuf,
91 write_lock: Arc<Mutex<()>>,
92}
93
94impl SessionWriter {
95 pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
96 let path = self.root.join(&self.relative_path);
97 if let Some(parent) = path.parent() {
98 tokio::fs::create_dir_all(parent)
99 .await
100 .wrap_err_with(|| format!("failed to create session log dir {}", parent.display()))?;
101 }
102 let mut buf = serde_json::to_vec(record)?;
103 buf.push(b'\n');
104 let _guard = self.write_lock.lock().await;
106 let mut file = OpenOptions::new()
107 .create(true)
108 .append(true)
109 .open(&path)
110 .await
111 .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
112 file.write_all(&buf).await?;
113 Ok(())
114 }
115}
116
117pub fn now_unix_ms() -> u128 {
118 SystemTime::now()
119 .duration_since(UNIX_EPOCH)
120 .map(|d| d.as_millis())
121 .unwrap_or(0)
122}
123
124pub fn sanitize_path_component(value: &str) -> String {
125 let sanitized: String = value
126 .chars()
127 .map(|ch| match ch {
128 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
129 _ => '-',
130 })
131 .collect();
132 let trimmed = sanitized.trim_matches('-');
133 if trimmed.is_empty() {
134 "agent".to_string()
135 } else {
136 trimmed.to_string()
137 }
138}