1use std::collections::HashMap;
4use std::fmt;
5
6use adk_core::Result;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use tokio::sync::RwLock;
11
12#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct ShellLedgerEntry {
26 pub function_call_id: String,
28 pub command: String,
30 pub sandboxed: bool,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub enforcer: Option<String>,
35 pub exit_code: Option<i32>,
37 #[serde(default)]
39 pub denial_suspected: bool,
40 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub retried_by: Option<String>,
43 pub at: DateTime<Utc>,
45}
46
47impl ShellLedgerEntry {
48 pub fn new(
50 function_call_id: impl Into<String>,
51 command: impl Into<String>,
52 sandboxed: bool,
53 exit_code: Option<i32>,
54 ) -> Self {
55 Self {
56 function_call_id: function_call_id.into(),
57 command: command.into(),
58 sandboxed,
59 enforcer: None,
60 exit_code,
61 denial_suspected: false,
62 retried_by: None,
63 at: Utc::now(),
64 }
65 }
66
67 pub fn failed(&self) -> bool {
69 self.exit_code != Some(0)
70 }
71
72 pub fn digest(&self) -> String {
85 let failure = serde_json::json!({
86 "functionCallId": self.function_call_id,
87 "command": self.command,
88 "sandboxed": self.sandboxed,
89 "enforcer": self.enforcer,
90 "exitCode": self.exit_code,
91 "denialSuspected": self.denial_suspected,
92 });
93 format!("sha256:{}", crate::fsutil::sha256_hex(&failure.to_string()))
94 }
95}
96
97#[async_trait]
117pub trait ShellLedger: fmt::Debug + Send + Sync {
118 async fn record(
120 &self,
121 app: &str,
122 user: &str,
123 session: &str,
124 entry: ShellLedgerEntry,
125 ) -> Result<()>;
126 async fn get(
128 &self,
129 app: &str,
130 user: &str,
131 session: &str,
132 function_call_id: &str,
133 ) -> Result<Option<ShellLedgerEntry>>;
134 async fn mark_retried(
137 &self,
138 app: &str,
139 user: &str,
140 session: &str,
141 function_call_id: &str,
142 by: &str,
143 ) -> Result<bool>;
144}
145
146type LedgerKey = (String, String, String, String);
147
148#[derive(Debug, Default)]
157pub struct InMemoryShellLedger {
158 entries: RwLock<HashMap<LedgerKey, ShellLedgerEntry>>,
159}
160
161impl InMemoryShellLedger {
162 pub fn new() -> Self {
164 Self::default()
165 }
166}
167
168fn key(app: &str, user: &str, session: &str, call: &str) -> LedgerKey {
169 (app.to_string(), user.to_string(), session.to_string(), call.to_string())
170}
171
172#[async_trait]
173impl ShellLedger for InMemoryShellLedger {
174 async fn record(
175 &self,
176 app: &str,
177 user: &str,
178 session: &str,
179 entry: ShellLedgerEntry,
180 ) -> Result<()> {
181 self.entries.write().await.insert(key(app, user, session, &entry.function_call_id), entry);
182 Ok(())
183 }
184
185 async fn get(
186 &self,
187 app: &str,
188 user: &str,
189 session: &str,
190 function_call_id: &str,
191 ) -> Result<Option<ShellLedgerEntry>> {
192 Ok(self.entries.read().await.get(&key(app, user, session, function_call_id)).cloned())
193 }
194
195 async fn mark_retried(
196 &self,
197 app: &str,
198 user: &str,
199 session: &str,
200 function_call_id: &str,
201 by: &str,
202 ) -> Result<bool> {
203 let mut entries = self.entries.write().await;
204 match entries.get_mut(&key(app, user, session, function_call_id)) {
205 Some(entry) if entry.retried_by.is_none() => {
206 entry.retried_by = Some(by.to_string());
207 Ok(true)
208 }
209 _ => Ok(false),
210 }
211 }
212}
213
214#[cfg(feature = "sqlite")]
226#[derive(Debug, Clone)]
227pub struct SqliteShellLedger {
228 pool: sqlx::SqlitePool,
229 #[cfg(feature = "encrypted")]
230 envelope: Option<crate::encrypted::StoreEnvelope>,
231}
232
233#[cfg(feature = "sqlite")]
234impl SqliteShellLedger {
235 pub fn new(pool: sqlx::SqlitePool) -> Self {
237 Self {
238 pool,
239 #[cfg(feature = "encrypted")]
240 envelope: None,
241 }
242 }
243
244 #[cfg(feature = "encrypted")]
246 #[must_use]
247 pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
248 self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "shell-ledger"));
249 self
250 }
251
252 #[cfg(feature = "encrypted")]
261 pub async fn rewrap(&self) -> Result<u64> {
262 let Some(envelope) = &self.envelope else {
263 return Ok(0);
264 };
265 let rows: Vec<(String, String, String, String, String)> = sqlx::query_as("SELECT app_name, user_id, session_id, function_call_id, entry FROM adk_harness_shell_ledger")
266 .fetch_all(&self.pool)
267 .await
268 .map_err(crate::fsutil::db_error)?;
269 let mut changed = 0;
270 for (app, user, session, call, text) in rows {
271 if let Some(resealed) =
272 envelope.reseal_or_seal(&[&app, &user, &session, &call], &text)?
273 {
274 sqlx::query("UPDATE adk_harness_shell_ledger SET entry = ? WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ?")
275 .bind(resealed)
276 .bind(&app)
277 .bind(&user)
278 .bind(&session)
279 .bind(&call)
280 .execute(&self.pool)
281 .await
282 .map_err(crate::fsutil::db_error)?;
283 changed += 1;
284 }
285 }
286 Ok(changed)
287 }
288
289 #[cfg(feature = "encrypted")]
290 fn encode(&self, address: &[&str], text: String) -> Result<String> {
291 crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
292 }
293
294 #[cfg(not(feature = "encrypted"))]
295 fn encode(&self, _address: &[&str], text: String) -> Result<String> {
296 Ok(text)
297 }
298
299 #[cfg(feature = "encrypted")]
300 fn decode(&self, address: &[&str], text: String) -> Result<String> {
301 crate::encrypted::decode_row(self.envelope.as_ref(), "shell-ledger", address, text)
302 }
303
304 #[cfg(not(feature = "encrypted"))]
305 fn decode(&self, _address: &[&str], text: String) -> Result<String> {
306 Ok(text)
307 }
308
309 pub async fn migrate(&self) -> Result<()> {
315 sqlx::query(
316 "CREATE TABLE IF NOT EXISTS adk_harness_shell_ledger (\
317 app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
318 function_call_id TEXT NOT NULL, entry TEXT NOT NULL, retried_by TEXT, \
319 PRIMARY KEY (app_name, user_id, session_id, function_call_id))",
320 )
321 .execute(&self.pool)
322 .await
323 .map_err(crate::fsutil::db_error)?;
324 Ok(())
325 }
326}
327
328#[cfg(feature = "sqlite")]
329#[async_trait]
330impl ShellLedger for SqliteShellLedger {
331 async fn record(
332 &self,
333 app: &str,
334 user: &str,
335 session: &str,
336 entry: ShellLedgerEntry,
337 ) -> Result<()> {
338 let text = serde_json::to_string(&entry)
339 .map_err(|error| crate::fsutil::serialize_error("shell ledger entry", &error))?;
340 let text = self.encode(&[app, user, session, &entry.function_call_id], text)?;
341 sqlx::query(
342 "INSERT INTO adk_harness_shell_ledger \
343 (app_name, user_id, session_id, function_call_id, entry, retried_by) VALUES (?, ?, ?, ?, ?, ?) \
344 ON CONFLICT (app_name, user_id, session_id, function_call_id) \
345 DO UPDATE SET entry = excluded.entry",
346 )
347 .bind(app)
348 .bind(user)
349 .bind(session)
350 .bind(&entry.function_call_id)
351 .bind(text)
352 .bind(entry.retried_by.as_deref())
353 .execute(&self.pool)
354 .await
355 .map_err(crate::fsutil::db_error)?;
356 Ok(())
357 }
358
359 async fn get(
360 &self,
361 app: &str,
362 user: &str,
363 session: &str,
364 function_call_id: &str,
365 ) -> Result<Option<ShellLedgerEntry>> {
366 let row: Option<(String, Option<String>)> = sqlx::query_as(
367 "SELECT entry, retried_by FROM adk_harness_shell_ledger \
368 WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ?",
369 )
370 .bind(app)
371 .bind(user)
372 .bind(session)
373 .bind(function_call_id)
374 .fetch_optional(&self.pool)
375 .await
376 .map_err(crate::fsutil::db_error)?;
377 let Some((text, retried_by)) = row else {
378 return Ok(None);
379 };
380 let text = self.decode(&[app, user, session, function_call_id], text)?;
381 Ok(serde_json::from_str::<ShellLedgerEntry>(&text).ok().map(|mut entry| {
382 entry.retried_by = retried_by;
383 entry
384 }))
385 }
386
387 async fn mark_retried(
388 &self,
389 app: &str,
390 user: &str,
391 session: &str,
392 function_call_id: &str,
393 by: &str,
394 ) -> Result<bool> {
395 let result = sqlx::query(
396 "UPDATE adk_harness_shell_ledger SET retried_by = ? \
397 WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ? \
398 AND retried_by IS NULL",
399 )
400 .bind(by)
401 .bind(app)
402 .bind(user)
403 .bind(session)
404 .bind(function_call_id)
405 .execute(&self.pool)
406 .await
407 .map_err(crate::fsutil::db_error)?;
408 Ok(result.rows_affected() == 1)
409 }
410}