@robhowley/pi-structured-return 1.10.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +37 -83
- package/extensions/structured-return/config/registry.ts +4 -36
- package/extensions/structured-return/index.ts +105 -90
- package/extensions/structured-return/native.ts +223 -0
- package/extensions/structured-return/parsers/ava-text.ts +2 -168
- package/extensions/structured-return/parsers/bandit-json.ts +2 -79
- package/extensions/structured-return/parsers/black-text.ts +2 -73
- package/extensions/structured-return/parsers/cargo-build.ts +2 -78
- package/extensions/structured-return/parsers/cargo-test.ts +2 -135
- package/extensions/structured-return/parsers/checkstyle-xml.ts +2 -182
- package/extensions/structured-return/parsers/clang-text.ts +2 -60
- package/extensions/structured-return/parsers/dbt-json.ts +2 -135
- package/extensions/structured-return/parsers/dotnet-build-text.ts +2 -49
- package/extensions/structured-return/parsers/eslint-json.ts +2 -38
- package/extensions/structured-return/parsers/go-test-json.ts +2 -138
- package/extensions/structured-return/parsers/hadolint-json.ts +2 -60
- package/extensions/structured-return/parsers/htmlhint-json.ts +2 -73
- package/extensions/structured-return/parsers/isort-text.ts +2 -63
- package/extensions/structured-return/parsers/javac-text.ts +2 -82
- package/extensions/structured-return/parsers/jsonlint-text.ts +2 -65
- package/extensions/structured-return/parsers/junit-xml.ts +2 -325
- package/extensions/structured-return/parsers/markdownlint-json.ts +2 -74
- package/extensions/structured-return/parsers/minitest-text.ts +2 -107
- package/extensions/structured-return/parsers/mocha-json.ts +2 -83
- package/extensions/structured-return/parsers/mypy-json.ts +2 -79
- package/extensions/structured-return/parsers/node-test-text.ts +2 -92
- package/extensions/structured-return/parsers/npm-audit-json.ts +2 -90
- package/extensions/structured-return/parsers/prettier-text.ts +2 -66
- package/extensions/structured-return/parsers/pylint-json.ts +2 -63
- package/extensions/structured-return/parsers/pyright-json.ts +2 -82
- package/extensions/structured-return/parsers/rspec-json.ts +2 -75
- package/extensions/structured-return/parsers/rubocop-json.ts +2 -75
- package/extensions/structured-return/parsers/ruff-json.ts +2 -36
- package/extensions/structured-return/parsers/shellcheck-json.ts +2 -60
- package/extensions/structured-return/parsers/stylelint-json.ts +2 -75
- package/extensions/structured-return/parsers/swiftc-text.ts +2 -52
- package/extensions/structured-return/parsers/tail-fallback.ts +2 -19
- package/extensions/structured-return/parsers/tidy-text.ts +2 -66
- package/extensions/structured-return/parsers/tsc-text.ts +2 -46
- package/extensions/structured-return/parsers/unittest-text.ts +2 -125
- package/extensions/structured-return/parsers/utils.ts +28 -0
- package/extensions/structured-return/parsers/vale-json.ts +2 -79
- package/extensions/structured-return/parsers/vitest-json.ts +2 -59
- package/extensions/structured-return/storage/log-store.ts +0 -15
- package/extensions/structured-return/types.ts +1 -14
- package/native/Cargo.lock +193 -0
- package/native/Cargo.toml +21 -0
- package/native/THIRD-PARTY-LICENSES.txt +3660 -0
- package/native/bin/darwin-arm64/build.json +7 -0
- package/native/bin/darwin-arm64/structured-return-native +0 -0
- package/native/bin/darwin-x64/build.json +7 -0
- package/native/bin/darwin-x64/structured-return-native +0 -0
- package/native/bin/linux-arm64-musl/build.json +7 -0
- package/native/bin/linux-arm64-musl/structured-return-native +0 -0
- package/native/bin/linux-x64-musl/build.json +7 -0
- package/native/bin/linux-x64-musl/structured-return-native +0 -0
- package/native/src/common.rs +118 -0
- package/native/src/main.rs +55 -0
- package/native/src/parsers/ava_text.rs +125 -0
- package/native/src/parsers/bandit_json.rs +120 -0
- package/native/src/parsers/black_text.rs +45 -0
- package/native/src/parsers/cargo_build.rs +96 -0
- package/native/src/parsers/cargo_test.rs +140 -0
- package/native/src/parsers/checkstyle_xml.rs +137 -0
- package/native/src/parsers/clang_text.rs +39 -0
- package/native/src/parsers/compiler_helpers.rs +74 -0
- package/native/src/parsers/dbt_json.rs +243 -0
- package/native/src/parsers/dotnet_build_text.rs +50 -0
- package/native/src/parsers/eslint_json.rs +58 -0
- package/native/src/parsers/go_test_json.rs +346 -0
- package/native/src/parsers/hadolint_json.rs +37 -0
- package/native/src/parsers/htmlhint_json.rs +71 -0
- package/native/src/parsers/isort_text.rs +22 -0
- package/native/src/parsers/javac_text.rs +49 -0
- package/native/src/parsers/json_support.rs +287 -0
- package/native/src/parsers/jsonlint_text.rs +50 -0
- package/native/src/parsers/junit_xml.rs +430 -0
- package/native/src/parsers/markdownlint_json.rs +68 -0
- package/native/src/parsers/minitest_text.rs +91 -0
- package/native/src/parsers/mocha_json.rs +75 -0
- package/native/src/parsers/mod.rs +119 -0
- package/native/src/parsers/mypy_json.rs +93 -0
- package/native/src/parsers/node_test_text.rs +106 -0
- package/native/src/parsers/npm_audit_json.rs +119 -0
- package/native/src/parsers/prettier_text.rs +34 -0
- package/native/src/parsers/pylint_json.rs +44 -0
- package/native/src/parsers/pyright_json.rs +88 -0
- package/native/src/parsers/rspec_json.rs +84 -0
- package/native/src/parsers/rubocop_json.rs +46 -0
- package/native/src/parsers/ruff_json.rs +30 -0
- package/native/src/parsers/shellcheck_json.rs +40 -0
- package/native/src/parsers/stylelint_json.rs +46 -0
- package/native/src/parsers/swiftc_text.rs +38 -0
- package/native/src/parsers/tail_fallback.rs +51 -0
- package/native/src/parsers/test_helpers.rs +172 -0
- package/native/src/parsers/tidy_text.rs +77 -0
- package/native/src/parsers/tsc_text.rs +28 -0
- package/native/src/parsers/unittest_text.rs +125 -0
- package/native/src/parsers/vale_json.rs +66 -0
- package/native/src/parsers/vitest_json.rs +71 -0
- package/native/src/parsers/xml_support.rs +241 -0
- package/native/src/runner.rs +252 -0
- package/package.json +21 -7
- package/scripts/build-native.mjs +73 -0
- package/scripts/native-artifacts.mjs +69 -0
- package/skills/structured-return/SKILL.md +103 -249
- package/extensions/structured-return/config/project-config.ts +0 -10
- package/extensions/structured-return/examples/.pi/machine-readable.json +0 -18
- package/extensions/structured-return/examples/.pi/parsers/foo-cli.ts +0 -25
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
use super::json_support::{
|
|
2
|
+
copy_field, entries, js_string, parse_error, relative_input, required_array, required_string,
|
|
3
|
+
};
|
|
4
|
+
use crate::common::{read_file, result, trim, Context};
|
|
5
|
+
use serde_json::{json, Map, Value};
|
|
6
|
+
use std::collections::HashMap;
|
|
7
|
+
|
|
8
|
+
pub fn parse(ctx: &Context) -> Result<Value, String> {
|
|
9
|
+
let source = read_file(&ctx.stdout_path)?;
|
|
10
|
+
if trim(&source).is_empty() {
|
|
11
|
+
return Ok(result("vale", "pass", "no prose issues", Vec::new(), ctx));
|
|
12
|
+
}
|
|
13
|
+
let report: Value = match super::json_support::parse_json(trim(&source)) {
|
|
14
|
+
Ok(v) => v,
|
|
15
|
+
Err(_) => return Ok(parse_error("vale", ctx)),
|
|
16
|
+
};
|
|
17
|
+
let mut failures = Vec::new();
|
|
18
|
+
let mut severities: HashMap<String, usize> = HashMap::new();
|
|
19
|
+
for (file_name, alerts) in entries(&report)? {
|
|
20
|
+
let file = relative_input(&ctx.cwd, &file_name);
|
|
21
|
+
for alert in required_array(Some(alerts), "alerts")? {
|
|
22
|
+
let severity = required_string(alert.get("Severity"), "Severity")?.to_lowercase();
|
|
23
|
+
*severities.entry(severity).or_default() += 1;
|
|
24
|
+
let mut out = Map::new();
|
|
25
|
+
out.insert(
|
|
26
|
+
"id".into(),
|
|
27
|
+
json!(format!(
|
|
28
|
+
"{}:{}:{}",
|
|
29
|
+
file,
|
|
30
|
+
js_string(alert.get("Line")),
|
|
31
|
+
js_string(alert.get("Check"))
|
|
32
|
+
)),
|
|
33
|
+
);
|
|
34
|
+
out.insert("file".into(), json!(file));
|
|
35
|
+
copy_field(&mut out, "line", alert.get("Line"));
|
|
36
|
+
copy_field(&mut out, "message", alert.get("Message"));
|
|
37
|
+
copy_field(&mut out, "rule", alert.get("Check"));
|
|
38
|
+
failures.push(Value::Object(out));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
let parts: Vec<_> = ["error", "warning", "suggestion"]
|
|
42
|
+
.iter()
|
|
43
|
+
.filter_map(|s| {
|
|
44
|
+
severities
|
|
45
|
+
.get(*s)
|
|
46
|
+
.filter(|n| **n > 0)
|
|
47
|
+
.map(|n| format!("{n} {s}{}", if *n == 1 { "" } else { "s" }))
|
|
48
|
+
})
|
|
49
|
+
.collect();
|
|
50
|
+
let summary = if failures.is_empty() {
|
|
51
|
+
"no prose issues".into()
|
|
52
|
+
} else {
|
|
53
|
+
parts.join(", ")
|
|
54
|
+
};
|
|
55
|
+
Ok(result(
|
|
56
|
+
"vale",
|
|
57
|
+
if severities.get("error").is_some_and(|n| *n > 0) {
|
|
58
|
+
"fail"
|
|
59
|
+
} else {
|
|
60
|
+
"pass"
|
|
61
|
+
},
|
|
62
|
+
summary,
|
|
63
|
+
failures,
|
|
64
|
+
ctx,
|
|
65
|
+
))
|
|
66
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
use super::json_support::{
|
|
2
|
+
copy_field, js_string, no_output, number, read_json, relative_input, required_array,
|
|
3
|
+
required_string,
|
|
4
|
+
};
|
|
5
|
+
use crate::common::{result, truthy, Context};
|
|
6
|
+
use serde_json::{json, Map, Value};
|
|
7
|
+
|
|
8
|
+
pub fn parse(ctx: &Context) -> Result<Value, String> {
|
|
9
|
+
let report = read_json(&ctx.stdout_path, Value::Null)?;
|
|
10
|
+
if !truthy(&report) {
|
|
11
|
+
return Ok(no_output("vitest", ctx));
|
|
12
|
+
}
|
|
13
|
+
let mut failures = Vec::new();
|
|
14
|
+
let mut suite_failures = 0;
|
|
15
|
+
for suite in required_array(report.get("testResults"), "testResults")? {
|
|
16
|
+
let before = failures.len();
|
|
17
|
+
for test in required_array(suite.get("assertionResults"), "assertionResults")? {
|
|
18
|
+
if test.get("status").and_then(Value::as_str) != Some("failed") {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
let messages = required_array(test.get("failureMessages"), "failureMessages")?;
|
|
22
|
+
let message = match messages.first().filter(|v| !v.is_null()) {
|
|
23
|
+
Some(v) => required_string(Some(v), "failure message")?
|
|
24
|
+
.split('\n')
|
|
25
|
+
.next()
|
|
26
|
+
.unwrap_or(""),
|
|
27
|
+
None => "test failed",
|
|
28
|
+
};
|
|
29
|
+
let file = relative_input(&ctx.cwd, required_string(suite.get("name"), "suite name")?);
|
|
30
|
+
let mut out = Map::new();
|
|
31
|
+
copy_field(&mut out, "id", test.get("fullName"));
|
|
32
|
+
out.insert("file".into(), json!(file));
|
|
33
|
+
out.insert("message".into(), json!(message));
|
|
34
|
+
failures.push(Value::Object(out));
|
|
35
|
+
}
|
|
36
|
+
// A load/setup failure has no failed assertion to carry its message.
|
|
37
|
+
if suite.get("status").and_then(Value::as_str) == Some("failed") && failures.len() == before
|
|
38
|
+
{
|
|
39
|
+
suite_failures += 1;
|
|
40
|
+
let file = relative_input(&ctx.cwd, required_string(suite.get("name"), "suite name")?);
|
|
41
|
+
let message = suite
|
|
42
|
+
.get("message")
|
|
43
|
+
.and_then(Value::as_str)
|
|
44
|
+
.filter(|message| !message.trim().is_empty())
|
|
45
|
+
.unwrap_or("suite failed to load");
|
|
46
|
+
failures.push(json!({"id":format!("suite::{file}"),"file":file,"message":message}));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
let failed = report.get("numFailedTests");
|
|
50
|
+
let passed = js_string(report.get("numPassedTests"));
|
|
51
|
+
let is_failure = number(failed) > 0.0 || suite_failures > 0;
|
|
52
|
+
let mut parts = Vec::new();
|
|
53
|
+
if number(failed) > 0.0 {
|
|
54
|
+
parts.push(format!("{} failed", js_string(failed)));
|
|
55
|
+
}
|
|
56
|
+
if suite_failures > 0 {
|
|
57
|
+
parts.push(format!(
|
|
58
|
+
"{suite_failures} suite{} failed",
|
|
59
|
+
if suite_failures == 1 { "" } else { "s" }
|
|
60
|
+
));
|
|
61
|
+
}
|
|
62
|
+
parts.push(format!("{passed} passed"));
|
|
63
|
+
let summary = parts.join(", ");
|
|
64
|
+
Ok(result(
|
|
65
|
+
"vitest",
|
|
66
|
+
if is_failure { "fail" } else { "pass" },
|
|
67
|
+
summary,
|
|
68
|
+
failures,
|
|
69
|
+
ctx,
|
|
70
|
+
))
|
|
71
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
use quick_xml::escape::resolve_xml_entity;
|
|
2
|
+
use quick_xml::{
|
|
3
|
+
events::{BytesStart, Event},
|
|
4
|
+
Reader,
|
|
5
|
+
};
|
|
6
|
+
use regex::Regex;
|
|
7
|
+
use std::{collections::BTreeMap, sync::LazyLock};
|
|
8
|
+
|
|
9
|
+
// Match literal general entities, skipping comments and quoted DTD text so
|
|
10
|
+
// declarations inside either cannot become entities. SYSTEM/PUBLIC and
|
|
11
|
+
// parameter entities are never loaded or substituted.
|
|
12
|
+
static DTD_TOKENS: LazyLock<Regex> = LazyLock::new(|| {
|
|
13
|
+
Regex::new(
|
|
14
|
+
r#"(?s)<!--.*?-->|<!ENTITY\s+([^\s%<>"']+)\s+(?:"([^"]*)"|'([^']*)')\s*>|"[^"]*"|'[^']*'"#,
|
|
15
|
+
)
|
|
16
|
+
.unwrap()
|
|
17
|
+
});
|
|
18
|
+
const MAX_ENTITY_COUNT: usize = 100;
|
|
19
|
+
const MAX_ENTITY_SIZE: usize = 10_000;
|
|
20
|
+
const MAX_ENTITY_EXPANSION: usize = 16 * 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
fn internal_entities(doctype: &str) -> Result<BTreeMap<String, String>, String> {
|
|
23
|
+
let mut entities = BTreeMap::new();
|
|
24
|
+
let mut count = 0;
|
|
25
|
+
for token in DTD_TOKENS.captures_iter(doctype) {
|
|
26
|
+
let Some(name) = token.get(1) else { continue };
|
|
27
|
+
let value = token.get(2).or_else(|| token.get(3)).unwrap().as_str();
|
|
28
|
+
// Match the previous parser's literal-only support. No recursive or
|
|
29
|
+
// parameter entity expansion, including exponential entity chains.
|
|
30
|
+
if value.contains('&') {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
count += 1;
|
|
34
|
+
if count > MAX_ENTITY_COUNT || value.len() > MAX_ENTITY_SIZE {
|
|
35
|
+
return Err("XML internal entity declaration limit exceeded".into());
|
|
36
|
+
}
|
|
37
|
+
entities
|
|
38
|
+
.entry(name.as_str().to_owned())
|
|
39
|
+
.or_insert_with(|| value.to_owned());
|
|
40
|
+
}
|
|
41
|
+
Ok(entities)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
fn resolve_entity<'a>(
|
|
45
|
+
name: &str,
|
|
46
|
+
entities: &'a BTreeMap<String, String>,
|
|
47
|
+
remaining: &mut usize,
|
|
48
|
+
) -> Option<&'a str> {
|
|
49
|
+
if let Some(value) = resolve_xml_entity(name) {
|
|
50
|
+
return Some(value);
|
|
51
|
+
}
|
|
52
|
+
let value = entities.get(name)?;
|
|
53
|
+
*remaining = remaining.checked_sub(value.len())?;
|
|
54
|
+
Some(value)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
#[derive(Debug, Default)]
|
|
58
|
+
pub struct CaseCounts {
|
|
59
|
+
pub tests: usize,
|
|
60
|
+
pub failures: usize,
|
|
61
|
+
pub errors: usize,
|
|
62
|
+
pub skipped: usize,
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
#[derive(Debug, Default)]
|
|
66
|
+
pub struct Node {
|
|
67
|
+
pub name: String,
|
|
68
|
+
pub attrs: BTreeMap<String, String>,
|
|
69
|
+
pub text: String,
|
|
70
|
+
pub children: Vec<Node>,
|
|
71
|
+
pub direct_cases: CaseCounts,
|
|
72
|
+
}
|
|
73
|
+
fn append_node(parent: &mut Node, node: Node) {
|
|
74
|
+
if node.name == "testcase" {
|
|
75
|
+
parent.direct_cases.tests += 1;
|
|
76
|
+
if node.child("failure").is_some() {
|
|
77
|
+
parent.direct_cases.failures += 1;
|
|
78
|
+
} else if node.child("error").is_some() {
|
|
79
|
+
parent.direct_cases.errors += 1;
|
|
80
|
+
} else {
|
|
81
|
+
if node.child("skipped").is_some() {
|
|
82
|
+
parent.direct_cases.skipped += 1;
|
|
83
|
+
}
|
|
84
|
+
// Count successful cases without retaining their attributes/tree.
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
parent.children.push(node);
|
|
89
|
+
}
|
|
90
|
+
impl Node {
|
|
91
|
+
pub fn attr(&self, name: &str) -> Option<&str> {
|
|
92
|
+
self.attrs.get(name).map(String::as_str)
|
|
93
|
+
}
|
|
94
|
+
pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Node> {
|
|
95
|
+
self.children.iter().filter(move |n| n.name == name)
|
|
96
|
+
}
|
|
97
|
+
pub fn child(&self, name: &str) -> Option<&Node> {
|
|
98
|
+
self.children.iter().find(|n| n.name == name)
|
|
99
|
+
}
|
|
100
|
+
pub fn body(&self) -> &str {
|
|
101
|
+
self.text.trim()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
fn start(
|
|
105
|
+
reader: &Reader<&[u8]>,
|
|
106
|
+
event: &BytesStart<'_>,
|
|
107
|
+
entities: &BTreeMap<String, String>,
|
|
108
|
+
remaining: &mut usize,
|
|
109
|
+
) -> Result<Node, String> {
|
|
110
|
+
let mut node = Node {
|
|
111
|
+
name: String::from_utf8_lossy(event.name().as_ref()).into_owned(),
|
|
112
|
+
..Node::default()
|
|
113
|
+
};
|
|
114
|
+
for attr in event.attributes().with_checks(false) {
|
|
115
|
+
let attr = attr.map_err(|e| e.to_string())?;
|
|
116
|
+
let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
|
|
117
|
+
let value = attr
|
|
118
|
+
.decode_and_unescape_value_with(reader.decoder(), |name| {
|
|
119
|
+
resolve_entity(name, entities, remaining)
|
|
120
|
+
})
|
|
121
|
+
.map_err(|e| e.to_string())?;
|
|
122
|
+
node.attrs.insert(key, value.trim().to_owned());
|
|
123
|
+
}
|
|
124
|
+
Ok(node)
|
|
125
|
+
}
|
|
126
|
+
/// Retain structured XML nodes; unlike the legacy JSON-like tree, passing test
|
|
127
|
+
/// cases are discarded as soon as their closing tag is seen.
|
|
128
|
+
pub fn parse_xml(source: &str) -> Result<Node, String> {
|
|
129
|
+
let mut reader = Reader::from_str(source);
|
|
130
|
+
let mut stack = vec![Node::default()];
|
|
131
|
+
let mut entities = BTreeMap::new();
|
|
132
|
+
let mut remaining = MAX_ENTITY_EXPANSION;
|
|
133
|
+
loop {
|
|
134
|
+
match reader.read_event() {
|
|
135
|
+
Ok(Event::DocType(e)) => {
|
|
136
|
+
let doctype = std::str::from_utf8(e.as_ref()).map_err(|e| e.to_string())?;
|
|
137
|
+
entities = internal_entities(doctype)?;
|
|
138
|
+
}
|
|
139
|
+
Ok(Event::Start(e)) => stack.push(start(&reader, &e, &entities, &mut remaining)?),
|
|
140
|
+
Ok(Event::Empty(e)) => {
|
|
141
|
+
let node = start(&reader, &e, &entities, &mut remaining)?;
|
|
142
|
+
append_node(stack.last_mut().unwrap(), node);
|
|
143
|
+
}
|
|
144
|
+
Ok(Event::Text(e)) => stack.last_mut().unwrap().text.push_str(
|
|
145
|
+
&e.unescape_with(|name| resolve_entity(name, &entities, &mut remaining))
|
|
146
|
+
.map_err(|e| e.to_string())?,
|
|
147
|
+
),
|
|
148
|
+
Ok(Event::CData(e)) => stack
|
|
149
|
+
.last_mut()
|
|
150
|
+
.unwrap()
|
|
151
|
+
.text
|
|
152
|
+
.push_str(&e.decode().map_err(|e| e.to_string())?),
|
|
153
|
+
Ok(Event::End(_)) => {
|
|
154
|
+
if stack.len() > 1 {
|
|
155
|
+
let node = stack.pop().unwrap();
|
|
156
|
+
append_node(stack.last_mut().unwrap(), node);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
Ok(Event::Eof) => break,
|
|
160
|
+
Ok(_) => {}
|
|
161
|
+
Err(e) => return Err(e.to_string()),
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if stack.len() != 1 {
|
|
165
|
+
return Err("XML ended before all elements were closed".into());
|
|
166
|
+
}
|
|
167
|
+
Ok(stack.pop().unwrap())
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
#[cfg(test)]
|
|
171
|
+
mod tests {
|
|
172
|
+
use super::*;
|
|
173
|
+
|
|
174
|
+
#[test]
|
|
175
|
+
fn rejects_unclosed_and_mismatched_elements() {
|
|
176
|
+
for xml in [
|
|
177
|
+
"<root><child>",
|
|
178
|
+
"<root><child/>",
|
|
179
|
+
"<root><child></root></child>",
|
|
180
|
+
"<root></other>",
|
|
181
|
+
"</root>",
|
|
182
|
+
] {
|
|
183
|
+
assert!(parse_xml(xml).is_err(), "{xml}");
|
|
184
|
+
}
|
|
185
|
+
assert!(parse_xml("<root><child/></root>").is_ok());
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
#[test]
|
|
189
|
+
fn entities_are_literal_and_do_not_apply_in_cdata() {
|
|
190
|
+
let doc = parse_xml(
|
|
191
|
+
r#"<!DOCTYPE root [
|
|
192
|
+
<!-- <!ENTITY fake "not a declaration"> -->
|
|
193
|
+
<!ENTITY local "hello">
|
|
194
|
+
]><root attr="&local; & A">&local;<![CDATA[&local;]]></root>"#,
|
|
195
|
+
)
|
|
196
|
+
.unwrap();
|
|
197
|
+
let root = doc.child("root").unwrap();
|
|
198
|
+
assert_eq!(root.attr("attr"), Some("hello & A"));
|
|
199
|
+
assert_eq!(root.text, "hello&local;");
|
|
200
|
+
assert!(parse_xml(
|
|
201
|
+
r#"<!DOCTYPE root [<!-- <!ENTITY fake "hidden"> -->]><root>&fake;</root>"#
|
|
202
|
+
)
|
|
203
|
+
.is_err());
|
|
204
|
+
assert!(
|
|
205
|
+
parse_xml(r#"<!DOCTYPE root [<!ENTITY local '&local;'>]><root>&local;</root>"#)
|
|
206
|
+
.is_err()
|
|
207
|
+
);
|
|
208
|
+
assert!(parse_xml(
|
|
209
|
+
r#"<!DOCTYPE root [<!ENTITY a 'hello'><!ENTITY b '&a;&a;'>]><root>&b;</root>"#
|
|
210
|
+
)
|
|
211
|
+
.is_err());
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
#[test]
|
|
215
|
+
fn entity_declarations_and_expansion_are_bounded() {
|
|
216
|
+
let value = "x".repeat(MAX_ENTITY_SIZE);
|
|
217
|
+
assert!(internal_entities(&format!("root [<!ENTITY local '{value}'>]")).is_ok());
|
|
218
|
+
assert!(internal_entities(&format!("root [<!ENTITY local '{value}x'>]")).is_err());
|
|
219
|
+
let declarations: String = (0..MAX_ENTITY_COUNT)
|
|
220
|
+
.map(|i| format!("<!ENTITY e{i} 'x'>"))
|
|
221
|
+
.collect();
|
|
222
|
+
assert!(internal_entities(&format!("root [{declarations}]")).is_ok());
|
|
223
|
+
assert!(internal_entities(&format!("root [{declarations}<!ENTITY extra 'x'>]")).is_err());
|
|
224
|
+
let references = "&local;".repeat(MAX_ENTITY_EXPANSION / MAX_ENTITY_SIZE + 1);
|
|
225
|
+
let xml = format!("<!DOCTYPE root [<!ENTITY local '{value}'>]><root>{references}</root>");
|
|
226
|
+
assert!(parse_xml(&xml).is_err());
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
#[test]
|
|
230
|
+
fn never_resolves_external_or_parameter_entities() {
|
|
231
|
+
for declaration in [
|
|
232
|
+
r#"<!ENTITY ext SYSTEM "file:///etc/passwd">"#,
|
|
233
|
+
r#"<!ENTITY ext SYSTEM "http://127.0.0.1:1/secret">"#,
|
|
234
|
+
r#"<!ENTITY ext PUBLIC "public-id" "file:///etc/passwd">"#,
|
|
235
|
+
r#"<!ENTITY % ext "secret">"#,
|
|
236
|
+
] {
|
|
237
|
+
let xml = format!("<!DOCTYPE root [{declaration}]><root>&ext;</root>");
|
|
238
|
+
assert!(parse_xml(&xml).is_err(), "{declaration}");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
//! Run one shell command with bounded buffers and durable stdout/stderr artifacts.
|
|
2
|
+
use serde::Deserialize;
|
|
3
|
+
use serde_json::{json, Value};
|
|
4
|
+
use std::{
|
|
5
|
+
fs::{self, File, OpenOptions},
|
|
6
|
+
io::{self, BufRead, Write},
|
|
7
|
+
path::Path,
|
|
8
|
+
process::{Child, Command, Stdio},
|
|
9
|
+
sync::{
|
|
10
|
+
atomic::{AtomicBool, Ordering},
|
|
11
|
+
Arc,
|
|
12
|
+
},
|
|
13
|
+
thread,
|
|
14
|
+
time::{Duration, Instant},
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
#[derive(Deserialize)]
|
|
18
|
+
#[serde(rename_all = "camelCase")]
|
|
19
|
+
pub struct RunRequest {
|
|
20
|
+
pub command: String,
|
|
21
|
+
pub cwd: String,
|
|
22
|
+
pub run_dir: String,
|
|
23
|
+
pub run_id: String,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
fn create(path: &Path) -> Result<File, String> {
|
|
27
|
+
OpenOptions::new()
|
|
28
|
+
.write(true)
|
|
29
|
+
.create_new(true)
|
|
30
|
+
.open(path)
|
|
31
|
+
.map_err(|e| format!("{}: {e}", path.display()))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
#[cfg(unix)]
|
|
35
|
+
fn terminate_group(pid: u32, force: bool) {
|
|
36
|
+
// The child is the leader of its own process group. Its descendants inherit it.
|
|
37
|
+
unsafe {
|
|
38
|
+
libc::kill(
|
|
39
|
+
-(pid as i32),
|
|
40
|
+
if force { libc::SIGKILL } else { libc::SIGTERM },
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
struct ChildGuard {
|
|
46
|
+
child: Child,
|
|
47
|
+
armed: bool,
|
|
48
|
+
}
|
|
49
|
+
impl Drop for ChildGuard {
|
|
50
|
+
fn drop(&mut self) {
|
|
51
|
+
if self.armed {
|
|
52
|
+
terminate_group(self.child.id(), true);
|
|
53
|
+
let _ = self.child.wait();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
#[cfg(windows)]
|
|
58
|
+
fn terminate_group(pid: u32, force: bool) {
|
|
59
|
+
let mut taskkill = Command::new("taskkill");
|
|
60
|
+
taskkill.args(["/PID", &pid.to_string(), "/T"]);
|
|
61
|
+
if force {
|
|
62
|
+
taskkill.arg("/F");
|
|
63
|
+
}
|
|
64
|
+
let _ = taskkill
|
|
65
|
+
.stdout(Stdio::null())
|
|
66
|
+
.stderr(Stdio::null())
|
|
67
|
+
.status();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pub fn run(request: RunRequest) -> Result<Value, String> {
|
|
71
|
+
let result = run_command(&request);
|
|
72
|
+
result.map_err(|mut error| {
|
|
73
|
+
// Setup or capture may fail after creating some artifacts. Keep recovery paths.
|
|
74
|
+
for stream in ["stdout", "stderr", "combined"] {
|
|
75
|
+
let path = Path::new(&request.run_dir).join(format!("{}.{stream}.log", request.run_id));
|
|
76
|
+
if path.is_file() {
|
|
77
|
+
error.push_str(&format!(
|
|
78
|
+
"\n{stream} log (may be incomplete): {}",
|
|
79
|
+
path.display()
|
|
80
|
+
));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
error
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
fn run_command(request: &RunRequest) -> Result<Value, String> {
|
|
88
|
+
if request.run_id.is_empty()
|
|
89
|
+
|| !request
|
|
90
|
+
.run_id
|
|
91
|
+
.chars()
|
|
92
|
+
.all(|c| c.is_ascii_alphanumeric() || c == '-')
|
|
93
|
+
{
|
|
94
|
+
return Err("runId must contain only ASCII letters, digits and hyphens".into());
|
|
95
|
+
}
|
|
96
|
+
fs::create_dir_all(&request.run_dir).map_err(|e| e.to_string())?;
|
|
97
|
+
let dir = Path::new(&request.run_dir);
|
|
98
|
+
let stdout_path = dir.join(format!("{}.stdout.log", request.run_id));
|
|
99
|
+
let stderr_path = dir.join(format!("{}.stderr.log", request.run_id));
|
|
100
|
+
let log_path = dir.join(format!("{}.combined.log", request.run_id));
|
|
101
|
+
let mut stdout_file = create(&stdout_path)?;
|
|
102
|
+
let mut stderr_file = create(&stderr_path)?;
|
|
103
|
+
let mut combined = create(&log_path)?;
|
|
104
|
+
#[cfg(unix)]
|
|
105
|
+
let mut command = {
|
|
106
|
+
let mut c = Command::new("/bin/sh");
|
|
107
|
+
// EOF on this private gate prevents command side effects if the helper dies
|
|
108
|
+
// before the parent can receive the command's process-group ID.
|
|
109
|
+
c.args([
|
|
110
|
+
"-c",
|
|
111
|
+
"read -r _sr_start && exec /bin/sh -c \"$1\" </dev/null",
|
|
112
|
+
"structured-return",
|
|
113
|
+
&request.command,
|
|
114
|
+
]);
|
|
115
|
+
c
|
|
116
|
+
};
|
|
117
|
+
#[cfg(windows)]
|
|
118
|
+
let mut command = {
|
|
119
|
+
let mut c = Command::new(std::env::var_os("COMSPEC").unwrap_or_else(|| "cmd.exe".into()));
|
|
120
|
+
c.args(["/d", "/s", "/c", &request.command]);
|
|
121
|
+
c
|
|
122
|
+
};
|
|
123
|
+
#[cfg(unix)]
|
|
124
|
+
{
|
|
125
|
+
use std::os::unix::process::CommandExt;
|
|
126
|
+
command.process_group(0);
|
|
127
|
+
}
|
|
128
|
+
let child = command
|
|
129
|
+
.current_dir(&request.cwd)
|
|
130
|
+
.stdin(if cfg!(unix) {
|
|
131
|
+
Stdio::piped()
|
|
132
|
+
} else {
|
|
133
|
+
Stdio::null()
|
|
134
|
+
})
|
|
135
|
+
.stdout(Stdio::piped())
|
|
136
|
+
.stderr(Stdio::piped())
|
|
137
|
+
.spawn()
|
|
138
|
+
.map_err(|e| e.to_string())?;
|
|
139
|
+
let mut guard = ChildGuard { child, armed: true };
|
|
140
|
+
let pid = guard.child.id();
|
|
141
|
+
{
|
|
142
|
+
let mut output = io::stdout().lock();
|
|
143
|
+
writeln!(
|
|
144
|
+
output,
|
|
145
|
+
"{}",
|
|
146
|
+
crate::message(json!({"event":"started", "pid":pid}))
|
|
147
|
+
)
|
|
148
|
+
.map_err(|e| e.to_string())?;
|
|
149
|
+
output.flush().map_err(|e| e.to_string())?;
|
|
150
|
+
}
|
|
151
|
+
#[cfg(unix)]
|
|
152
|
+
guard
|
|
153
|
+
.child
|
|
154
|
+
.stdin
|
|
155
|
+
.take()
|
|
156
|
+
.ok_or("launch gate unavailable")?
|
|
157
|
+
.write_all(b"\n")
|
|
158
|
+
.map_err(|e| e.to_string())?;
|
|
159
|
+
let mut stdout = guard.child.stdout.take().ok_or("stdout unavailable")?;
|
|
160
|
+
let mut stderr = guard.child.stderr.take().ok_or("stderr unavailable")?;
|
|
161
|
+
let cancelled = Arc::new(AtomicBool::new(false));
|
|
162
|
+
let out_cancel = cancelled.clone();
|
|
163
|
+
let err_cancel = cancelled.clone();
|
|
164
|
+
let out_thread = thread::spawn(move || {
|
|
165
|
+
let result = io::copy(&mut stdout, &mut stdout_file);
|
|
166
|
+
if result.is_err() {
|
|
167
|
+
out_cancel.store(true, Ordering::Relaxed);
|
|
168
|
+
}
|
|
169
|
+
result
|
|
170
|
+
});
|
|
171
|
+
let err_thread = thread::spawn(move || {
|
|
172
|
+
let result = io::copy(&mut stderr, &mut stderr_file);
|
|
173
|
+
if result.is_err() {
|
|
174
|
+
err_cancel.store(true, Ordering::Relaxed);
|
|
175
|
+
}
|
|
176
|
+
result
|
|
177
|
+
});
|
|
178
|
+
let cancel_control = cancelled.clone();
|
|
179
|
+
// A closed parent pipe also cancels the run, so an exited Pi process cannot orphan work.
|
|
180
|
+
thread::spawn(move || {
|
|
181
|
+
let mut input = io::stdin().lock();
|
|
182
|
+
let mut line = String::new();
|
|
183
|
+
loop {
|
|
184
|
+
match input.read_line(&mut line) {
|
|
185
|
+
Ok(0) | Err(_) => {
|
|
186
|
+
cancel_control.store(true, Ordering::Relaxed);
|
|
187
|
+
break;
|
|
188
|
+
}
|
|
189
|
+
Ok(_) if line.trim() == "cancel" => {
|
|
190
|
+
cancel_control.store(true, Ordering::Relaxed);
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
Ok(_) => line.clear(),
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
let mut exit = None;
|
|
198
|
+
let mut cancel_started = None;
|
|
199
|
+
let mut killed = false;
|
|
200
|
+
loop {
|
|
201
|
+
if cancelled.load(Ordering::Relaxed) && cancel_started.is_none() {
|
|
202
|
+
terminate_group(pid, false);
|
|
203
|
+
cancel_started = Some(Instant::now());
|
|
204
|
+
}
|
|
205
|
+
if cancel_started.is_some_and(|t| t.elapsed() >= Duration::from_millis(500)) && !killed {
|
|
206
|
+
terminate_group(pid, true);
|
|
207
|
+
killed = true;
|
|
208
|
+
}
|
|
209
|
+
if exit.is_none() {
|
|
210
|
+
exit = guard.child.try_wait().map_err(|e| e.to_string())?;
|
|
211
|
+
}
|
|
212
|
+
if exit.is_some() && out_thread.is_finished() && err_thread.is_finished() {
|
|
213
|
+
// Commands cannot leave background work running after the captured operation ends.
|
|
214
|
+
terminate_group(pid, true);
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
thread::sleep(Duration::from_millis(10));
|
|
218
|
+
}
|
|
219
|
+
let out_bytes = out_thread
|
|
220
|
+
.join()
|
|
221
|
+
.map_err(|_| "stdout capture thread panicked")?
|
|
222
|
+
.map_err(|e| e.to_string())?;
|
|
223
|
+
let err_bytes = err_thread
|
|
224
|
+
.join()
|
|
225
|
+
.map_err(|_| "stderr capture thread panicked")?
|
|
226
|
+
.map_err(|e| e.to_string())?;
|
|
227
|
+
io::copy(
|
|
228
|
+
&mut File::open(&stdout_path).map_err(|e| e.to_string())?,
|
|
229
|
+
&mut combined,
|
|
230
|
+
)
|
|
231
|
+
.map_err(|e| e.to_string())?;
|
|
232
|
+
if out_bytes > 0 && err_bytes > 0 {
|
|
233
|
+
combined.write_all(b"\n").map_err(|e| e.to_string())?;
|
|
234
|
+
}
|
|
235
|
+
io::copy(
|
|
236
|
+
&mut File::open(&stderr_path).map_err(|e| e.to_string())?,
|
|
237
|
+
&mut combined,
|
|
238
|
+
)
|
|
239
|
+
.map_err(|e| e.to_string())?;
|
|
240
|
+
combined.flush().map_err(|e| e.to_string())?;
|
|
241
|
+
let cancelled = cancel_started.is_some();
|
|
242
|
+
let exit_code = if cancelled {
|
|
243
|
+
130
|
|
244
|
+
} else {
|
|
245
|
+
exit.and_then(|s| s.code()).unwrap_or(1)
|
|
246
|
+
};
|
|
247
|
+
guard.armed = false;
|
|
248
|
+
Ok(
|
|
249
|
+
json!({"stdoutPath":stdout_path,"stderrPath":stderr_path,"logPath":log_path,
|
|
250
|
+
"exitCode":exit_code,"cancelled":cancelled,"rawBytes":out_bytes+err_bytes}),
|
|
251
|
+
)
|
|
252
|
+
}
|
package/package.json
CHANGED
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robhowley/pi-structured-return",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "Turn noisy CLI output into compact structured results (fewer tokens), full logs
|
|
3
|
+
"version": "2.0.1",
|
|
4
|
+
"description": "Turn noisy CLI output into compact structured results (up to 95% fewer tokens), preserving diagnostics and full logs.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
7
7
|
"extensions",
|
|
8
8
|
"skills",
|
|
9
|
+
"native/src",
|
|
10
|
+
"native/Cargo.toml",
|
|
11
|
+
"native/Cargo.lock",
|
|
12
|
+
"native/bin",
|
|
13
|
+
"native/THIRD-PARTY-LICENSES.txt",
|
|
14
|
+
"scripts/build-native.mjs",
|
|
15
|
+
"scripts/native-artifacts.mjs",
|
|
9
16
|
"README.md",
|
|
10
|
-
"
|
|
17
|
+
"LICENSE"
|
|
11
18
|
],
|
|
12
19
|
"publishConfig": {
|
|
13
20
|
"access": "public"
|
|
@@ -37,17 +44,24 @@
|
|
|
37
44
|
"format:check": "prettier --check extensions/",
|
|
38
45
|
"format:write": "prettier --write extensions/",
|
|
39
46
|
"typecheck": "tsc --noEmit",
|
|
40
|
-
"test": "vitest run __tests__"
|
|
47
|
+
"test": "vitest run __tests__",
|
|
48
|
+
"build": "node scripts/build-native.mjs",
|
|
49
|
+
"build:native": "node scripts/build-native.mjs",
|
|
50
|
+
"prepack": "node scripts/native-artifacts.mjs",
|
|
51
|
+
"pack:smoke": "node scripts/pack-smoke.mjs --host",
|
|
52
|
+
"test:parity": "vitest run --config vitest.native.config.ts",
|
|
53
|
+
"test:native": "cargo test --manifest-path native/Cargo.toml --locked"
|
|
41
54
|
},
|
|
42
55
|
"dependencies": {
|
|
43
|
-
"fast-xml-parser": "^5.4.1",
|
|
44
56
|
"glob": "^11.0.0"
|
|
45
57
|
},
|
|
46
58
|
"peerDependencies": {
|
|
47
59
|
"@mariozechner/pi-coding-agent": "*",
|
|
48
|
-
"@mariozechner/pi-tui": "*"
|
|
60
|
+
"@mariozechner/pi-tui": "*",
|
|
61
|
+
"@sinclair/typebox": "*"
|
|
49
62
|
},
|
|
50
63
|
"devDependencies": {
|
|
51
|
-
"@types/node": "^22.15.17"
|
|
64
|
+
"@types/node": "^22.15.17",
|
|
65
|
+
"fast-xml-parser": "^5.4.1"
|
|
52
66
|
}
|
|
53
67
|
}
|