Skip to content

Commit 1ff6377

Browse files
committed
Decode versioned OpenCLI structured help with explicit unknown states
Refs #5
1 parent bf4498d commit 1ff6377

7 files changed

Lines changed: 352 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ Notes:
201201
- A collect timeout raises `OpenCliRemoteTimeoutException`. After dispatch to the HTTP transport, `isRemoteOutcomeUnknown()` is true. Collect does not automatically retry or follow redirects.
202202
- Inspect `getRemoteExecutionDetails()` on the result or on an exception’s `getPartialResult()` to distinguish HTTP status, Agent business status and the source of `items`. The legacy 0/1 returned by `getExitCode()` is synthetic. HTTP and protocol failure snapshots have no exit code. Accepted response text is available in those snapshots only when raw capture is enabled.
203203
- If your Agent accepts a credential header, configure `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`. Supply the complete header value. The Agent base URL must use HTTPS for credentials and contain no user info, query or fragment. The SDK sends the configured header on `/collect`. OAuth discovery and request signing are unsupported.
204+
- Parse previously captured CLI help with `OpenCliHelpParser.parse(stdout)`. The result retains the original text and reports whether the schema is available. Structured commands preserve placeholders and separate command, namespace, global and common options.
204205
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
205206

206207
### Windows npm launcher

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ cli.gemini().deepResearch("topic",
201201
- 远程调用超时抛出 `OpenCliRemoteTimeoutException`。请求提交给 HTTP 传输后,`isRemoteOutcomeUnknown()` 为 true。客户端不会自动重试或跟随重定向。
202202
- 通过结果或异常的 `getPartialResult()` 调用 `getRemoteExecutionDetails()`,查看 HTTP 状态、Agent 业务状态和 `items` 的来源。`getExitCode()` 的 0/1 是兼容映射。HTTP 或协议失败快照没有退出码。仅在开启原文捕获时,失败快照才携带已通过字节上限检查的响应正文。
203203
- Agent 支持认证请求头时,可调用 `setRemoteAuthentication(new OpenCliRemoteAuthentication("Authorization", System.getenv("OPENCLI_AGENT_AUTHORIZATION")))`,传入完整请求头值。认证须使用 HTTPS,Agent 基础地址须省略用户信息、查询参数和片段。SDK 只在 `/collect` 请求上发送已配置的认证头。OAuth 发现和请求签名尚不支持。
204+
- 对已采集的 CLI 帮助调用 `OpenCliHelpParser.parse(stdout)`,可读取结构化命令、占位符、不同作用域的选项和原文。纯文本、混合输出或无效结构会返回未知状态及原因。
204205
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
205206

206207
### Windows npm 启动入口

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,10 @@
2424
## 证据交付模板(实施时填写)
2525

2626
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
27+
28+
29+
## OC-CAP-001/002/005 结构化帮助解析
30+
31+
`OpenCliHelpParser` 在 Java 8 API 范围内提供帮助解析结果。根目录、站点、命名空间和叶子按真实 1.8.8 结构识别。Schema 保留命令显示路径、会话占位符、命令层级、位置参数、别名和分作用域选项。缺失字段、显式 false、可选取值、否定和默认值分别保留。原文和各节点的来源 JSON 可以追溯未解释字段。纯文本、JSON 后缀、重复字段或无效结构返回 `UNKNOWN` 及对应原因。
32+
33+
基线的 API 验收先因缺少解析入口而无法编译。加入实现后,以 1.8.8 的七个 JSON 样本、两个原始负例和合成扩展验证,详见 `OpenCliHelpParserTest`。当前验证范围为原文解码,运行时探测、快照来源与失效、类型化会话绑定仍由其余任务验收。
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import com.fasterxml.jackson.core.JsonProcessingException;
4+
import com.fasterxml.jackson.databind.DeserializationFeature;
5+
import com.fasterxml.jackson.databind.JsonNode;
6+
import com.fasterxml.jackson.databind.ObjectReader;
7+
import com.fasterxml.jackson.databind.json.JsonMapper;
8+
import io.github.easy4j.opencli.parser.OpenCliHelpResult.Reason;
9+
import io.github.easy4j.opencli.parser.OpenCliHelpResult.Status;
10+
import io.github.easy4j.opencli.util.OpenCliStrings;
11+
import java.util.ArrayList;
12+
import java.util.Collections;
13+
import java.util.List;
14+
import java.util.Objects;
15+
import java.util.function.Function;
16+
17+
/** Decodes the OpenCLI structured-help response shapes without executing their contents. */
18+
public final class OpenCliHelpParser {
19+
20+
private static final ObjectReader READER = new JsonMapper().reader().with(
21+
DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
22+
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY,
23+
DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
24+
25+
private OpenCliHelpParser() {
26+
}
27+
28+
/**
29+
* @param rawHelp stdout from a bounded help probe or a previously collected sample
30+
* @return a structured schema or a reason it could not be recognized
31+
*/
32+
public static OpenCliHelpResult parse(String rawHelp) {
33+
if (OpenCliStrings.isBlank(rawHelp)) {
34+
return unknown(rawHelp, Reason.EMPTY);
35+
}
36+
String input = rawHelp.trim();
37+
if (input.charAt(0) != '{') {
38+
return unknown(rawHelp, Reason.UNSUPPORTED_FORMAT);
39+
}
40+
41+
JsonNode root;
42+
try {
43+
root = READER.readTree(input);
44+
} catch (JsonProcessingException ex) {
45+
return unknown(rawHelp, Reason.INVALID_JSON);
46+
}
47+
try {
48+
if (!isHelpRoot(root)) {
49+
return unknown(rawHelp, Reason.INVALID_SCHEMA);
50+
}
51+
return new OpenCliHelpResult(Status.AVAILABLE, null, rawHelp, schema(root));
52+
} catch (IllegalArgumentException ex) {
53+
return unknown(rawHelp, Reason.INVALID_SCHEMA);
54+
}
55+
}
56+
57+
private static OpenCliHelpResult unknown(String rawHelp, Reason reason) {
58+
return new OpenCliHelpResult(Status.UNKNOWN, reason, rawHelp, null);
59+
}
60+
61+
private static boolean isHelpRoot(JsonNode root) {
62+
if (!root.isObject()) {
63+
return false;
64+
}
65+
boolean directory = root.path("commands").isArray();
66+
if (directory && "opencli".equals(text(root.path("name"))) && root.path("site_adapters").isObject()) {
67+
return true;
68+
}
69+
if (directory && OpenCliStrings.isNotBlank(text(root.path("site")))) {
70+
return true;
71+
}
72+
return (OpenCliStrings.isNotBlank(text(root.path("namespace")))
73+
|| OpenCliStrings.isNotBlank(text(root.path("site"))))
74+
&& OpenCliStrings.isNotBlank(text(root.path("command")))
75+
&& (directory || (OpenCliStrings.isNotBlank(text(root.path("name")))
76+
&& (root.path("positionals").isArray() || root.path("command_options").isArray())));
77+
}
78+
79+
private static OpenCliHelpSchema schema(JsonNode node) {
80+
String name = text(node.path("name"));
81+
String command = text(node.path("command"));
82+
String site = text(node.path("site"));
83+
if (!node.isObject() || (OpenCliStrings.isBlank(name)
84+
&& OpenCliStrings.isBlank(command) && OpenCliStrings.isBlank(site))) {
85+
throw invalidSchema();
86+
}
87+
return OpenCliHelpSchema.builder()
88+
.name(name)
89+
.command(command)
90+
.namespace(text(node.path("namespace")))
91+
.site(site)
92+
.aliases(array(node.path("aliases"), OpenCliHelpParser::requiredText))
93+
.commands(array(node.path("commands"), OpenCliHelpParser::schema))
94+
.positionals(array(node.path("positionals"), OpenCliHelpParser::argument))
95+
.commandOptions(array(node.path("command_options"), OpenCliHelpParser::argument))
96+
.namespaceOptions(array(node.path("namespace_options"), OpenCliHelpParser::argument))
97+
.globalOptions(array(node.path("global_options"), OpenCliHelpParser::argument))
98+
.commonOptions(array(node.path("common_options"), OpenCliHelpParser::argument))
99+
.sourceJson(node.toString())
100+
.build();
101+
}
102+
103+
private static OpenCliHelpSchema.Argument argument(JsonNode node) {
104+
if (!node.isObject()) {
105+
throw invalidSchema();
106+
}
107+
JsonNode defaultValue = node.path("default");
108+
return OpenCliHelpSchema.Argument.builder()
109+
.name(requiredText(node.path("name")))
110+
.flags(text(node.path("flags")))
111+
.type(text(node.path("type")))
112+
.takesValue(text(node.path("takes_value")))
113+
.required(bool(node.path("required")))
114+
.negate(bool(node.path("negate")))
115+
.variadic(bool(node.path("variadic")))
116+
.choices(array(node.path("choices"), OpenCliHelpParser::requiredText))
117+
.defaultJson(defaultValue.isMissingNode() ? null : defaultValue.toString())
118+
.sourceJson(node.toString())
119+
.build();
120+
}
121+
122+
private static <T> List<T> array(JsonNode node, Function<JsonNode, T> decode) {
123+
if (node.isMissingNode()) {
124+
return Collections.emptyList();
125+
}
126+
if (!node.isArray()) {
127+
throw invalidSchema();
128+
}
129+
List<T> values = new ArrayList<>(node.size());
130+
for (JsonNode value : node) {
131+
values.add(decode.apply(value));
132+
}
133+
return Collections.unmodifiableList(values);
134+
}
135+
136+
private static String text(JsonNode node) {
137+
if (node.isMissingNode()) {
138+
return null;
139+
}
140+
if (!node.isTextual()) {
141+
throw invalidSchema();
142+
}
143+
return node.asText();
144+
}
145+
146+
private static String requiredText(JsonNode node) {
147+
String value = text(node);
148+
if (Objects.isNull(value)) {
149+
throw invalidSchema();
150+
}
151+
return value;
152+
}
153+
154+
private static Boolean bool(JsonNode node) {
155+
if (node.isMissingNode()) {
156+
return null;
157+
}
158+
if (!node.isBoolean()) {
159+
throw invalidSchema();
160+
}
161+
return node.booleanValue();
162+
}
163+
164+
private static IllegalArgumentException invalidSchema() {
165+
return new IllegalArgumentException("Invalid OpenCLI help schema");
166+
}
167+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import lombok.Getter;
4+
5+
/** Result of interpreting one supplied OpenCLI help document. */
6+
@Getter
7+
public final class OpenCliHelpResult {
8+
9+
public enum Status { AVAILABLE, UNKNOWN }
10+
11+
public enum Reason { EMPTY, UNSUPPORTED_FORMAT, INVALID_JSON, INVALID_SCHEMA }
12+
13+
private final Status status;
14+
/** Null for recognized help. */
15+
private final Reason reason;
16+
/** Exact text passed to the parser, including any trailing output. */
17+
private final String rawHelp;
18+
/** Available only for recognized structured help. */
19+
private final OpenCliHelpSchema schema;
20+
21+
OpenCliHelpResult(Status status, Reason reason, String rawHelp, OpenCliHelpSchema schema) {
22+
this.status = status;
23+
this.reason = reason;
24+
this.rawHelp = rawHelp;
25+
this.schema = schema;
26+
}
27+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package io.github.easy4j.opencli.parser;
2+
3+
import java.util.List;
4+
import lombok.AccessLevel;
5+
import lombok.Builder;
6+
import lombok.Getter;
7+
8+
/** Read-only projection of a recognized help document or command entry. */
9+
@Getter
10+
@Builder(access = AccessLevel.PACKAGE)
11+
public final class OpenCliHelpSchema {
12+
13+
private final String name;
14+
/** Upstream display path, including any unbound placeholders. */
15+
private final String command;
16+
private final String namespace;
17+
private final String site;
18+
private final List<String> aliases;
19+
private final List<OpenCliHelpSchema> commands;
20+
private final List<Argument> positionals;
21+
private final List<Argument> commandOptions;
22+
private final List<Argument> namespaceOptions;
23+
private final List<Argument> globalOptions;
24+
private final List<Argument> commonOptions;
25+
/** Source JSON for this entry, including fields the SDK does not interpret. */
26+
private final String sourceJson;
27+
28+
/** Option or positional metadata as reported by OpenCLI. Missing scalar fields are null. */
29+
@Getter
30+
@Builder(access = AccessLevel.PACKAGE)
31+
public static final class Argument {
32+
33+
private final String name;
34+
private final String flags;
35+
private final String type;
36+
private final String takesValue;
37+
private final Boolean required;
38+
private final Boolean negate;
39+
private final Boolean variadic;
40+
private final List<String> choices;
41+
/** JSON representation of the reported default. Explicit null is the literal "null". */
42+
private final String defaultJson;
43+
private final String sourceJson;
44+
}
45+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package io.github.easy4j.opencli.contract;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertFalse;
5+
import static org.junit.jupiter.api.Assertions.assertNull;
6+
import static org.junit.jupiter.api.Assertions.assertThrows;
7+
import static org.junit.jupiter.api.Assertions.assertTrue;
8+
9+
import io.github.easy4j.opencli.parser.OpenCliHelpParser;
10+
import io.github.easy4j.opencli.parser.OpenCliHelpResult;
11+
import io.github.easy4j.opencli.parser.OpenCliHelpSchema;
12+
import java.io.InputStream;
13+
import java.nio.charset.StandardCharsets;
14+
import java.util.Scanner;
15+
import org.junit.jupiter.api.Test;
16+
17+
class OpenCliHelpParserTest {
18+
19+
@Test
20+
void decodesRealSnapshotsWithoutMergingScopes() {
21+
String raw = sample("browser-tab.json");
22+
OpenCliHelpResult result = OpenCliHelpParser.parse(raw);
23+
assertEquals(OpenCliHelpResult.Status.AVAILABLE, result.getStatus());
24+
assertEquals(raw, result.getRawHelp());
25+
OpenCliHelpSchema schema = result.getSchema();
26+
assertEquals("opencli browser <session> tab", schema.getCommand());
27+
assertEquals("tab close", schema.getCommands().get(0).getName());
28+
assertEquals("tab", schema.getCommands().get(0).getCommandOptions().get(0).getName());
29+
assertEquals("window", schema.getNamespaceOptions().get(0).getName());
30+
assertTrue(schema.getGlobalOptions().stream().anyMatch(option -> "profile".equals(option.getName())));
31+
assertTrue(schema.getSourceJson().contains("\"structured_help\""));
32+
}
33+
34+
@Test
35+
void decodesRealCatalogAndRetainsAbsentMetadata() {
36+
OpenCliHelpSchema root = OpenCliHelpParser.parse(sample("root.json")).getSchema();
37+
assertEquals("opencli", root.getName());
38+
assertNull(root.getCommands().get(0).getCommand());
39+
OpenCliHelpSchema npm = OpenCliHelpParser.parse(sample("site-npm-search.json")).getSchema();
40+
assertEquals("npm", npm.getSite());
41+
assertEquals("opencli npm search", npm.getCommand());
42+
assertEquals(Boolean.TRUE, npm.getPositionals().get(0).getRequired());
43+
assertEquals("false", npm.getCommonOptions().get(2).getDefaultJson());
44+
assertNull(npm.getCommonOptions().get(3).getDefaultJson());
45+
assertEquals("required", OpenCliHelpParser.parse(sample("browser-state.json")).getSchema()
46+
.getNamespaceOptions().get(0).getTakesValue());
47+
assertEquals("npm", OpenCliHelpParser.parse(sample("site-npm.json")).getSchema().getSite());
48+
assertEquals("opencli auth", OpenCliHelpParser.parse(sample("meta-auth.json")).getSchema().getCommand());
49+
assertEquals("opencli browser <session> get",
50+
OpenCliHelpParser.parse(sample("browser-get.json")).getSchema().getCommand());
51+
}
52+
53+
@Test
54+
void preservesFutureFieldsOptionalValuesAndExplicitFalse() {
55+
String raw = "{\"namespace\":\"browser\",\"name\":\"probe\",\"command\":\"opencli browser <session> probe\","
56+
+ "\"aliases\":[\"inspect\"],\"future\":{\"version\":2,\"large\":1e400},"
57+
+ "\"positionals\":[{\"name\":\"target\",\"variadic\":true}],"
58+
+ "\"command_options\":[{\"name\":\"sample\",\"takes_value\":\"optional\","
59+
+ "\"required\":false,\"negate\":true,\"default\":false,\"choices\":[\"a\",\"b\"],\"extra\":42}]}";
60+
OpenCliHelpResult result = OpenCliHelpParser.parse(raw);
61+
assertEquals(OpenCliHelpResult.Status.AVAILABLE, result.getStatus(), String.valueOf(result.getReason()));
62+
OpenCliHelpSchema schema = result.getSchema();
63+
assertEquals("inspect", schema.getAliases().get(0));
64+
assertThrows(UnsupportedOperationException.class, () -> schema.getAliases().add("changed"));
65+
assertEquals(Boolean.TRUE, schema.getPositionals().get(0).getVariadic());
66+
assertEquals("optional", schema.getCommandOptions().get(0).getTakesValue());
67+
assertEquals(Boolean.TRUE, schema.getCommandOptions().get(0).getNegate());
68+
assertFalse(schema.getCommandOptions().get(0).getRequired());
69+
assertEquals("false", schema.getCommandOptions().get(0).getDefaultJson());
70+
assertEquals("b", schema.getCommandOptions().get(0).getChoices().get(1));
71+
assertTrue(schema.getSourceJson().contains("\"future\""));
72+
assertTrue(schema.getSourceJson().contains("1E+400"));
73+
assertTrue(schema.getCommandOptions().get(0).getSourceJson().contains("\"extra\":42"));
74+
}
75+
76+
@Test
77+
void returnsUnknownForNonJsonOrInvalidHelpShapes() {
78+
assertUnknown(sample("meta-list.txt"), OpenCliHelpResult.Reason.UNSUPPORTED_FORMAT);
79+
assertUnknown(sample("browser.stdout"), OpenCliHelpResult.Reason.INVALID_JSON);
80+
assertUnknown("{\"latest\":true}", OpenCliHelpResult.Reason.INVALID_SCHEMA);
81+
assertUnknown("{\"site\":\"npm\",\"site\":\"other\",\"commands\":[]}", OpenCliHelpResult.Reason.INVALID_JSON);
82+
assertUnknown("{\"namespace\":\"browser\",\"command\":\"opencli browser\",\"commands\":{}}",
83+
OpenCliHelpResult.Reason.INVALID_SCHEMA);
84+
assertUnknown("{\"site\":\"npm\",\"commands\":[{\"name\":17}]}",
85+
OpenCliHelpResult.Reason.INVALID_SCHEMA);
86+
assertUnknown(" ", OpenCliHelpResult.Reason.EMPTY);
87+
}
88+
89+
private static void assertUnknown(String raw, OpenCliHelpResult.Reason reason) {
90+
OpenCliHelpResult result = OpenCliHelpParser.parse(raw);
91+
assertEquals(OpenCliHelpResult.Status.UNKNOWN, result.getStatus());
92+
assertEquals(reason, result.getReason());
93+
assertEquals(raw, result.getRawHelp());
94+
assertNull(result.getSchema());
95+
}
96+
97+
private static String sample(String name) {
98+
InputStream stream = OpenCliHelpParserTest.class
99+
.getResourceAsStream("/opencli-contracts/v1/structured-help-1.8.8/" + name);
100+
try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
101+
return scanner.useDelimiter("\\A").next();
102+
}
103+
}
104+
}

0 commit comments

Comments
 (0)