Skip to content

Commit 2555ab9

Browse files
committed
Retain status and exit provenance for legacy collect
Refs #5 (cherry picked from commit 106585e)
1 parent 869bef6 commit 2555ab9

9 files changed

Lines changed: 171 additions & 32 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,7 @@ Notes:
194194
- A legacy HTTP `/collect` reply must contain a JSON boolean `success`. Invalid envelopes raise `OpenCliRemoteProtocolException`, which extends `OpenCliExecutableFailureException`. A valid reply with `success: true` and omitted or null `items` still returns `[]`.
195195
- Legacy HTTP argv dispatch accepts SDK-listed adapters and one subcommand. Root metadata, Browser sessions, external passthrough, repeated options, `--`, and tokens whose spacing or leading dash cannot be preserved are rejected before HTTP. Place positionals before options. Use local execution for commands that need the original argv. A deployment with its own adapter contract can use the explicit `OpenCliCollectRequest` API.
196196
- A collect timeout raises `OpenCliRemoteTimeoutException`. After dispatch to the HTTP transport, `isRemoteOutcomeUnknown()` is true. Collect does not automatically retry or follow redirects.
197+
- 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.
197198
- `execution-target=REMOTE_AGENT_HTTP` makes the availability probe report `SKIPPED_REMOTE_MODE` (treated as startable).
198199

199200
<a id="8-core-usage"></a>

