Skip to content

Commit 7d85857

Browse files
committed
Probe trusted local OpenCLI root capabilities with bounded execution
1 parent 49726d1 commit 7d85857

5 files changed

Lines changed: 346 additions & 0 deletions

File tree

‎openspec/changes/add-opencli-capability-discovery/tasks.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,9 @@
3131
`OpenCliHelpParser` 在 Java 8 API 范围内提供帮助解析结果。根目录、站点、命名空间和叶子按真实 1.8.8 结构识别。Schema 保留命令显示路径、会话占位符、命令层级、位置参数、别名和分作用域选项。缺失字段、显式 false、可选取值、否定和默认值分别保留。原文和各节点的来源 JSON 可以追溯未解释字段。纯文本、JSON 后缀、重复字段或无效结构返回 `UNKNOWN` 及对应原因。
3232

3333
基线的 API 验收先因缺少解析入口而无法编译。加入实现后,以 1.8.8 的七个 JSON 样本、两个原始负例和合成扩展验证,详见 `OpenCliHelpParserTest`。当前验证范围为原文解码,运行时探测、快照来源与失效、类型化会话绑定仍由其余任务验收。
34+
35+
## OC-CAP-004/005/006 本地根发现
36+
37+
`OpenCliClient.discoverCapabilities()` 接受调用者信任的绝对本地可执行文件配置,记录规范路径、观测版本、采集时刻、配置指纹及完整帮助文本的 SHA-256。探测固定为 `--version` 和 `--help -f json`,复用客户端执行器的本地并发容量、队列和进程清理。每次探测的队列与运行合计最多 10 秒,清理最多 1 秒,每路最多保留 1 MiB,调用者设置的更小预算优先。命令来源为 `UNKNOWN`,观察范围为 `ROOT_HELP`。采用按需重新观测,同版本改动可形成不同帮助摘要;缓存和 STALE 仍待实现。远端和 PATH 查找的发现请求返回 `UNSUPPORTED`,原有显式本地调用仍可使用。
38+
39+
`OpenCliCapabilityDiscoveryTest` 先因缺少公开发现 API 无法编译。真实 JVM 子进程验收固定参数、同版本变更、无来源推断、文本降级、输出超限、非零退出、超时及 local raw。Maven 定向测试同时验证原有帮助解析。范围仍为根级目录,细粒度帮助探测及类型化执行仍未验收。

‎src/main/java/io/github/easy4j/opencli/OpenCliClient.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
import io.github.easy4j.opencli.adapter.publicapi.pypi.PypiOpenCliClient;
1919
import io.github.easy4j.opencli.adapter.publicapi.wikipedia.WikipediaOpenCliClient;
2020
import io.github.easy4j.opencli.browser.OpenCliBrowserClient;
21+
import io.github.easy4j.opencli.capability.OpenCliCapabilityDiscovery;
22+
import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot;
2123
import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
2224
import io.github.easy4j.opencli.meta.OpenCliMetaClient;
2325
import io.github.easy4j.opencli.core.OpenCliExecutor;
@@ -83,6 +85,14 @@ public OpenCliAdapterChannel adapter(String adapterId) {
8385
return new OpenCliAdapterChannel(executor, adapterId);
8486
}
8587

88+
/**
89+
* Probes version and root structured help on the configured absolute local executable.
90+
* @return a fresh observation with help, provenance and failure status
91+
*/
92+
public OpenCliCapabilitySnapshot discoverCapabilities() {
93+
return OpenCliCapabilityDiscovery.discover(executor);
94+
}
95+
8696
// ----- 参考强类型门面(Desktop) -----
8797

