Skip to content

Commit 1eb2c97

Browse files
feat(dgw): turn a finished recording into transcript chunks and a session log
These are the pieces of the AI analysis that work on files, without any AI call yet: - the recording manager tells whether a session is done recording; the caller then reads its manifest, off the manager task; - the terminal recordings of a session (asciicast and TRP) are streamed into transcript chunk files of bounded size, so memory use depends on the chunk size, not on the recording size, and the work can be cancelled between two events; - what the AI answers for a chunk is saved as a checkpoint, so a retry does not ask again; - AI actions are written as a Session Recording Log (`.slog`). The AI analysis job that uses them comes next. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent b9bedc0 commit 1eb2c97

9 files changed

Lines changed: 1132 additions & 2 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎devolutions-gateway/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ transport.path = "../crates/transport"
2424
jmux-proxy.path = "../crates/jmux-proxy"
2525
devolutions-agent-shared.path = "../crates/devolutions-agent-shared"
2626
devolutions-gateway-task.path = "../crates/devolutions-gateway-task"
27+
devolutions-gateway-ai.path = "../crates/devolutions-gateway-ai"
2728
devolutions-log.path = "../crates/devolutions-log"
2829
job-queue.path = "../crates/job-queue"
2930
job-queue-libsql.path = "../crates/job-queue-libsql"
@@ -91,6 +92,7 @@ tracing = "0.1"
9192

9293
# Async, futures…
9394
tokio = { version = "1.52", features = ["signal", "net", "io-util", "time", "rt", "rt-multi-thread", "sync", "macros", "parking_lot", "fs"] }
95+
tokio-util = "0.7"
9496
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12", "ring"] }
9597
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json", "stream", "http2", "socks"] }
9698
http-client-proxy = { path = "../crates/http-client-proxy" }

