Skip to content

Commit 2eb97e4

Browse files
committed
Bind isolated OpenCLI invocation context to verified option scopes
1 parent 7aaac86 commit 2eb97e4

17 files changed

Lines changed: 486 additions & 14 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# OpenCLI 1.8.8 的单次调用上下文
2+
3+
使用 npm 发布包 `@jackwener/opencli@1.8.8`、Node 24.18.0 和隔离的 macOS arm64 用户目录。仅采集 `profile --help -f json` 和 `zhihu hot --help -f json`。原始 stdout 与 SHA-256 保存在 [结构化帮助样本目录](../../../../src/test/resources/opencli-contracts/v1/structured-help-1.8.8/)。
4+
5+
| 选项 | 证据 | SDK 绑定位置 |
6+
|---|---|---|
7+
| `--profile` | profile 与 Browser state 帮助中的 global_options | 根命令之前 |
8+
| `--window` | Browser state namespace_options 或站点 browser_common_options | 浏览器会话名之后,站点参数位 |
9+
| `--site-session`、`--keep-tab` | 已声明 browser=true 的 zhihu hot browser_common_options | 站点参数位 |
10+
| `--trace` | 站点 common_options | 站点参数位 |
11+
12+
[argv 预处理](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/cli-argv-preprocess.ts) 要求 Browser 之后先读到会话名。[站点适配器注册器](https://github.com/jackwener/OpenCLI/blob/8271afc67e8504bda94c147f446ee29775d08274/src/commanderAdapter.ts) 从根选项读取 profile 并单独读取 Browser 通用选项。SDK 在已验证的 `zhihu hot` 范围需要 profile 时,只取当前 profile 帮助的根参数定义。旧的 Browser 会话入口同步调整 `--window` 位置。
13+
14+
```java
15+
OpenCliInvocationContext defaults = OpenCliInvocationContext.builder().keepTab(true).build();
16+
properties.setInvocationDefaults(defaults);
17+
OpenCliInvocationContext request = OpenCliInvocationContext.builder().keepTab(false).build();
18+
client.invokeDiscovered(OpenCliHelpScope.SITE_ZHIHU_HOT, "opencli zhihu hot",
19+
null, null, null, request);
20+
```
21+
22+
显式上下文和调用选项覆盖默认值。两种显式输入冲突时拒绝提交。默认值只应用于发现后严格校验的本地调用。业务调用按调用者选中的叶子正常执行。SDK 不修改环境或全局 profile。只读诊断留待 C08 后续验收。

‎openspec/changes/add-opencli-context-and-diagnostics/tasks.md‎

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

2626
每项任务的完成记录包含:Requirement/Scenario、分支HEAD、测试命令、失败→通过证据、测试数/跳过数、退出码、报告位置。没有记录的任务保持未完成。
27+
28+
## OC-CTX-001/002 不可变上下文与作用域
29+
30+
提供不可变 `OpenCliInvocationContext` 与 `OpenCliProperties.invocationDefaults`。调用的显式值覆盖默认值,false 会生成有值的 `--keep-tab false`。冲突的显式选项或当前范围不支持的参数在业务进程启动前拒绝。Browser 全局、命名空间和叶子选项分别绑定。见 [锁定版证据与使用示例](evidence/2026-11-19-invocation-context.md)。
31+
32+
`OpenCliInvocationContextTest` 首先因缺少 API 无法编译。实现后用 JVM 子进程验证并发 profile/window、false 与默认继承、非 Browser scope 拒绝及显式冲突。仍需验收诊断与其只读边界。

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,21 @@ public OpenCliResult invokeDiscovered(OpenCliHelpScope scope, String command, St
122122
return capabilityDiscovery.invoke(scope, command, session, positionals, options);
123123
}
124124

125+
/**
126+
* Dispatches a schema-validated command with explicit invocation context.
127+
* @param scope verified help query containing the leaf
128+
* @param command exact leaf display path
129+
* @param session browser session identifier, or null
130+
* @param positionals literal arguments in schema order, or null
131+
* @param options explicit command flags, or null
132+
* @param context immutable overrides of client context defaults
133+
* @return local execution result
134+
*/
135+
public OpenCliResult invokeDiscovered(OpenCliHelpScope scope, String command, String session,
136+
List<String> positionals, Map<String, String> options, OpenCliInvocationContext context) {
137+
return capabilityDiscovery.invoke(scope, command, session, positionals, options, context);
138+
}
139+
125140
// ----- 参考强类型门面(Desktop) -----
126141

127142
/** @return Codex 桌面适配器客户端 */
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package io.github.easy4j.opencli;
2+
3+
import io.github.easy4j.opencli.util.OpenCliStrings;
4+
import java.util.Collections;
5+
import java.util.LinkedHashMap;
6+
import java.util.Locale;
7+
import java.util.Map;
8+
import java.util.Objects;
9+
import lombok.Builder;
10+
import lombok.Getter;
11+
12+
/** Immutable overrides for one schema-validated local invocation. */
13+
@Getter
14+
@Builder
15+
public final class OpenCliInvocationContext {
16+
public enum WindowMode { FOREGROUND, BACKGROUND }
17+
public enum SiteSession { EPHEMERAL, PERSISTENT }
18+
public enum TraceMode { OFF, ON, RETAIN_ON_FAILURE }
19+
20+
private final String profile;
21+
private final WindowMode window;
22+
private final SiteSession siteSession;
23+
private final Boolean keepTab;
24+
private final TraceMode trace;
25+
26+
/**
27+
* @param defaults client defaults
28+
* @param invocation explicit invocation context
29+
* @param options explicit command flags
30+
* @return effective options, preserving the distinction between missing and false
31+
*/
32+
public static Map<String, String> mergeOptions(OpenCliInvocationContext defaults, OpenCliInvocationContext invocation,
33+
Map<String, String> options) {
34+
Map<String, String> result = new LinkedHashMap<>();
35+
Map<String, String> explicit = new LinkedHashMap<>();
36+
if (Objects.nonNull(defaults)) {
37+
result.putAll(defaults.flags());
38+
}
39+
if (Objects.nonNull(options)) {
40+
explicit.putAll(options);
41+
}
42+
if (Objects.nonNull(invocation)) {
43+
invocation.flags().forEach((flag, value) -> {
44+
if (explicit.containsKey(flag) && !Objects.equals(explicit.get(flag), value)) {
45+
throw new IllegalArgumentException("Conflicting explicit invocation option " + flag);
46+
}
47+
explicit.put(flag, value);
48+
});
49+
}
50+
result.putAll(explicit);
51+
return Collections.unmodifiableMap(result);
52+
}
53+
54+
private Map<String, String> flags() {
55+
Map<String, String> flags = new LinkedHashMap<>();
56+
if (Objects.nonNull(profile)) {
57+
if (OpenCliStrings.isBlank(profile) || profile.indexOf(0) >= 0) {
58+
throw new IllegalArgumentException("profile must be a nonblank literal identifier");
59+
}
60+
flags.put("--profile", profile);
61+
}
62+
putEnum(flags, "--window", window);
63+
putEnum(flags, "--site-session", siteSession);
64+
if (Objects.nonNull(keepTab)) {
65+
flags.put("--keep-tab", keepTab.toString());
66+
}
67+
putEnum(flags, "--trace", trace);
68+
return flags;
69+
}
70+
71+
private static void putEnum(Map<String, String> flags, String name, Enum<?> value) {
72+
if (Objects.nonNull(value)) {
73+
flags.put(name, value.name().toLowerCase(Locale.ROOT).replace('_', '-'));
74+
}
75+
}
76+
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ public class OpenCliProperties {
3232
/** Maximum decoded HTTP response body bytes accepted from a remote Agent. */
3333
private int maxRemoteResponseBytes = 10 * 1024 * 1024;
3434
private String executable = "opencli";
35+
/** Defaults applied when dispatching a schema-validated local command. */
36+
private OpenCliInvocationContext invocationDefaults;
3537
private String workingDirectory;
3638
/** Total local queue and execution budget, or the remote HTTP transport budget. */
3739
private long commandTimeoutMillis = 300_000L;
@@ -60,6 +62,7 @@ public class OpenCliProperties {
6062
public OpenCliProperties copyForLocalCliExecution() {
6163
OpenCliProperties c = new OpenCliProperties();
6264
c.setExecutable(this.executable);
65+
c.setInvocationDefaults(this.invocationDefaults);
6366
c.setWorkingDirectory(this.workingDirectory);
6467
c.setCommandTimeoutMillis(this.commandTimeoutMillis);
6568
c.setMaxOutputBytes(this.maxOutputBytes);

‎src/main/java/io/github/easy4j/opencli/browser/OpenCliBrowserSession.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,10 @@ public final class OpenCliBrowserSession {
5858
private List<String> sessionPrefix() {
5959
List<String> tokens = new ArrayList<>();
6060
tokens.add("browser");
61+
tokens.add(sessionName);
6162
if (Objects.nonNull(windowMode)) {
6263
OpenCliArgSupport.addOptionPair(tokens, "--window", windowMode);
6364
}
64-
tokens.add(sessionName);
6565
return tokens;
6666
}
6767

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

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ private OpenCliCapabilityCommand() {
3333
*/
3434
public static List<String> bind(OpenCliCapabilitySnapshot snapshot, String command, String session,
3535
List<String> positionals, Map<String, String> options) {
36+
return bind(snapshot, command, session, positionals, options, Collections.emptyList());
37+
}
38+
39+
static List<String> bind(OpenCliCapabilitySnapshot snapshot, String command, String session,
40+
List<String> positionals, Map<String, String> options, List<Argument> supplementaryGlobals) {
3641
Objects.requireNonNull(snapshot, "snapshot");
3742
Objects.requireNonNull(command, "command");
3843
if (snapshot.getStatus() != OpenCliCapabilitySnapshot.Status.AVAILABLE
@@ -46,13 +51,17 @@ public static List<String> bind(OpenCliCapabilitySnapshot snapshot, String comma
4651
throw new IllegalArgumentException("The help command path cannot be bound");
4752
}
4853

49-
List<String> prefixOptions = new ArrayList<>();
54+
List<String> rootOptions = new ArrayList<>();
55+
List<String> namespaceOptions = new ArrayList<>();
5056
List<String> leafOptions = new ArrayList<>();
51-
appendOptions(scope, leaf, options, prefixOptions, leafOptions);
57+
appendOptions(scope, leaf, options, supplementaryGlobals, rootOptions, namespaceOptions, leafOptions);
5258

53-
List<String> argv = new ArrayList<>();
59+
List<String> argv = new ArrayList<>(rootOptions);
5460
argv.add(path[1]);
55-
argv.addAll(prefixOptions);
61+
boolean browserSessionPath = "browser".equals(path[1]) && "<session>".equals(path[2]);
62+
if (!browserSessionPath) {
63+
argv.addAll(namespaceOptions);
64+
}
5665
boolean sessionUsed = false;
5766
for (int index = 2; index < path.length; index++) {
5867
String token = path[index];
@@ -61,6 +70,7 @@ public static List<String> bind(OpenCliCapabilitySnapshot snapshot, String comma
6170
throw new IllegalArgumentException("A literal browser session identifier is required");
6271
}
6372
argv.add(session);
73+
argv.addAll(namespaceOptions);
6474
sessionUsed = true;
6575
} else {
6676
if (!COMMAND_TOKEN.matcher(token).matches()) {
@@ -110,11 +120,15 @@ private static void validatePositionals(List<Argument> definitions, List<String>
110120
}
111121

112122
private static void appendOptions(OpenCliHelpSchema scope, OpenCliHelpSchema leaf, Map<String, String> options,
113-
List<String> prefix, List<String> local) {
123+
List<Argument> supplementaryGlobals, List<String> root, List<String> namespace, List<String> local) {
114124
Map<String, Option> definitions = new LinkedHashMap<>();
115-
index(definitions, inherited(leaf.getGlobalOptions(), scope.getGlobalOptions()), prefix);
116-
index(definitions, inherited(leaf.getNamespaceOptions(), scope.getNamespaceOptions()), prefix);
125+
index(definitions, inherited(leaf.getGlobalOptions(), scope.getGlobalOptions()), root);
126+
index(definitions, supplementaryGlobals, root);
127+
index(definitions, inherited(leaf.getNamespaceOptions(), scope.getNamespaceOptions()), namespace);
117128
index(definitions, inherited(leaf.getCommonOptions(), scope.getCommonOptions()), local);
129+
if (Boolean.TRUE.equals(leaf.getBrowser())) {
130+
index(definitions, inherited(leaf.getBrowserCommonOptions(), scope.getBrowserCommonOptions()), local);
131+
}
118132
index(definitions, leaf.getCommandOptions(), local);
119133
Set<Option> supplied = new HashSet<>();
120134
if (Objects.nonNull(options)) {

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

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.github.easy4j.opencli.capability;
22

33
import io.github.easy4j.opencli.OpenCliExecutionTarget;
4+
import io.github.easy4j.opencli.OpenCliInvocationContext;
45
import io.github.easy4j.opencli.OpenCliProperties;
56
import io.github.easy4j.opencli.capability.OpenCliCapabilitySnapshot.Status;
67
import io.github.easy4j.opencli.core.OpenCliExecutionDetails.TerminationReason;
@@ -10,6 +11,7 @@
1011
import io.github.easy4j.opencli.exception.OpenCliTimeoutException;
1112
import io.github.easy4j.opencli.parser.OpenCliHelpParser;
1213
import io.github.easy4j.opencli.parser.OpenCliHelpResult;
14+
import io.github.easy4j.opencli.parser.OpenCliHelpSchema.Argument;
1315
import io.github.easy4j.opencli.util.OpenCliStrings;
1416
import java.io.IOException;
1517
import java.nio.ByteBuffer;
@@ -89,22 +91,63 @@ public OpenCliCapabilitySnapshot refresh(OpenCliHelpScope scope) {
8991
*/
9092
public OpenCliResult invoke(OpenCliHelpScope scope, String command, String session,
9193
List<String> positionals, Map<String, String> options) {
94+
return invoke(scope, command, session, positionals, options, null);
95+
}
96+
97+
/**
98+
* Executes a local leaf with immutable invocation overrides.
99+
* @param scope verified query containing the leaf
100+
* @param command exact leaf display path
101+
* @param session explicit browser session, or null
102+
* @param positionals literal arguments in schema order, or null
103+
* @param options declared flags and values, or null
104+
* @param context invocation overrides, or null
105+
* @return local execution result
106+
*/
107+
public OpenCliResult invoke(OpenCliHelpScope scope, String command, String session,
108+
List<String> positionals, Map<String, String> options, OpenCliInvocationContext context) {
92109
OpenCliProperties configured = executor.getProperties();
93110
if (configured.getExecutionTarget() != OpenCliExecutionTarget.LOCAL_PROCESS) {
94111
throw new UnsupportedOperationException("Discovered command execution requires a local process");
95112
}
96113
OpenCliProperties local = configured.copyForLocalCliExecution();
114+
Map<String, String> effectiveOptions =
115+
OpenCliInvocationContext.mergeOptions(local.getInvocationDefaults(), context, options);
97116
OpenCliCapabilitySnapshot snapshot = refresh(scope, local);
98117
if (snapshot.getStatus() == Status.AVAILABLE && !VERIFIED_HELP_VERSION.equals(snapshot.getObservedVersion())) {
99118
throw new UnsupportedOperationException("Discovered command execution requires the verified help version");
100119
}
101-
List<String> argv = OpenCliCapabilityCommand.bind(snapshot, command, session, positionals, options);
120+
List<Argument> globals = verifiedAdapterGlobals(snapshot, local, effectiveOptions);
121+
List<String> argv = OpenCliCapabilityCommand.bind(snapshot, command, session, positionals, effectiveOptions, globals);
102122
local.setExecutable(snapshot.getExecutable());
103123
try (OpenCliExecutor invocation = new OpenCliExecutor(local, executor.getProcessRuntime())) {
104124
return invocation.invokeLocalOnly(argv);
105125
}
106126
}
107127

128+
private List<Argument> verifiedAdapterGlobals(OpenCliCapabilitySnapshot snapshot, OpenCliProperties local,
129+
Map<String, String> options) {
130+
if (snapshot.getStatus() != Status.AVAILABLE || snapshot.getHelpScope() != OpenCliHelpScope.SITE_ZHIHU_HOT
131+
|| !options.containsKey("--profile") || !Boolean.TRUE.equals(snapshot.getHelp().getSchema().getBrowser())) {
132+
return Collections.emptyList();
133+
}
134+
if (snapshot.getHelp().getSchema().getGlobalOptions().stream().anyMatch(OpenCliCapabilityDiscovery::isProfileFlag)) {
135+
return Collections.emptyList();
136+
}
137+
OpenCliCapabilitySnapshot metadata = refresh(OpenCliHelpScope.META_PROFILE, local);
138+
if (metadata.getStatus() != Status.AVAILABLE) {
139+
throw new IllegalStateException("Current global profile help is unavailable");
140+
}
141+
Argument profile = metadata.getHelp().getSchema().getGlobalOptions().stream()
142+
.filter(OpenCliCapabilityDiscovery::isProfileFlag)
143+
.findFirst().orElseThrow(() -> new IllegalStateException("Current global profile flag is unverified"));
144+
return Collections.singletonList(profile);
145+
}
146+
147+
private static boolean isProfileFlag(Argument argument) {
148+
return "profile".equals(argument.getName()) && "--profile <name>".equals(argument.getFlags());
149+
}
150+
108151
private OpenCliCapabilitySnapshot refresh(OpenCliHelpScope scope, OpenCliProperties configured) {
109152
Objects.requireNonNull(scope, "scope");
110153
long attempt;

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,11 @@ public enum OpenCliHelpScope {
1515
BROWSER_GET("opencli browser <session> get", null, null, "browser", "browser", "fixture", "get"),
1616
BROWSER_STATE("opencli browser <session> state", "state", null, "browser", "browser", "fixture", "state"),
1717
META_AUTH("opencli auth", null, null, "auth", "auth"),
18+
META_PROFILE("opencli profile", null, null, "profile", "profile"),
1819
META_LIST("opencli list", "list", null, null, "list"),
1920
SITE_NPM(null, null, "npm", null, "npm"),
20-
SITE_NPM_SEARCH("opencli npm search", "search", "npm", null, "npm", "search");
21+
SITE_NPM_SEARCH("opencli npm search", "search", "npm", null, "npm", "search"),
22+
SITE_ZHIHU_HOT("opencli zhihu hot", "hot", "zhihu", null, "zhihu", "hot");
2123

2224
private final String command;
2325
private final String name;

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,15 @@ private static OpenCliHelpSchema schema(JsonNode node) {
106106
.command(command)
107107
.namespace(text(node.path("namespace")))
108108
.site(site)
109+
.browser(bool(node.path("browser")))
109110
.aliases(array(node.path("aliases"), OpenCliHelpParser::requiredName))
110111
.commands(array(node.path("commands"), OpenCliHelpParser::schema))
111112
.positionals(array(node.path("positionals"), OpenCliHelpParser::argument))
112113
.commandOptions(array(node.path("command_options"), OpenCliHelpParser::argument))
113114
.namespaceOptions(array(node.path("namespace_options"), OpenCliHelpParser::argument))
114115
.globalOptions(array(node.path("global_options"), OpenCliHelpParser::argument))
115116
.commonOptions(array(node.path("common_options"), OpenCliHelpParser::argument))
117+
.browserCommonOptions(array(node.path("browser_common_options"), OpenCliHelpParser::argument))
116118
.sourceJson(node.toString())
117119
.build();
118120
}

0 commit comments

Comments
 (0)