‎README.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ cli.gemini().deepResearch("topic",
193193
- 旧版 HTTP `/collect` 响应须包含 JSON 布尔字段 `success`。无效响应抛出 `OpenCliRemoteProtocolException`,它继承 `OpenCliExecutableFailureException`。当 `success: true` 且 `items` 缺失或为 null 时,仍返回 `[]`。
194194
- 旧版 HTTP argv 调用仅接收 SDK 清单中的适配器及其子命令。根命令、Browser 会话、外部程序透传、重复选项、`--` 以及无法保留边界空格或前导短横的参数会在发请求前被拒绝。位置参数应在选项前。需要原样传递 argv 时使用本地执行,已有自定义 Agent 契约时可用显式 `OpenCliCollectRequest` API。
195195
- 远程调用超时抛出 `OpenCliRemoteTimeoutException`。请求提交给 HTTP 传输后,`isRemoteOutcomeUnknown()` 为 true。客户端不会自动重试或跟随重定向。
196+
- 通过结果或异常的 `getPartialResult()` 调用 `getRemoteExecutionDetails()`,查看 HTTP 状态、Agent 业务状态和 `items` 的来源。`getExitCode()` 的 0/1 是兼容映射。HTTP 或协议失败快照没有退出码。仅在开启原文捕获时,失败快照才携带已通过字节上限检查的响应正文。
196197
- `execution-target=REMOTE_AGENT_HTTP` 时可用性探测报告 `SKIPPED_REMOTE_MODE`(视为可启动)。
197198

198199
<a id="8-core-usage"></a>

‎openspec/changes/harden-opencli-remote-collect/tasks.md‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
## 2. 最小适配修复
1414

1515
- [ ] 2.1 引入显式 legacy capability guard 和保真转换子集,避免无条件解析任意 argv。
16-
- [ ] 2.2 区分 HTTP/协议/命令失败、synthetic exit 与未观察的退出码。
16+
- [x] 2.2 区分 HTTP、协议与命令失败,保留兼容退出码及其来源。见 OC-REMOTE-003/004 验证。
1717
- [ ] 2.3 使 body/timeout 有界并实现可测试的显式 header 配置,保持 TLS。
1818

1919
## 3. 三线与安全
@@ -55,3 +55,10 @@ JDK 17 基线在 42 项 HTTP 用例中有 4 项失败,覆盖多字节响应超
5555
JDK 17 基线中,chunked 响应每 125 ms 持续发送数据,900 ms 的原套接字超时未能终止调用,测试在 3 秒断言窗口失败。使用现有 Apache HttpClient 的可取消请求后,连接池等待、建连、HTTP 头及有界读取共享一个单调时钟预算。超时只中止当前请求,已提交传输的调用返回远端结果未知,无自动重试。原始预算耗尽且尚未提交时返回未发送。当前响应池可继续处理后续调用,并保留 JVM 信任配置。另有 307 回归验证不会转发采集请求。
5656

5757
本轮验证的是 SDK 侧 HTTP 传输与回环 HTTP 桩。真实部署、系统 DNS 解析器或本地解析处理的执行时延,以及认证 header 仍需独立验收。
58+
59+
60+
## OC-REMOTE-003/004 状态与退出码来源
61+
62+
对基线加入结果证据断言后,HTTP 200 业务失败、HTTP 503、缺省 `items` 和十种畸形响应共 13 项未能提供所需证据。修改后,`getRemoteExecutionDetails()` 保留 HTTP 状态、Agent 业务状态、失败层级和 `items` 来源。兼容退出值标记为 `SYNTHETIC_COMPATIBILITY`,观测到的远端退出码为空。HTTP 或协议失败快照保留真实状态且退出值为空,按原文捕获开关提供通过字节上限检查的完整响应。超限和超时沿用原有异常及保留策略。
63+
64+
验证覆盖 503 的 HTML 响应、可选原文与安全诊断、合法业务失败和协议失败。显式诊断导出先输出退出码来源,再输出兼容退出值,避免截断产生缺少来源的数字。

‎src/main/java/io/github/easy4j/opencli/core/OpenCliDiagnosticExport.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,12 @@ public static String export(OpenCliResult result, int maxBytes) {
3434
}
3535

3636
Integer exitCode = result.getExitCode();
37+
OpenCliRemoteExecutionDetails remote = result.getRemoteExecutionDetails();
3738
String[] fields = {
3839
"success=" + result.isSuccess() + "\n",
40+
Objects.isNull(remote) ? "" : "exitCodeSource=" + remote.getExitCodeSource() + "\n",
3941
Objects.isNull(exitCode) ? "" : "exitCode=" + exitCode + "\n",
42+
Objects.isNull(remote) ? "" : "httpStatus=" + remote.getHttpStatus() + "\n",
4043
characterCount("stdoutChars", result.getStdout()),
4144
characterCount("stderrChars", result.getStderr()),
4245
characterCount("rawHttpChars", result.getRemoteRawHttpBody())
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package io.github.easy4j.opencli.core;
2+
3+
import java.util.Objects;
4+
import java.util.OptionalInt;
5+
import lombok.Builder;
6+
import lombok.Getter;
7+
8+
/** Observable evidence from an HTTP response to a legacy collect request. */
9+
@Getter
10+
@Builder
11+
public final class OpenCliRemoteExecutionDetails {
12+
13+
/** The layer that supplied the failed or successful result. */
14+
public enum Outcome { SUCCESS, COMMAND_FAILURE, HTTP_FAILURE, PROTOCOL_FAILURE }
15+
16+
/** Origin of the compatibility exit code on the associated result. */
17+
public enum ExitCodeSource { SYNTHETIC_COMPATIBILITY, UNAVAILABLE }
18+
19+
/** Origin of the items projected to stdout. */
20+
public enum ItemsSource { RESPONSE, ABSENT_DEFAULT, NULL_DEFAULT, UNAVAILABLE }
21+
22+
private final int httpStatus;
23+
private final Outcome outcome;
24+
/** Null when a business status was unavailable or its envelope failed validation. */
25+
private final Boolean legacySuccess;
26+
private final ItemsSource itemsSource;
27+
28+
/** @return whether the associated 0/1 exit code is a mapping of the business status */
29+
public ExitCodeSource getExitCodeSource() {
30+
return Objects.isNull(legacySuccess) ? ExitCodeSource.UNAVAILABLE : ExitCodeSource.SYNTHETIC_COMPATIBILITY;
31+
}
32+
33+
/** @return empty because the legacy collect response does not report a process exit */
34+
public OptionalInt getObservedRemoteExitCode() {
35+
return OptionalInt.empty();
36+
}
37+
}

‎src/main/java/io/github/easy4j/opencli/core/OpenCliResult.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,6 @@ public class OpenCliResult {
4949

5050
/** Bounded local execution evidence, when available. */
5151
private final OpenCliExecutionDetails executionDetails;
52+
/** Evidence from a legacy HTTP collect response, if available. */
53+
private final OpenCliRemoteExecutionDetails remoteExecutionDetails;
5254
}
Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,20 @@
11
package io.github.easy4j.opencli.exception;
22

3+
import io.github.easy4j.opencli.core.OpenCliResult;
4+
35
/** 远端 /collect 响应不符合协议,保留既有远程异常捕获类型。 */
46
public final class OpenCliRemoteProtocolException extends OpenCliExecutableFailureException {
57

68
public OpenCliRemoteProtocolException(String message, String correlationId) {
7-
super(message + " correlationId=" + correlationId, null);
9+
this(message, correlationId, null);
10+
}
11+
12+
/**
13+
* @param message safe summary of the protocol failure
14+
* @param correlationId SDK request correlation identifier
15+
* @param partialResult bounded HTTP response evidence
16+
*/
17+
public OpenCliRemoteProtocolException(String message, String correlationId, OpenCliResult partialResult) {
18+
super(message + " correlationId=" + correlationId, null, partialResult);
819
}
920
}

‎src/main/java/io/github/easy4j/opencli/remote/OpenCliRemoteAgentHttpClient.java‎

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
import tools.jackson.databind.json.JsonMapper;
88
import io.github.easy4j.opencli.OpenCliProperties;
99
import io.github.easy4j.opencli.core.OpenCliOutputParser;
10+
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails;
11+
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails.ItemsSource;
12+
import io.github.easy4j.opencli.core.OpenCliRemoteExecutionDetails.Outcome;
1013
import io.github.easy4j.opencli.core.OpenCliResult;
1114
import io.github.easy4j.opencli.exception.OpenCliExecutableFailureException;
1215
import io.github.easy4j.opencli.exception.OpenCliNonZeroExitException;
@@ -139,9 +142,10 @@ public OpenCliResult collect(OpenCliCollectRequest request, long submittedAtNano
139142
if (status < 200 || status >= 300) {
140143
log.warn("Agent HTTP non-2xx correlationId={} status={} responseChars={}",
141144
correlationId, status, respBody.length());
142-
throw failure("Agent HTTP " + status, correlationId);
145+
throw new OpenCliExecutableFailureException("Agent HTTP " + status + " correlationId=" + correlationId,
146+
null, failureSnapshot(status, Outcome.HTTP_FAILURE, respBody));
143147
}
144-
return mapResponse(respBody, correlationId);
148+
return mapResponse(status, respBody, correlationId);
145149
} catch (JacksonException e) {
146150
log.warn("Agent response parse failed correlationId={}", correlationId);
147151
throw failure("Failed to parse agent response", correlationId);
@@ -232,63 +236,75 @@ private static OpenCliExecutableFailureException failure(String message, String
232236
return new OpenCliExecutableFailureException(message + " correlationId=" + correlationId, null);
233237
}
234238

235-
private OpenCliResult mapResponse(String respBody, String correlationId) {
239+
private OpenCliResult mapResponse(int status, String respBody, String correlationId) {
236240
String rawCapture = captureRawIfEnabled(respBody);
237241
JsonNode envelope;
238242
try {
239243
envelope = ENVELOPE_READER.readTree(respBody);
240244
} catch (JacksonException e) {
241245
log.warn("Agent response envelope parse failed correlationId={} responseChars={}",
242246
correlationId, respBody.length());
243-
throw new OpenCliRemoteProtocolException("Failed to parse agent response envelope", correlationId);
247+
throw new OpenCliRemoteProtocolException("Failed to parse agent response envelope", correlationId,
248+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, respBody));
244249
}
245250
if (Objects.isNull(envelope) || !envelope.isObject() || !envelope.path("success").isBoolean()) {
246251
log.warn("Agent response envelope status invalid correlationId={} responseChars={}",
247252
correlationId, respBody.length());
248-
throw new OpenCliRemoteProtocolException("Invalid agent response envelope status", correlationId);
253+
throw new OpenCliRemoteProtocolException("Invalid agent response envelope status", correlationId,
254+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, respBody));
249255
}
250256
JsonNode error = envelope.path("error");
251257
if (!error.isMissingNode() && !error.isNull() && !error.isTextual()) {
252258
log.warn("Agent response envelope error field invalid correlationId={} responseChars={}",
253259
correlationId, respBody.length());
254-
throw new OpenCliRemoteProtocolException("Invalid agent response envelope error field", correlationId);
260+
throw new OpenCliRemoteProtocolException("Invalid agent response envelope error field", correlationId,
261+
failureSnapshot(status, Outcome.PROTOCOL_FAILURE, respBody));
255262
}
256263
boolean success = envelope.path("success").booleanValue();
257264
String err = error.isTextual() ? error.asText() : "";
258265
JsonNode items = envelope.path("items");
259266
String stdout;
267+
ItemsSource itemsSource;
260268
if (items.isMissingNode() || items.isNull()) {
261269
stdout = "[]";
262-
} else if (items.isArray()) {
263-
stdout = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(items);
270+
itemsSource = items.isMissingNode() ? ItemsSource.ABSENT_DEFAULT : ItemsSource.NULL_DEFAULT;
264271
} else {
265-
stdout = items.toPrettyString();
272+
stdout = items.isArray() ? MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(items)
273+
: items.toPrettyString();
274+
itemsSource = ItemsSource.RESPONSE;
266275
}
267276
OpenCliParsedFields parsed = OpenCliOutputParser.parseBestEffort(stdout, err);
268-
if (!success) {
269-
log.warn(
270-
"Agent collect reported failure correlationId={} errorChars={} stdoutLength={}",
271-
correlationId,
272-
err.length(),
273-
stdout.length());
274-
OpenCliResult failed =
275-
OpenCliResult.builder()
276-
.stdout(stdout)
277-
.stderr(err)
278-
.exitCode(1)
279-
.success(false)
280-
.parsed(parsed)
281-
.remoteRawHttpBody(rawCapture)
282-
.build();
283-
throw new OpenCliNonZeroExitException("OpenCLI agent reported failure correlationId=" + correlationId, failed);
284-
}
285-
return OpenCliResult.builder()
277+
OpenCliResult result = OpenCliResult.builder()
286278
.stdout(stdout)
287-
.stderr(err.isEmpty() ? "" : err)
288-
.exitCode(0)
289-
.success(true)
279+
.stderr(err)
280+
.exitCode(success ? 0 : 1)
281+
.success(success)
290282
.parsed(parsed)
291283
.remoteRawHttpBody(rawCapture)
284+
.remoteExecutionDetails(OpenCliRemoteExecutionDetails.builder()
285+
.httpStatus(status)
286+
.legacySuccess(success)
287+
.outcome(success ? Outcome.SUCCESS : Outcome.COMMAND_FAILURE)
288+
.itemsSource(itemsSource)
289+
.build())
290+
.build();
291+
if (!success) {
292+
log.warn("Agent collect reported failure correlationId={} errorChars={} stdoutLength={}",
293+
correlationId, err.length(), stdout.length());
294+
throw new OpenCliNonZeroExitException("OpenCLI agent reported failure correlationId=" + correlationId, result);
295+
}
296+
return result;
297+
}
298+
299+
private OpenCliResult failureSnapshot(int status, Outcome outcome, String respBody) {
300+
return OpenCliResult.builder()
301+
.success(false)
302+
.remoteRawHttpBody(captureRawIfEnabled(respBody))
303+
.remoteExecutionDetails(OpenCliRemoteExecutionDetails.builder()
304+
.httpStatus(status)
305+
.outcome(outcome)
306+
.itemsSource(ItemsSource.UNAVAILABLE)
307+
.build())
292308
.build();
293309
}
294310

0 commit comments

Comments
 (0)