‎devolutions-gateway/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ pub mod log;
3030
pub mod middleware;
3131
pub mod ngrok;
3232
pub mod plugin_manager;
33+
mod provisioner_tasks;
3334
pub mod provisioning;
3435
pub mod proxy;
3536
pub mod rd_clean_path;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
//! Work the provisioner asks Gateway to do.
2+
3+
#[cfg_attr(not(test), expect(dead_code, reason = "the AI analysis job uses it"))]
4+
mod recording_ai_analysis;
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
//! What the AI answered for one transcript chunk, saved in the task workspace so a retry does not ask the AI again.
2+
3+
use std::collections::BTreeMap;
4+
use std::io::{BufReader, BufWriter};
5+
use std::time::Duration;
6+
7+
use anyhow::Context as _;
8+
use camino::{Utf8Path, Utf8PathBuf};
9+
use devolutions_gateway_ai::Usage;
10+
use devolutions_gateway_ai::session_actions::Action;
11+
12+
/// Tokens counted by the AI provider, as kept in checkpoints and Task results.
13+
///
14+
/// It mirrors [`Usage`], so a change in the AI crate never changes what we store.
15+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16+
#[serde(rename_all = "camelCase")]
17+
pub(super) struct TokenUsage {
18+
pub(super) input_tokens: u64,
19+
pub(super) output_tokens: u64,
20+
}
21+
22+
impl From<Usage> for TokenUsage {
23+
fn from(usage: Usage) -> Self {
24+
Self {
25+
input_tokens: usage.input_tokens,
26+
output_tokens: usage.output_tokens,
27+
}
28+
}
29+
}
30+
31+
impl From<TokenUsage> for Usage {
32+
fn from(usage: TokenUsage) -> Self {
33+
Self {
34+
input_tokens: usage.input_tokens,
35+
output_tokens: usage.output_tokens,
36+
}
37+
}
38+
}
39+
40+
pub(super) fn path(workspace: &Utf8Path, index: usize) -> Utf8PathBuf {
41+
workspace.join(format!("chunk-{index:04}.json"))
42+
}
43+
44+
/// Actions found in one chunk, with what the AI provider reported for the requests about it.
45+
#[derive(Debug, Clone, PartialEq)]
46+
pub(super) struct DescribedChunk {
47+
pub(super) actions: Vec<Action>,
48+
/// Model that answered, as reported by the provider.
49+
pub(super) model: Option<String>,
50+
/// Tokens of every request about the chunk, answers cut and asked again included; `None` when one was not reported.
51+
pub(super) usage: Option<Usage>,
52+
}
53+
54+
#[derive(Serialize, Deserialize)]
55+
#[serde(rename_all = "camelCase")]
56+
struct SavedChunk {
57+
#[serde(default, skip_serializing_if = "Option::is_none")]
58+
model: Option<String>,
59+
#[serde(default, skip_serializing_if = "Option::is_none")]
60+
usage: Option<TokenUsage>,
61+
actions: Vec<SavedAction>,
62+
}
63+
64+
#[derive(Serialize, Deserialize)]
65+
#[serde(rename_all = "camelCase")]
66+
struct SavedAction {
67+
offset_seconds: f64,
68+
description: String,
69+
#[serde(default, skip_serializing_if = "Option::is_none")]
70+
object: Option<String>,
71+
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
72+
parameters: BTreeMap<String, String>,
73+
}
74+
75+
/// Writes the checkpoint through a temporary file, so a crash never leaves a partial one.
76+
pub(super) fn write(path: &Utf8Path, chunk: &DescribedChunk) -> anyhow::Result<()> {
77+
let partial = path.with_extension("partial");
78+
79+
let saved = SavedChunk {
80+
model: chunk.model.clone(),
81+
usage: chunk.usage.map(TokenUsage::from),
82+
actions: chunk
83+
.actions
84+
.iter()
85+
.map(|action| SavedAction {
86+
offset_seconds: action.offset.as_secs_f64(),
87+
description: action.description.clone(),
88+
object: action.object.clone(),
89+
parameters: action.parameters.clone(),
90+
})
91+
.collect(),
92+
};
93+
94+
let mut out = BufWriter::new(std::fs::File::create(&partial).with_context(|| format!("create {partial}"))?);
95+
serde_json::to_writer(&mut out, &saved)?;
96+
out.into_inner()?.sync_all()?;
97+
std::fs::rename(&partial, path).with_context(|| format!("rename {partial}"))?;
98+
99+
Ok(())
100+
}
101+
102+
pub(super) fn read(path: &Utf8Path) -> anyhow::Result<DescribedChunk> {
103+
let file = BufReader::new(std::fs::File::open(path).with_context(|| format!("open {path}"))?);
104+
let saved: SavedChunk = serde_json::from_reader(file).with_context(|| format!("read {path}"))?;
105+
106+
let actions = saved
107+
.actions
108+
.into_iter()
109+
.map(|saved| {
110+
Ok(Action {
111+
offset: Duration::try_from_secs_f64(saved.offset_seconds)?,
112+
description: saved.description,
113+
object: saved.object,
114+
parameters: saved.parameters,
115+
})
116+
})
117+
.collect::<anyhow::Result<_>>()?;
118+
119+
Ok(DescribedChunk {
120+
actions,
121+
model: saved.model,
122+
usage: saved.usage.map(Usage::from),
123+
})
124+
}
125+
126+
#[cfg(test)]
127+
mod tests {
128+
use super::*;
129+
130+
#[test]
131+
fn described_chunk_round_trips() {
132+
let dir = tempfile::tempdir().expect("temp dir");
133+
let path = path(Utf8Path::from_path(dir.path()).expect("UTF-8"), 3);
134+
let chunk = DescribedChunk {
135+
actions: vec![
136+
Action {
137+
offset: Duration::from_millis(1500),
138+
description: "Listed files".to_owned(),
139+
object: Some("/var/log".to_owned()),
140+
parameters: BTreeMap::from([("Command".to_owned(), "ls".to_owned())]),
141+
},
142+
Action {
143+
offset: Duration::from_secs(62),
144+
description: "Closed the shell".to_owned(),
145+
object: None,
146+
parameters: BTreeMap::new(),
147+
},
148+
],
149+
model: Some("gpt-test-2026-09-30".to_owned()),
150+
usage: Some(Usage {
151+
input_tokens: 10,
152+
output_tokens: 20,
153+
}),
154+
};
155+
156+
write(&path, &chunk).expect("written");
157+
158+
assert!(path.as_str().ends_with("chunk-0003.json"));
159+
assert_eq!(read(&path).expect("read"), chunk);
160+
assert!(!path.with_extension("partial").exists());
161+
}
162+
163+
#[test]
164+
fn unreported_model_and_usage_stay_unknown() {
165+
let dir = tempfile::tempdir().expect("temp dir");
166+
let path = path(Utf8Path::from_path(dir.path()).expect("UTF-8"), 0);
167+
let chunk = DescribedChunk {
168+
actions: Vec::new(),
169+
model: None,
170+
usage: None,
171+
};
172+
173+
write(&path, &chunk).expect("written");
174+
175+
assert_eq!(std::fs::read_to_string(&path).expect("checkpoint"), r#"{"actions":[]}"#);
176+
assert_eq!(read(&path).expect("read"), chunk);
177+
}
178+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
//! AI analysis (`recording.ai-analysis`): describes what the user did in one recorded session, and adds the result to
2+
//! the session as a new log.
3+
//!
4+
//! The work goes in steps, keeping its files in a workspace folder:
5+
//! 1. stream the terminal recordings into transcript chunk files (`chunk-NNNN.txt`), see [`transcript`];
6+
//! 2. save what the AI answered for each chunk as a checkpoint (`chunk-NNNN.json`), see [`checkpoint`];
7+
//! 3. merge the checkpoints into a `.slog` file, see [`slog`].
8+
9+
mod checkpoint;
10+
mod slog;
11+
mod transcript;

0 commit comments

Comments
 (0)