Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/sdk-java/qwencode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,15 @@ The client permits only one active prompt identity per Session while allowing di

## Legacy stdio API

The existing `com.alibaba.qwen.code.cli` API remains available:
The existing `com.alibaba.qwen.code.cli` API remains available.

If a custom `SessionEventConsumers.onControlRequest` handler throws, times out, returns no response envelope, returns a missing or mismatched request ID, returns an unknown response subtype, or returns a success envelope without a response payload, the session sends a correlated `control_response` error to the CLI. The error preserves the original `request_id`, so a request still pending in the CLI can fail when the reply arrives. Timeout errors name the handler's configured budget. Unexpected handler failures include the exception type after bounded wrapper unwrapping but keep the host exception's message and full cause chain in the SDK log. Validation errors describe the invalid response, including both IDs for a correlation failure. Valid success responses and error responses without a success payload are forwarded unchanged.

The default simple consumer has two timeout layers. If the inner `onPermissionRequestTimeout` expires, it logs the failure and returns `Behavior.defaultBehavior()` (deny) in a correlated `subtype: "success"` envelope. If `onOtherControlRequestTimeout` expires, it instead returns a success envelope with an empty, non-null response payload. Neither inner fallback emits a timeout error. Only expiry of the session's outer `onControlRequestTimeout` wait produces the correlated `Control request handler timed out after ...` error. The default outer limit is 180 seconds and the default inner limits are 60 seconds; the session uses its own 60-second fallback when the outer timeout method returns null.

CLI deadlines depend on the request path: leader and workflow tool approvals default to 60 seconds (unless configured otherwise), while teammate approvals use the generic 30-second request deadline. Choose the outer SDK limit below the shortest applicable CLI deadline, leaving time for reply delivery. Keeping the inner limits below that outer limit lets their normal fallback replies settle first; it does not turn them into errors. Letting the outer limit expire first produces an error but can discard an inner callback's later approval. These settings do not shorten CLI deadlines or change any default fallback behavior.

