Skip to content

Commit 3b97f2c

Browse files
committed
Bind and validate discovered OpenCLI commands before local execution
1 parent 2eab964 commit 3b97f2c

8 files changed

Lines changed: 363 additions & 4 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
@@ -49,3 +49,9 @@
4949
`discoverCapabilities(OpenCliHelpScope)` 提供根目录、浏览器、浏览器 tab/get/state、auth、list 及 npm 站点和 search 的九个固定查询。细粒度参数只在已验证的 OpenCLI 1.8.8 启用。浏览器查询使用固定的帮助会话占位,不接受调用者提供的命令路径,也不执行帮助描述中的内容。结构化结果需匹配请求范围;纯文本和混合输出维持原有失败原因。
5050

5151
每个范围只保存其最近成功的观察,且配置或已观测版本变化使其他不匹配的范围一并失效。OpenCLI 能力仍按请求观察,并保留来源未知标记。增加 `OpenCliCapabilityDiscoveryTest` 的进程验收后,缺少范围 API 时失败,加入实现后定向测试通过。类型化会话绑定及执行前参数校验仍待验收。
52+
53+
## OC-CAP-002/003 类型化本地调用
54+
55+
`OpenCliClient.invokeDiscovered` 对本地配置取快照,刷新指定范围,选择显式给定的叶子路径,校验后通过同一执行器运行时提交字面参数。需要提供浏览器会话时,必须填入合法会话标识。校验覆盖必选项和值、声明 choices、可选值 flag、显式 false、否定拼写和可变位置参数;用字面分隔符隔离可能像选项的位置参数。不可用或过期的帮助无法进入类型化执行。原有本地 raw 入口独立可用。
56+
57+
`OpenCliCapabilityCommandTest` 和 `OpenCliCapabilityDiscoveryTest` 以失败→通过验证新 API、字段级错误和真实 JVM 子进程收到的 argv。当前仅对已验证的 OpenCLI 1.8.8 执行发现绑定;测试不依赖浏览器账户。

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,12 @@
2424
import io.github.easy4j.opencli.core.OpenCliAdapterChannel;
2525
import io.github.easy4j.opencli.meta.OpenCliMetaClient;
2626
import io.github.easy4j.opencli.core.OpenCliExecutor;
27+
import io.github.easy4j.opencli.core.OpenCliResult;
2728
import io.github.easy4j.opencli.facade.BrowserClient;
2829
import io.github.easy4j.opencli.facade.DesktopClient;
2930
import io.github.easy4j.opencli.facade.PublicApiClient;
31+
import java.util.List;
32+
import java.util.Map;
3033
import java.util.Objects;
3134
import lombok.Getter;
3235

@@ -105,6 +108,20 @@ public OpenCliCapabilitySnapshot discoverCapabilities(OpenCliHelpScope scope) {
105108
return capabilityDiscovery.refresh(scope);
106109
}
107110

111+
/**
112+
* Refreshes structured help and invokes an explicitly selected, validated local command.
113+
* @param scope verified help query containing the leaf
114+
* @param command exact leaf display path from help
115+
* @param session browser session identifier, or null when the command has no session
116+
* @param positionals user-supplied positionals in schema order, or null
117+
* @param options option spellings and values, with null for bare flags
118+
* @return local execution result
119+
*/
120+
public OpenCliResult invokeDiscovered(OpenCliHelpScope scope, String command, String session,
121+
List<String> positionals, Map<String, String> options) {
122+
return capabilityDiscovery.invoke(scope, command, session, positionals, options);
123+
}
124+
108125
// ----- 参考强类型门面(Desktop) -----
109126