8898
/** @return Codex 桌面适配器客户端 */
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
package io.github.easy4j.opencli.capability;
2+
3+
import io.github.easy4j.opencli.OpenCliExecutionTarget;
4+
import io.github.easy4j.opencli.OpenCliProperties;
5+
import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot.Status;
6+
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
7+
import io.github.easy4j.opencli.core.OpenCliExecutor;
8+
import io.github.easy4j.opencli.core.OpenCliResult;
9+
import io.github.easy4j.opencli.exception.OpenCliException;
10+
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
11+
import io.github.easy4j.opencli.parser.OpenCliHelpParser;
12+
import io.github.easy4j.opencli.parser.OpenCliHelpResult;
13+
import io.github.easy4j.opencli.util.OpenCliStrings;
14+
import java.io.IOException;
15+
import java.nio.ByteBuffer;
16+
import java.nio.charset.StandardCharsets;
17+
import java.nio.file.Files;
18+
import java.nio.file.InvalidPathException;
19+
import java.nio.file.Path;
20+
import java.nio.file.Paths;
21+
import java.security.MessageDigest;
22+
import java.security.NoSuchAlgorithmException;
23+
import java.time.Instant;
24+
import java.util.Arrays;
25+
import java.util.Collections;
26+
import java.util.Map;
27+
import java.util.Objects;
28+
import java.util.TreeMap;
29+
import java.util.regex.Pattern;
30+
31+
/** Fixed, bounded metadata probes through the existing local subprocess runtime. */
32+
public final class OpenCliCapabilityDiscovery {
33+
private static final int MAX_PROBE_OUTPUT_BYTES = 1024 * 1024;
34+
private static final long MAX_PROBE_MILLIS = 10_000;
35+
private static final long MAX_CLEANUP_MILLIS = 1_000;
36+
private static final Pattern VERSION = Pattern.compile(
37+
"[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?");
38+
39+
private OpenCliCapabilityDiscovery() {
40+
}
41+
42+
/**
43+
* Observes version and root help on a configured, trusted absolute executable.
44+
* Installation, launcher arguments and environment are supplied by the trusted caller.
45+
*
46+
* @param executor client executor whose local process capacity is shared
47+
* @return the root observation or an explicit reason it could not be made
48+
*/
49+
public static OpenCliCapabilitySnapshot discover(OpenCliExecutor executor) {
50+
OpenCliProperties configured = executor.getProperties();
51+
OpenCliCapabilitySnapshot.OpenCliCapabilitySnapshotBuilder snapshot =
52+
OpenCliCapabilitySnapshot.builder().observedAt(Instant.now());
53+
if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) {
54+
return snapshot.status(Status.UNSUPPORTED).reason("LOCAL_DISCOVERY_ONLY").build();
55+
}
56+
if (OpenCliStrings.isBlank(configured.getExecutable())) {
57+
return snapshot.status(Status.UNSUPPORTED).reason("ABSOLUTE_EXECUTABLE_REQUIRED").build();
58+
}
59+
60+
OpenCliProperties probe = configured.copyForLocalCliExecution();
61+
Path executable;
62+
try {
63+
Path configuredPath = Paths.get(probe.getExecutable().trim());
64+
if (!configuredPath.isAbsolute()) {
65+
return snapshot.status(Status.UNSUPPORTED).reason("ABSOLUTE_EXECUTABLE_REQUIRED").build();
66+
}
67+
executable = configuredPath.toRealPath();
68+
if (!Files.isRegularFile(executable) || !Files.isExecutable(executable)) {
69+
return snapshot.status(Status.UNKNOWN).reason("EXECUTABLE_UNAVAILABLE").build();
70+
}
71+
} catch (IOException | InvalidPathException | SecurityException ex) {
72+
return snapshot.status(Status.UNKNOWN).reason("EXECUTABLE_UNAVAILABLE").build();
73+
}
74+
75+
probe.setExecutable(executable.toString());
76+
probe.setCommandTimeoutMillis(Math.min(MAX_PROBE_MILLIS,
77+
Math.min(probe.getStartupProbeTimeoutMillis(), probe.getCommandTimeoutMillis())));
78+
probe.setCleanupGraceMillis(Math.min(MAX_CLEANUP_MILLIS, probe.getCleanupGraceMillis()));
79+
probe.setMaxStdoutBytes(Math.min(MAX_PROBE_OUTPUT_BYTES, probe.getMaxStdoutBytes()));
80+
probe.setMaxStderrBytes(Math.min(MAX_PROBE_OUTPUT_BYTES, probe.getMaxStderrBytes()));
81+
snapshot.executable(probe.getExecutable()).configurationSha256(configurationDigest(probe));
82+
try (OpenCliExecutor local = new OpenCliExecutor(probe, executor.getProcessRuntime())) {
83+
String phase = "VERSION";
84+
try {
85+
OpenCliResult versionResult = local.invokeLocalOnly(Collections.singletonList("--version"));
86+
String version = versionResult.getStdout().trim();
87+
if (versionResult.getExecutionDetails().isStdoutTruncated() || !VERSION.matcher(version).matches()) {
88+
return snapshot.status(Status.UNKNOWN).reason("INVALID_VERSION_OUTPUT").build();
89+
}
90+
snapshot.observedVersion(version);
91+
phase = "HELP";
92+
OpenCliResult helpResult = local.invokeLocalOnly(Arrays.asList("--help", "-f", "json"));
93+
if (helpResult.getExecutionDetails().isStdoutTruncated()) {
94+
return snapshot.status(Status.UNKNOWN).reason("HELP_TRUNCATED").build();
95+
}
96+
String stdout = helpResult.getStdout();
97+
OpenCliHelpResult help = OpenCliHelpParser.parse(stdout);
98+
snapshot.help(help).helpSha256(hex(sha256().digest(stdout.getBytes(StandardCharsets.UTF_8))));
99+
if (help.getStatus() == OpenCliHelpResult.Status.AVAILABLE) {
100+
return snapshot.status(Status.AVAILABLE).build();
101+
}
102+
return snapshot.status(Status.UNKNOWN).reason(help.getReason().name()).build();
103+
} catch (OpenCliTimeoutException ex) {
104+
return snapshot.status(Status.UNKNOWN).reason(phase + "_TIMEOUT").build();
105+
} catch (OpenCliException ex) {
106+
OpenCliResult partial = ex.getPartialResult();
107+
if (Objects.nonNull(partial) && partial.getExecutionDetails().getTerminationReason() == TerminationReason.OUTPUT_LIMIT) {
108+
return snapshot.status(Status.UNKNOWN).reason(phase + "_TRUNCATED").build();
109+
}
110+
return snapshot.status(Status.UNKNOWN).reason(phase + "_PROBE_FAILED").build();
111+
} catch (IllegalArgumentException | IllegalStateException | UnsupportedOperationException ex) {
112+
return snapshot.status(Status.UNKNOWN).reason(phase + "_PROBE_FAILED").build();
113+
}
114+
}
115+
}
116+
117+
private static String configurationDigest(OpenCliProperties probe) {
118+
MessageDigest digest = sha256();
119+
add(digest, probe.getExecutable());
120+
String directory = probe.getWorkingDirectory();
121+
add(digest, OpenCliStrings.isBlank(directory) ? System.getProperty("user.dir") : directory.trim());
122+
add(digest, Integer.toString(probe.getLeadingArguments().size()));
123+
for (String argument : probe.getLeadingArguments()) {
124+
add(digest, argument);
125+
}
126+
Map<String, String> environment = new TreeMap<>(System.getenv());
127+
probe.getEnvironment().forEach((key, value) -> {
128+
if (Objects.nonNull(key) && Objects.nonNull(value)) {
129+
environment.put(key, value);
130+
}
131+
});
132+
environment.forEach((key, value) -> {
133+
add(digest, key);
134+
add(digest, value);
135+
});
136+
return hex(digest.digest());
137+
}
138+
139+
private static void add(MessageDigest digest, String value) {
140+
if (Objects.isNull(value)) {
141+
digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(-1).array());
142+
return;
143+
}
144+
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
145+
digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(bytes.length).array());
146+
digest.update(bytes);
147+
}
148+
149+
private static MessageDigest sha256() {
150+
try {
151+
return MessageDigest.getInstance("SHA-256");
152+
} catch (NoSuchAlgorithmException ex) {
153+
throw new IllegalStateException("The Java runtime must provide SHA-256", ex);
154+
}
155+
}
156+
157+
private static String hex(byte[] digest) {
158+
char[] digits = "0123456789abcdef".toCharArray();
159+
char[] result = new char[digest.length * 2];
160+
for (int index = 0; index < digest.length; index++) {
161+
int value = digest[index] & 0xff;
162+
result[index * 2] = digits[value >>> 4];
163+
result[index * 2 + 1] = digits[value & 0xf];
164+
}
165+
return new String(result);
166+
}
167+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package io.github.easy4j.opencli.capability;
2+
3+
import io.github.easy4j.opencli.parser.OpenCliHelpResult;
4+
import java.time.Instant;
5+
import lombok.Builder;
6+
import lombok.Getter;
7+
8+
/** Immutable observation of the configured local CLI's root help. */
9+
@Getter
10+
@Builder
11+
public final class OpenCliCapabilitySnapshot {
12+
public enum Status { AVAILABLE, UNKNOWN, UNSUPPORTED }
13+
14+
private final Status status;
15+
private final String reason;
16+
private final String executable;
17+
private final String observedVersion;
18+
private final Instant observedAt;
19+
private final String configurationSha256;
20+
private final String helpSha256;
21+
private final OpenCliHelpResult help;
22+
23+
/** @return scope of the metadata probe */
24+
public String getScope() {
25+
return "ROOT_HELP";
26+
}
27+
28+
/** @return unresolved origin, since help does not attribute overrides or plugins */
29+
public String getCommandOrigin() {
30+
return "UNKNOWN";
31+
}
32+
}
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
package io.github.easy4j.opencli.capability;
2+
3+
import io.github.easy4j.opencli.OpenCliClient;
4+
import io.github.easy4j.opencli.OpenCliExecutionTarget;
5+
import io.github.easy4j.opencli.OpenCliProperties;
6+
import java.io.File;
7+
import java.io.InputStream;
8+
import java.util.Arrays;
9+
import java.util.Scanner;
10+
import org.junit.jupiter.api.Test;
11+
12+
import static org.junit.jupiter.api.Assertions.*;
13+
14+
class OpenCliCapabilityDiscoveryTest {
15+
@Test
16+
void rootProbePreservesUnknownSourceAndUsesOnlyDescriptiveCommands() {
17+
OpenCliProperties properties = properties("structured");
18+
try (OpenCliClient client = new OpenCliClient(properties)) {
19+
OpenCliCapabilitySnapshot result = client.discoverCapabilities();
20+
assertEquals(OpenCliCapabilitySnapshot.Status.AVAILABLE, result.getStatus());
21+
assertEquals("1.8.8", result.getObservedVersion());
22+
assertEquals("UNKNOWN", result.getCommandOrigin());
23+
assertEquals("ROOT_HELP", result.getScope());
24+
assertNotNull(result.getObservedAt());
25+
assertTrue(new File(result.getExecutable()).isAbsolute());
26+
assertEquals(64, result.getConfigurationSha256().length());
27+
assertEquals(64, result.getHelpSha256().length());
28+
assertTrue(result.getHelp().getRawHelp().contains("do not run this example"));
29+
String structuredHash = result.getHelpSha256();
30+
properties.getEnvironment().put("OPENCLI_TEST_HELP_MODE", "revised");
31+
OpenCliCapabilitySnapshot revised = client.discoverCapabilities();
32+
assertEquals("1.8.8", revised.getObservedVersion());
33+
assertNotEquals(structuredHash, revised.getHelpSha256());
34+
assertNotEquals(result.getConfigurationSha256(), revised.getConfigurationSha256());
35+
}
36+
}
37+
38+
@Test
39+
void plainHelpLeavesLocalInvocationAvailable() {
40+
try (OpenCliClient client = new OpenCliClient(properties("plain"))) {
41+
OpenCliCapabilitySnapshot result = client.discoverCapabilities();
42+
assertEquals(OpenCliCapabilitySnapshot.Status.UNKNOWN, result.getStatus());
43+
assertEquals("UNSUPPORTED_FORMAT", result.getReason());
44+
assertEquals("Usage: opencli\n", result.getHelp().getRawHelp());
45+
assertEquals("raw available", client.getExecutor().invoke("npm", "search").getStdout());
46+
}
47+
}
48+
49+
@Test
50+
void pathLookupAndRemoteModeAreUnsupported() {
51+
try (OpenCliClient client = new OpenCliClient()) {
52+
assertEquals("ABSOLUTE_EXECUTABLE_REQUIRED", client.discoverCapabilities().getReason());
53+
}
54+
OpenCliProperties props = properties("structured");
55+
props.setExecutionTarget(OpenCliExecutionTarget.REMOTE_AGENT_HTTP);
56+
try (OpenCliClient client = new OpenCliClient(props)) {
57+
assertEquals("LOCAL_DISCOVERY_ONLY", client.discoverCapabilities().getReason());
58+
}
59+
}
60+
61+
@Test
62+
void truncatedHelpAndNonzeroOutputAreDiscoveryFailures() {
63+
OpenCliProperties limited = properties("structured");
64+
limited.setMaxStdoutBytes(16);
65+
try (OpenCliClient client = new OpenCliClient(limited)) {
66+
OpenCliCapabilitySnapshot result = client.discoverCapabilities();
67+
assertEquals(OpenCliCapabilitySnapshot.Status.UNKNOWN, result.getStatus());
68+
assertEquals("HELP_TRUNCATED", result.getReason());
69+
}
70+
try (OpenCliClient client = new OpenCliClient(properties("error"))) {
71+
assertEquals("HELP_PROBE_FAILED", client.discoverCapabilities().getReason());
72+
}
73+
}
74+
75+
@Test
76+
void slowHelpReturnsTimeoutWithinTheConfiguredProbeBudget() {
77+
OpenCliProperties limited = properties("slow");
78+
limited.setStartupProbeTimeoutMillis(2_000);
79+
try (OpenCliClient client = new OpenCliClient(limited)) {
80+
OpenCliCapabilitySnapshot result = client.discoverCapabilities();
81+
assertEquals(OpenCliCapabilitySnapshot.Status.UNKNOWN, result.getStatus());
82+
assertEquals("HELP_TIMEOUT", result.getReason());
83+
assertEquals("1.8.8", result.getObservedVersion());
84+
}
85+
}
86+
87+
private static OpenCliProperties properties(String mode) {
88+
OpenCliProperties props = new OpenCliProperties();
89+
String binary = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java";
90+
props.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), binary).getAbsolutePath());
91+
props.setLeadingArguments(Arrays.asList("-cp",
92+
System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")),
93+
DiscoveryFixture.class.getName()));
94+
props.getEnvironment().put("OPENCLI_TEST_HELP_MODE", mode);
95+
return props;
96+
}
97+
98+
public static class DiscoveryFixture {
99+
public static void main(String[] args) throws Exception {
100+
if (Arrays.equals(args, new String[]{"--version"})) {
101+
System.out.println("1.8.8");
102+
return;
103+
}
104+
if (Arrays.equals(args, new String[]{"npm", "search"})) {
105+
System.out.print("raw available");
106+
return;
107+
}
108+
if (!Arrays.equals(args, new String[]{"--help", "-f", "json"})) {
109+
System.exit(2);
110+
}
111+
String mode = System.getenv("OPENCLI_TEST_HELP_MODE");
112+
if ("error".equals(mode)) {
113+
System.exit(3);
114+
}
115+
if ("slow".equals(mode)) {
116+
Thread.sleep(30_000);
117+
}
118+
if ("plain".equals(mode)) {
119+
System.out.print("Usage: opencli\n");
120+
return;
121+
}
122+
try (InputStream input = DiscoveryFixture.class.getResourceAsStream(
123+
"/opencli-contracts/v1/structured-help-1.8.8/root.json");
124+
Scanner scan = new Scanner(input, "UTF-8").useDelimiter("\\A")) {
125+
String root = scan.next().trim();
126+
System.out.print(root.substring(0, root.length() - 1)
127+
+ ",\"description_fixture\":\"do not run this example " + mode + "\"}");
128+
}
129+
}
130+
}
131+
}

0 commit comments

Comments
 (0)