The legacy `ProcessTransport` currently logs callback write failures inside its asynchronous read loop and can return from `sendPrompt` without consuming a result. A successfully constructed error response therefore does not guarantee delivery after the process input stream has closed. The broader asynchronous-wait behavior is tracked separately in [#8835: java-runnable-runandwait-swallows-timeout](https://github.com/QwenLM/qwen-code/issues/8835#issuecomment-5565612693).

```java
public static void runSimpleExample() {
Expand Down Expand Up @@ -348,6 +356,8 @@ For proper operation, the following timeout relationships should be maintained:
- `onAssistantMessageTimeout` return value should be greater than `onTextTimeout`, `onThinkingTimeout`, `onToolUseTimeout`, `onToolResultTimeout`, and `onOtherContentTimeout` return values
- `onControlRequestTimeout` return value should be greater than `onPermissionRequestTimeout` and `onOtherControlRequestTimeout` return values

For control requests, `inner callback timeout < onControlRequestTimeout` lets the default inner fallback complete first: permission denial or an empty other-control payload, both with a success envelope. Only the outer wait's expiry produces a timeout error. Keep that outer limit below the shortest CLI deadline the handler serves (30 seconds for teammate approvals; 60 seconds by default for leader/workflow approvals), with a margin for reply delivery. An outer timeout can discard a later inner approval.

### Transport Options

The `TransportOptions` class allows configuration of how the SDK communicates with the Qwen Code CLI:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ public static class Response<R> {
* The subtype of the response.
*/
private String subtype = "success";
/**
* The error message or structured error for an error response.
*/
private Object error;
/**
* The actual response.
*/
Expand Down Expand Up @@ -115,6 +119,26 @@ public Response<R> setSubtype(String subtype) {
return this;
}

/**
* Gets the error message or structured error.
*
* @return The error, or null for a successful response
*/
public Object getError() {
return error;
}

/**
* Sets the error message or structured error.
*
* @param error The error message or structured error
* @return This instance for method chaining
*/
public Response<R> setError(Object error) {
this.error = error;
return this;
}

/**
* Gets the actual response.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.alibaba.qwen.code.cli.session;

import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
Expand Down Expand Up @@ -235,20 +238,59 @@ public void sendPrompt(String prompt, SessionEventConsumers sessionEventConsumer
}
return false;
} else if ("control_request".equals(messageType)) {
CLIControlResponse<? extends ControlResponsePayload> controlResponse;
String requestId = jsonObject.getString("request_id");
CLIControlResponse<? extends ControlResponsePayload> controlResponse = null;
Timeout controlRequestTimeout = defaultEventTimeout;
String error = null;
try {
CLIControlRequest<? extends ControlRequestPayload> controlRequest = jsonObject.to(
new TypeReference<CLIControlRequest<? extends ControlRequestPayload>>() {});
controlRequestTimeout = Optional.ofNullable(sessionEventConsumers.onControlRequestTimeout(this, controlRequest))
.orElse(defaultEventTimeout);
controlResponse = MyConcurrentUtils.runAndWait(
() -> sessionEventConsumers.onControlRequest(this, controlRequest),
Optional.ofNullable(sessionEventConsumers.onControlRequestTimeout(this, controlRequest)).orElse(defaultEventTimeout));
() -> sessionEventConsumers.onControlRequest(this, controlRequest), controlRequestTimeout);
} catch (Exception e) {
log.error("Failed to process control request", e);
Throwable cause = e;
if (cause instanceof ExecutionException && cause.getCause() != null) {
cause = cause.getCause();
// MyConcurrentUtils adds one RuntimeException below ExecutionException.
if (cause.getClass() == RuntimeException.class && cause.getCause() != null) {
cause = cause.getCause();
Comment thread
Afloat16 marked this conversation as resolved.
Resolved
}
}
error = e instanceof TimeoutException
? "Control request handler timed out after " + controlRequestTimeout.getValue() + " "
+ controlRequestTimeout.getUnit().name().toLowerCase(Locale.ROOT)
: "Control request handler failed (" + cause.getClass().getSimpleName() + "); see SDK logs for details";
log.error(error, e);
}
if (error == null) {
if (controlResponse == null || controlResponse.getResponse() == null) {
error = "Control request handler returned no response";
} else {
CLIControlResponse.Response<? extends ControlResponsePayload> response = controlResponse.getResponse();
if (response.getRequestId() == null || !response.getRequestId().equals(requestId)) {
error = "Control request handler returned an uncorrelated response: expected request_id="
+ requestId + ", got " + response.getRequestId();
} else if ("success".equals(response.getSubtype()) && response.getResponse() == null) {
error = "Control request handler returned success without a response payload";
} else if (!"success".equals(response.getSubtype()) && !"error".equals(response.getSubtype())) {
error = "Control request handler returned an unknown response subtype; expected success or error";
}
}
if (error != null) {
log.error(error);
}
}
if (error != null) {
controlResponse = new CLIControlResponse<>();
controlResponse.createResponse()
.setRequestId(requestId)
.setSubtype("error")
.setError(error);
}
try {
transport.inputNoWaitResponse(Optional.ofNullable(controlResponse).map(CLIControlResponse::toString)
.orElse(new CLIControlResponse<ControlResponsePayload>().toString()));
transport.inputNoWaitResponse(controlResponse.toString());
} catch (Exception e) {
throw new RuntimeException("Failed to send control response", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,10 @@ public void onControlResponse(Session session, CLIControlResponse<?> cliControlR
@Override
public CLIControlResponse<? extends ControlResponsePayload> onControlRequest(Session session, CLIControlRequest<?> cliControlRequest) {
logger.info("Received controlRequest {}", JSON.toJSONString(cliControlRequest));
return new CLIControlResponse<>();
CLIControlResponse<ControlResponsePayload> response = new CLIControlResponse<>();
response.createResponse().setRequestId(cliControlRequest.getRequestId()).setSubtype("error")
.setError("This example does not implement control requests");
return response;
}

@Override
Expand Down
Loading
Loading