110127
/** @return Codex 桌面适配器客户端 */
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
package io.github.easy4j.opencli.capability;
2+
3+
import io.github.easy4j.opencli.core.OpenCliArgSupport;
4+
import io.github.easy4j.opencli.parser.OpenCliHelpSchema;
5+
import io.github.easy4j.opencli.parser.OpenCliHelpSchema.Argument;
6+
import io.github.easy4j.opencli.util.OpenCliStrings;
7+
import java.util.ArrayList;
8+
import java.util.Collections;
9+
import java.util.HashSet;
10+
import java.util.LinkedHashMap;
11+
import java.util.List;
12+
import java.util.Map;
13+
import java.util.Objects;
14+
import java.util.Set;
15+
import java.util.regex.Pattern;
16+
import lombok.RequiredArgsConstructor;
17+
18+
/** Converts one explicitly selected help leaf into validated literal CLI arguments. */
19+
public final class OpenCliCapabilityCommand {
20+
private static final Pattern COMMAND_TOKEN = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_-]*");
21+
private static final Pattern OPTION_TOKEN = Pattern.compile("--[A-Za-z0-9][A-Za-z0-9-]*|-[A-Za-z0-9]");
22+
23+
private OpenCliCapabilityCommand() {
24+
}
25+
26+
/**
27+
* @param snapshot currently available structured help
28+
* @param command exact leaf display path from help, including any placeholders
29+
* @param session explicit browser session, or null for a non-browser leaf
30+
* @param positionals literal values in declared order, or null
31+
* @param options declared option spellings and values, with null values for bare flags
32+
* @return immutable literal arguments excluding the executable
33+
*/
34+
public static List<String> bind(OpenCliCapabilitySnapshot snapshot, String command, String session,
35+
List<String> positionals, Map<String, String> options) {
36+
Objects.requireNonNull(snapshot, "snapshot");
37+
Objects.requireNonNull(command, "command");
38+
if (snapshot.getStatus() != OpenCliCapabilitySnapshot.Status.AVAILABLE
39+
|| Objects.isNull(snapshot.getHelp()) || Objects.isNull(snapshot.getHelp().getSchema())) {
40+
throw new IllegalStateException("Current structured help is unavailable");
41+
}
42+
OpenCliHelpSchema scope = snapshot.getHelp().getSchema();
43+
OpenCliHelpSchema leaf = locateLeaf(scope, command);
44+
String[] path = command.split(" ", -1);
45+
if (path.length < 3 || !"opencli".equals(path[0])) {
46+
throw new IllegalArgumentException("The help command path cannot be bound");
47+
}
48+
49+
List<String> prefixOptions = new ArrayList<>();
50+
List<String> leafOptions = new ArrayList<>();
51+
appendOptions(scope, leaf, options, prefixOptions, leafOptions);
52+
53+
List<String> argv = new ArrayList<>();
54+
argv.add(path[1]);
55+
argv.addAll(prefixOptions);
56+
boolean sessionUsed = false;
57+
for (int index = 2; index < path.length; index++) {
58+
String token = path[index];
59+
if ("<session>".equals(token) && index == 2 && "browser".equals(path[1])) {
60+
if (OpenCliStrings.isBlank(session) || !COMMAND_TOKEN.matcher(session).matches()) {
61+
throw new IllegalArgumentException("A literal browser session identifier is required");
62+
}
63+
argv.add(session);
64+
sessionUsed = true;
65+
} else {
66+
if (!COMMAND_TOKEN.matcher(token).matches()) {
67+
throw new IllegalArgumentException("The help command path contains an unsupported token");
68+
}
69+
argv.add(token);
70+
}
71+
}
72+
if (!sessionUsed && Objects.nonNull(session)) {
73+
throw new IllegalArgumentException("This command has no browser session binding");
74+
}
75+
argv.addAll(leafOptions);
76+
List<String> values = OpenCliArgSupport.merge(null, positionals);
77+
validatePositionals(leaf.getPositionals(), values);
78+
if (!values.isEmpty()) {
79+
argv.add("--");
80+
argv.addAll(values);
81+
}
82+
return Collections.unmodifiableList(argv);
83+
}
84+
85+
private static OpenCliHelpSchema locateLeaf(OpenCliHelpSchema scope, String command) {
86+
if (command.equals(scope.getCommand()) && scope.getCommands().isEmpty()) {
87+
return scope;
88+
}
89+
return scope.getCommands().stream()
90+
.filter(child -> command.equals(child.getCommand()) && child.getCommands().isEmpty())
91+
.findFirst()
92+
.orElseThrow(() -> new IllegalArgumentException("The requested command is not a leaf in this help scope"));
93+
}
94+
95+
private static void validatePositionals(List<Argument> definitions, List<String> values) {
96+
int consumed = 0;
97+
for (Argument definition : definitions) {
98+
int count = Boolean.TRUE.equals(definition.getVariadic()) ? values.size() - consumed
99+
: Math.min(1, values.size() - consumed);
100+
if (count == 0 && Boolean.TRUE.equals(definition.getRequired())) {
101+
throw invalid(definition, "is required");
102+
}
103+
for (int index = 0; index < count; index++) {
104+
validateValue(definition, values.get(consumed++));
105+
}
106+
}
107+
if (consumed != values.size()) {
108+
throw new IllegalArgumentException("Too many positional arguments");
109+
}
110+
}
111+
112+
private static void appendOptions(OpenCliHelpSchema scope, OpenCliHelpSchema leaf, Map<String, String> options,
113+
List<String> prefix, List<String> local) {
114+
Map<String, Option> definitions = new LinkedHashMap<>();
115+
index(definitions, inherited(leaf.getGlobalOptions(), scope.getGlobalOptions()), prefix);
116+
index(definitions, inherited(leaf.getNamespaceOptions(), scope.getNamespaceOptions()), prefix);
117+
index(definitions, inherited(leaf.getCommonOptions(), scope.getCommonOptions()), local);
118+
index(definitions, leaf.getCommandOptions(), local);
119+
Set<Option> supplied = new HashSet<>();
120+
if (Objects.nonNull(options)) {
121+
new LinkedHashMap<>(options).forEach((flag, value) -> {
122+
Option option = definitions.get(flag);
123+
if (Objects.isNull(option)) {
124+
throw new IllegalArgumentException("An option identifier was not declared by help");
125+
}
126+
if (!supplied.add(option)) {
127+
throw invalid(option.argument, "was supplied more than once");
128+
}
129+
option.append(flag, value);
130+
});
131+
}
132+
for (Option option : new HashSet<>(definitions.values())) {
133+
if (Boolean.TRUE.equals(option.argument.getRequired()) && !supplied.contains(option)) {
134+
throw invalid(option.argument, "is required");
135+
}
136+
}
137+
}
138+
139+
private static List<Argument> inherited(List<Argument> own, List<Argument> parent) {
140+
return own.isEmpty() ? parent : own;
141+
}
142+
143+
private static void index(Map<String, Option> definitions, List<Argument> arguments, List<String> target) {
144+
for (Argument argument : arguments) {
145+
Option option = new Option(argument, target);
146+
String flags = argument.getFlags();
147+
if (OpenCliStrings.isBlank(flags)) {
148+
flags = "--" + argument.getName();
149+
}
150+
for (String flag : flags.split("[,\\s]+")) {
151+
if (OPTION_TOKEN.matcher(flag).matches() && Objects.nonNull(definitions.putIfAbsent(flag, option))) {
152+
throw invalid(argument, "has an ambiguous flag in this help scope");
153+
}
154+
}
155+
}
156+
}
157+
158+
private static void validateValue(Argument argument, String value) {
159+
if (value.indexOf(0) >= 0) {
160+
throw invalid(argument, "contains an invalid character");
161+
}
162+
if (!argument.getChoices().isEmpty() && !argument.getChoices().contains(value)) {
163+
throw invalid(argument, "must be one of the declared choices");
164+
}
165+
}
166+
167+
private static IllegalArgumentException invalid(Argument argument, String reason) {
168+
return new IllegalArgumentException("Argument '" + argument.getName() + "' " + reason);
169+
}
170+
171+
@RequiredArgsConstructor
172+
private static class Option {
173+
private final Argument argument;
174+
private final List<String> target;
175+
176+
private void append(String flag, String value) {
177+
String arity = argument.getTakesValue();
178+
String flags = argument.getFlags();
179+
if (Objects.isNull(arity)) {
180+
if (Boolean.TRUE.equals(argument.getValueRequired()) || Boolean.TRUE.equals(argument.getRequired())
181+
|| (Objects.nonNull(flags) && flags.indexOf('<') >= 0)) {
182+
arity = "required";
183+
} else if (OpenCliStrings.isBlank(flags) || flags.indexOf('[') >= 0) {
184+
arity = "optional";
185+
} else {
186+
arity = "none";
187+
}
188+
}
189+
if (flag.startsWith("--no-") || Boolean.TRUE.equals(argument.getNegate())) {
190+
arity = "none";
191+
}
192+
switch (arity) {
193+
case "required":
194+
if (Objects.isNull(value)) {
195+
throw invalid(argument, "requires a value");
196+
}
197+
validateValue(argument, value);
198+
OpenCliArgSupport.addOptionPair(target, flag, value);
199+
break;
200+
case "optional":
201+
if (Objects.isNull(value)) {
202+
target.add(flag);
203+
} else {
204+
validateValue(argument, value);
205+
if (flag.startsWith("--")) {
206+
OpenCliArgSupport.addOptionEquals(target, flag, value);
207+
} else if (!value.isEmpty()) {
208+
target.add(flag + value);
209+
} else {
210+
throw invalid(argument, "requires a long option spelling for an empty value");
211+
}
212+
}
213+
break;
214+
case "none":
215+
if (Objects.nonNull(value)) {
216+
throw invalid(argument, "does not take a value");
217+
}
218+
target.add(flag);
219+
break;
220+
default:
221+
throw invalid(argument, "has unknown value semantics");
222+
}
223+
}
224+
}
225+
}

