docs: consolidate assorted documentation corrections (#9855)

* docs(zed): use real debug log env var (#9853)

* docs(headless): fix JSON jq examples (#9858)

* docs(cli): align status line default preset prose (#9864)

* docs(acp): update permission mediator status (#9866)

* docs(sdk): align query option reference (#9855)

---------

Co-authored-by: zhangyu.34 <zhangyu.34@bytedance.com>
Co-authored-by: 易良 <1204183885@qq.com>
This commit is contained in:
Yu Zhang 2026-08-26 08:52:13 +00:00 • committed by GitHub
parent ba657c0678
commit 652cd76781
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 104 additions and 116 deletions

View file

@ -15,9 +15,7 @@ npm install @qwen-code/sdk
## Requirements
- Node.js >= 22.0.0
- [Qwen Code](https://github.com/QwenLM/qwen-code) >= 0.4.0 (stable) installed and accessible in PATH
> **Note for nvm users**: If you use nvm to manage Node.js versions, the SDK may not be able to auto-detect the Qwen Code executable. You should explicitly set the `pathToQwenExecutable` option to the full path of the `qwen` binary.
- [Qwen Code](https://github.com/QwenLM/qwen-code) >= 0.4.0 (stable). The SDK uses its bundled CLI by default; set `pathToQwenExecutable` only when you need to run a custom `qwen` binary or CLI bundle.
## Quick Start
@ -55,27 +53,27 @@ Creates a new query session with the Qwen Code.
#### QueryOptions
| Option | Type | Default | Description |
| ------------------------ | -------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. |
| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. |
| `pathToQwenExecutable` | `string` | Auto-detected | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, auto-detects from: `QWEN_CODE_CLI_PATH` env var, `~/.volta/bin/qwen`, `~/.npm-global/bin/qwen`, `/usr/local/bin/qwen`, `~/.local/bin/qwen`, `~/node_modules/.bin/qwen`, `~/.yarn/bin/qwen`. |
| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. |
| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). |
| `env` | `Record<string, string>` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. |
| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. |
| `mcpServers` | `Record<string, McpServerConfig>` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. |
| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. |
| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. |
| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. |
| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is separate from `permissions.allow` in settings.json, which also activates a registry-level allowlist at startup: when at least one valid allow rule is configured there (malformed entries do not count), built-in tools not covered by any allow or ask rule are not registered (MCP tools, the `--json-schema` `structured_output` contract, the plan-mode lifecycle tools, `task_stop`, `tool_search`, and the `computer_use__*` family are exempt; requires restart, #9827). The SDK `allowedTools` parameter cannot activate the allowlist on its own, but while the allowlist is active its rules are merged into the effective allow set and count toward coverage, keeping covered built-ins registered. Example: `['read_file', 'edit', 'run_shell_command']`. |
| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). |
| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Unlike `permissions.allow` in settings.json, this parameter alone does not activate the registry allowlist; however, while a settings-provided allowlist is active, `allowedTools` rules are merged into the effective allow set and count toward coverage, so covered built-ins stay registered. Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. |
| `authType` | `'openai' \| 'qwen-oauth'` | `'openai'` | Authentication type for the AI service. Qwen OAuth free tier was discontinued on 2026-04-15; new SDK setups should use OpenAI-compatible authentication or another supported provider. |
| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. |
| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. |
| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. |
| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. |
| Option | Type | Default | Description |
| ------------------------ | -------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. |
| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. |
| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. |
| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. |
| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). |
| `env` | `Record<string, string>` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. |
| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. |
| `mcpServers` | `Record<string, McpServerConfig>` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. |
| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. |
| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. |
| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. |
| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is separate from `permissions.allow` in settings.json, which also activates a registry-level allowlist at startup: when at least one valid allow rule is configured there (malformed entries do not count), built-in tools not covered by any allow or ask rule are not registered (MCP tools, the `--json-schema` `structured_output` contract, the plan-mode lifecycle tools, `task_stop`, `tool_search`, and the `computer_use__*` family are exempt; requires restart, #9827). The SDK `allowedTools` parameter cannot activate the allowlist on its own, but while the allowlist is active its rules are merged into the effective allow set and count toward coverage, keeping covered built-ins registered. Example: `['read_file', 'edit', 'run_shell_command']`. |
| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). |
| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Unlike `permissions.allow` in settings.json, this parameter alone does not activate the registry allowlist; however, while a settings-provided allowlist is active, `allowedTools` rules are merged into the effective allow set and count toward coverage, so covered built-ins stay registered. Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. |
| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. |
| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. |
| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. |
| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. |
| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. |
> [!note]
> For `coreTools`, aliases like `Read`, `Edit`, and `Bash` also work, but invocation specifiers such as `Bash(git *)` are stripped. `coreTools` restricts tool registration, not invocation patterns.

View file

@ -249,7 +249,7 @@ qwen -p "Explain Docker" --output-format json > docker-explanation.json
qwen -p "Add more details" >> docker-explanation.txt
# Pipe to other tools
qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "What is Kubernetes?" --output-format json | jq -r '.[-1].result'
qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python"
@ -325,14 +325,14 @@ cat src/auth.py | qwen -p "Review this authentication code for security issues"
```bash
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'
echo "$result" | jq -r '.[-1].result'
```
### API documentation
```bash
result=$(cat api/routes.js | qwen -p "Generate OpenAPI spec for these routes" --output-format json)
echo "$result" | jq -r '.response' > openapi.json
echo "$result" | jq -r '.[-1].result' > openapi.json
```
### Batch code analysis
@ -341,7 +341,7 @@ echo "$result" | jq -r '.response' > openapi.json
for file in src/*.py; do
echo "Analyzing $file..."
result=$(cat "$file" | qwen -p "Find potential bugs and suggest improvements" --output-format json)
echo "$result" | jq -r '.response' > "reports/$(basename "$file").analysis"
echo "$result" | jq -r '.[-1].result' > "reports/$(basename "$file").analysis"
echo "Completed analysis for $(basename "$file")" >> reports/progress.log
done
```
@ -350,7 +350,7 @@ done
```bash
result=$(git diff origin/main...HEAD | qwen -p "Review these changes for bugs, security issues, and code quality" --output-format json)
echo "$result" | jq -r '.response' > pr-review.json
echo "$result" | jq -r '.[-1].result' > pr-review.json
```
### Log analysis
@ -363,7 +363,7 @@ grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and sug
```bash
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
response=$(echo "$result" | jq -r '.response')
response=$(echo "$result" | jq -r '.[-1].result')
echo "$response"
echo "$response" >> CHANGELOG.md
```
@ -372,12 +372,12 @@ echo "$response" >> CHANGELOG.md
```bash
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)
total_tokens=$(echo "$result" | jq -r '.stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
total_tokens=$(echo "$result" | jq -r '.[-1].stats.models // {} | to_entries | map(.value.tokens.total) | add // 0')
models_used=$(echo "$result" | jq -r '.[-1].stats.models // {} | keys | join(", ") | if . == "" then "none" else . end')
tool_calls=$(echo "$result" | jq -r '.[-1].stats.tools.totalCalls // 0')
tools_used=$(echo "$result" | jq -r '.[-1].stats.tools.byName // {} | keys | join(", ") | if . == "" then "none" else . end')
echo "$(date): $total_tokens tokens, $tool_calls tool calls ($tools_used) used with models: $models_used" >> usage.log
echo "$result" | jq -r '.response' > schema-docs.md
echo "$result" | jq -r '.[-1].result' > schema-docs.md
echo "Recent usage trends:"
tail -5 usage.log
```

View file

@ -87,11 +87,11 @@ Add a `statusLine` object under the `ui` key in `~/.qwen/settings.json`:
| `model-with-reasoning` | Yes | Current model name with reasoning level (e.g. `qwen-3-235b high`) |
| `model` | | Current model name without reasoning level |
| `git-branch` | Yes | Current Git branch name (hidden when not in a git repo) |
| `context-remaining` | Yes | Percentage of context window remaining (e.g. `Context 65.7% left`) |
| `context-remaining` | | Percentage of context window remaining (e.g. `Context 65.7% left`) |
| `total-input-tokens` | | Cumulative input tokens used in session (e.g. `30.0k total in`) |
| `total-output-tokens` | | Cumulative output tokens used in session (e.g. `5.0k total out`) |
| `current-dir` | Yes | Current working directory |
| `project-name` | | Project name (basename of working directory) |
| `current-dir` | | Current working directory |
| `project-name` | Yes | Project name (basename of working directory) |
| `pull-request-number` | | Open PR number for the current branch (requires `gh` CLI) |
| `branch-changes` | | Session file change stats (e.g. `+120 -30`) |
| `context-used` | Yes | Percentage of context window used (e.g. `Context 34.3% used`) |

View file

@ -5,13 +5,13 @@ and remote-control adapters. Lives in the monorepo, not published to npm.
Lift history (#4175 Mode B daemon roadmap):
| Slice | Scope | Status |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| **PR 22a** (#4295) | Skeleton + `EventBus` + `inMemoryChannel` + `AcpChannel` types + `PermissionMediator` type-only stub | ✅ merged |
| **PR 22b/1** (#4298) | Lift `status` + `workspacePaths` + `bridgeErrors` + `bridgeTypes` | ✅ merged |
| **PR 22b/2** (#4304) | Lift `BridgeOptions` + new `DaemonStatusProvider` injection seam | ✅ merged |
| **F1** (this PR) | Lift `defaultSpawnChannelFactory` + `BridgeClient` + `createHttpAcpBridge` factory closure + new `BridgeFileSystem` injection seam (22b' scope) | ✅ in this PR |
| **F3 PR 24** | Implement the four `PermissionMediator` strategies (`first-responder`, `designated`, `consensus`, `local-only`) + pair-token revocation + audit log | F3 in the feature-cohesive plan |
| Slice | Scope | Status |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
| **PR 22a** (#4295) | Skeleton + `EventBus` + `inMemoryChannel` + `AcpChannel` types + `PermissionMediator` type-only stub | ✅ merged |
| **PR 22b/1** (#4298) | Lift `status` + `workspacePaths` + `bridgeErrors` + `bridgeTypes` | ✅ merged |
| **PR 22b/2** (#4304) | Lift `BridgeOptions` + new `DaemonStatusProvider` injection seam | ✅ merged |
| **F1** (#4490) | Lift `defaultSpawnChannelFactory` + `BridgeClient` + `createHttpAcpBridge` factory closure + new `BridgeFileSystem` injection seam (22b' scope) | ✅ merged |
| **F3 PR 24** | Implement the four `PermissionMediator` policies (`first-responder`, `designated`, `consensus`, `local-only`) plus audit/emit fan-out; pair-token binding and revocation stay future scope | ✅ implemented |
## What's here today
@ -25,13 +25,12 @@ Lift history (#4175 Mode B daemon roadmap):
type contract that `createHttpAcpBridge` (now in this package) plus
the channels / VSCode IDE companion's own-spawn paths consume via
`BridgeOptions.channelFactory`.
- `permission` — type-only `PermissionMediator` interface,
- `permission` — `PermissionMediator` interface,
`PermissionPolicy` literal union (4 strategies), and
`PermissionResolution` discriminated union. **No implementation
yet** — first-responder voting still lives in
`BridgeClient.requestPermission` (in `bridgeClient.ts` after F1).
F3 PR 24 will move that and add the other three policies behind
this interface.
`PermissionResolution` discriminated union. `MultiClientPermissionMediator`
implements the four policies, owns pending/resolved permission state, and
handles strategy dispatch plus audit/emit fan-out; `BridgeClient` only
plumbs `requestPermission` into `mediator.request`.
- `status` (PR 22b/1) — wire-contract status types for
`/workspace/{mcp,skills,providers,env,preflight}` and
`/session/:id/{context,supported-commands,tasks}` routes, the
@ -75,20 +74,20 @@ Lift history (#4175 Mode B daemon roadmap):
companion consume this directly instead of each reimplementing the
child lifecycle.
- `bridgeClient` (F1) — `BridgeClient` class implementing the ACP
`Client` surface: first-responder permission flow, session-update
fan-out into `EventBus`, child-side `extNotification` routing,
early-event buffer + tombstone bookkeeping, inline fs proxy for
`writeTextFile` / `readTextFile`. Exports the supporting
`PendingPermission` / `PermissionResolutionRecord` /
`BridgeClientSessionEntry` types + `MAX_RESOLVED_PERMISSION_RECORDS`
cap that the factory's bookkeeping maps consume.
`Client` surface: permission requests delegated to
`PermissionMediator`, session-update fan-out into `EventBus`,
child-side `extNotification` routing, early-event buffer + tombstone
bookkeeping, inline fs proxy for `writeTextFile` / `readTextFile`.
Exports the supporting `BridgeClientSessionEntry` type consumed by
the session-entry lookup passed in by the factory.
- `bridge` (F1) — `createHttpAcpBridge` factory closure (~3000 LOC)
- `ChannelInfo` / `SessionEntry` interfaces + factory-only
helpers (`withTimeout`, `canonicalizeExistingAncestor`,
`verifyParentWithinWorkspace`, debug log helpers,
`hasControlCharacter`) + factory constants. Builds the
bookkeeping closures (`resolveEntry`, `registerPending`, etc.)
and wires them into `BridgeClient`.
`hasControlCharacter`) + factory constants. Owns session
bookkeeping, constructs the `MultiClientPermissionMediator` that
owns permission state, and passes the session-entry lookup into
`BridgeClient`.
- `bridgeFileSystem` (F1) — `BridgeFileSystem` interface for the
ACP fs proxy. When wired through `BridgeOptions.fileSystem`,
`BridgeClient.readTextFile` / `BridgeClient.writeTextFile`
@ -135,6 +134,6 @@ exported symbols (`createHttpAcpBridge`, `defaultSpawnChannelFactory`,
- #4175 Mode B daemon roadmap (feature-cohesive F1-F5 plan targeting
`daemon_mode_b_main`)
- #3803 `Stage 1.5-prereq AcpChannel lift` (chiga0's original framing)
- F3 PR 24 will replace the inline first-responder logic in
`BridgeClient.requestPermission` with the four `PermissionMediator`
strategies declared in `permission.ts`.
- `permissionMediator.ts` implements the four `PermissionMediator`
strategies declared in `permission.ts`; `BridgeClient.requestPermission`
delegates to that mediator.

View file

@ -5,36 +5,32 @@
*/
/**
* `PermissionMediator` — type-only interface contract for daemon
* permission flow. **No implementation lives here.** Permission voting
* still runs inside `BridgeClient.requestPermission`
* (`@qwen-code/acp-bridge/bridgeClient`) and
* `respondToPermission` (inside `createHttpAcpBridge` factory closure
* at `@qwen-code/acp-bridge/bridge` after F1 step 3), hard-coded to
* `first-responder`. A future change will move that code behind this
* interface and add the other three policies.
* `PermissionMediator` — interface contract for daemon permission flow.
* `MultiClientPermissionMediator` in `permissionMediator.ts` owns the
* policy dispatch and pending/resolved permission state used by
* `BridgeClient.requestPermission` plus the `respondToPermission` route
* in `createHttpAcpBridge`.
*
* The four policies are ordered from cheapest to strongest:
* The four policy contracts are ordered from cheapest to strongest:
*
* - `first-responder` — first valid `POST /permission/:requestId`
* wins; later voters get `permission_already_resolved`. Today's
* default; preserves the live-collaboration UX.
* - `designated` — only the `originatorClientId` that started the
* prompt may answer; other clients see `permission_forbidden`.
* Use case: per-tenant SaaS where a UI surface must own its own
* approvals.
* - `consensus` — N-of-M quorum across pair-token-authenticated
* clients before resolving; intermediate `permission_partial_vote`
* events let UIs render progress. Use case: enterprise change
* review where two operators must agree.
* Prompts with no originator fall back to first-responder. Use case:
* per-tenant SaaS where a UI surface must own its own approvals.
* - `consensus` — N-of-M quorum across the session client IDs
* captured when the permission request is issued. Client identity is
* self-declared until pair-token authentication lands; intermediate
* `permission_partial_vote` events let UIs render progress. Use case:
* enterprise change review where two operators must agree.
* - `local-only` — refuses any HTTP voter; the prompt blocks until
* a loopback client (the local TUI super-client) resolves it.
* Use case: workstations where remote control should never grant
* privilege escalation.
*
* See `bridgeClient.ts BridgeClient.requestPermission` for the
* current first-responder implementation; the `FIXME(stage-1.5)`
* block above that method scoped this contract.
* See `permissionMediator.ts` for the implementation details.
*/
export type PermissionPolicy =
| 'first-responder'
@ -43,10 +39,7 @@ export type PermissionPolicy =
| 'local-only';
/**
* One pending permission tracked by a `PermissionMediator`. The
* shape mirrors the current `PendingPermission` record in
* `@qwen-code/acp-bridge/bridgeClient`
* so the mediation implementation's lift is a structural rename rather than a redesign.
* One pending permission tracked by a `PermissionMediator`.
*/
export interface PermissionRequestRecord {
/** ACP `RequestPermission` request id, unique per session. */
@ -148,9 +141,7 @@ export type PermissionResolution =
/**
* The contract `qwen serve`'s permission route layer talks to.
* Today there is one implementation (first-responder) wired
* inline in `BridgeClient`; The implementation will provide all four behind
* this surface plus pair-token authentication and an audit log.
* `MultiClientPermissionMediator` provides the implementation.
*/
export interface PermissionMediator {
/** Active policy. May be reconfigured per session in future

View file

@ -940,7 +940,7 @@ const SETTINGS_SCHEMA = {
)
| undefined,
description:
'Status line display configuration. Use `type: "preset"` with built-in item ids, or `type: "command"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section, or `false` to always show it. When `hideContextIndicator` is unset, the footer indicator is hidden automatically for preset status lines that already include `context-used` or `context-remaining`, and shown otherwise (including for `command` status lines). When unset (default), the built-in default preset (model, git branch, context usage, current dir) is shown automatically; set to `null` to explicitly disable the status line.',
'Status line display configuration. Use `type: "preset"` with built-in item ids, or `type: "command"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section, or `false` to always show it. When `hideContextIndicator` is unset, the footer indicator is hidden automatically for preset status lines that already include `context-used` or `context-remaining`, and shown otherwise (including for `command` status lines). When unset (default), the built-in default preset (project name, git branch, model, context usage) is shown automatically; set to `null` to explicitly disable the status line.',
showInDialog: false,
},
customThemes: {

View file

@ -52,27 +52,27 @@ Creates a new query session with the Qwen Code.
#### QueryOptions
| Option | Type | Default | Description |
| ------------------------ | -------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. |
| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. |
| `pathToQwenExecutable` | `string` | Auto-detected | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, auto-detects from: `QWEN_CODE_CLI_PATH` env var, `~/.volta/bin/qwen`, `~/.npm-global/bin/qwen`, `/usr/local/bin/qwen`, `~/.local/bin/qwen`, `~/node_modules/.bin/qwen`, `~/.yarn/bin/qwen`. |
| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. |
| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). |
| `env` | `Record<string, string>` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. |
| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. |
| `mcpServers` | `Record<string, McpServerConfig>` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. |
| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. |
| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. |
| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. |
| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is separate from `permissions.allow` in settings.json, which also activates a registry-level allowlist at startup: when at least one valid allow rule is configured there (malformed entries do not count), built-in tools not covered by any allow or ask rule are not registered (MCP tools, the `--json-schema` `structured_output` contract, the plan-mode lifecycle tools, `task_stop`, `tool_search`, and the `computer_use__*` family are exempt; requires restart, #9827). The SDK `allowedTools` parameter cannot activate the allowlist on its own, but while the allowlist is active its rules are merged into the effective allow set and count toward coverage, keeping covered built-ins registered. Example: `['read_file', 'edit', 'run_shell_command']`. |
| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). |
| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Unlike `permissions.allow` in settings.json, this parameter alone does not activate the registry allowlist; however, while a settings-provided allowlist is active, `allowedTools` rules are merged into the effective allow set and count toward coverage, so covered built-ins stay registered. Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. |
| `authType` | `'openai' \| 'qwen-oauth'` | `'openai'` | Authentication type for the AI service. Qwen OAuth free tier was discontinued on 2026-04-15; new SDK setups should use OpenAI-compatible authentication or another supported provider. |
| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. |
| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. |
| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. |
| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. |
| Option | Type | Default | Description |
| ------------------------ | -------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cwd` | `string` | `process.cwd()` | The working directory for the query session. Determines the context in which file operations and commands are executed. |
| `model` | `string` | - | The AI model to use (e.g., `'qwen-max'`, `'qwen-plus'`, `'qwen-turbo'`). Takes precedence over `OPENAI_MODEL` and `QWEN_MODEL` environment variables. |
| `pathToQwenExecutable` | `string` | Bundled CLI | Path to the Qwen Code executable. Supports multiple formats: `'qwen'` (native binary from PATH), `'/path/to/qwen'` (explicit path), `'/path/to/cli.js'` (Node.js bundle), `'node:/path/to/cli.js'` (force Node.js runtime), `'bun:/path/to/cli.js'` (force Bun runtime). If not provided, the SDK uses the bundled CLI included with the package. |
| `permissionMode` | `'default' \| 'plan' \| 'auto-edit' \| 'auto' \| 'yolo'` | `'default'` | Permission mode controlling tool execution approval. See [Permission Modes](#permission-modes) for details. |
| `canUseTool` | `CanUseTool` | - | Custom permission handler for tool execution approval. Invoked when a tool requires confirmation. Must respond within 60 seconds or the request will be auto-denied. See [Custom Permission Handler](#custom-permission-handler). |
| `env` | `Record<string, string>` | - | Environment variables to pass to the Qwen Code process. Merged with the current process environment. |
| `systemPrompt` | `string \| QuerySystemPromptPreset` | - | System prompt configuration for the main session. Use a string to fully override the built-in Qwen Code system prompt, or a preset object to keep the built-in prompt and append extra instructions. |
| `mcpServers` | `Record<string, McpServerConfig>` | - | MCP (Model Context Protocol) servers to connect. Supports external servers (stdio/SSE/HTTP) and SDK-embedded servers. External servers are configured with transport options like `command`, `args`, `url`, `httpUrl`, etc. SDK servers use `{ type: 'sdk', name: string, instance: Server }`. |
| `abortController` | `AbortController` | - | Controller to cancel the query session. Call `abortController.abort()` to terminate the session and cleanup resources. |
| `debug` | `boolean` | `false` | Enable debug mode for verbose logging from the CLI process. |
| `maxSessionTurns` | `number` | `-1` (unlimited) | Maximum number of conversation turns before the session automatically terminates. Must be an integer. A turn consists of a user message and an assistant response. |
| `coreTools` | `string[]` | - | Uses the legacy `coreTools` / CLI `--core-tools` allowlist semantics. If specified, only matching core tools are registered for the session. This is separate from `permissions.allow` in settings.json, which also activates a registry-level allowlist at startup: when at least one valid allow rule is configured there (malformed entries do not count), built-in tools not covered by any allow or ask rule are not registered (MCP tools, the `--json-schema` `structured_output` contract, the plan-mode lifecycle tools, `task_stop`, `tool_search`, and the `computer_use__*` family are exempt; requires restart, #9827). The SDK `allowedTools` parameter cannot activate the allowlist on its own, but while the allowlist is active its rules are merged into the effective allow set and count toward coverage, keeping covered built-ins registered. Example: `['read_file', 'edit', 'run_shell_command']`. |
| `excludeTools` | `string[]` | - | Equivalent to `permissions.deny` in settings.json. Excluded tools return a permission error immediately. Takes highest priority over all other permission settings. Supports tool name aliases and pattern matching: tool name (`'write_file'`), shell command prefix (`'Bash(rm *)'`), or path patterns (`'Read(.env)'`, `'Edit(/src/**)'`). |
| `allowedTools` | `string[]` | - | Equivalent to `permissions.allow` in settings.json for auto-approval. Matching tools bypass `canUseTool` callback and execute automatically. Only applies when tool requires confirmation. Unlike `permissions.allow` in settings.json, this parameter alone does not activate the registry allowlist; however, while a settings-provided allowlist is active, `allowedTools` rules are merged into the effective allow set and count toward coverage, so covered built-ins stay registered. Supports same pattern matching as `excludeTools`. Example: `['Bash(git status)', 'Bash(npm test)']`. |
| `authType` | `'openai' \| 'anthropic' \| 'qwen-oauth' \| 'gemini' \| 'vertex-ai'` | - | Authentication type for the AI service. When provided, the SDK forwards it to the CLI as `--auth-type`. |
| `agents` | `SubagentConfig[]` | - | Configuration for subagents that can be invoked during the session. Subagents are specialized AI agents for specific tasks or domains. |
| `includePartialMessages` | `boolean` | `false` | When `true`, the SDK emits incomplete messages as they are being generated, allowing real-time streaming of the AI's response. |
| `resume` | `string` | - | Resume a previous session by providing its session ID. Equivalent to CLI's `--resume` flag. |
| `sessionId` | `string` | - | Specify a session ID for the new session. Ensures SDK and CLI use the same ID without resuming history. Equivalent to CLI's `--session-id` flag. |
> [!tip]
> If you need to configure `coreTools`, `excludeTools`, or `allowedTools`, it is **strongly recommended** to read the [permissions configuration documentation](../../docs/users/configuration/settings.md#permissions) first, especially the **Tool name aliases** and **Rule syntax examples** sections. Rule patterns such as `Bash(git *)`, `Read(.env)`, and `Edit(/src/**)` apply to `excludeTools` and `allowedTools`; `coreTools` accepts aliases but strips invocation specifiers.

View file

@ -477,10 +477,10 @@ export interface QueryOptions {
/**
* Authentication type for the AI service.
* - 'openai': Use OpenAI-compatible authentication
* - 'anthropic': Use Anthropic-compatible authentication
* - 'qwen-oauth': Legacy Qwen OAuth authentication
*
* Qwen OAuth free tier was discontinued on 2026-04-15. New SDK setups should
* use OpenAI-compatible authentication or another supported provider.
* - 'gemini': Use Gemini authentication
* - 'vertex-ai': Use Vertex AI authentication
*/
authType?: AuthType;

View file

@ -325,7 +325,7 @@
"default": false
},
"statusLine": {
"description": "Status line display configuration. Use `type: \"preset\"` with built-in item ids, or `type: \"command\"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section, or `false` to always show it. When `hideContextIndicator` is unset, the footer indicator is hidden automatically for preset status lines that already include `context-used` or `context-remaining`, and shown otherwise (including for `command` status lines). When unset (default), the built-in default preset (model, git branch, context usage, current dir) is shown automatically; set to `null` to explicitly disable the status line.",
"description": "Status line display configuration. Use `type: \"preset\"` with built-in item ids, or `type: \"command\"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section, or `false` to always show it. When `hideContextIndicator` is unset, the footer indicator is hidden automatically for preset status lines that already include `context-used` or `context-remaining`, and shown otherwise (including for `command` status lines). When unset (default), the built-in default preset (project name, git branch, model, context usage) is shown automatically; set to `null` to explicitly disable the status line.",
"type": "object",
"additionalProperties": true
},

View file

@ -60,7 +60,7 @@ For additional environment variables, configure them in your Zed settings:
"agent_servers": {
"qwen-code": {
"env": {
"QWEN_LOG_LEVEL": "info",
"QWEN_DEBUG_LOG_FILE": "1",
"YOUR_CUSTOM_VAR": "value"
}
}