packages/sdk-java/qwencode/QWEN.md
The Qwen Code Java SDK is a minimum experimental SDK for programmatic access to Qwen Code functionality. It provides a Java interface to interact with the Qwen Code CLI, allowing developers to integrate Qwen Code capabilities into their Java applications.
Context Information:
The SDK follows a layered architecture:
QwenCodeCli class with simple static methods for basic usageSession classProcessTransport)QwenCodeCli: Main entry point with static methods for simple queriesSession: Manages communication sessions with the CLITransport: Abstracts the communication mechanism (currently using process transport)ProcessTransport: Implementation that communicates via process executionTransportOptions: Configuration class for transport layer settingsSessionEventSimpleConsumers: High-level event handler for processing responsesAssistantContentSimpleConsumers: Handles different types of content within assistant messages# Compile the project
mvn compile
# Run tests
mvn test
# Package the JAR
mvn package
# Install to local repository
mvn install
# Run checkstyle verification
mvn checkstyle:check
# Generate Javadoc
mvn javadoc:javadoc
The project includes basic unit tests using JUnit 5. The main test class QwenCodeCliTest demonstrates how to use the SDK to make simple queries to the Qwen Code CLI.
The project uses Checkstyle for code formatting and style enforcement. The configuration is defined in checkstyle.xml and includes rules for:
src/test/java directory*Test.java for test classesThe main class provides several primary methods:
simpleQuery(String prompt): Synchronous method that returns a list of responsessimpleQuery(String prompt, TransportOptions transportOptions): Synchronous method with custom transport optionssimpleQuery(String prompt, TransportOptions transportOptions, AssistantContentConsumers assistantContentConsumers): Advanced method with custom content consumersnewSession(): Creates a new session with default optionsnewSession(TransportOptions transportOptions): Creates a new session with custom optionsThe SDK supports different permission modes for controlling tool execution:
default: Write tools are denied unless approved via canUseTool callback or in allowedTools. Read-only tools execute without confirmation.plan: Blocks all write tools, instructing AI to present a plan first.auto-edit: Auto-approve edit tools (edit, write_file) while other tools require confirmation.yolo: All tools execute automatically without confirmation.The TransportOptions class allows configuration of how the SDK communicates with the Qwen Code CLI:
pathToQwenExecutable: Path to the Qwen Code CLI executablecwd: Working directory for the CLI processmodel: AI model to use for the sessionpermissionMode: Permission mode that controls tool executionenv: Environment variables to pass to the CLI processmaxSessionTurns: Limits the number of conversation turns in a sessioncoreTools: List of core tools that should be available to the AIexcludeTools: List of tools to exclude from being available to the AIallowedTools: List of tools that are pre-approved for use without additional confirmationauthType: Authentication type to use for the sessionincludePartialMessages: Enables receiving partial messages during streaming responsesturnTimeout: Timeout for a complete turn of conversationmessageTimeout: Timeout for individual messages within a turnresumeSessionId: ID of a previous session to resumeotherOptions: Additional command-line options to pass to the CLIQwenCodeCli.newSession() to create a new session with custom optionsSession class provides methods to send prompts, handle responses, and manage session statesession.close() to properly terminate the CLI processsetResumeSessionId() in TransportOptions to resume a previous sessionsession.interrupt() to interrupt a currently running promptsession.setModel() to change the model during a sessionsession.setPermissionMode() to change the permission mode during a sessionThe SDK uses a thread pool for managing concurrent operations with the following default configuration:
The SDK provides two key interfaces for handling events and content from the CLI:
The SessionEventConsumers interface provides callbacks for different types of messages during a session:
onSystemMessage: Handles system messages from the CLI (receives Session and SDKSystemMessage)onResultMessage: Handles result messages from the CLI (receives Session and SDKResultMessage)onAssistantMessage: Handles assistant messages (AI responses) (receives Session and SDKAssistantMessage)onPartialAssistantMessage: Handles partial assistant messages during streaming (receives Session and SDKPartialAssistantMessage)onUserMessage: Handles user messages (receives Session and SDKUserMessage)onOtherMessage: Handles other types of messages (receives Session and String message)onControlResponse: Handles control responses (receives Session and CLIControlResponse)onControlRequest: Handles control requests (receives Session and CLIControlRequest, returns CLIControlResponse)onPermissionRequest: Handles permission requests (receives Session and CLIControlRequest<CLIControlPermissionRequest>, returns Behavior)The AssistantContentConsumers interface handles different types of content within assistant messages:
onText: Handles text content (receives Session and TextAssistantContent)onThinking: Handles thinking content (receives Session and ThinkingAssistantContent)onToolUse: Handles tool use content (receives Session and ToolUseAssistantContent)onToolResult: Handles tool result content (receives Session and ToolResultAssistantContent)onOtherContent: Handles other content types (receives Session and AssistantContent)onUsage: Handles usage information (receives Session and AssistantUsage)onPermissionRequest: Handles permission requests (receives Session and CLIControlPermissionRequest, returns Behavior)onOtherControlRequest: Handles other control requests (receives Session and ControlRequestPayload, returns ControlResponsePayload)Important Note on Event Hierarchy:
SessionEventConsumers is the high-level event processor that handles different message types (system, assistant, user, etc.)AssistantContentConsumers is the low-level content processor that handles different types of content within assistant messages (text, tools, thinking, etc.)Processor Relationship:
SessionEventConsumers → AssistantContentConsumers (SessionEventConsumers uses AssistantContentConsumers to process content within assistant messages)Event Derivation Relationships:
onAssistantMessage → onText, onThinking, onToolUse, onToolResult, onOtherContent, onUsageonPartialAssistantMessage → onText, onThinking, onToolUse, onToolResult, onOtherContentonControlRequest → onPermissionRequest, onOtherControlRequestEvent Timeout Relationships:
Each event handler method has a corresponding timeout method that allows customizing the timeout behavior for that specific event:
onSystemMessage ↔ onSystemMessageTimeoutonResultMessage ↔ onResultMessageTimeoutonAssistantMessage ↔ onAssistantMessageTimeoutonPartialAssistantMessage ↔ onPartialAssistantMessageTimeoutonUserMessage ↔ onUserMessageTimeoutonOtherMessage ↔ onOtherMessageTimeoutonControlResponse ↔ onControlResponseTimeoutonControlRequest ↔ onControlRequestTimeoutFor AssistantContentConsumers timeout methods:
onText ↔ onTextTimeoutonThinking ↔ onThinkingTimeoutonToolUse ↔ onToolUseTimeoutonToolResult ↔ onToolResultTimeoutonOtherContent ↔ onOtherContentTimeoutonPermissionRequest ↔ onPermissionRequestTimeoutonOtherControlRequest ↔ onOtherControlRequestTimeoutDefault Timeout Values:
SessionEventSimpleConsumers default timeout: 180 seconds (Timeout.TIMEOUT_180_SECONDS)AssistantContentSimpleConsumers default timeout: 60 seconds (Timeout.TIMEOUT_60_SECONDS)Timeout Hierarchy Requirements:
For proper operation, the following timeout relationships should be maintained:
onAssistantMessageTimeout return value should be greater than onTextTimeout, onThinkingTimeout, onToolUseTimeout, onToolResultTimeout, and onOtherContentTimeout return valuesonControlRequestTimeout return value should be greater than onPermissionRequestTimeout and onOtherControlRequestTimeout return valuesAssistantContentSimpleConsumers is the default implementation of AssistantContentConsumersSessionEventSimpleConsumers is the concrete implementation that combines both interfaces and depends on an AssistantContentConsumers instance to handle content within assistant messagesSessionEventConsumers now include the message object as a parameter (e.g., onSystemMessageTimeout(Session session, SDKSystemMessage systemMessage))Event processing is subject to the timeout settings configured in TransportOptions and SessionEventConsumers. For detailed timeout configuration options, see the "Timeout" section above.
The SDK includes several example files in src/test/java/com/alibaba/qwen/code/cli/example/ that demonstrate different aspects of the API:
QuickStartExample.java: Demonstrates simple query usage, transport options configuration, and streaming content handlingSessionExample.java: Shows session control features including permission mode changes, model switching, interruption, and event handlingThreadPoolConfigurationExample.java: Shows how to configure the thread pool used by the SDKThe SDK provides specific exception types for different error scenarios:
SessionControlException: Thrown when there's an issue with session control (creation, initialization, etc.)SessionSendPromptException: Thrown when there's an issue sending a prompt or receiving a responseSessionClosedException: Thrown when attempting to use a closed sessionsrc/
├── example/
│ └── java/
│ └── com/
│ └── alibaba/
│ └── qwen/
│ └── code/
│ └── example/
├── main/
│ └── java/
│ └── com/
│ └── alibaba/
│ └── qwen/
│ └── code/
│ └── cli/
│ ├── QwenCodeCli.java
│ ├── protocol/
│ ├── session/
│ ├── transport/
│ └── utils/
└── test/
├── java/
│ └── com/
│ └── alibaba/
│ └── qwen/
│ └── code/
│ └── cli/
│ ├── QwenCodeCliTest.java
│ ├── session/
│ │ └── SessionTest.java
│ └── transport/
│ ├── PermissionModeTest.java
│ └── process/
│ └── ProcessTransportTest.java
└── temp/
pom.xml: Maven build configuration and dependenciescheckstyle.xml: Code style and formatting rules.editorconfig: Editor configuration settingsA: No, from v0.1.1, the CLI is bundled with the SDK, so no standalone CLI installation is needed.
A: The SDK requires Java 1.8 or higher.
A: The SDK includes timeout utilities. You can configure timeouts using the Timeout class in TransportOptions.
A: This is likely due to permission modes. Check your permission mode settings and consider using allowedTools to pre-approve certain tools.
A: Use the setResumeSessionId() method in TransportOptions to resume a previous session.
A: Yes, use the setEnv() method in TransportOptions to pass environment variables to the CLI process.
A: The SDK will throw appropriate exceptions. Make sure to handle SessionControlException and implement retry logic if needed.