‎src/main/java/io/github/easy4j/opencli/capability/OpenCliCapabilityDiscovery.java‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.time.Instant;
2424
import java.util.Collections;
2525
import java.util.EnumMap;
26+
import java.util.List;
2627
import java.util.Map;
2728
import java.util.Objects;
2829
import java.util.TreeMap;
@@ -31,6 +32,7 @@
3132

3233
/** Fixed, bounded metadata probes through the existing local subprocess runtime. */
3334
public final class OpenCliCapabilityDiscovery {
35+
private static final String VERIFIED_HELP_VERSION = "1.8.8";
3436
private static final int MAX_PROBE_OUTPUT_BYTES = 1024 * 1024;
3537
private static final long MAX_PROBE_MILLIS = 10_000;
3638
private static final long MAX_CLEANUP_MILLIS = 1_000;
@@ -73,12 +75,43 @@ public OpenCliCapabilitySnapshot refresh() {
7375
* @return current scoped observation or the explicit stale or failure status
7476
*/
7577
public OpenCliCapabilitySnapshot refresh(OpenCliHelpScope scope) {
78+
return refresh(scope, executor.getProperties());
79+
}
80+
81+
/**
82+
* Executes a leaf after querying and validating it against the same local configuration.
83+
* @param scope verified query containing the leaf
84+
* @param command exact leaf display path
85+
* @param session explicit browser session, or null
86+
* @param positionals literal arguments in schema order, or null
87+
* @param options declared flag spellings and values, or null
88+
* @return local execution result
89+
*/
90+
public OpenCliResult invoke(OpenCliHelpScope scope, String command, String session,
91+
List<String> positionals, Map<String, String> options) {
92+
OpenCliProperties configured = executor.getProperties();
93+
if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) {
94+
throw new UnsupportedOperationException("Discovered command execution requires a local process");
95+
}
96+
OpenCliProperties local = configured.copyForLocalCliExecution();
97+
OpenCliCapabilitySnapshot snapshot = refresh(scope, local);
98+
if (snapshot.getStatus() == Status.AVAILABLE && !VERIFIED_HELP_VERSION.equals(snapshot.getObservedVersion())) {
99+
throw new UnsupportedOperationException("Discovered command execution requires the verified help version");
100+
}
101+
List<String> argv = OpenCliCapabilityCommand.bind(snapshot, command, session, positionals, options);
102+
local.setExecutable(snapshot.getExecutable());
103+
try (OpenCliExecutor invocation = new OpenCliExecutor(local, executor.getProcessRuntime())) {
104+
return invocation.invokeLocalOnly(argv);
105+
}
106+
}
107+
108+
private OpenCliCapabilitySnapshot refresh(OpenCliHelpScope scope, OpenCliProperties configured) {
76109
Objects.requireNonNull(scope, "scope");
77110
long attempt;
78111
synchronized (this) {
79112
attempt = ++nextAttempt;
80113
}
81-
return publish(attempt, observe(scope));
114+
return publish(attempt, observe(scope, configured));
82115
}
83116

84117
private synchronized OpenCliCapabilitySnapshot publish(long attempt, OpenCliCapabilitySnapshot current) {
@@ -104,8 +137,7 @@ private synchronized OpenCliCapabilitySnapshot publish(long attempt, OpenCliCapa
104137
return current;
105138
}
106139

107-
private OpenCliCapabilitySnapshot observe(OpenCliHelpScope scope) {
108-
OpenCliProperties configured = executor.getProperties();
140+
private OpenCliCapabilitySnapshot observe(OpenCliHelpScope scope, OpenCliProperties configured) {
109141
OpenCliCapabilitySnapshot.OpenCliCapabilitySnapshotBuilder snapshot =
110142
OpenCliCapabilitySnapshot.builder().helpScope(scope).observedAt(Instant.now());
111143
if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) {
@@ -147,7 +179,7 @@ private OpenCliCapabilitySnapshot observe(OpenCliHelpScope scope) {
147179
}
148180
String version = versionOutput.group(1);
149181
snapshot.observedVersion(version);
150-
if (scope != OpenCliHelpScope.ROOT_HELP && !"1.8.8".equals(version)) {
182+
if (scope != OpenCliHelpScope.ROOT_HELP && !VERIFIED_HELP_VERSION.equals(version)) {
151183
return snapshot.status(Status.UNSUPPORTED).reason("UNVERIFIED_HELP_VERSION").build();
152184
}
153185
phase = "HELP";

‎src/main/java/io/github/easy4j/opencli/parser/OpenCliHelpParser.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ private static OpenCliHelpSchema.Argument argument(JsonNode node) {
128128
.type(text(node.path("type")))
129129
.takesValue(text(node.path("takes_value")))
130130
.required(bool(node.path("required")))
131+
.valueRequired(bool(node.path("valueRequired")))
131132
.negate(bool(node.path("negate")))
132133
.variadic(bool(node.path("variadic")))
133134
.choices(array(node.path("choices"), OpenCliHelpParser::requiredText))

‎src/main/java/io/github/easy4j/opencli/parser/OpenCliHelpSchema.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public static final class Argument {
3535
private final String type;
3636
private final String takesValue;
3737
private final Boolean required;
38+
private final Boolean valueRequired;
3839
private final Boolean negate;
3940
private final Boolean variadic;
4041
private final List<String> choices;

0 commit comments

Comments
 (0)