#[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 std::{borrow::Cow, ops::Range};
fn escaped(text: &str, at: usize) -> bool {
text.as_bytes()[..at]
.iter()
.rev()
.take_while(|&&byte| byte == b'\\')
.count()
% 2
== 1
}
pub(crate) fn quoted_spans(text: &str) -> Vec<Range<usize>> {
let mut spans = Vec::new();
let mut open = None;
for (at, ch) in text.char_indices() {
if let Some((from, end)) = open {
if ch == end && !escaped(text, at) {
let after = at + ch.len_utf8();
if matches!(ch, '\'' | '’') && text[after..].starts_with(char::is_alphanumeric) {
continue;
}
spans.push(from..after);
open = None;
}
} else {
let end = match ch {
'"' | '\'' | '`' => ch,
'“' => '”',
'‘' => '’',
_ => continue,
};
if !text[..at].ends_with(char::is_alphanumeric) && !escaped(text, at) {
open = Some((at, end));
}
}
}
spans
}
fn words(text: &str) -> impl Iterator<Item = &str> {
text.split(|c: char| !c.is_alphanumeric() && c != '\'')
.filter(|w| !w.is_empty())
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Role {
Transform,
Language,
Meaning,
Count,
Check,
Find,
Create,
Change,
}
impl Role {
fn acts_on_words_or_quantity(self) -> bool {
matches!(
self,
Self::Transform | Self::Language | Self::Meaning | Self::Count
)
}
}
fn operator(w: &str) -> Option<Role> {
match w {
"translate" | "alphabetize" | "alphabetise" | "reorder" | "transcribe" | "uppercase"
| "lowercase" | "capitalize" | "capitalise" | "paraphrase" | "proofread" | "rephrase"
| "rewrite" => Some(Role::Transform),
"define" => Some(Role::Meaning),
"count" | "calculate" | "enumerate" => Some(Role::Count),
"verify" | "confirm" | "check" | "validate" | "crosscheck" | "compare" | "inspect"
| "diagnose" | "audit" | "debug" => Some(Role::Check),
"locate" | "search" | "find" | "grep" | "scan" | "filter" | "look" | "retrieve" => {
Some(Role::Find)
}
"write" | "prepare" | "draft" | "produce" | "compose" | "generate" | "make" | "create"
| "build" | "print" | "publish" | "deliver" | "send" => Some(Role::Create),
"change" | "add" | "repair" | "fix" | "remove" | "arrange" | "organize" | "sort"
| "update" => Some(Role::Change),
_ => None,
}
}
fn unit(w: &str) -> bool {
matches!(
w,
"word"
| "words"
| "letter"
| "letters"
| "character"
| "characters"
| "lines"
| "syllables"
)
}
fn syntax_word(w: &str) -> bool {
matches!(
w,
"verb"
| "noun"
| "adjective"
| "adverb"
| "pronoun"
| "subject"
| "tense"
| "syllable"
| "grammar"
| "punctuation"
)
}
fn filler(w: &str) -> bool {
matches!(
w,
"please"
| "can"
| "could"
| "would"
| "you"
| "kindly"
| "just"
| "then"
| "also"
| "separately"
| "still"
| "when"
| "to"
| "i"
| "we"
| "need"
| "want"
| "should"
)
}
fn clause_role(terms: &[&str]) -> Option<Role> {
let start = terms.iter().position(|w| !filler(w)).unwrap_or(terms.len());
let terms = &terms[start..];
let first = *terms.first()?;
let asks = matches!(
first,
"is" | "are"
| "does"
| "do"
| "how"
| "what"
| "which"
| "in"
| "within"
| "from"
| "identify"
| "tell"
| "find"
| "spot"
| "give"
| "explain"
);
let has = |w: &str| terms.contains(&w);
if terms.windows(2).any(|p| p == ["how", "many"])
|| (first == "count" && terms.iter().skip(1).take(4).any(|w| unit(w)))
{
return Some(Role::Count);
}
if first == "define"
|| has("definition")
&& !matches!(
operator(first),
Some(Role::Check | Role::Find | Role::Change)
)
|| (asks && has("difference") && has("between"))
|| (matches!(first, "what" | "explain")
&& has("mean")
&& terms.iter().any(|w| {
matches!(
*w,
"term" | "word" | "phrase" | "expression" | "acronym" | "abbreviation"
)
}))
{
return Some(Role::Meaning);
}
let refers_to_words = terms.iter().any(|w| {
matches!(
*w,
"wording" | "phrase" | "sentence" | "phrasing" | "spelling" | "typo"
)
});
let tone = terms.iter().any(|w| {
matches!(
*w,
"formal"
| "informal"
| "natural"
| "polite"
| "rude"
| "harsh"
| "abrupt"
| "clear"
| "awkward"
| "friendly"
| "grammatical"
)
});
if (refers_to_words
&& (matches!(
first,
"soften" | "reword" | "correct" | "spot" | "proofread" | "rephrase"
) || asks && (tone || has("typo") || has("wording"))))
|| (asks
&& terms.iter().any(|w| syntax_word(w))
&& (has("which") || has("what") || has("or")))
|| (asks && (has("sound") || has("read")) && tone)
{
return Some(Role::Language);
}
operator(first)
}
fn is_source(prefix: &str, suffix: &str) -> bool {
let before = prefix
.rsplit(['.', '!', '?', ';', ',', '\n'])
.next()
.unwrap_or("");
let mut after = String::new();
for word in suffix.split_whitespace().take(16) {
if let Some(end) = word.find(['.', '!', '?', ';']) {
after.push_str(&word[..end]);
break;
}
after.push_str(word);
after.push(' ');
}
let lower = before.to_lowercase();
let terms: Vec<_> = words(&lower).collect();
let cut = terms
.windows(2)
.rposition(|p| matches!(p[0], "then" | "also" | "and" | "but") && operator(p[1]).is_some())
.map_or(0, |i| i + 1);
let after = after.to_lowercase();
let mut surrounding = terms[cut..].to_vec();
surrounding.extend(words(&after));
match clause_role(&surrounding) {
Some(Role::Count) => surrounding.iter().any(|w| unit(w)),
Some(role) => role.acts_on_words_or_quantity(),
None => false,
}
}
pub(crate) fn action_text(text: &str) -> Cow<'_, str> {
if !text.contains(['"', '\'', '`', '“', '‘']) {
return Cow::Borrowed(text);
}
let mut copied = 0;
let mut last_source = false;
let mut out = String::new();
for range in quoted_spans(text) {
let between = &text[copied..range.start];
out.push_str(between);
let continuation = last_source
&& !between.contains(['.', '!', '?', ';', '\n'])
&& words(between).all(|w| matches!(w, "and" | "or"));
last_source = continuation || is_source(between, &text[range.end..]);
if last_source {
out.push(' ');
} else {
out.push_str(&text[range.clone()]);
}
copied = range.end;
}
if copied == 0 || out == text[..copied] {
return Cow::Borrowed(text);
}
out.push_str(&text[copied..]);
Cow::Owned(out)
}
fn split_roles(text: &str) -> Vec<(Role, String)> {
let mut found = Vec::new();
for sentence in text.split(['.', '!', '?', ';', '\n']) {
let lower = sentence.to_lowercase();
let terms: Vec<_> = words(&lower).collect();
let mut starts = vec![0];
for (i, pair) in terms.windows(2).enumerate() {
if matches!(pair[0], "and" | "then" | "also" | "but" | "separately")
&& operator(pair[1]).is_some()
{
starts.push(i + 1);
}
}
starts.push(terms.len());
for range in starts.windows(2) {
let part = &terms[range[0]..range[1]];
let role = clause_role(part).or_else(|| {
if starts.len() == 2 {
let tail = lower.rsplit_once(',')?.1;
clause_role(&words(tail).collect::<Vec<_>>())
} else {
None
}
});
if let Some(role) = role {
found.push((role, part.join(" ")));
}
}
}
found
}
pub(crate) struct TaskRoles(Vec<(Role, std::collections::HashSet<String>)>);
impl TaskRoles {
pub(crate) fn parse(text: &str) -> Self {
if !words(text).any(|w| {
let folded;
let term = if w.bytes().any(|b| b.is_ascii_uppercase()) {
folded = w.to_ascii_lowercase();
&folded
} else {
w
};
operator(term).is_some_and(Role::acts_on_words_or_quantity)
|| matches!(
term,
"how"
| "meaning"
| "mean"
| "difference"
| "definition"
| "wording"
| "phrasing"
| "phrase"
| "sentence"
| "spot"
| "sound"
| "read"
| "typo"
| "soften"
)
|| syntax_word(term)
}) {
return Self(Vec::new());
}
let parts = split_roles(text);
if !parts
.iter()
.any(|(role, _)| role.acts_on_words_or_quantity())
{
return Self(Vec::new());
}
Self(
parts
.into_iter()
.map(|(r, s)| (r, super::anchors(&s)))
.collect(),
)
}
pub(crate) fn allows(&self, cue: &str, method: &str, tags: &str) -> bool {
if self.0.is_empty() {
return true;
}
let mut method_roles = split_roles(cue);
method_roles.extend(split_roles(method));
let cue_words = super::anchors(&format!("{} {} {}", cue, method, tags));
for (role, args) in &self.0 {
let agreement = method_roles.iter().any(|(r, _)| {
r == role
|| matches!(
(r, role),
(Role::Transform, Role::Language) | (Role::Language, Role::Transform)
)
});
if agreement && args.intersection(&cue_words).take(2).count() >= 2 {
return true;
}
if !role.acts_on_words_or_quantity()
&& method_roles.is_empty()
&& args.intersection(&cue_words).take(2).count() >= 2
{
return true;
}
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quoted_data_and_commands_take_different_roles() {
assert!(
!action_text("Please translate ‘deliver the annual report’ into Spanish.")
.contains("annual report")
);
assert!(!action_text("Count the words in \"send the invoices\".").contains("invoices"));
assert!(action_text("Debug the message \"missing route file\".").contains("route file"));
assert!(
action_text("Proofread 'this message'. Then diagnose 'expired lease'.")
.contains("expired lease")
);
assert!(action_text("Translate 'unfinished phrase").contains("unfinished phrase"));
assert!(!action_text("Does ‘install the generator’ sound abrupt?").contains("generator"));
assert!(!action_text("In `clean the kettle`, what noun is the object?").contains("kettle"));
assert!(
action_text("Does 'service unavailable' indicate a broken endpoint?")
.contains("service unavailable")
);
assert!(action_text("Does `route lookup` read from the cache?").contains("route lookup"));
assert!(action_text("Count records matching 'connection refused'.")
.contains("connection refused"));
assert!(
action_text("What does 'connection refused' mean when starting the service?")
.contains("connection refused")
);
assert!(!action_text("Translate 'blue' and 'yellow'.").contains("yellow"));
}
#[test]
fn quoted_subject_and_separate_search_can_need_different_methods() {
let q = action_text(
"Translate ‘solar power’. Then search all archived logs for the solar power.",
);
assert!(q.contains("search all archived logs for the solar power"));
let roles = TaskRoles::parse(&q);
assert!(roles.allows(
"Search archived logs for solar power",
"Find its original source",
""
));
assert!(!roles.allows("Create a solar power supply", "Install the equipment", ""));
let q = action_text("Count the words and letters in ‘check cooling pressure’.");
assert!(!q.contains("cooling pressure"));
assert!(TaskRoles::parse(&q).allows(
"Count words and letters",
"Count alphabetic characters separately",
""
));
assert!(!TaskRoles::parse(&q).allows("Check cooling pressure", "Read the gauge", ""));
}
#[test]
fn apostrophes_and_escapes_do_not_split_balanced_spans() {
let s = r#"Don't strip \"unquoted\" or 'this isn't a command', “nor this” and ‘unfinished"#;
assert_eq!(
quoted_spans(s)
.into_iter()
.map(|r| &s[r])
.collect::<Vec<_>>(),
["'this isn't a command'", "“nor this”"]
);
}
}