#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
use super::{mine, scan, Json};
use super::check::json::{self, J};
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::Path,
};
pub(crate) const MAX_TAIL: usize = 4 * 1024 * 1024;
const CHUNK: usize = 16 * 1024;
const MAX_TOOLS: usize = 1024;
const MAX_ITEMS: usize = 128;
#[cfg(test)]
#[path = "last_turn_tests.rs"]
mod tests;
#[derive(Debug, Default, PartialEq)]
pub(crate) struct Facts {
pub files_written: Vec<String>,
pub files_read: Vec<String>,
pub shell_reads: Vec<String>,
pub commands: Vec<String>,
pub tool_call_count: usize,
pub read_before_first_edit: bool,
pub wall_time_ms: Option<u64>,
pub bytes_read: usize,
}
fn text<'a>(v: &'a Json, key: &str) -> &'a str {
v.get(key).and_then(Json::as_str).unwrap_or("")
}
fn convert(v: J) -> Json {
match v {
J::Null => Json::Null,
J::Bool(x) => Json::Bool(x),
J::Num(n) => Json::Num(n.parse().unwrap_or(f64::NAN)),
J::Str(s) => Json::Str(s),
J::Arr(a) => Json::Arr(a.into_iter().map(convert).collect()),
J::Obj(o) => Json::Obj(o.into_iter().map(|(k, v)| (k, convert(v))).collect()),
}
}
fn parse(bytes: &[u8]) -> Option<Json> {
json::parse(bytes).ok().map(convert)
}
fn excluded(v: &Json) -> bool {
matches!(v.get("isSidechain"), Some(Json::Bool(true)))
|| matches!(v.get("isMeta"), Some(Json::Bool(true)))
|| matches!(v.get("isCompactSummary"), Some(Json::Bool(true)))
|| matches!(v.get("isVisibleInTranscriptOnly"), Some(Json::Bool(true)))
}
fn assistant(v: &Json) -> bool {
text(v, "type") == "assistant"
|| (text(v, "type") == "response_item"
&& v.get("payload").is_some_and(|p| {
matches!(text(p, "type"), "function_call" | "custom_tool_call")
|| (text(p, "type") == "message" && text(p, "role") == "assistant")
}))
}
#[derive(Clone)]
struct Call {
name: String,
input: Json,
}
fn calls(v: &Json) -> Option<Vec<Call>> {
let mut out = Vec::new();
if text(v, "type") == "assistant" {
if let Some(Json::Arr(blocks)) = v.get("message").and_then(|m| m.get("content")) {
for b in blocks {
if text(b, "type") == "tool_use" {
out.push(Call {
name: text(b, "name").into(),
input: b.get("input").cloned().unwrap_or(Json::Null),
});
}
}
}
}
else if text(v, "type") == "response_item" {
if let Some(p) = v.get("payload") {
if text(p, "type") == "function_call" {
let input = parse(text(p, "arguments").as_bytes())?;
out.push(Call {
name: text(p, "name").into(),
input,
});
} else if text(p, "type") == "custom_tool_call" {
out.push(Call {
name: text(p, "name").into(),
input: Json::Str(text(p, "input").into()),
});
}
}
}
Some(out)
}
fn add(out: &mut Vec<String>, value: &str) -> Option<()> {
if value.is_empty() {
return Some(());
}
if value.len() > 4096 {
return None;
}
if !out.iter().any(|x| x == value) {
if out.len() >= MAX_ITEMS {
return None;
}
out.push(value.into());
}
Some(())
}
fn patch_files(raw: &str, out: &mut Vec<String>) -> Option<()> {
for line in raw.lines() {
for prefix in [
"*** Add File: ",
"*** Update File: ",
"*** Delete File: ",
"*** Move to: ",
] {
if let Some(p) = line.strip_prefix(prefix) {
add(out, p)?;
}
}
}
Some(())
}
fn shell_paths(cmd: &str) -> Vec<String> {
if cmd.len() > 8192
|| cmd.chars().any(|c| {
matches!(
c,
';' | '|'
| '&'
| '('
| ')'
| '<'
| '>'
| '`'
| '$'
| '\\'
| '\n'
| '\r'
| '*'
| '?'
| '['
| ']'
| '{'
| '}'
| '~'
)
})
{
return vec![];
}
let mut words = Vec::new();
let mut word = String::new();
let mut quote = None;
for c in cmd.chars() {
if let Some(q) = quote {
if c == q {
quote = None
} else {
word.push(c)
}
} else if c == '\'' || c == '"' {
quote = Some(c)
} else if c.is_whitespace() {
if !word.is_empty() {
words.push(std::mem::take(&mut word));
}
} else {
word.push(c)
}
}
if quote.is_some() {
return vec![];
}
if !word.is_empty() {
words.push(word)
}
let Some(program) = words.first().and_then(|w| w.rsplit('/').next()) else {
return vec![];
};
let args = &words[1..];
let mut i = 0;
let mut pattern = false;
let mut paths = Vec::new();
if program == "sed" {
if args.len() < 3 || args[0] != "-n" {
return vec![];
}
let script = &args[1];
if !script.ends_with('p')
|| script.len() < 2
|| !script[..script.len() - 1]
.chars()
.all(|c| c.is_ascii_digit() || c == ',')
{
return vec![];
}
i = 2;
}
else {
if !matches!(
program,
"cat" | "head" | "tail" | "less" | "grep" | "rg" | "egrep" | "fgrep" | "zgrep"
) || !super::tripwire::command_words(cmd).is_empty()
{
return vec![];
}
}
while i < args.len() {
let arg = &args[i];
if arg == "--" {
i += 1;
for p in &args[i..] {
if matches!(program, "grep" | "rg" | "egrep" | "fgrep" | "zgrep") && !pattern {
pattern = true
} else if !p.is_empty() && p != "-" {
paths.push(p.clone())
}
}
break;
}
if arg.starts_with('-') {
let safe = match program {
"cat" => matches!(arg.as_str(), "-n" | "-b" | "-s" | "-v" | "-A"),
"less" => matches!(arg.as_str(), "-N" | "-F" | "-S" | "-R"),
"head" | "tail" => {
if matches!(arg.as_str(), "-n" | "-c") {
i += 1;
if !args.get(i).is_some_and(|s| {
s.chars()
.all(|c| c.is_ascii_digit() || c == '+' || c == '-')
}) {
return vec![];
}
true
} else {
arg.len() > 1 && arg[1..].chars().all(|c| c.is_ascii_digit())
|| matches!(arg.as_str(), "-q" | "-v")
}
}
"grep" | "rg" | "egrep" | "fgrep" | "zgrep" => matches!(
arg.as_str(),
"-n" | "-i" | "-v" | "-F" | "-E" | "-H" | "-h" | "-l" | "--line-number"
),
_ => false,
};
if !safe {
return vec![];
}
}
else if matches!(program, "grep" | "rg" | "egrep" | "fgrep" | "zgrep") && !pattern {
pattern = true
} else if arg != "-" && !arg.is_empty() {
paths.push(arg.clone())
}
i += 1;
}
if matches!(program, "grep" | "rg" | "egrep" | "fgrep" | "zgrep") && !pattern {
return vec![];
}
paths
}
fn summarize(calls: Vec<Call>, wall: Option<u64>, bytes: usize) -> Option<Facts> {
let mut f = Facts {
wall_time_ms: wall,
bytes_read: bytes,
..Facts::default()
};
let mut read = false;
let mut edited = false;
for call in calls {
f.tool_call_count += 1;
if f.tool_call_count > MAX_TOOLS {
return None;
}
let name = call.name.rsplit(['.', ':']).next().unwrap_or(&call.name);
let input = &call.input;
if matches!(name, "Read" | "read_file") {
let path = if text(input, "file_path").is_empty() {
text(input, "path")
} else {
text(input, "file_path")
};
if !path.is_empty() {
add(&mut f.files_read, path)?;
read = true;
}
}
if matches!(name, "Edit" | "Write" | "MultiEdit" | "apply_patch") {
if !edited {
f.read_before_first_edit = read;
edited = true;
}
if name == "apply_patch" {
let raw = if let Json::Str(s) = input {
s.as_str()
} else {
["patch", "input"]
.iter()
.map(|k| text(input, k))
.find(|x| !x.is_empty())
.unwrap_or("")
};
patch_files(raw, &mut f.files_written)?;
} else {
let path = if text(input, "file_path").is_empty() {
text(input, "path")
} else {
text(input, "file_path")
};
add(&mut f.files_written, path)?;
}
}
if matches!(name, "Bash" | "shell" | "shell_command" | "exec_command") {
let cmd = match input.get("command").or_else(|| input.get("cmd")) {
Some(Json::Str(s)) => s.as_str(),
Some(Json::Arr(a)) => a.last().and_then(Json::as_str).unwrap_or(""),
_ => "",
};
if !cmd.is_empty() {
for path in shell_paths(cmd) {
add(&mut f.shell_reads, &path)?;
}
let redacted = scan::redact_snippet(cmd);
let clipped: String = redacted.chars().take(80).collect();
add(&mut f.commands, &clipped)?;
}
}
}
Some(f)
}
fn timestamp(v: &Json) -> Option<i64> {
let s = text(v, "timestamp");
let b = s.as_bytes();
if b.len() < 20
|| b[4] != b'-'
|| b[7] != b'-'
|| b[10] != b'T'
|| b[13] != b':'
|| b[16] != b':'
|| *b.last()? != b'Z'
{
return None;
}
let n = |start: usize, len: usize| -> Option<i64> {
let bytes = b.get(start..start + len)?;
if !bytes.iter().all(u8::is_ascii_digit) {
return None;
}
std::str::from_utf8(bytes).ok()?.parse().ok()
};
let (mut y, m, d) = (n(0, 4)?, n(5, 2)?, n(8, 2)?);
let (h, min, sec) = (n(11, 2)?, n(14, 2)?, n(17, 2)?);
if !(1..=12).contains(&m) || h > 23 || min > 59 || sec > 59 {
return None;
}
let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
let mdays = match m {
2 => {
if leap {
29
} else {
28
}
}
4 | 6 | 9 | 11 => 30,
_ => 31,
};
if d < 1 || d > mdays {
return None;
}
let millis = if b.len() == 20 {
0
} else {
if b[19] != b'.' {
return None;
}
let frac = &b[20..b.len() - 1];
if frac.is_empty() || frac.len() > 9 || !frac.iter().all(u8::is_ascii_digit) {
return None;
}
frac.iter()
.take(3)
.fold(0i64, |a, x| a * 10 + (x - b'0') as i64)
* 10i64.pow(3 - frac.len().min(3) as u32)
};
y -= i64::from(m <= 2);
let era = y.div_euclid(400);
let yo = y - era * 400;
let mp = m + if m > 2 { -3 } else { 9 };
let doy = (153 * mp + 2) / 5 + d - 1;
let days = era * 146097 + yo * 365 + yo / 4 - yo / 100 + doy - 719468;
Some((((days * 24 + h) * 60 + min) * 60 + sec) * 1000 + millis)
}
#[derive(Default)]
struct Scan {
calls_reverse: Vec<Vec<Call>>,
tool_count: usize,
saw_assistant: bool,
trailing_users: usize,
end: Option<i64>,
prior: Option<i64>,
clock_valid: bool,
initialized: bool,
}
impl Scan {
fn line(&mut self, raw: &[u8], bytes: usize) -> Option<Option<Facts>> {
if raw.iter().all(u8::is_ascii_whitespace) {
return Some(None);
}
let v = parse(raw)?;
if excluded(&v) {
return Some(None);
}
if mine::is_typed_user_record(&v) {
if self.saw_assistant {
let wall = if self.clock_valid {
timestamp(&v).zip(self.end).and_then(|(start, end)| {
if self.prior.is_some_and(|first| start > first) {
None
} else {
u64::try_from(end - start).ok()
}
})
} else {
None
};
let calls = std::mem::take(&mut self.calls_reverse)
.into_iter()
.rev()
.flatten()
.collect();
return Some(Some(summarize(calls, wall, bytes)?));
}
self.trailing_users += 1;
if self.trailing_users > 1 {
return None;
}
return Some(None);
}
if assistant(&v) {
self.saw_assistant = true;
let ts = timestamp(&v);
if !self.initialized {
self.end = ts;
self.clock_valid = ts.is_some();
self.initialized = true;
} else if ts.is_none() || ts.zip(self.prior).is_some_and(|(t, p)| t > p) {
self.clock_valid = false;
}
self.prior = ts;
let c = calls(&v)?;
self.tool_count = self.tool_count.checked_add(c.len())?;
if self.tool_count > MAX_TOOLS {
return None;
}
if !c.is_empty() {
self.calls_reverse.push(c);
}
}
Some(None)
}
}
pub(crate) fn from_event(event: &Json) -> Option<Facts> {
if text(event, "hook_event_name") != "UserPromptSubmit" {
return None;
}
let path = Path::new(event.get("transcript_path")?.as_str()?);
if !path.is_absolute() {
return None;
}
extract(path)
}
pub(crate) fn extract(path: &Path) -> Option<Facts> {
let metadata = std::fs::symlink_metadata(path).ok()?;
if !metadata.is_file() {
return None;
}
let mut file = File::open(path).ok()?;
let len = file.metadata().ok()?.len();
let mut pos = len;
let mut read = 0usize;
let mut pending = Vec::new();
let mut state = Scan::default();
while pos > 0 && read < MAX_TAIL {
let take = (pos.min(CHUNK as u64) as usize).min(MAX_TAIL - read);
pos -= take as u64;
file.seek(SeekFrom::Start(pos)).ok()?;
let mut block = vec![0; take];
file.read_exact(&mut block).ok()?;
read += take;
block.extend_from_slice(&pending);
pending = block;
let start = if pos == 0 {
0
} else {
match pending.iter().position(|b| *b == b'\n') {
Some(i) => i + 1,
None => {
if pending.len() > json::MAX_BYTES {
return None;
}
continue;
}
}
};
let mut end = pending.len();
if end > start && pending[end - 1] == b'\n' {
end -= 1;
}
while end > start {
let begin = pending[start..end]
.iter()
.rposition(|b| *b == b'\n')
.map_or(start, |i| start + i + 1);
if let Some(facts) = state.line(&pending[begin..end], read)? {
return Some(facts);
}
if begin == start {
break;
}
end = begin - 1;
}
pending.truncate(start);
if pos == 0 {
break;
}
}
None
}