Compare commits

...

356 Commits

Author SHA1 Message Date
github-actions[bot]
6e4acfb062 chore(release): v0.5.0-preview.0 2025-12-13 07:23:46 +00:00
tanzhenxin
0d90d5c118 Merge pull request #1240 from QwenLM/feat/acp-authenticate-update
Add ACP authenticate update message
2025-12-13 14:41:59 +08:00
pomelo
cc0d688c8b Merge pull request #1235 from afarber/501-remove-duplicated-if-check
fix: remove redundant if-check and add tests for OpenAI converter
2025-12-13 12:07:24 +08:00
tanzhenxin
4eb7aa5448 add acp authenticate update message 2025-12-13 12:01:46 +08:00
pomelo
9978fe107b Merge pull request #1236 from afarber/1102-add-slash-language
test(cli): add tests for /language command and fix LLM output language parsing
2025-12-13 12:00:18 +08:00
pomelo
b95bb2cd95 Merge pull request #1238 from fazilus/feat/russian
feat(i18n): add Russian language support
2025-12-13 11:44:02 +08:00
Fazil
026fd468b1 feat(i18n): add Russian language support 2025-12-12 21:12:37 +03:00
Alexander Farber
d25af87eaf Fix the copyright 2025-12-12 15:46:37 +01:00
Alexander Farber
a5039d15bf Revert to SupportedLanguage 2025-12-12 15:36:50 +01:00
Alexander Farber
3ff916a5f1 Add tests for /language command and fix regex parsing 2025-12-12 15:28:43 +01:00
Alexander Farber
7bb9bc1e5e Remove redundant if-check and add tests for tool conversion in converter.ts 2025-12-12 14:29:37 +01:00
tanzhenxin
8b29dd130e Merge pull request #1233 from QwenLM/chore/v0.5.0
pump version to 0.5.0
2025-12-12 16:32:13 +08:00
tanzhenxin
d0be8b43d7 pump version to 0.5.0 2025-12-12 16:29:50 +08:00
tanzhenxin
3095442eb3 Merge pull request #1223 from QwenLM/fix/vscode-ide-companion-login-twice
fix(vscode-ide-companion/auth): deduplicate concurrent authentication calls
2025-12-12 16:19:25 +08:00
tanzhenxin
2ceecab503 Merge pull request #1226 from QwenLM/feat/support-channel-field
feat: Add channel field support for client identification
2025-12-12 16:16:36 +08:00
pomelo
e5ed0334ab Merge pull request #1230 from BlockHand/docker-ide 2025-12-12 16:16:23 +08:00
刘伟光
2b62b1e8bc feat: 将注释修改成英文 2025-12-12 14:40:30 +08:00
yiliang114
89be6edb5e chore(vscode-ide-companion): add comment 2025-12-12 13:59:05 +08:00
yiliang114
d812c9dcf2 chore(vscode-ide-companion): add fixme comment for auth delay 2025-12-12 13:51:14 +08:00
yiliang114
d754767e73 chore(vscode-ide-companion): rm authState manager in vscode-ide-companion to simplify the login architecture 2025-12-12 13:40:18 +08:00
刘伟光
bb8447edd7 fix: 修复在docker环境中无法连接ide的问题 2025-12-12 11:36:15 +08:00
yiliang114
02234f5434 chore(vscode-ide-companion): change comments and delays 2025-12-12 01:17:38 +08:00
yiliang114
25261ab88d fix(vscode-ide-companion): slight delay to ensure auth state settlement 2025-12-12 01:14:28 +08:00
DragonnZhang
60a58ad8e5 feat: add support for the channel field to CLI parameters and configurations 2025-12-12 01:06:00 +08:00
yiliang114
c20df192a8 chore(vscode-ide-companion): revert some log util, will continue next time 2025-12-11 23:57:21 +08:00
yiliang114
b34894c8ea feat(vscode-ide-companion/auth): deduplicate concurrent authentication calls
Prevent multiple simultaneous authentication flows by:
- Adding static authInFlight promise tracking in AcpConnection
- Implementing runExclusiveAuth method in AuthStateManager
- Adding sessionCreateInFlight tracking in QwenAgentManager
- Ensuring only one auth flow runs at a time across different components

This prevents race conditions and duplicate login prompts when multiple components request authentication simultaneously.
2025-12-11 22:56:58 +08:00
tanzhenxin
58d3a9c253 Merge pull request #1176 from QwenLM/feat/acp-usage-metadata
Feat/acp usage metadata
2025-12-11 14:09:43 +08:00
TianHao Zhang
d06a6d7ef9 feat: update references from Gemini to Qwen in setup commands and gitignore handling (#1156) 2025-12-11 14:09:22 +08:00
pomelo
ae9753a326 Merge pull request #1189 from afarber/security-fixes
fix: update vulnerable dependencies (glob, jws, tar, js-yaml)
2025-12-11 09:42:30 +08:00
pomelo
a02c4b2765 Merge pull request #1059 from yiliang114/feat/jinjing/write-and-read-file-in-vscode
feat: VSCode Extension Implementation
2025-12-10 16:15:28 +08:00
pomelo
0055399cba Merge pull request #1191 from afarber/remove-vertical-borders
feat(ui): remove vertical borders from input prompt for easier copy/paste
2025-12-10 16:08:04 +08:00
yiliang114
5ef3d32f16 refactor(vscode-ide-companion/qwenAgentManager): remove saveCheckpointViaCommand method
refactor(vscode-ide-companion/webview): improve message handling during checkpoint saves
feat(vscode-ide-companion/markdown): enhance file path link handling with line numbers support
feat(vscode-ide-companion/message): add enableFileLinks prop to MessageContent component
feat(vscode-ide-companion/user-message): disable file links in user messages
2025-12-10 01:31:39 +08:00
xuewenjie
49c032492a fix: prefer UTF-8 encoding for shell output on Windows when detected
pump versionm to 0.4.1 (#1177)
2025-12-10 01:31:32 +08:00
yiliang114
4345b9370e feat(vscode-ide-companion): enhance panel manager group tracking and ui improvements
chore(vscode-ide-companion): remove unused todo comment in auth state manager
2025-12-10 01:31:27 +08:00
yiliang114
d2e2a07327 chore(vscode-ide-companion): bump version to 0.4.1 and add semver dependency and improve cli version checking with semver package 2025-12-10 01:31:09 +08:00
Alexander Farber
5b74422be6 Do not skip the tests 2025-12-09 16:46:18 +01:00
Alexander Farber
06c398a015 Remove vertical borders from input prompt for easier copy/paste 2025-12-09 16:37:32 +01:00
Alexander Farber
aec5d6463a Update vulnerable dependencies (glob, jws, tar, js-yaml) 2025-12-09 15:14:20 +01:00
yiliang114
29032d2c6a chore(vscode-ide-companion): bump version to 0.4.1 2025-12-09 21:48:40 +08:00
yiliang114
e91ea3ac1a refactor(vscode-ide-companion): simplify openDiff tool implementation
- Remove redundant file reading logic from ide-server
- Leverage diffManager's new capability to read old content internally
- Simplify openDiff tool call site to pass only newContent
- Update comments to reflect the simplified implementation
2025-12-09 15:53:41 +08:00
yiliang114
f2a74c74b6 feat(vscode-ide-companion): enhance panel manager group tracking and cleanup
- Add panelGroupViewColumn tracking for precise group identification
- Implement improved tab capture mechanism with delayed execution
- Add robust group cleanup logic to close empty locked columns
- Implement focusGroupByColumn helper for reliable group focusing
- Add proper error handling and fallback mechanisms for group operations
2025-12-09 15:53:19 +08:00
yiliang114
21651410c8 feat(vscode-ide-companion): update approval mode cycling behavior
- Add NEXT_APPROVAL_MODE constant for cyclic mode mapping
- Remove 'plan' mode from public toggle sequence
- Simplify handleToggleEditMode implementation using NEXT_APPROVAL_MODE mapping
- Update import statements to include NEXT_APPROVAL_MODE
- Remove unused comment about plan mode in toggle sequence
2025-12-09 15:53:06 +08:00
yiliang114
09cefbcf67 feat(vscode-ide-companion): add showDiff overload and file reading capability
- Add overloaded showDiff method to support calling with only newContent
- Implement readOldContentFromFs helper to read existing file content
- Simplify IDE server openDiff tool to use minimal call site
- Improve diff manager documentation and code clarity
2025-12-09 15:52:52 +08:00
tanzhenxin
5fddcd509c pump versionm to 0.4.1 (#1177) 2025-12-09 10:25:07 +08:00
tanzhenxin
d7b9466516 #1129, add usage update in ACP mode 2025-12-09 09:58:19 +08:00
yiliang114
fcd4bb9c03 style(vscode-ide-companion): adjust EmptyState component layout
- Remove max-width constraint from EmptyState component wrapper
- Improve responsive layout for empty state view
2025-12-09 00:15:56 +08:00
yiliang114
828b760820 refactor(vscode-ide-companion): clean up code and improve type safety
- Remove commented out error handling code in acpMessageHandler
- Simplify session update handler by removing redundant comments
- Clean up chat types interface definitions
- Simplify null check in MessageRouter
- Improve type safety in SettingsMessageHandler with ApprovalModeValue type
2025-12-09 00:15:44 +08:00
yiliang114
ef3d7b92d0 feat(vscode-ide-companion): improve message handling and diff auto-opening
- Ignore messages during checkpoint saves in WebViewProvider
- Move diff auto-opening logic from useEffect to useWebViewMessages hook
- Remove unused imports and variables in EditToolCall component
- Enhance tool call handling for edit operations with diff content
2025-12-09 00:15:30 +08:00
yiliang114
58b9e477bc feat(vscode-ide-companion): implement session rehydration for loading past conversations
- Add rehydratingSessionId flag to track session loading state
- Route message chunks as discrete messages during rehydration instead of streaming
- Update session handlers to properly manage conversation switching
- Improve session manager documentation
2025-12-09 00:14:35 +08:00
yiliang114
f4edcc5cd2 fix(vscode-ide-companion): global auth state 2025-12-08 23:38:16 +08:00
yiliang114
7adb9ed7ff refactor(vscode-ide-companion): introduce ApprovalMode enum and improve mode handling
- Create new approvalModeTypes.ts with ApprovalMode enum and helper functions
- Replace hardcoded string literals with ApprovalModeValue type
- Consolidate mode mapping logic using new helper functions
2025-12-08 23:12:04 +08:00
yiliang114
f146f062cb chore(vscode-ide-companion): rm markdown code copy button 2025-12-08 21:00:29 +08:00
yiliang114
111234eb24 refactor(vscode-ide-companion): simplify ACP connection and cleanup configurations
- Remove .claude from .gitignore
- Update CSS file path in eslint config
- Simplify VS Code extension title
- Remove unused keybinding for openChat command
- Delete unused auth constants file
- Simplify ACP connection by removing backend parameter
- Move authMethod to acpTypes
- Restrict ACP backend to Qwen only
- Remove backend property from connection state
- Minor formatting update in webview index.tsx
2025-12-08 20:44:48 +08:00
pomelo
a6a572336c Merge pull request #1157 from QwenLM/fix/windows-shell-output-garbled 2025-12-08 16:45:05 +08:00
yiliang114
96cd685b1b chore(vscode-ide-companion): rm comment about claude 2025-12-08 13:04:06 +08:00
yiliang114
e8b4ee111c fix(vscode-ide-companion): rm useless component 2025-12-08 12:58:05 +08:00
yiliang114
ac0d5206ba chore(vscode-ide-companion): rm useTerminal & some useless code about openDiff 2025-12-08 12:46:42 +08:00
xuewenjie
e5e1e6a3da Merge branch 'main' of github.com:QwenLM/qwen-code into fix/windows-shell-output-garbled 2025-12-08 11:35:47 +08:00
yiliang114
6269415e7b chore(vscode-ide-companion): reorder dlv dependency in package-lock.json 2025-12-08 11:31:58 +08:00
yiliang114
efccd44cb4 fix(vscode-ide-companion/permission-drawer): improve ref typing for input element 2025-12-08 11:31:50 +08:00
tanzhenxin
efbf50554d Merge branch 'main' into feat/acp-usage-metadata 2025-12-08 10:27:38 +08:00
yiliang114
63e4794633 chore(vscode-ide-companion): temporarily annotate some logic to suppress showDiff 2025-12-08 10:18:55 +08:00
yiliang114
be71976a1f chore(vscode-ide-companion): refactor directory structure 2025-12-08 00:54:26 +08:00
yiliang114
e47263f7c9 Merge branch 'main' of https://github.com/QwenLM/qwen-code into feat/jinjing/write-and-read-file-in-vscode 2025-12-07 23:05:36 +08:00
yiliang114
51b4de0c23 fix(vscode-ide-companion): resolve ESLint errors and improve code quality
- Fix unused variable issues by removing unused variables and renaming caught errors to match ESLint rules
- Fix TypeScript type mismatches in mode handling
- Add missing curly braces to if statements to comply with ESLint rules
- Resolve missing dependency warnings in React hooks
- Clean up empty catch blocks by adding appropriate comments
- Remove unused _lastEditorState variables that were declared but never read

These changes ensure the codebase passes ESLint checks and follows best practices for code quality.
2025-12-07 16:57:40 +08:00
yiliang114
67eee14ca9 style(vscode-ide-companion): adjust chat session initialization logic and optimize tool invocation component style 2025-12-06 22:44:31 +08:00
yiliang114
ed44520e51 fix(vscode-ide-companion): clean up deprecated permission drawer file
Remove obsolete PermissionDrawer.tsx file that has been replaced by the new directory structure
2025-12-06 21:46:31 +08:00
yiliang114
7cd26f728d feat(vscode-ide-companion): implement session message handling and UI improvements
Complete session message handling with JSONL support and UI enhancements

- Add JSONL session file reading capability

- Improve error handling and authentication flows

- Update UI components for better user experience

- Fix command identifier references

- Enhance MarkdownRenderer with copy functionality

- Update Tailwind configuration for better component coverage
2025-12-06 21:46:14 +08:00
yiliang114
ad79b9bcab refactor(vscode-ide-companion): restructure tool call components
Restructure tool call components with dedicated container implementations

- Move tool call components to done subdirectory

- Implement specialized ToolCallContainer for each tool type

- Update component routing in ToolCallRouter

- Add isFirst/isLast props for better layout control

- Improve shared types and layout components
2025-12-06 21:45:51 +08:00
yiliang114
ad301963a6 feat(vscode-ide-companion): enhance session management with pagination support
Implement cursor-based pagination for session listing and improve session handling

- Add pagination state management in useSessionManagement hook

- Implement handleLoadMoreSessions for infinite scrolling

- Update SessionMessageHandler to support paged session requests

- Add ChatHeader component for improved UI layout

- Fix session title duplication issue

- Improve error handling in session operations
2025-12-06 21:45:36 +08:00
yiliang114
e538a3d1bf fix(vscode-ide-companion): improve ACP connection and session management
Enhance session/load and session/list ACP methods with proper cwd handling and pagination support

- Add workingDir tracking in AcpConnection

- Improve parameter handling in loadSession and listSessions

- Add pagination support for session listing

- Fix null/undefined checks in message handling
2025-12-06 21:45:18 +08:00
yiliang114
413c143004 feat(vscode-ide-companion): update command identifiers to use kebab-case
Standardize command naming convention by changing qwenCode.* to qwen-code.* in package.json configuration
2025-12-06 21:45:04 +08:00
Mingholy
b4be2c6c7f Merge pull request #1166 from QwenLM/mingholy/fix/unstable-e2e-test
test: skip unstable e2e test
2025-12-06 18:42:29 +08:00
mingholy.lmh
8b5b8d2b90 test: skip unstable e2e test 2025-12-06 18:41:19 +08:00
Mingholy
6e826b815e Merge pull request #1165 from QwenLM/mingholy/fix/sdk-timeout
fix: update timeout settings and default logging level in SDK
2025-12-06 18:18:23 +08:00
mingholy.lmh
86b166bb1d fix: adjust e2e tests via timeout option 2025-12-06 17:53:31 +08:00
yiliang114
57a684ad97 WIP: All changes including session and toolcall improvements 2025-12-06 16:53:40 +08:00
mingholy.lmh
bf6abf7752 fix: update timeout settings and default logging level in SDK 2025-12-06 12:27:16 +08:00
yiliang114
541d0b22e5 chore(vscode-ide-companion): code style & command register bugfix 2025-12-06 01:32:52 +08:00
yiliang114
96b275a756 fix(vscode-ide-companion): fix bugs & support terminal mode operation 2025-12-06 00:30:22 +08:00
Mingholy
ab228c682f Merge pull request #1161 from QwenLM/mingholy/fix/integration-test-scripts
test: separating integration tests for the CLI and SDK
2025-12-05 22:34:30 +08:00
mingholy.lmh
22943b888d test: clean up integration test by removing unnecessary console logs 2025-12-05 22:11:27 +08:00
mingholy.lmh
96d458fa8c chore: rename @qwen-code/sdk-typescript to @qwen-code/sdk 2025-12-05 21:47:26 +08:00
mingholy.lmh
0e9255b122 fix: integration test scripts 2025-12-05 21:27:12 +08:00
Mingholy
3ed0a34b5e Merge pull request #1147 from QwenLM/mingholy/feat/cli-sdk-stage-2
Custom tools support via SDK controlled MCP servers
2025-12-05 21:19:58 +08:00
mingholy.lmh
2949b33a4e chore: enhance integration testing for SDK and CLI 2025-12-05 21:05:36 +08:00
mingholy.lmh
c218048551 fix: prevent sending control request when query is closed 2025-12-05 18:46:51 +08:00
yiliang114
be44e7af56 refactor(vscode-ide-companion): update message handling and configuration 2025-12-05 18:03:46 +08:00
yiliang114
ac9cb3a6d3 style(vscode-ide-companion/ui): improve component styling and layout 2025-12-05 18:03:37 +08:00
yiliang114
13aa4b03c7 feat(vscode-ide-companion/ui): improve permission drawer UI and logic 2025-12-05 18:03:29 +08:00
yiliang114
75fd2a5dcc feat(vscode-ide-companion/markdown): add copy button to code blocks in markdown renderer 2025-12-05 18:03:23 +08:00
yiliang114
811b332bc3 feat(vscode-ide-companion/ui): add context toggle control to input form 2025-12-05 18:03:18 +08:00
yiliang114
bf4673b00b feat(vscode-ide-companion/webview): enhance text selection tracking and restore path 2025-12-05 18:03:08 +08:00
yiliang114
645a5b181a fix(vscode-ide-companion/panel): update chat webview placement strategy to dedicated left group 2025-12-05 18:03:03 +08:00
yiliang114
2957058521 feat(vscode-ide-companion/webview): persist info banner dismissal state and add context control 2025-12-05 18:02:54 +08:00
yiliang114
e7b92622ce feat(vscode-ide-companion/diff): implement diff auto-open functionality in preferred editor group 2025-12-05 18:02:46 +08:00
yiliang114
82f97fe56d fix(vscode-ide-companion/acp): correct optionId mapping and outcome handling in acpMessageHandler 2025-12-05 18:02:40 +08:00
xuewenjie
2c1a836f18 fix: prefer UTF-8 encoding for shell output on Windows when detected 2025-12-05 16:49:26 +08:00
tanzhenxin
3a7b1159ae feat: add usage metadata in acp session/update event 2025-12-05 15:40:49 +08:00
tanzhenxin
3e2a2255ee DeepSeek V3.2 Thinking Mode Integration (#1134) 2025-12-05 15:08:35 +08:00
mingholy.lmh
46478e5dd3 fix: try fix sandbox integration test failure 2025-12-05 13:14:55 +08:00
mingholy.lmh
64de3520b3 docs: update README to include SDK-embedded MCP server details and usage examples 2025-12-05 13:14:55 +08:00
mingholy.lmh
322ce80e2c feat: implement SDK MCP server support and enhance control request handling
- Added new `SdkMcpController` to manage communication between CLI MCP clients and SDK MCP servers.
- Introduced `createSdkMcpServer` function for creating SDK-embedded MCP servers.
- Updated configuration options to support both external and SDK MCP servers.
- Enhanced timeout settings for various SDK operations, including MCP requests.
- Refactored existing control request handling to accommodate new SDK MCP server functionality.
- Updated tests to cover new SDK MCP server features and ensure proper integration.
2025-12-05 13:14:54 +08:00
yiliang114
c6f5a4585e style(vscode-ide-companion/ui): improve InfoBanner layout and centering
Add maxWidth constraint and auto margins to center the InfoBanner component
for better visual presentation.
2025-12-05 12:44:56 +08:00
yiliang114
b1a439e38f feat(vscode-ide-companion/read): implement diff auto-open functionality
Add diff viewing capabilities to Read tool calls with automatic opening of
VS Code diff tabs when diff content is detected. Includes:
- Import necessary React hooks and VS Code context
- Memoize content grouping for performance
- Auto-open diff in VS Code with useEffect
- Handle diff messages with useCallback
- Display compact UI when diff content is present
2025-12-05 12:42:58 +08:00
yiliang114
a6467e7f9b fix(vscode-ide-companion/ui): remove active background from focused permission options
Remove bg-[var(--app-list-active-background)] from focused permission drawer
options to improve visual consistency.
2025-12-05 12:42:50 +08:00
yiliang114
5ed60348d6 refactor(vscode-ide-companion/extension): disable unused path import and diff relay
Temporarily disable unused path import and diff event relaying functionality
that was causing issues.

TODO: 没有生效 - temporarily disabled due to commented out usage
2025-12-05 12:42:44 +08:00
yiliang114
0851ab572d fix(vscode-ide-companion/acp): correct optionId mapping in acpMessageHandler
Simplify the optionId mapping logic to directly use the provided optionId
rather than transforming 'reject_once' to 'cancel'. This ensures the
original optionId value is preserved in the outcome.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 11:41:33 +08:00
pomelo
a58d3f7aaf Merge pull request #1148 from QwenLM/feat/no-quit-confirm
Remove `/quit-confirm` flow
2025-12-05 10:56:08 +08:00
yiliang114
8203f6582f feat(vscode-ide-companion/extension): relay diff accept/cancel events to chat webview
Added functionality to relay diff accepted/cancelled events from the IDE to the chat webview
so users get immediate feedback when they accept or cancel diffs in the Claude Code style.
2025-12-05 02:45:44 +08:00
yiliang114
2d844d11df fix(vscode-ide-companion): improve message logging and permission handling
- Increase message logging truncation limit from 500 to 1500 characters
- Fix permission option mapping logic for reject_once/cancel options
- Add TODO comments for diff accept/cancel responses during permission requests

Resolves issues with permission handling and improves debugging capabilities.
2025-12-05 02:15:48 +08:00
Mingholy
aacc4b43ff Merge pull request #1150 from QwenLM/mingholy/ci/skip-case
test: skip qwen-oauth test in containerized environments
2025-12-04 20:53:12 +08:00
mingholy.lmh
57b519db9a test: skip qwen-oauth e2 case in sandbox 2025-12-04 20:39:51 +08:00
Mingholy
43f23f8ce5 Merge pull request #1103 from QwenLM/mingholy/feat/cli-sdk-stage-1
feat: basic TypeScript SDK
2025-12-04 18:06:22 +08:00
mingholy.lmh
427c69ba07 chore: fix sdk release workflow and verified with yamllint and act 2025-12-04 17:52:07 +08:00
tanzhenxin
1c45ef563d remove unused files 2025-12-04 17:41:52 +08:00
mingholy.lmh
0630908e0c fix: lint error 2025-12-04 17:36:22 +08:00
mingholy.lmh
c18fed574f chore: fix RELEASE_TAG fallback in workflow 2025-12-04 17:22:20 +08:00
mingholy.lmh
51b9281774 chore: remove scheduled triggers from SDK release workflow 2025-12-04 17:10:24 +08:00
mingholy.lmh
839a1d9d8c fix: mock path for cross platform compability in test cases 2025-12-04 17:10:24 +08:00
mingholy.lmh
56f61bc0b8 fix: path literals in windows 2025-12-04 17:10:24 +08:00
mingholy.lmh
b1d848f935 chore: update lockfile 2025-12-04 17:10:24 +08:00
mingholy.lmh
81c8b3eaec feat: add GitHub Actions workflow for SDK release automation 2025-12-04 17:10:23 +08:00
mingholy.lmh
50e3a6ee0a fix: enhance 429 error handling and fix failed cases 2025-12-04 17:10:23 +08:00
mingholy.lmh
3056f8a63d feat(tests): move SDK integration tests to integration-tests to share globalSetup 2025-12-04 17:10:23 +08:00
mingholy.lmh
ae7d6af717 fix(test): remove unused test cases 2025-12-04 17:10:22 +08:00
mingholy.lmh
8035be6f8d fix: plan mode adjustments 2025-12-04 17:10:22 +08:00
mingholy.lmh
249b141f19 feat: add allowedTools for SDK use and re-organize test setup 2025-12-04 17:10:22 +08:00
mingholy.lmh
56957a687b refactor: rename ambiguous exported types 2025-12-04 17:10:21 +08:00
mingholy.lmh
638b7bb466 feat: add allowedTools support 2025-12-04 17:10:21 +08:00
mingholy.lmh
d76341b8d8 chore: keep comments for queryOptions 2025-12-04 17:10:21 +08:00
mingholy.lmh
769a438fa4 feat: enhance logging capabilities and update query options in sdk-typescript
- Introduced a new logging system with adjustable log levels (debug, info, warn, error).
- Updated query options to include a logLevel parameter for controlling verbosity.
- Refactored existing code to utilize the new logging system for better error handling and debugging.
- Cleaned up unused code and improved the structure of the SDK.
2025-12-04 17:10:20 +08:00
mingholy.lmh
49dc84ac0e feat: add support for includePartialMessages option in query and transport layers 2025-12-04 17:10:20 +08:00
mingholy.lmh
ac6aecb622 refactor: update test structure and clean up unused code in cli and sdk 2025-12-04 17:10:20 +08:00
mingholy.lmh
ad9ba914e1 refactor: clean up exports in sdk-typescript index file 2025-12-04 17:10:20 +08:00
mingholy.lmh
d76cdf1076 feat: sdk subagent support 2025-12-04 17:10:20 +08:00
mingholy.lmh
e1ffaec499 feat: create draft framework for cli & sdk 2025-12-04 17:10:16 +08:00
tanzhenxin
5b2f3e285c remove /quit-confirm slash command 2025-12-04 16:21:32 +08:00
yiliang114
4145f45c7c fix(vscode-ide-companion): fix send/stop button state timing issue
- Show stop button immediately when request is submitted (isWaitingForResponse=true)
- Prevent confusing state where send button appears disabled instead of stop button
- Improve UX by providing immediate visual feedback on request submission

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-04 12:47:18 +08:00
tanzhenxin
6729980b47 skip acp integration test in sandbox env (#1141) 2025-12-04 10:28:21 +08:00
yiliang114
d56923b657 refactor(vscode-ide-companion): remove deprecated file locations
- Removed old InfoBanner.tsx file location
- Removed old ReadToolCall.tsx file location

These files have been moved to new directory structures.
2025-12-04 08:29:34 +08:00
yiliang114
32258f2f04 fix(vscode-ide-companion): ensure restored panel title resets to default
- Added code to reset restored panel title to 'Qwen Code' on initialization
- Added error handling for title reset operation

This ensures consistent panel labeling when restoring previous sessions.
2025-12-04 08:29:22 +08:00
yiliang114
5dec3e653c feat(vscode-ide-companion): add specialized tool call components
- Added ExecuteNodeToolCall for specialized node/npm command execution
- Added UpdatedPlanToolCall for enhanced plan visualization with checkboxes
- Created ExecuteNode CSS styling
- Refactored ReadToolCall to new directory structure
- Updated tool call router to handle new component types
- Enhanced LayoutComponents with className prop support
- Added specialized handling for todo_write and updated_plan tool kinds

These additions improve the visualization and handling of various tool call types in the UI.
2025-12-04 08:29:07 +08:00
yiliang114
3053e6c41f style(vscode-ide-companion): update UI components and styling
- Updated chat message container spacing and styling
- Adjusted AssistantMessage text color handling
- Enhanced QwenMessageTimeline CSS rules for better visual flow
- Moved InfoBanner to ui directory for better organization
- Updated InputForm styling
- Added new CSS classes and updated tailwind configuration
- Improved timeline connection lines and message item spacing

These changes enhance the visual appearance and user experience of the chat interface.
2025-12-04 08:28:54 +08:00
yiliang114
86cd06ef43 feat(vscode-ide-companion): add MarkdownRenderer component for rich message formatting
- Added MarkdownRenderer component with markdown-it integration
- Updated MessageContent to use MarkdownRenderer instead of custom parsing
- Added CSS styling for markdown-rendered content

This improves message display with proper markdown rendering support.
2025-12-04 08:28:42 +08:00
yiliang114
7270983821 feat(vscode-ide-companion): add markdown-it dependency for markdown rendering
- Added markdown-it as a dependency for enhanced markdown processing
- Updated @types/markdown-it as dev dependency
- Updated NOTICES.txt with new dependency licenses

This enables rich markdown rendering capabilities in the VS Code extension.
2025-12-04 08:28:30 +08:00
yiliang114
b1901f103f refactor(vscode-ide-companion): remove merged timeline CSS file
- Remove MergedSimpleTimeline.css in favor of SimpleTimeline.css
2025-12-04 01:54:16 +08:00
yiliang114
5701a3c897 refactor(vscode-ide-companion): update timeline CSS files
- Replace MergedSimpleTimeline.css with SimpleTimeline.css
- Update timeline styling for tool calls and messages
2025-12-04 01:54:07 +08:00
yiliang114
2145b28f8b style(vscode-ide-companion): update message components and layout styling
- Add qwen-message class to AssistantMessage container
- Update LayoutComponents styling
- Add custom timeline styles for message items
2025-12-04 01:53:42 +08:00
yiliang114
e3c456a430 feat(vscode-ide-companion): add cancel streaming functionality
- Add handleCancel callback to App component
- Implement cancelStreaming message posting to VS Code
- Add onCancel prop to InputForm component
- Replace send button with stop button during streaming
2025-12-04 01:53:19 +08:00
yiliang114
35f98723ca style(vscode-ide-companion): bash toolcall 2025-12-04 00:23:19 +08:00
yiliang114
b9b3b6d62e style(vscode-ide-companion): header & empty state 2025-12-04 00:18:04 +08:00
yiliang114
cec6b8691a Merge branch 'main' of https://github.com/QwenLM/qwen-code into feat/jinjing/write-and-read-file-in-vscode 2025-12-03 23:14:44 +08:00
tanzhenxin
2ca36d7508 skip one flaky integration test (#1137) 2025-12-03 19:40:14 +08:00
tanzhenxin
e426c15e9e pump version to 0.4.0 (#1132) 2025-12-03 18:10:11 +08:00
tanzhenxin
0a75d85ac9 Session-Level Conversation History Management (#1113) 2025-12-03 18:04:48 +08:00
yiliang114
05f5189bb4 refactor(vscode-ide-companion/panel): reimplement editor group locking with proper error handling 2025-12-03 01:03:10 +08:00
yiliang114
c6299bf135 feat(vscode-ide-companion): improve CLI path detection and error handling
- Move determineNodePathForCli function to dedicated cliPathDetector.ts file
- Enhance error handling with specific guidance for permission issues
- Add detailed error messages for different failure scenarios
- Improve logging for debugging CLI path detection issues

This change improves the reliability of CLI path detection by providing better error messages and handling edge cases more gracefully.
2025-12-03 00:27:20 +08:00
yiliang114
2e449f4d45 wip(vscode-ide-companion): timelint 2025-12-02 14:41:00 +08:00
Zijun Yang
a7abd8d09f fix(shell-utils): resolve command detection on Ubuntu by using shell for builtins (#1123) 2025-12-02 11:49:40 +08:00
yiliang114
90fc53a9df refactor(webview): Refactoring Input Form and Timeline Components 2025-12-02 01:29:33 +08:00
yiliang114
ed0d5f67db style(vscode-ide-companion): form component style opt 2025-12-01 00:15:18 +08:00
yiliang114
1b37d729cb style(vscode-ide-companion): use tailwind to refactor some ui components 2025-11-30 23:06:37 +08:00
yiliang114
1acc24bc17 fix(vscode-ide-companion): Interactive unification of first login and login 2025-11-30 22:26:04 +08:00
yiliang114
b1e74e5732 style(vscode-ide-companion): optimize header & message style 2025-11-30 21:27:55 +08:00
yiliang114
82205034cc chore(vscode-ide-companion): remove the ui component of the active save session temporarily 2025-11-29 18:29:43 +08:00
yiliang114
c038745897 fix(vscode-ide-companion): 修复 Tailwind 可重用组件类和 ESLint 配置, 调整 ChatHeader 按钮样式
- 在 tailwind.css 中正确定义可重用的 Tailwind 组件类
- 修复 ChatHeader 组件中的按钮样式,确保 hover 效果正常工作
- 修复 ESLint 配置中的 importPlugin 导入问题
- 清理 App.css 中重复的 CSS 变量定义
- 为 btn-ghost 类设置 4px border radius
- 为按钮内的 span 添加左右 4px padding (使用 px-1)
- 确保按钮 hover 时有背景色效果
2025-11-29 18:13:50 +08:00
yiliang114
6885138cf0 refactor(vscode-ide-companion): Refactoring the project structure and updating dependencies 2025-11-29 13:16:58 +08:00
yiliang114
9ae45c01a6 refactor(vscode): 重构消息排序和展示逻辑
- 移除旧的消息排序改进总结文档
- 重新组织消息渲染逻辑,合并所有类型的消息按时间戳排序
- 优化工具调用处理流程,添加时间戳支持
- 改进会话保存机制,直接使用SessionManager保存检查点
- 重构部分组件以提高可维护性
2025-11-28 22:35:31 +08:00
yiliang114
5ce40085d5 fix(vscode-ide-companion): 优化 CLI 检测和连接逻辑 2025-11-28 17:44:18 +08:00
yiliang114
627f5fb43a refactor(vscode-ide-companion): 优化代码结构和性能
- 移除未使用的依赖项 qwen-code
- 优化 completion 刷新逻辑,避免渲染循环
- 更新 CompletionMenu 组件,增加空状态提示
2025-11-28 10:04:29 +08:00
yiliang114
9cc48f12da feat(vscode-ide-companion): 改进消息排序和显示逻辑
- 添加时间戳支持,确保消息按时间顺序排列
- 更新工具调用处理逻辑,自动添加和保留时间戳
- 修改消息渲染逻辑,将所有类型的消息合并排序后统一渲染
- 优化完成的工具调用显示,修复显示顺序问题
- 调整进行中的工具调用显示,统一到消息流中展示
- 移除重复的计划展示逻辑,避免最新块重复出现
- 重构消息处理和渲染代码,提高可维护性
2025-11-28 09:55:06 +08:00
yiliang114
dc340daf8b feat(vscode-ide-companion): 0.2.4 版本ACP 协议检测和实现
- 新增 session/list 方法支持
- 改进 session/load 方法兼容性
- 优化代理环境变量设置
- 调整 CLI 安装流程
- 移除未使用的随机加载消息功能
2025-11-28 01:17:55 +08:00
yiliang114
f78b1eff93 build(vscode-ide-companion): 更新包准备命令
- 将 "prepare1" 命令重命名为 "prepare",以提高可读性和一致性
- 优化了包生成流程,确保在构建前生成必要的 notices
2025-11-28 01:14:36 +08:00
yiliang114
8bc9bea5a1 feat(cli): 添加 CLI 版本检测和会话验证功能
- 新增 CLI 版本检测功能,支持检测 CLI 版本并缓存结果
- 实现会话验证方法,用于检查当前会话是否有效
- 在连接处理中集成 CLI 版本检测和会话验证逻辑
- 优化 WebViewProvider 中的初始化流程,支持背景初始化
- 更新消息处理逻辑,增加与 CLI 相关的错误处理
2025-11-28 01:13:57 +08:00
yiliang114
b986692f94 feat(auth): 优化认证流程并添加认证状态管理
- 新增 AuthStateManager 类用于管理认证状态
- 修改 createNewSession 方法以使用缓存的认证信息
- 添加清除认证缓存的功能
- 优化登录命令处理,增加加载状态显示
- 新增登录成功和失败的消息处理
2025-11-28 01:06:36 +08:00
yiliang114
4f63d92bb1 Add unit tests for CLI modules and fix ESLint issues
- Add comprehensive unit tests for all CLI-related modules:
  - CliContextManager
  - CliVersionManager
  - cliDetector
  - CliInstaller
- Fix ESLint issues by replacing @ts-ignore with @ts-expect-error
- Fix any type issues in test files
- Add tests for diff-manager functionality
- Improve loading messages random selection stability

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 01:06:21 +08:00
yiliang114
3c09ad46ca refactor(vscode-ide-companion): translate Chinese comments to English
- Translate all Chinese comments in TypeScript files to English for better code readability
- Update documentation comments to be in English
- Maintain code functionality while improving internationalization

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 01:01:47 +08:00
yiliang114
d5ede56e62 Revert "fix(vscode-ide-companion): 解决 mac 环境多个 node 版本的安装问题"
This reverts commit 530039c517.
2025-11-28 00:57:33 +08:00
yiliang114
530039c517 fix(vscode-ide-companion): 解决 mac 环境多个 node 版本的安装问题 2025-11-25 20:24:26 +08:00
yiliang114
0cbf95d6b3 chore(vscode-ide-companion): update dependencies in package-lock.json
Added new dependencies including:
- @cfworker/json-schema
- @parcel/watcher and related platform-specific packages
- autoprefixer
- browserslist
- chokidar
- Various other utility packages

These updates likely support enhanced functionality and improved compatibility.
2025-11-25 15:30:36 +08:00
yiliang114
579772197a chore(vscode-ide-companion): 更新 .gitignore 文件
- 移除了 pnpm-lock.yaml 文件的忽略规则
- 保留了 .claude 目录的忽略规则
2025-11-25 13:46:38 +08:00
yiliang114
934365c41f style(vscode-ide-companion): improve UI styling for chat components 2025-11-25 13:39:49 +08:00
yiliang114
f623bfbb34 chore(vscode-ide-companion): add qwen-code dependency to package files 2025-11-25 13:39:07 +08:00
yiliang114
f503eb2520 feat(vscode-ide-companion): split module & notes in english 2025-11-25 00:32:51 +08:00
yiliang114
3cf22c065f Merge branch 'main' of https://github.com/QwenLM/qwen-code into feat/jinjing/write-and-read-file-in-vscode 2025-11-24 20:40:19 +08:00
yiliang114
a1ec1227cc refactor(vscode-ide-companion): reorganize component structure
重构组件结构,优化目录组织:
- 将 ChatHeader 从 ui/ 移动到 layouts/ 目录
- 删除未使用的 Button 和 Card 组件
- 更新 tailwind.config.js 扫描路径为 layouts/
- 简化组件目录结构,提高可维护性
2025-11-24 20:38:36 +08:00
yiliang114
36af718616 chore(vscode-ide-companion): add testing infrastructure and improve config files
添加测试基础设施和改进配置文件:
- 添加 vitest.config.js 用于单元测试配置
- 配置测试覆盖率报告(v8 provider)
- 修复 postcss.config.js 的 eslint 警告
- 设置测试环境为 Node.js
2025-11-24 20:38:35 +08:00
yiliang114
795e7fa2c5 fix(vscode-ide-companion): improve type safety in webview components
修复 webview 组件的类型安全问题:
- App.tsx: 规范化工具调用状态为联合类型
- InProgressToolCall.tsx: 安全处理非字符串类型的 title 属性
- InputForm.tsx: 修正 RefObject 泛型类型声明
- ReadToolCall.tsx: 添加空 children 避免 ToolCallContainer 警告
2025-11-24 20:38:35 +08:00
yiliang114
b6914c6b33 feat(vscode-ide-companion): enhance WebViewProvider with force re-login functionality
增强 WebViewProvider 的重新登录功能:
- 修复 _lastEditorState 变量声明错误(const -> let)
- 在强制重新登录后添加清理等待时间
- 添加登录成功/失败的 WebView 消息通知
- 改进错误处理和日志记录
- 为用户提供更好的登录状态反馈
2025-11-24 20:38:35 +08:00
yiliang114
f11d054a47 feat(vscode-ide-companion): improve authentication flow with cached auth state
优化认证流程,支持缓存认证状态避免重复认证:
- 在 qwenAgentManager 中创建会话前先进行认证
- 在 qwenConnectionHandler 中检查缓存的认证状态
- 只在没有有效缓存时触发新的认证流程
- 认证失败时清除无效缓存
- 添加详细的日志记录用于调试
2025-11-24 20:32:08 +08:00
yiliang114
4ad377b0d8 chore(vscode-ide-companion): update lock 2025-11-24 10:04:03 +08:00
yiliang114
b7f9acf0ff refactor(vscode-ide-companion): migrate session save to CLI /chat save command
- Replace manual checkpoint file writing with CLI's native /chat save command
- Add saveCheckpointViaCommand method to use CLI's built-in save functionality
- Deprecate saveSessionViaAcp as CLI doesn't support session/save ACP method
- Update saveCheckpoint to delegate to CLI command for complete context preservation
- Enhanced error logging in acpSessionManager session load
- Mark saveSessionViaAcp as deprecated with fallback to command-based save
- Fix ESLint errors: remove unused imports and catch variables, wrap case block declarations

This ensures checkpoints are saved with complete session context including tool calls,
leveraging CLI's native save functionality instead of manual file operations.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-24 01:00:31 +08:00
yiliang114
4dfbdcddca feat(vscode-ide-companion): 增强工具调用与输入表单组件功能
- 新增 InProgressToolCall 组件用于展示进行中的工具调用状态
- 重构 InputForm 为独立组件,提升代码可维护性
- 改进 tool_call_update 处理逻辑,支持创建缺失的初始工具调用
- 添加思考块(thought chunk)日志以便调试 AI 思维过程
- 更新样式以支持新的进行中工具调用卡片显示
- 在权限请求时自动创建对应的工具调用记录
```
2025-11-23 22:28:11 +08:00
yiliang114
826516581b feat(vscode-ide-companion): send initial active editor state to WebView on initialization
- Send activeEditorChanged message with initial editor state when WebView is created
- Include fileName, filePath, and selection info if available
- Applied in both side panel and editor panel initialization

This ensures the WebView displays the current file context immediately on load.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 21:45:44 +08:00
yiliang114
4f964b5281 refactor(vscode-ide-companion): extract AssistantMessage as standalone component with Claude Code styles
- Extract AssistantMessage component from inline implementation
- Add status prop support (default, success, error, warning, loading)
- Implement bullet point indicator using CSS pseudo-elements (::before)
- Use inline styles for layout to prevent Tailwind override
- Add AssistantMessage.css with pseudo-element styles for different states
- Import AssistantMessage.css in ClaudeCodeStyles.css

Restores Claude Code DOM structure and styling:
- Outer container with padding-left: 30px for bullet spacing
- Bullet point colors based on status (green, red, yellow, gray)
- Loading state with pulse animation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 21:44:40 +08:00
yiliang114
de8ea0678d feat(vscode-ide-companion): refactor message components with modular architecture
Refactor UI message rendering by extracting message types into dedicated components. Add ChatHeader component for better session management interface.

- Extract message components: UserMessage, AssistantMessage, ThinkingMessage, StreamingMessage, WaitingMessage
- Add ChatHeader component with session selector and action buttons
- Delete MessageContent.css and consolidate styles into App.scss
- Update Tailwind config for component styling
- Improve message rendering with proper TypeScript typing
2025-11-23 20:56:15 +08:00
yiliang114
c4bcd178a4 feat(vscode-ide-companion): implement manual login via /login command
BREAKING CHANGE: Login is no longer automatic when opening webview

Changes:
- Remove auto-login on webview open and restore
- Add /login slash command for manual authentication
- Add VSCode progress notification during login process
- Add warning notification when user tries to chat without login
- Implement pending message auto-retry after successful login
- Add NotLoggedInMessage component (for future use)
- Improve InfoBanner close button styling consistency

User flow:
1. Open webview - no automatic login
2. Type /login or select from completion menu to login
3. Show "Logging in to Qwen Code..." progress notification
4. After login, show success message and auto-retry pending messages
5. If user tries to chat without login, show warning with "Login Now" button

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 19:20:01 +08:00
yiliang114
e5729b0420 Merge branch 'feat/jinjing/implement-ui-from-cc-vscode-extension' of https://github.com/yiliang114/qwen-code into feat/jinjing/implement-ui-from-cc-vscode-extension 2025-11-23 18:37:00 +08:00
yiliang114
aceb857436 refactor(vscode-ide-companion): extract InfoBanner as standalone component
Move info banner UI from App.tsx to dedicated component with open settings functionality.
2025-11-23 18:11:47 +08:00
yiliang114
e15dd2f5c9 refactor(vscode-ide-companion): extract InfoBanner as standalone component
Move info banner UI from App.tsx to dedicated component with open settings functionality.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-23 18:09:43 +08:00
Mingholy
c9af74816a fix: reset authType settings (#1091)
* fix: reset authType settings

* fix: failed json-output tests

* fix: sandbox exception log to stderr
2025-11-23 17:59:35 +08:00
yiliang114
8ac38aad92 chore(vscode-ide-companion): tailwind base 2025-11-23 17:33:10 +08:00
yiliang114
38fd303b07 docs(vscode-ide-companion): add Tailwind CSS integration guides
添加 Tailwind CSS 渐进式集成文档,包括:
- 渐进式采用策略文档
- 集成计划文档
- 渐进式集成指南
2025-11-23 16:41:22 +08:00
yiliang114
9899d872a2 feat(vscode-ide-companion): add Tailwind CSS demo components
添加 Tailwind CSS 示例组件和重构的 PermissionDrawer:
- TailwindDemo: 展示 Tailwind CSS 基础用法
- PermissionDrawer.tailwind: 使用 Tailwind CSS 重构的权限抽屉组件
2025-11-23 16:41:09 +08:00
yiliang114
36a96a7b5c feat(vscode-ide-companion): add shadcn/ui components and utilities
添加 shadcn/ui 基础组件库和 cn 工具函数,包括:
- Button 按钮组件
- Dialog 对话框组件
- cn 类名合并工具函数
2025-11-23 16:40:55 +08:00
yiliang114
951f6b2829 feat(vscode-ide-companion): add global Tailwind CSS styles
添加全局 Tailwind CSS 样式文件,包含基础层、组件层和工具层
2025-11-23 16:40:42 +08:00
yiliang114
eff01819a8 build(vscode-ide-companion): add Tailwind CSS configuration
添加 Tailwind CSS、PostCSS 和 Autoprefixer 配置,为渐进式采用 Tailwind CSS 做准备
2025-11-23 16:40:30 +08:00
yiliang114
31f8ca07b6 chore: remove root package-lock.json
移除根目录的 package-lock.json 文件,采用各子包独立管理依赖的策略
2025-11-23 16:40:17 +08:00
yiliang114
39adaaff11 refactor(vscode-ide-companion): minor adjustments to SaveSessionDialog and SessionManager components 2025-11-23 15:17:40 +08:00
yiliang114
fd2e5b0933 feat(vscode-ide-companion): improve PermissionDrawer UI with enhanced styling and responsiveness 2025-11-23 15:17:17 +08:00
yiliang114
49a2be195d chore: add .claude/ to gitignore 2025-11-23 15:17:05 +08:00
pomelo
9cfea73207 Merge pull request #1097 from QwenLM/chore-action
fix(ci): remove non-existent label from release failure issue creation
2025-11-23 08:27:34 +08:00
pomelo-nwu
87b1ffe017 fix(ci): remove non-existent label from release failure issue creation 2025-11-22 14:23:49 +08:00
yiliang114
ce07fb2b3f feat(session): 实现会话保存和加载功能
- 在 AcpConnection 和 AcpSessionManager 中添加会话保存方法
- 在 QwenAgentManager 中实现通过 ACP 和直接保存会话的功能
- 在前端添加保存会话对话框和相关交互逻辑
- 新增 QwenSessionManager 用于直接操作文件系统保存和加载会话
2025-11-21 23:51:48 +08:00
pomelo
83fc321e15 Merge pull request #1090 from QwenLM/feat/logger-enhancement
Improve Usage Statistics by Moving Key Snapshot Fields into Properties
2025-11-21 15:55:26 +08:00
pomelo
48b77541c3 feat(i18n): Add Internationalization Support for UI and LLM Output (#1058) 2025-11-21 15:44:37 +08:00
tanzhenxin
f2439f8d53 fix: skip one unstable test case 2025-11-21 15:43:05 +08:00
tanzhenxin
fb6d0b43fa feat: change shortcut for subagent execution display 2025-11-21 15:42:17 +08:00
tanzhenxin
627283d357 feat: enhance usage statistics in qwen logger 2025-11-21 15:17:34 +08:00
tanzhenxin
640f30655d chore: pump version to 0.3.0 (#1085) 2025-11-21 09:37:38 +08:00
Kdump
9e5387f159 Headless enhancement: add stream-json as input-format/output-format to support programmatically use (#926) 2025-11-21 09:26:05 +08:00
yiliang114
e2beecb9c4 feat(vscode-ide-companion): 更新核心服务和扩展功能
- 增强 extension.ts,集成新增功能
- 优化 ide-server.ts,改进服务端逻辑
- 更新 diff-manager.ts,提升差异管理能力
- 改进 ACP 连接和消息处理
- 更新会话处理器,支持新的交互模式

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:54:24 +08:00
yiliang114
ecc6e22002 feat(vscode-ide-companion): 更新 UI 样式
- 重构 PlanDisplay 组件和样式
- 更新 PermissionRequest 组件逻辑
- 增强 PermissionDrawer 样式,提升视觉体验

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:54:03 +08:00
yiliang114
99f93b457c feat(vscode-ide-companion): 更新主应用界面和消息处理
- 重构 App.tsx,集成新增的 UI 组件
- 增强 MessageHandler,支持更多消息类型处理
- 优化 FileOperations,改进文件操作逻辑

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:53:46 +08:00
yiliang114
748ad8f4dd refactor(vscode-ide-companion): 重构工具调用组件
- 重构 ExecuteToolCall、GenericToolCall、ReadToolCall 等组件
- 统一工具调用组件的展示样式和交互逻辑
- 优化代码结构,提高可维护性

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:53:25 +08:00
yiliang114
a33187ed7a feat(vscode-ide-companion): 新增时间线组件
- 新增 Timeline 组件用于显示会话历史
- 支持展示消息、工具调用等事件
- 提供清晰的时间轴视图

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:53:05 +08:00
yiliang114
088c766c22 feat(vscode-ide-companion): 新增自动完成功能
- 新增 CompletionMenu 组件支持 @ 和 / 触发补全
- 新增 useCompletionTrigger hook 处理补全触发逻辑
- 支持实时查询和过滤补全项

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:52:47 +08:00
yiliang114
b82ef5b73f feat(vscode-ide-companion): 新增上下文附件管理功能
- 新增 ContextAttachmentManager 管理上下文附件
- 新增 ContextPills 组件用于显示上下文标签
- 支持文件、符号、选区等多种上下文类型

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:52:29 +08:00
yiliang114
328924f578 feat(vscode-ide-companion): 新增 DiffDisplay 组件和 diff 统计工具
- 增强 DiffDisplay 组件,支持更丰富的差异展示
- 新增 diffStats.ts 工具,提供差异统计功能
- 新增样式文件 DiffDisplay.css

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:52:10 +08:00
yiliang114
1eedd36542 feat(vscode-ide-companion): 新增共享 UI 组件 FileLink
- 新增 FileLink 组件用于显示文件链接
- 更新 LayoutComponents 增加通用布局组件
- 新增 utils.ts 提供工具函数

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 01:51:50 +08:00
yiliang114
9ba99177b9 refactor(vscode-ide-companion): 重构主动完成和会话管理
- 移除了 QwenAgentManager 中的冗余类型导出
- 优化了 App 组件中的会话管理和标题更新逻辑
- 改进了消息输入框的中文输入法支持
- 调整了活动文件指示器的样式
2025-11-20 23:50:41 +08:00
yiliang114
7d2411e72f feat(vscode-ide-companion): 优化 Qwen Code 聊天窗口创建逻辑
- 修改 createPanel 方法返回值类型,使其支持异步操作
- 实现聚焦当前激活编辑器的功能
- 优化多窗口创建逻辑,允许在已有 Qwen Code 窗口旁边创建新窗口
- 移除自动锁定编辑器组的功能,以支持多个 Qwen Code 标签页
- 在 UI 中添加聚焦当前文件的按钮
2025-11-20 23:41:41 +08:00
yiliang114
5a9f5e3432 fix(vscode-ide-companion): 修复新建会话按钮,在同一 view column 创建新 tab
问题:
- 之前的实现会复用现有 panel 并清空当前会话
- 期望行为是在同一 view column(不创建分屏)中创建新的 VS Code tab

解决方案:
1. 修改 qwenCode.openNewChatTab 命令
   - 总是创建新的 WebviewProvider 和 WebviewPanel
   - PanelManager 的 findExistingQwenCodeViewColumn() 确保在同一 column 打开
2. 修改 MessageHandler 中的 openNewChatTab 处理
   - 调用 VS Code 命令创建新 panel/tab
3. 移除不再需要的 createNewSession 方法

效果:
- 点击新建会话按钮会在同一 view column 中创建新的 VS Code tab
- 类似 Claude Code 的交互方式
- 不会创建新的分屏

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-20 23:14:40 +08:00
yiliang114
95b67bbebd fix(vscode-ide-companion): 修复新建会话按钮创建新分屏的问题
问题:
- 点击新建会话按钮时,会在 VS Code 中创建一个新的 webview panel(分屏)
- 期望行为是在同一个 panel 内创建新会话,类似 Claude Code 的交互方式

解决方案:
1. 修改 extension.ts 中的 openNewChatTab 命令
   - 检查是否已有 webview panel 打开
   - 如果有,则在现有 panel 中创建新会话
   - 如果没有,才创建新 panel
2. 在 WebViewProvider 中添加 createNewSession 方法
   - 通过 agentManager 创建新会话
   - 清空当前对话 UI
3. 修改 MessageHandler 中的 openNewChatTab 处理
   - 直接调用 handleNewQwenSession 创建新会话
   - 不再执行 VS Code 命令创建新 panel

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-20 23:07:56 +08:00
tanzhenxin
442a9aed58 Replace spawn with execFile for memory-safe command execution (#1068) 2025-11-20 15:04:00 +08:00
Mingholy
a15b84e2a1 refactor(auth): enhance useAuthCommand to include history management and improve error handling in QwenOAuth2Client (#1077) 2025-11-20 14:37:39 +08:00
tanzhenxin
07069f00d1 feat: remove prompt completion feature (#1076) 2025-11-20 14:36:51 +08:00
pomelo
e1e7a0d606 Merge pull request #1074 from cwtuan/patch-1
fix: remove broken link
2025-11-20 14:33:14 +08:00
yiliang114
492c56a780 test(vscode-ide-companion): registerWebviewPanelSerializer 添加 mock 实现 2025-11-20 14:31:20 +08:00
cwtuan
fc638851e7 fix: remove broken link 2025-11-20 12:50:06 +08:00
yiliang114
06a8580361 refactor(vscode-ide-companion): 重构 WebViewProvider 组件 2025-11-20 11:37:28 +08:00
yiliang114
dcc10eb0a9 fix(vscode-ide-companion): 重构 useVSCode hook 实现, 解决 webview 中 vscode api 重复声明 2025-11-20 11:07:09 +08:00
yiliang114
805e5f92c1 docs(readme): 添加 VS Code 扩展相关信息
- 在主 README 中添加 VS Code 扩展部分,介绍扩展的功能和用途
- 更新 VS Code 扩展的 README,详细说明调试和开发指南
- 优化扩展开发流程说明,提供两种调试选项
2025-11-20 10:41:23 +08:00
citlalinda
e1f793b2e0 fix: character encoding corruption when executing the /copy command on Windows. (#1069)
Co-authored-by: linda <hxn@163.com>
2025-11-20 10:23:17 +08:00
tanzhenxin
3c64f7bff5 chore: pump version to 0.2.3 (#1073) 2025-11-20 10:09:12 +08:00
yiliang114
8cb7ea0d3d Merge branch 'main' of https://github.com/QwenLM/qwen-code into feat/jinjing/implement-ui-from-cc-vscode-extension 2025-11-20 10:06:14 +08:00
yiliang114
b534bd2b18 chore: rm wip doc 2025-11-20 10:05:47 +08:00
yiliang114
6286b8b6e8 feat(vscode-ide-companion): 增加代码编辑功能和文件操作支持
- 实现了与 Claude Code 类似的代码编辑功能
- 添加了文件打开、保存等操作的支持
- 优化了消息显示,增加了代码高亮和文件路径点击功能
- 改进了用户界面,增加了编辑模式切换和思考模式功能
2025-11-20 01:04:11 +08:00
yiliang114
e81255e589 feat(vscode-ide-companion): 优化权限请求组件并添加错误处理功能
- 移动权限请求组件到抽屉中,优化用户体验
- 为权限选项添加编号,提高可识别性
- 实现错误对象的特殊处理,提取更有意义的错误信息
- 优化工具调用错误内容的展示,提高错误信息的可读性
2025-11-20 00:01:18 +08:00
yiliang114
018990b7f6 build(vscode-ide-companion): 添加 SCSS 支持
- 在 esbuild.js 中添加 SCSS 文件处理逻辑
- 在 package.json 中添加 sass 依赖
- 新增代码使用 sass 编译 SCSS 文件,并将其注入到页面中
2025-11-19 23:34:05 +08:00
yiliang114
bc2b503e8d test(vscode-ide-companion): 尝试通过 session/load 旧会话
- 修改了 WebViewProvider 中的逻辑,先尝试通过 ACP 加载旧会话
- 如果加载失败,则创建新会话作为回退方案
- 在 AcpConnection 中添加了初始化响应的日志输出
- 在 QwenAgentManager 中添加了新的 loadSessionViaAcp 方法,用于测试 ACP 的 session/load 功能
2025-11-19 17:08:25 +08:00
yiliang114
454cbfdde4 refactor(webview): 重构工具调用显示逻辑
- 新增多个工具调用组件,分别处理不同类型的工具调用
- 优化工具调用卡片的样式和布局
- 添加加载状态和随机加载消息
- 重构 App 组件,支持新的工具调用显示逻辑
2025-11-19 15:42:35 +08:00
yiliang114
04dfad7ab5 docs(implementation): 更新实现总结文档 2025-11-19 13:50:52 +08:00
tanzhenxin
97bf48b14c fix: skip problematic integration test (#1065) 2025-11-19 11:55:19 +08:00
Mingholy
d0e76c76a8 refactor(auth): save authType after successfully authenticated (#1036) 2025-11-19 11:21:46 +08:00
yiliang114
e02866d06f refactor(vscode-ide-companion): 重构代码并更新文件命名
- 更新文件命名规则,使用小写字母和下划线
- 修复部分代码导入路径
- 删除未使用的 WEBVIEW_PIN_FEATURE.md 文件
2025-11-19 10:40:16 +08:00
tanzhenxin
3ed93d5b5d fix: integration tests (#1062) 2025-11-19 10:23:16 +08:00
yiliang114
9fcdd3fa77 Merge branch 'main' of https://github.com/QwenLM/qwen-code into feat/jinjing/implement-ui-from-cc-vscode-extension 2025-11-19 10:08:21 +08:00
yiliang114
754ae30939 refactor(vscode-ide-companion): 重构 WebViewProvider 初始化逻辑
- 抽离初始化代理连接逻辑到单独的方法中
- 优化面板恢复时的代理连接流程
- 移除 EmptyState 组件中的信息横幅
- 在 App 组件中添加可关闭的信息横幅
- 调整输入表单样式,移除冗余样式
2025-11-19 00:40:48 +08:00
yiliang114
0577fe6f36 refactor(vscode-ide-companion): 重构 WebViewProvider 初始化逻辑
- 抽离初始化代理连接逻辑到单独的方法中
- 优化面板恢复时的代理连接流程
- 移除 EmptyState 组件中的信息横幅
- 在 App 组件中添加可关闭的信息横幅
- 调整输入表单样式,移除冗余样式
2025-11-19 00:34:45 +08:00
yiliang114
732220e651 wip(vscode-ide-companion): 实现 quick win 功能
- 将 WebView 调整到编辑器右侧
- 添加 ChatHeader 组件,实现会话下拉菜单
- 替换模态框为紧凑型下拉菜单
- 更新会话切换逻辑,显示当前标题
- 清理旧的会话选择器样式
基于 Claude Code v2.0.43 UI 分析实现。
2025-11-19 00:16:45 +08:00
tanzhenxin
71646490f1 Fix: Improve ripgrep binary detection and cross-platform compatibility (#1060) 2025-11-18 19:38:30 +08:00
yiliang114
729a3d0ab3 Merge branch 'feat/jinjing/write-and-read-file-in-vscode' into feat/jinjing/implement-ui-from-cc-vscode-extension 2025-11-18 19:15:18 +08:00
yiliang114
0e3759fbd2 chore(vscode-ide-companion): 新建文件版权头更新 2025-11-18 19:14:38 +08:00
yiliang114
f8db157a5d Merge branch 'feat/jinjing/qwen-code-vscode-extension-init' into feat/jinjing/write-and-read-file-in-vscode 2025-11-18 19:13:11 +08:00
yiliang114
f827aadd76 Revert "refactor(vscode-ide-companion): 文件版权头 Copyright 2025 Google LLC"
This reverts commit 91af599823.
2025-11-18 19:10:07 +08:00
yiliang114
39426be9a1 wip 2025-11-18 14:25:05 +08:00
DS-Controller2
f0bbeac04a fix(core): add modelscope provider to handle stream_options (#848)
* fix(core): add modelscope provider to handle stream_options

---------

Co-authored-by: Qwen Code <qwen-code@alibaba-inc.com>
Co-authored-by: mingholy.lmh <mingholy.lmh@alibaba-inc.com>
2025-11-18 13:47:20 +08:00
Mingholy
efca0bc795 fix: basic slash command support (#1020) 2025-11-18 13:46:42 +08:00
tanzhenxin
6bb829f876 feat: Add Terminal Attention Notifications for User Alerts (#1052) 2025-11-18 13:43:43 +08:00
tanzhenxin
5bc309b3dc feat: add os platform and version in log report (#1053) 2025-11-18 13:43:17 +08:00
yiliang114
f95f6e63bb Merge branch 'feat/jinjing/qwen-code-vscode-extension-init' into feat/jinjing/write-and-read-file-in-vscode 2025-11-18 10:40:59 +08:00
yiliang114
91af599823 refactor(vscode-ide-companion): 文件版权头 Copyright 2025 Google LLC 2025-11-18 10:34:27 +08:00
yiliang114
ad8d7aae8a refactor(vscode-ide-companion): 文件版权头 Copyright 2025 Google LLC 2025-11-18 10:33:40 +08:00
yiliang114
d22d07a840 feat(vscode-ide-companion): 添加 Qwen Code CLI 安装检测和提示功能
- 新增 CliDetector 类用于检测 Qwen Code CLI 安装状态
- 在 WebViewProvider 中集成 CLI 检测逻辑
- 添加 CLI 未安装时的提示和安装引导功能
- 优化 agent 连接流程,增加 CLI 安装检测步骤
2025-11-18 01:52:46 +08:00
yiliang114
28892996b3 feat(vscode): 重构 Qwen 交互模型并优化权限请求 UI
- 重构 QwenAgentManager 类,支持处理多种类型的消息更新
- 改进权限请求界面,增加详细信息展示和选项选择功能
- 新增工具调用卡片组件,用于展示工具调用相关信息
- 优化消息流处理逻辑,支持不同类型的内容块
- 调整会话切换和新会话创建的处理方式
2025-11-18 01:00:25 +08:00
yiliang114
eeeb1d490a feat(vscode-ide-companion): 实现自定义权限请求 UI 并添加文件读写功能
- 新增 fs/read_text_file 和 fs/write_text_file 方法处理
- 实现精美的 Claude 风格权限请求 UI
- 优化权限请求处理逻辑,支持取消操作
- 添加日志输出以便调试
2025-11-17 21:44:39 +08:00
yiliang114
247c237647 fix(vscode-ide-companion): 优化缓存 Qwen Chat UI 的登录态机制 2025-11-17 20:00:52 +08:00
yiliang114
c423e12aa7 feat(vscode-ide-companion): update qwen logo 2025-11-17 19:10:17 +08:00
yiliang114
dc40995e70 feat(vscode-ide-companion): import chat chat customEditor to vscode extension folder 2025-11-17 18:53:00 +08:00
yyyanghj
0eeffc6875 feat: add support for Trae editor (#1037) 2025-11-17 10:58:33 +08:00
hj C
f0e21374c1 feat: add support for alternative cached_tokens format in OpenAI converter (#1035)
Co-authored-by: chenhuanjie <chenhuanjie@xiaohongshu.com>
2025-11-14 18:09:33 +08:00
BlockHand
29261c75e1 feat: openApi configurable window (#1019) 2025-11-14 10:18:57 +08:00
tanzhenxin
b4eba6584a chore: pump version to 0.2.2 (#1027) 2025-11-13 20:39:14 +08:00
XinlongWu
e6d08f0596 Change deepseek token limits regex patterns for deepseek-chat (#817) 2025-11-13 19:12:10 +08:00
tanzhenxin
160b64523e Add Interactive Approval Mode Dialog (#1012) 2025-11-13 19:02:53 +08:00
tanzhenxin
0752a31e1e 🎯 PR: Improve Edit Tool Reliability with Fuzzy Matching Pipeline (#1025) 2025-11-13 19:01:09 +08:00
fffly.Zzz
b029f0d2ce docs: correct YAML list format for tools field in agent template (#1026)
Co-authored-by: zhangxiao <xiao.zhang@ucloud.cn>
2025-11-13 17:41:22 +08:00
tanzhenxin
d5d96c726a fix: print request errors for logging only in debug mode (#1006) 2025-11-12 19:46:28 +08:00
tanzhenxin
06141cda8d Refactor: Standardize Tool Naming and Configuration System (#1004) 2025-11-12 19:46:05 +08:00
tanzhenxin
22edef0cb9 chore: pump version to 0.2.1 (#1005) 2025-11-10 15:18:59 +08:00
pomelo
ca1ae19715 Merge pull request #996 from wrapss/windows-newline-fix
fix: Stream parsing for Windows Zed integration
2025-11-10 09:52:47 +08:00
Matthieu Beaumont
6aaac12d70 fix(acp): replace EOL with newline for content splitting
- Replace `EOL` from `node:os` with `\n` for consistent line splitting in ACP connection output processing
- This ensures cross-platform compatibility since `EOL` is platform-specific while `\n` is universally used in text decoding
- The change maintains the same behavior on all platforms by using standard newline characters
2025-11-08 14:54:43 +01:00
Mingholy
3c01c7153b feat: enhance zed integration with TodoWriteTool and TaskTool support (#992)
- Implemented detection and handling for TodoWriteTool to route updates as plan entries instead of tool call events.
- Added sub-agent tool tracking for TaskTool, allowing for event emission and cleanup.
- Updated event listeners to manage sub-agent tool calls and approval requests effectively.
2025-11-07 19:55:23 +08:00
tanzhenxin
7a472e4fcf chore: pump version to 0.2.0 (#991) 2025-11-07 17:34:38 +08:00
pomelo
5390f662fc fix: VSCode detection null check and debug message optimization (#983) 2025-11-07 17:28:37 +08:00
tanzhenxin
c3d427730e 🎯 Feature: Customizable Model Training and Tool Output Management (#981) 2025-11-07 17:28:16 +08:00
pomelo
21fba6eb89 Merge pull request #977 from QwenLM/refactor-about
refactor: Unifying the system information display between `/about` and `/bug` commands
2025-11-07 11:02:20 +08:00
tanzhenxin
d17c37af7d Feat: Simplify and Improve Search Tools (glob, grep, ripgrep) (#969) 2025-11-06 16:25:06 +08:00
pomelo-nwu
82170e96c6 refactor(cli): centralize system information collection 2025-11-06 10:42:52 +08:00
pomelo
decb04efc4 Merge pull request #974 from QwenLM/chore/v0.1.5
chore: pump version to 0.1.5
2025-11-05 21:40:15 +08:00
pomelo-nwu
3bd0cb36c4 chore: pump version to 0.1.5 2025-11-05 19:35:17 +08:00
pomelo
553a36302a Merge pull request #972 from QwenLM/custom-logging-dir
feat: support for custom OpenAI logging directory configuration
2025-11-05 19:22:46 +08:00
pomelo
498d7a083a Merge pull request #970 from seems20/fix-kimi2-token-limits
Fix kimi2 token limits
2025-11-05 19:22:30 +08:00
pomelo-nwu
3a69931791 feat: add docs for logging dir configuration 2025-11-05 18:58:53 +08:00
pomelo-nwu
d4ab328671 feat: support for custom OpenAI logging directory configuration 2025-11-05 18:49:04 +08:00
chenhuanjie
90500ea67b Merge branch 'main' into fix-kimi2-token-limits 2025-11-05 17:36:02 +08:00
pomelo
335e765df0 Merge pull request #936 from QwenLM/fix-AbortError
fix: handle AbortError gracefully when loading commands
2025-11-05 16:38:14 +08:00
pomelo-nwu
448e30bf88 feat: support custom working directory for child process in start.js 2025-11-05 16:06:35 +08:00
chenhuanjie
26215b6d0a Merge branch 'main' into fix-kimi2-token-limits 2025-11-05 15:44:39 +08:00
chenhuanjie
f6f76a17e6 fix 2025-11-05 15:12:20 +08:00
chenhuanjie
55a3b69a8e fix 2025-11-05 15:10:52 +08:00
pomelo
22bd108775 Merge pull request #885 from QwenLM/web-search
chore: Web Search Tool Refactoring with Multi-Provider Support
2025-11-05 14:51:40 +08:00
pomelo-nwu
7ff07fd88c fix(web-search): handle unconfigured state and improve tests 2025-11-05 11:37:56 +08:00
pomelo-nwu
2967bec11c feat: update code 2025-11-05 11:23:27 +08:00
pomelo-nwu
6357a5c87e feat(web-search): enable DashScope provider only for Qwen OAuth auth type 2025-11-04 19:59:19 +08:00
tanzhenxin
7e827833bf chore: pump version to 0.1.4 (#962) 2025-11-04 19:22:37 +08:00
pomelo-nwu
d1507e73fe feat(web-search): use resource_url from credentials for DashScope endpoint 2025-11-04 16:59:30 +08:00
tanzhenxin
45f1000dea fix (#958) 2025-11-04 15:53:31 +08:00
tanzhenxin
04f0996327 fix: /ide install failed to run on Windows (#957) 2025-11-04 15:53:03 +08:00
tanzhenxin
d8cc0a1f04 fix: #923 missing macos seatbelt files in npm package (#949) 2025-11-04 15:52:46 +08:00
pomelo-nwu
512c91a969 Merge branch 'main' into web-search 2025-11-03 17:34:03 +08:00
tanzhenxin
ff8a8ac693 chore: pump version to 0.1.3 (#939) 2025-10-31 19:22:18 +08:00
tanzhenxin
908ac5e1b0 fix: partial settings migration (#937) 2025-10-31 18:12:59 +08:00
tanzhenxin
ea4a7a2368 fix: compression tool (#935) 2025-10-31 18:09:08 +08:00
pomelo-nwu
50d5cc2f6a fix: handle AbortError gracefully when loading commands 2025-10-31 17:00:28 +08:00
pomelo
5386099559 Merge pull request #933 from vinhnx/tool-name-title-in-ToolsList
fix: update tool name from Gemini to Qwen Code in ToolsList component…
2025-10-31 16:21:57 +08:00
Huarong
495a9d6d92 change Launch Gemini CLI to Qwen Code CLI in help information (#929) 2025-10-31 11:36:31 +08:00
Vinh Nguyen
db58aaff3a fix: update tool name from Gemini to Qwen Code in ToolsList component and snapshots 2025-10-31 10:25:49 +07:00
tanzhenxin
817218f1cf feat: Refactor and Enhance Ripgrep Tool (#930) 2025-10-31 10:53:13 +08:00
pomelo
7843de882a feat: fix sessionId (#927) 2025-10-31 10:23:09 +08:00
pomelo-nwu
40d82a2b25 feat: add docs for web search tool 2025-10-31 10:19:44 +08:00
pomelo-nwu
a40479d40a feat: adjust the description of the web search tool 2025-10-30 20:21:30 +08:00
pomelo-nwu
7cb068ceb2 Merge branch 'main' into web-search 2025-10-30 19:42:00 +08:00
pomelo-nwu
864bf03fee docs: add DashScope quota limits to web search documentation
- Add quota information (200 requests/minute, 2000 requests/day) to DashScope provider description
- Update provider details section with quota limits
2025-10-30 19:06:46 +08:00
pomelo-nwu
9a41db612a Add unit tests for web search core logic 2025-10-30 16:18:41 +08:00
pomelo-nwu
4781736f99 Improve web search fallback with snippet and web_fetch hint 2025-10-30 16:15:42 +08:00
yjw0628
ced79cf4e3 fixbug: fix qwen help des (#915) 2025-10-29 19:09:17 +08:00
tanzhenxin
33e22713a0 chore: pump version to v0.1.2 (#907) 2025-10-29 15:15:05 +08:00
tanzhenxin
92245f0f00 Merge branch 'main' of https://github.com/QwenLM/qwen-code 2025-10-29 14:25:31 +08:00
tanzhenxin
4f35f7431a fix: e2e test on cloud build 2025-10-29 14:25:15 +08:00
pomelo
84957bbb50 Merge pull request #904 from Willam2004/fix/docs
[to #12345678] docs: update excludeTools documentation in extensions …
2025-10-29 14:03:18 +08:00
tanzhenxin
c1164bdd7e fix: e2e test (#905) 2025-10-29 13:58:41 +08:00
tanzhenxin
f8be8a61c8 🐛 Bug Fixes Release v0.1.1 (#898) 2025-10-29 12:25:50 +08:00
家娃
c884dc080b [to #12345678] docs: update excludeTools documentation in extensions guide
- Added clarification that tools specified in excludeTools will be disabled for the entire conversation context
- Added note that excludeTools configuration affects all subsequent queries in the current session

This change improves documentation clarity for extension developers by better explaining the scope and impact of the excludeTools configuration.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2025-10-29 10:55:57 +08:00
pomelo
32a71986d5 Merge pull request #892 from UncleFB/main
fix input filter
2025-10-29 10:33:40 +08:00
UncleFB
6da6bc0dfd fix input filter 2025-10-28 14:38:46 +08:00
pomelo-nwu
7ccba75621 test: update /chat list test to match plain text output
Updated the test expectations to match the new plain text format
without ANSI escape codes.
2025-10-28 09:15:07 +08:00
pomelo-nwu
e0e5fa5084 fix: remove hardcoded ANSI escape codes in /chat list command
The /chat list command was displaying raw ANSI escape codes instead of
colored text. This was caused by the escapeAnsiCtrlCodes function in
HistoryItemDisplay that escapes all ANSI control characters.

Changed to plain text format for better compatibility and cleaner output.
2025-10-28 09:14:00 +08:00
pomelo-nwu
799d2bf0db feat: add oauth credit token 2025-10-27 19:59:13 +08:00
tanzhenxin
65cf80f4ab chore: pump version to 0.1.1 (#883) 2025-10-27 19:32:52 +08:00
pomelo-nwu
741eaf91c2 feat: add web_search docs 2025-10-27 17:05:47 +08:00
pomelo-nwu
79b4821499 feat: Optimize the code 2025-10-27 11:24:38 +08:00
pomelo-nwu
b1ece177b7 feat: Optimize the code 2025-10-27 11:01:48 +08:00
pomelo-nwu
f9f6eb52dd feat: add multi websearch provider 2025-10-24 17:16:14 +08:00
570 changed files with 83162 additions and 11582 deletions

237
.github/workflows/release-sdk.yml vendored Normal file
View File

@@ -0,0 +1,237 @@
name: 'Release SDK'
on:
workflow_dispatch:
inputs:
version:
description: 'The version to release (e.g., v0.1.11). Required for manual patch releases.'
required: false
type: 'string'
ref:
description: 'The branch or ref (full git sha) to release from.'
required: true
type: 'string'
default: 'main'
dry_run:
description: 'Run a dry-run of the release process; no branches, npm packages or GitHub releases will be created.'
required: true
type: 'boolean'
default: true
create_nightly_release:
description: 'Auto apply the nightly release tag, input version is ignored.'
required: false
type: 'boolean'
default: false
create_preview_release:
description: 'Auto apply the preview release tag, input version is ignored.'
required: false
type: 'boolean'
default: false
force_skip_tests:
description: 'Select to skip the "Run Tests" step in testing. Prod releases should run tests'
required: false
type: 'boolean'
default: false
jobs:
release-sdk:
runs-on: 'ubuntu-latest'
environment:
name: 'production-release'
url: '${{ github.server_url }}/${{ github.repository }}/releases/tag/sdk-typescript-${{ steps.version.outputs.RELEASE_TAG }}'
if: |-
${{ github.repository == 'QwenLM/qwen-code' }}
permissions:
contents: 'write'
packages: 'write'
id-token: 'write'
issues: 'write'
outputs:
RELEASE_TAG: '${{ steps.version.outputs.RELEASE_TAG }}'
steps:
- name: 'Checkout'
uses: 'actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8' # ratchet:actions/checkout@v5
with:
ref: '${{ github.event.inputs.ref || github.sha }}'
fetch-depth: 0
- name: 'Set booleans for simplified logic'
env:
CREATE_NIGHTLY_RELEASE: '${{ github.event.inputs.create_nightly_release }}'
CREATE_PREVIEW_RELEASE: '${{ github.event.inputs.create_preview_release }}'
DRY_RUN_INPUT: '${{ github.event.inputs.dry_run }}'
id: 'vars'
run: |-
is_nightly="false"
if [[ "${CREATE_NIGHTLY_RELEASE}" == "true" ]]; then
is_nightly="true"
fi
echo "is_nightly=${is_nightly}" >> "${GITHUB_OUTPUT}"
is_preview="false"
if [[ "${CREATE_PREVIEW_RELEASE}" == "true" ]]; then
is_preview="true"
fi
echo "is_preview=${is_preview}" >> "${GITHUB_OUTPUT}"
is_dry_run="false"
if [[ "${DRY_RUN_INPUT}" == "true" ]]; then
is_dry_run="true"
fi
echo "is_dry_run=${is_dry_run}" >> "${GITHUB_OUTPUT}"
- name: 'Setup Node.js'
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: 'Install Dependencies'
run: |-
npm ci
- name: 'Get the version'
id: 'version'
run: |
VERSION_ARGS=()
if [[ "${IS_NIGHTLY}" == "true" ]]; then
VERSION_ARGS+=(--type=nightly)
elif [[ "${IS_PREVIEW}" == "true" ]]; then
VERSION_ARGS+=(--type=preview)
if [[ -n "${MANUAL_VERSION}" ]]; then
VERSION_ARGS+=("--preview_version_override=${MANUAL_VERSION}")
fi
else
VERSION_ARGS+=(--type=stable)
if [[ -n "${MANUAL_VERSION}" ]]; then
VERSION_ARGS+=("--stable_version_override=${MANUAL_VERSION}")
fi
fi
VERSION_JSON=$(node packages/sdk-typescript/scripts/get-release-version.js "${VERSION_ARGS[@]}")
echo "RELEASE_TAG=$(echo "$VERSION_JSON" | jq -r .releaseTag)" >> "$GITHUB_OUTPUT"
echo "RELEASE_VERSION=$(echo "$VERSION_JSON" | jq -r .releaseVersion)" >> "$GITHUB_OUTPUT"
echo "NPM_TAG=$(echo "$VERSION_JSON" | jq -r .npmTag)" >> "$GITHUB_OUTPUT"
echo "PREVIOUS_RELEASE_TAG=$(echo "$VERSION_JSON" | jq -r .previousReleaseTag)" >> "$GITHUB_OUTPUT"
env:
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
IS_NIGHTLY: '${{ steps.vars.outputs.is_nightly }}'
IS_PREVIEW: '${{ steps.vars.outputs.is_preview }}'
MANUAL_VERSION: '${{ inputs.version }}'
- name: 'Run Tests'
if: |-
${{ github.event.inputs.force_skip_tests != 'true' }}
working-directory: 'packages/sdk-typescript'
run: |
npm run test:ci
env:
OPENAI_API_KEY: '${{ secrets.OPENAI_API_KEY }}'
OPENAI_BASE_URL: '${{ secrets.OPENAI_BASE_URL }}'
OPENAI_MODEL: '${{ secrets.OPENAI_MODEL }}'
- name: 'Build CLI for Integration Tests'
if: |-
${{ github.event.inputs.force_skip_tests != 'true' }}
run: |
npm run build
npm run bundle
- name: 'Run SDK Integration Tests'
if: |-
${{ github.event.inputs.force_skip_tests != 'true' }}
run: |
npm run test:integration:sdk:sandbox:none
npm run test:integration:sdk:sandbox:docker
env:
OPENAI_API_KEY: '${{ secrets.OPENAI_API_KEY }}'
OPENAI_BASE_URL: '${{ secrets.OPENAI_BASE_URL }}'
OPENAI_MODEL: '${{ secrets.OPENAI_MODEL }}'
- name: 'Configure Git User'
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
- name: 'Create and switch to a release branch'
id: 'release_branch'
env:
RELEASE_TAG: '${{ steps.version.outputs.RELEASE_TAG }}'
run: |-
BRANCH_NAME="release/sdk-typescript/${RELEASE_TAG}"
git switch -c "${BRANCH_NAME}"
echo "BRANCH_NAME=${BRANCH_NAME}" >> "${GITHUB_OUTPUT}"
- name: 'Update package version'
working-directory: 'packages/sdk-typescript'
env:
RELEASE_VERSION: '${{ steps.version.outputs.RELEASE_VERSION }}'
run: |-
npm version "${RELEASE_VERSION}" --no-git-tag-version --allow-same-version
- name: 'Commit and Conditionally Push package version'
env:
BRANCH_NAME: '${{ steps.release_branch.outputs.BRANCH_NAME }}'
IS_DRY_RUN: '${{ steps.vars.outputs.is_dry_run }}'
RELEASE_TAG: '${{ steps.version.outputs.RELEASE_TAG }}'
run: |-
git add packages/sdk-typescript/package.json
if git diff --staged --quiet; then
echo "No version changes to commit"
else
git commit -m "chore(release): sdk-typescript ${RELEASE_TAG}"
fi
if [[ "${IS_DRY_RUN}" == "false" ]]; then
echo "Pushing release branch to remote..."
git push --set-upstream origin "${BRANCH_NAME}" --follow-tags
else
echo "Dry run enabled. Skipping push."
fi
- name: 'Build SDK'
working-directory: 'packages/sdk-typescript'
run: |-
npm run build
- name: 'Configure npm for publishing'
uses: 'actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020' # ratchet:actions/setup-node@v4
with:
node-version-file: '.nvmrc'
registry-url: 'https://registry.npmjs.org'
scope: '@qwen-code'
- name: 'Publish @qwen-code/sdk'
working-directory: 'packages/sdk-typescript'
run: |-
npm publish --access public --tag=${{ steps.version.outputs.NPM_TAG }} ${{ steps.vars.outputs.is_dry_run == 'true' && '--dry-run' || '' }}
env:
NODE_AUTH_TOKEN: '${{ secrets.NPM_TOKEN }}'
- name: 'Create GitHub Release and Tag'
if: |-
${{ steps.vars.outputs.is_dry_run == 'false' }}
env:
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
RELEASE_BRANCH: '${{ steps.release_branch.outputs.BRANCH_NAME }}'
RELEASE_TAG: '${{ steps.version.outputs.RELEASE_TAG }}'
PREVIOUS_RELEASE_TAG: '${{ steps.version.outputs.PREVIOUS_RELEASE_TAG }}'
run: |-
gh release create "sdk-typescript-${RELEASE_TAG}" \
--target "$RELEASE_BRANCH" \
--title "SDK TypeScript Release ${RELEASE_TAG}" \
--notes-start-tag "sdk-typescript-${PREVIOUS_RELEASE_TAG}" \
--generate-notes
- name: 'Create Issue on Failure'
if: |-
${{ failure() }}
env:
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
RELEASE_TAG: "${{ steps.version.outputs.RELEASE_TAG || 'N/A' }}"
DETAILS_URL: '${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}'
run: |-
gh issue create \
--title "SDK Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')" \
--body "The SDK release workflow failed. See the full run for details: ${DETAILS_URL}"

View File

@@ -224,5 +224,4 @@ jobs:
run: |-
gh issue create \
--title "Release Failed for ${RELEASE_TAG} on $(date +'%Y-%m-%d')" \
--body "The release workflow failed. See the full run for details: ${DETAILS_URL}" \
--label "kind/bug,release-failure"
--body "The release workflow failed. See the full run for details: ${DETAILS_URL}"

10
.vscode/launch.json vendored
View File

@@ -73,7 +73,15 @@
"request": "launch",
"name": "Launch CLI Non-Interactive",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "start", "--", "-p", "${input:prompt}", "-y"],
"runtimeArgs": [
"run",
"start",
"--",
"-p",
"${input:prompt}",
"--output-format",
"stream-json"
],
"skipFiles": ["<node_internals>/**"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",

View File

@@ -25,7 +25,7 @@
</div>
Qwen Code is a powerful command-line AI workflow tool adapted from [**Gemini CLI**](https://github.com/google-gemini/gemini-cli) ([details](./README.gemini.md)), specifically optimized for [Qwen3-Coder](https://github.com/QwenLM/Qwen3-Coder) models. It enhances your development workflow with advanced code understanding, automated tasks, and intelligent assistance.
Qwen Code is a powerful command-line AI workflow tool adapted from [**Gemini CLI**](https://github.com/google-gemini/gemini-cli), specifically optimized for [Qwen3-Coder](https://github.com/QwenLM/Qwen3-Coder) models. It enhances your development workflow with advanced code understanding, automated tasks, and intelligent assistance.
## 💡 Free Options Available
@@ -88,6 +88,12 @@ npm install -g .
brew install qwen-code
```
## VS Code Extension
In addition to the CLI tool, Qwen Code also provides a **VS Code extension** that brings AI-powered coding assistance directly into your editor with features like file system operations, native diffing, interactive chat, and more.
> 📦 The extension is currently in development. For installation, features, and development guide, see the [VS Code Extension README](./packages/vscode-ide-companion/README.md).
## Quick Start
```bash

View File

@@ -11,31 +11,8 @@ Slash commands provide meta-level control over the CLI itself.
- **`/bug`**
- **Description:** File an issue about Qwen Code. By default, the issue is filed within the GitHub repository for Qwen Code. The string you enter after `/bug` will become the headline for the bug being filed. The default `/bug` behavior can be modified using the `advanced.bugCommand` setting in your `.qwen/settings.json` files.
- **`/chat`**
- **Description:** Save and resume conversation history for branching conversation state interactively, or resuming a previous state from a later session.
- **Sub-commands:**
- **`save`**
- **Description:** Saves the current conversation history. You must add a `<tag>` for identifying the conversation state.
- **Usage:** `/chat save <tag>`
- **Details on Checkpoint Location:** The default locations for saved chat checkpoints are:
- Linux/macOS: `~/.qwen/tmp/<project_hash>/`
- Windows: `C:\Users\<YourUsername>\.qwen\tmp\<project_hash>\`
- When you run `/chat list`, the CLI only scans these specific directories to find available checkpoints.
- **Note:** These checkpoints are for manually saving and resuming conversation states. For automatic checkpoints created before file modifications, see the [Checkpointing documentation](../checkpointing.md).
- **`resume`**
- **Description:** Resumes a conversation from a previous save.
- **Usage:** `/chat resume <tag>`
- **`list`**
- **Description:** Lists available tags for chat state resumption.
- **`delete`**
- **Description:** Deletes a saved conversation checkpoint.
- **Usage:** `/chat delete <tag>`
- **`share`**
- **Description** Writes the current conversation to a provided Markdown or JSON file.
- **Usage** `/chat share file.md` or `/chat share file.json`. If no filename is provided, then the CLI will generate one.
- **`/clear`**
- **Description:** Clear the terminal screen, including the visible session history and scrollback within the CLI. The underlying session data (for history recall) might be preserved depending on the exact implementation, but the visual display is cleared.
- **`/clear`** (aliases: `reset`, `new`)
- **Description:** Clear conversation history and free up context by starting a fresh session. Also clears the terminal output and scrollback within the CLI.
- **Keyboard shortcut:** Press **Ctrl+L** at any time to perform a clear action.
- **`/summary`**
@@ -168,16 +145,6 @@ Slash commands provide meta-level control over the CLI itself.
- **`nodesc`** or **`nodescriptions`**:
- **Description:** Hide tool descriptions, showing only the tool names.
- **`/quit-confirm`**
- **Description:** Show a confirmation dialog before exiting Qwen Code, allowing you to choose how to handle your current session.
- **Usage:** `/quit-confirm`
- **Features:**
- **Quit immediately:** Exit without saving anything (equivalent to `/quit`)
- **Generate summary and quit:** Create a project summary using `/summary` before exiting
- **Save conversation and quit:** Save the current conversation with an auto-generated tag before exiting
- **Keyboard shortcut:** Press **Ctrl+C** twice to trigger the quit confirmation dialog
- **Note:** This command is automatically triggered when you press Ctrl+C once, providing a safety mechanism to prevent accidental exits.
- **`/quit`** (or **`/exit`**)
- **Description:** Exit Qwen Code immediately without any confirmation dialog.
@@ -195,6 +162,16 @@ Slash commands provide meta-level control over the CLI itself.
- **`/init`**
- **Description:** Analyzes the current directory and creates a `QWEN.md` context file by default (or the filename specified by `contextFileName`). If a non-empty file already exists, no changes are made. The command seeds an empty file and prompts the model to populate it with project-specific instructions.
- [**`/language`**](./language.md)
- **Description:** View or change the language setting for both UI and LLM output.
- **Sub-commands:**
- **`ui`**: Set the UI language (zh-CN or en-US)
- **`output`**: Set the LLM output language
- **Usage:** `/language [ui|output] [language]`
- **Examples:**
- `/language ui zh-CN` (set UI language to Simplified Chinese)
- `/language output English` (set LLM output language to English)
### Custom Commands
For a quick start, see the [example](#example-a-pure-function-refactoring-command) below.

View File

@@ -309,7 +309,8 @@ If you are experiencing performance issues with file searching (e.g., with `@` c
```
- **`tavilyApiKey`** (string):
- **Description:** API key for Tavily web search service. Required to enable the `web_search` tool functionality. If not configured, the web search tool will be disabled and skipped.
- **Description:** API key for Tavily web search service. Used to enable the `web_search` tool functionality.
- **Note:** This is a legacy configuration format. For Qwen OAuth users, DashScope provider is automatically available without any configuration. For other authentication types, configure Tavily or Google providers using the new `webSearch` configuration format.
- **Default:** `undefined` (web search disabled)
- **Example:** `"tavilyApiKey": "tvly-your-api-key-here"`
- **`chatCompression`** (object):
@@ -465,8 +466,8 @@ The CLI automatically loads environment variables from an `.env` file. The loadi
- This is useful for development and testing.
- **`TAVILY_API_KEY`**:
- Your API key for the Tavily web search service.
- Required to enable the `web_search` tool functionality.
- If not configured, the web search tool will be disabled and skipped.
- Used to enable the `web_search` tool functionality.
- **Note:** For Qwen OAuth users, DashScope provider is automatically available without any configuration. For other authentication types, configure Tavily or Google providers to enable web search.
- Example: `export TAVILY_API_KEY="tvly-your-api-key-here"`
## Command-Line Arguments
@@ -540,6 +541,9 @@ Arguments passed directly when running the CLI can override other configurations
- Displays the version of the CLI.
- **`--openai-logging`**:
- Enables logging of OpenAI API calls for debugging and analysis. This flag overrides the `enableOpenAILogging` setting in `settings.json`.
- **`--openai-logging-dir <directory>`**:
- Sets a custom directory path for OpenAI API logs. This flag overrides the `openAILoggingDir` setting in `settings.json`. Supports absolute paths, relative paths, and `~` expansion.
- **Example:** `qwen --openai-logging-dir "~/qwen-logs" --openai-logging`
- **`--tavily-api-key <api_key>`**:
- Sets the Tavily API key for web search functionality for this session.
- Example: `qwen --tavily-api-key tvly-your-api-key-here`
@@ -667,4 +671,4 @@ Note: When usage statistics are enabled, events are sent to an Alibaba Cloud RUM
- **Category:** UI
- **Requires Restart:** No
- **Example:** `"enableWelcomeBack": false`
- **Details:** When enabled, Qwen Code will automatically detect if you're returning to a project with a previously generated project summary (`.qwen/PROJECT_SUMMARY.md`) and show a dialog allowing you to continue your previous conversation or start fresh. This feature integrates with the `/chat summary` command and quit confirmation dialog. See the [Welcome Back documentation](./welcome-back.md) for more details.
- **Details:** When enabled, Qwen Code will automatically detect if you're returning to a project with a previously generated project summary (`.qwen/PROJECT_SUMMARY.md`) and show a dialog allowing you to continue your previous conversation or start fresh. This feature integrates with the `/summary` command. See the [Welcome Back documentation](./welcome-back.md) for more details.

View File

@@ -160,9 +160,30 @@ Settings are organized into categories. All settings should be placed within the
- **Default:** `undefined`
- **`model.chatCompression.contextPercentageThreshold`** (number):
- **Description:** Sets the threshold for chat history compression as a percentage of the model's total token limit. This is a value between 0 and 1 that applies to both automatic compression and the manual `/compress` command. For example, a value of `0.6` will trigger compression when the chat history exceeds 60% of the token limit.
- **Description:** Sets the threshold for chat history compression as a percentage of the model's total token limit. This is a value between 0 and 1 that applies to both automatic compression and the manual `/compress` command. For example, a value of `0.6` will trigger compression when the chat history exceeds 60% of the token limit. Use `0` to disable compression entirely.
- **Default:** `0.7`
- **`model.generationConfig`** (object):
- **Description:** Advanced overrides passed to the underlying content generator. Supports request controls such as `timeout`, `maxRetries`, and `disableCacheControl`, along with fine-tuning knobs under `samplingParams` (for example `temperature`, `top_p`, `max_tokens`). Leave unset to rely on provider defaults.
- **Default:** `undefined`
- **Example:**
```json
{
"model": {
"generationConfig": {
"timeout": 60000,
"disableCacheControl": false,
"samplingParams": {
"temperature": 0.2,
"top_p": 0.8,
"max_tokens": 1024
}
}
}
}
```
- **`model.skipNextSpeakerCheck`** (boolean):
- **Description:** Skip the next speaker check.
- **Default:** `false`
@@ -171,6 +192,22 @@ Settings are organized into categories. All settings should be placed within the
- **Description:** Disables loop detection checks. Loop detection prevents infinite loops in AI responses but can generate false positives that interrupt legitimate workflows. Enable this option if you experience frequent false positive loop detection interruptions.
- **Default:** `false`
- **`model.skipStartupContext`** (boolean):
- **Description:** Skips sending the startup workspace context (environment summary and acknowledgement) at the beginning of each session. Enable this if you prefer to provide context manually or want to save tokens on startup.
- **Default:** `false`
- **`model.enableOpenAILogging`** (boolean):
- **Description:** Enables logging of OpenAI API calls for debugging and analysis. When enabled, API requests and responses are logged to JSON files.
- **Default:** `false`
- **`model.openAILoggingDir`** (string):
- **Description:** Custom directory path for OpenAI API logs. If not specified, defaults to `logs/openai` in the current working directory. Supports absolute paths, relative paths (resolved from current working directory), and `~` expansion (home directory).
- **Default:** `undefined`
- **Examples:**
- `"~/qwen-logs"` - Logs to `~/qwen-logs` directory
- `"./custom-logs"` - Logs to `./custom-logs` relative to current directory
- `"/tmp/openai-logs"` - Logs to absolute path `/tmp/openai-logs`
#### `context`
- **`context.fileName`** (string or array of strings):
@@ -246,6 +283,29 @@ Settings are organized into categories. All settings should be placed within the
- It must return function output as JSON on `stdout`, analogous to [`functionResponse.response.content`](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#functionresponse).
- **Default:** `undefined`
- **`tools.useRipgrep`** (boolean):
- **Description:** Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance.
- **Default:** `true`
- **`tools.useBuiltinRipgrep`** (boolean):
- **Description:** Use the bundled ripgrep binary. When set to `false`, the system-level `rg` command will be used instead. This setting is only effective when `tools.useRipgrep` is `true`.
- **Default:** `true`
- **`tools.enableToolOutputTruncation`** (boolean):
- **Description:** Enable truncation of large tool outputs.
- **Default:** `true`
- **Requires restart:** Yes
- **`tools.truncateToolOutputThreshold`** (number):
- **Description:** Truncate tool output if it is larger than this many characters. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools.
- **Default:** `25000`
- **Requires restart:** Yes
- **`tools.truncateToolOutputLines`** (number):
- **Description:** Maximum lines or entries kept when truncating tool output. Applies to Shell, Grep, Glob, ReadFile and ReadManyFiles tools.
- **Default:** `1000`
- **Requires restart:** Yes
#### `mcp`
- **`mcp.serverCommand`** (string):
@@ -297,7 +357,8 @@ Settings are organized into categories. All settings should be placed within the
- **Default:** `undefined`
- **`advanced.tavilyApiKey`** (string):
- **Description:** API key for Tavily web search service. Required to enable the `web_search` tool functionality. If not configured, the web search tool will be disabled and skipped.
- **Description:** API key for Tavily web search service. Used to enable the `web_search` tool functionality.
- **Note:** This is a legacy configuration format. For Qwen OAuth users, DashScope provider is automatically available without any configuration. For other authentication types, configure Tavily or Google providers using the new `webSearch` configuration format.
- **Default:** `undefined`
#### `mcpServers`
@@ -378,6 +439,8 @@ Here is an example of a `settings.json` file with the nested structure, new as o
"model": {
"name": "qwen3-coder-plus",
"maxSessionTurns": 10,
"enableOpenAILogging": false,
"openAILoggingDir": "~/qwen-logs",
"summarizeToolOutput": {
"run_shell_command": {
"tokenBudget": 100
@@ -466,8 +529,8 @@ The CLI automatically loads environment variables from an `.env` file. The loadi
- Set to a string to customize the title of the CLI.
- **`TAVILY_API_KEY`**:
- Your API key for the Tavily web search service.
- Required to enable the `web_search` tool functionality.
- If not configured, the web search tool will be disabled and skipped.
- Used to enable the `web_search` tool functionality.
- **Note:** For Qwen OAuth users, DashScope provider is automatically available without any configuration. For other authentication types, configure Tavily or Google providers to enable web search.
- Example: `export TAVILY_API_KEY="tvly-your-api-key-here"`
## Command-Line Arguments
@@ -485,12 +548,31 @@ Arguments passed directly when running the CLI can override other configurations
- The prompt is processed within the interactive session, not before it.
- Cannot be used when piping input from stdin.
- Example: `qwen -i "explain this code"`
- **`--output-format <format>`**:
- **`--continue`**:
- Resume the most recent session for the current project (current working directory).
- Works in interactive and headless modes (e.g., `qwen --continue -p "Keep going"`).
- **`--resume [sessionId]`**:
- Resume a specific session for the current project. When called without an ID, an interactive picker lists only this project's sessions with prompt preview, timestamps, message count, and optional git branch.
- If an ID is provided and not found for this project, the CLI exits with an error.
- **`--output-format <format>`** (**`-o <format>`**):
- **Description:** Specifies the format of the CLI output for non-interactive mode.
- **Values:**
- `text`: (Default) The standard human-readable output.
- `json`: A machine-readable JSON output.
- **Note:** For structured output and scripting, use the `--output-format json` flag.
- `json`: A machine-readable JSON output emitted at the end of execution.
- `stream-json`: Streaming JSON messages emitted as they occur during execution.
- **Note:** For structured output and scripting, use the `--output-format json` or `--output-format stream-json` flag. See [Headless Mode](../features/headless.md) for detailed information.
- **`--input-format <format>`**:
- **Description:** Specifies the format consumed from standard input.
- **Values:**
- `text`: (Default) Standard text input from stdin or command-line arguments.
- `stream-json`: JSON message protocol via stdin for bidirectional communication.
- **Requirement:** `--input-format stream-json` requires `--output-format stream-json` to be set.
- **Note:** When using `stream-json`, stdin is reserved for protocol messages. See [Headless Mode](../features/headless.md) for detailed information.
- **`--include-partial-messages`**:
- **Description:** Include partial assistant messages when using `stream-json` output format. When enabled, emits stream events (message_start, content_block_delta, etc.) as they occur during streaming.
- **Default:** `false`
- **Requirement:** Requires `--output-format stream-json` to be set.
- **Note:** See [Headless Mode](../features/headless.md) for detailed information about stream events.
- **`--sandbox`** (**`-s`**):
- Enables sandbox mode for this session.
- **`--sandbox-image`**:
@@ -515,7 +597,7 @@ Arguments passed directly when running the CLI can override other configurations
- Example: `qwen --approval-mode auto-edit`
- **`--allowed-tools <tool1,tool2,...>`**:
- A comma-separated list of tool names that will bypass the confirmation dialog.
- Example: `qwen --allowed-tools "ShellTool(git status)"`
- Example: `qwen --allowed-tools "Shell(git status)"`
- **`--telemetry`**:
- Enables [telemetry](../telemetry.md).
- **`--telemetry-target`**:
@@ -548,6 +630,9 @@ Arguments passed directly when running the CLI can override other configurations
- Displays the version of the CLI.
- **`--openai-logging`**:
- Enables logging of OpenAI API calls for debugging and analysis. This flag overrides the `enableOpenAILogging` setting in `settings.json`.
- **`--openai-logging-dir <directory>`**:
- Sets a custom directory path for OpenAI API logs. This flag overrides the `openAILoggingDir` setting in `settings.json`. Supports absolute paths, relative paths, and `~` expansion.
- **Example:** `qwen --openai-logging-dir "~/qwen-logs" --openai-logging`
- **`--tavily-api-key <api_key>`**:
- Sets the Tavily API key for web search functionality for this session.
- Example: `qwen --tavily-api-key tvly-your-api-key-here`

74
docs/cli/language.md Normal file
View File

@@ -0,0 +1,74 @@
# Language Command
The `/language` command allows you to customize the language settings for both the Qwen Code user interface (UI) and the language model's output. This command supports two distinct functionalities:
1. Setting the UI language for the Qwen Code interface
2. Setting the output language for the language model (LLM)
## UI Language Settings
To change the UI language of Qwen Code, use the `ui` subcommand:
```
/language ui [zh-CN|en-US|ru-RU]
```
### Available UI Languages
- **zh-CN**: Simplified Chinese (简体中文)
- **en-US**: English
- **ru-RU**: Russian (Русский)
### Examples
```
/language ui zh-CN # Set UI language to Simplified Chinese
/language ui en-US # Set UI language to English
/language ui ru-RU # Set UI language to Russian
```
### UI Language Subcommands
You can also use direct subcommands for convenience:
- `/language ui zh-CN` or `/language ui zh` or `/language ui 中文`
- `/language ui en-US` or `/language ui en` or `/language ui english`
- `/language ui ru-RU` or `/language ui ru` or `/language ui русский`
## LLM Output Language Settings
To set the language for the language model's responses, use the `output` subcommand:
```
/language output <language>
```
This command generates a language rule file that instructs the LLM to respond in the specified language. The rule file is saved to `~/.qwen/output-language.md`.
### Examples
```
/language output 中文 # Set LLM output language to Chinese
/language output English # Set LLM output language to English
/language output 日本語 # Set LLM output language to Japanese
```
## Viewing Current Settings
When used without arguments, the `/language` command displays the current language settings:
```
/language
```
This will show:
- Current UI language
- Current LLM output language (if set)
- Available subcommands
## Notes
- UI language changes take effect immediately and reload all command descriptions
- LLM output language settings are persisted in a rule file that is automatically included in the model's context
- To request additional UI language packs, please open an issue on GitHub

View File

@@ -21,7 +21,7 @@ The Qwen Code core (`packages/core`) features a robust system for defining, regi
- **Returning Rich Content:** Tools are not limited to returning simple text. The `llmContent` can be a `PartListUnion`, which is an array that can contain a mix of `Part` objects (for images, audio, etc.) and `string`s. This allows a single tool execution to return multiple pieces of rich content.
- **Tool Registry (`tool-registry.ts`):** A class (`ToolRegistry`) responsible for:
- **Registering Tools:** Holding a collection of all available built-in tools (e.g., `ReadFileTool`, `ShellTool`).
- **Registering Tools:** Holding a collection of all available built-in tools (e.g., `ListFiles`, `ReadFile`).
- **Discovering Tools:** It can also discover tools dynamically:
- **Command-based Discovery:** If `tools.toolDiscoveryCommand` is configured in settings, this command is executed. It's expected to output JSON describing custom tools, which are then registered as `DiscoveredTool` instances.
- **MCP-based Discovery:** If `mcp.mcpServerCommand` is configured, the registry can connect to a Model Context Protocol (MCP) server to list and register tools (`DiscoveredMCPTool`).
@@ -33,20 +33,24 @@ The Qwen Code core (`packages/core`) features a robust system for defining, regi
The core comes with a suite of pre-defined tools, typically found in `packages/core/src/tools/`. These include:
- **File System Tools:**
- `LSTool` (`ls.ts`): Lists directory contents.
- `ReadFileTool` (`read-file.ts`): Reads the content of a single file. It takes an `absolute_path` parameter, which must be an absolute path.
- `WriteFileTool` (`write-file.ts`): Writes content to a file.
- `GrepTool` (`grep.ts`): Searches for patterns in files.
- `GlobTool` (`glob.ts`): Finds files matching glob patterns.
- `EditTool` (`edit.ts`): Performs in-place modifications to files (often requiring confirmation).
- `ReadManyFilesTool` (`read-many-files.ts`): Reads and concatenates content from multiple files or glob patterns (used by the `@` command in CLI).
- `ListFiles` (`ls.ts`): Lists directory contents.
- `ReadFile` (`read-file.ts`): Reads the content of a single file. It takes an `absolute_path` parameter, which must be an absolute path.
- `WriteFile` (`write-file.ts`): Writes content to a file.
- `ReadManyFiles` (`read-many-files.ts`): Reads and concatenates content from multiple files or glob patterns (used by the `@` command in CLI).
- `Grep` (`grep.ts`): Searches for patterns in files.
- `Glob` (`glob.ts`): Finds files matching glob patterns.
- `Edit` (`edit.ts`): Performs in-place modifications to files (often requiring confirmation).
- **Execution Tools:**
- `ShellTool` (`shell.ts`): Executes arbitrary shell commands (requires careful sandboxing and user confirmation).
- `Shell` (`shell.ts`): Executes arbitrary shell commands (requires careful sandboxing and user confirmation).
- **Web Tools:**
- `WebFetchTool` (`web-fetch.ts`): Fetches content from a URL.
- `WebSearchTool` (`web-search.ts`): Performs a web search.
- `WebFetch` (`web-fetch.ts`): Fetches content from a URL.
- `WebSearch` (`web-search.ts`): Performs a web search.
- **Memory Tools:**
- `MemoryTool` (`memoryTool.ts`): Interacts with the AI's memory.
- `SaveMemory` (`memoryTool.ts`): Interacts with the AI's memory.
- **Planning Tools:**
- `Task` (`task.ts`): Delegates tasks to specialized subagents.
- `TodoWrite` (`todoWrite.ts`): Creates and manages a structured task list.
- `ExitPlanMode` (`exitPlanMode.ts`): Exits plan mode and returns to normal operation.
Each of these tools extends `BaseTool` and implements the required methods for its specific functionality.

View File

@@ -107,7 +107,7 @@ The `qwen-extension.json` file contains the configuration for the extension. The
- `mcpServers`: A map of MCP servers to configure. The key is the name of the server, and the value is the server configuration. These servers will be loaded on startup just like MCP servers configured in a [`settings.json` file](./cli/configuration.md). If both an extension and a `settings.json` file configure an MCP server with the same name, the server defined in the `settings.json` file takes precedence.
- Note that all MCP server configuration options are supported except for `trust`.
- `contextFileName`: The name of the file that contains the context for the extension. This will be used to load the context from the extension directory. If this property is not used but a `QWEN.md` file is present in your extension directory, then that file will be loaded.
- `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. Note that this differs from the MCP server `excludeTools` functionality, which can be listed in the MCP server config.
- `excludeTools`: An array of tool names to exclude from the model. You can also specify command-specific restrictions for tools that support it, like the `run_shell_command` tool. For example, `"excludeTools": ["run_shell_command(rm -rf)"]` will block the `rm -rf` command. Note that this differs from the MCP server `excludeTools` functionality, which can be listed in the MCP server config. **Important:** Tools specified in `excludeTools` will be disabled for the entire conversation context and will affect all subsequent queries in the current session.
When Qwen Code starts, it loads all the extensions and merges their configurations. If there are any conflicts, the workspace configuration takes precedence.

View File

@@ -13,8 +13,9 @@ scripting, automation, CI/CD pipelines, and building AI-powered tools.
- [Output Formats](#output-formats)
- [Text Output (Default)](#text-output-default)
- [JSON Output](#json-output)
- [Response Schema](#response-schema)
- [Example Usage](#example-usage)
- [Stream-JSON Output](#stream-json-output)
- [Input Format](#input-format)
- [File Redirection](#file-redirection)
- [Configuration Options](#configuration-options)
- [Examples](#examples)
@@ -22,7 +23,7 @@ scripting, automation, CI/CD pipelines, and building AI-powered tools.
- [Generate commit messages](#generate-commit-messages)
- [API documentation](#api-documentation)
- [Batch code analysis](#batch-code-analysis)
- [Code review](#code-review-1)
- [PR code review](#pr-code-review)
- [Log analysis](#log-analysis)
- [Release notes generation](#release-notes-generation)
- [Model and tool usage tracking](#model-and-tool-usage-tracking)
@@ -37,6 +38,7 @@ The headless mode provides a headless interface to Qwen Code that:
- Supports file redirection and piping
- Enables automation and scripting workflows
- Provides consistent exit codes for error handling
- Can resume previous sessions scoped to the current project for multi-step automation
## Basic Usage
@@ -64,8 +66,27 @@ Read from files and process with Qwen Code:
cat README.md | qwen --prompt "Summarize this documentation"
```
### Resume Previous Sessions (Headless)
Reuse conversation context from the current project in headless scripts:
```bash
# Continue the most recent session for this project and run a new prompt
qwen --continue -p "Run the tests again and summarize failures"
# Resume a specific session ID directly (no UI)
qwen --resume 123e4567-e89b-12d3-a456-426614174000 -p "Apply the follow-up refactor"
```
Notes:
- Session data is project-scoped JSONL under `~/.qwen/projects/<sanitized-cwd>/chats`.
- Restores conversation history, tool outputs, and chat-compression checkpoints before sending the new prompt.
## Output Formats
Qwen Code supports multiple output formats for different use cases:
### Text Output (Default)
Standard human-readable output:
@@ -82,56 +103,9 @@ The capital of France is Paris.
### JSON Output
Returns structured data including response, statistics, and metadata. This
format is ideal for programmatic processing and automation scripts.
Returns structured data as a JSON array. All messages are buffered and output together when the session completes. This format is ideal for programmatic processing and automation scripts.
#### Response Schema
The JSON output follows this high-level structure:
```json
{
"response": "string", // The main AI-generated content answering your prompt
"stats": {
// Usage metrics and performance data
"models": {
// Per-model API and token usage statistics
"[model-name]": {
"api": {
/* request counts, errors, latency */
},
"tokens": {
/* prompt, response, cached, total counts */
}
}
},
"tools": {
// Tool execution statistics
"totalCalls": "number",
"totalSuccess": "number",
"totalFail": "number",
"totalDurationMs": "number",
"totalDecisions": {
/* accept, reject, modify, auto_accept counts */
},
"byName": {
/* per-tool detailed stats */
}
},
"files": {
// File modification statistics
"totalLinesAdded": "number",
"totalLinesRemoved": "number"
}
},
"error": {
// Present only when an error occurred
"type": "string", // Error type (e.g., "ApiError", "AuthError")
"message": "string", // Human-readable error description
"code": "number" // Optional error code
}
}
```
The JSON output is an array of message objects. The output includes multiple message types: system messages (session initialization), assistant messages (AI responses), and result messages (execution summary).
#### Example Usage
@@ -139,63 +113,81 @@ The JSON output follows this high-level structure:
qwen -p "What is the capital of France?" --output-format json
```
Response:
Output (at end of execution):
```json
{
"response": "The capital of France is Paris.",
"stats": {
"models": {
"qwen3-coder-plus": {
"api": {
"totalRequests": 2,
"totalErrors": 0,
"totalLatencyMs": 5053
},
"tokens": {
"prompt": 24939,
"candidates": 20,
"total": 25113,
"cached": 21263,
"thoughts": 154,
"tool": 0
[
{
"type": "system",
"subtype": "session_start",
"uuid": "...",
"session_id": "...",
"model": "qwen3-coder-plus",
...
},
{
"type": "assistant",
"uuid": "...",
"session_id": "...",
"message": {
"id": "...",
"type": "message",
"role": "assistant",
"model": "qwen3-coder-plus",
"content": [
{
"type": "text",
"text": "The capital of France is Paris."
}
}
],
"usage": {...}
},
"tools": {
"totalCalls": 1,
"totalSuccess": 1,
"totalFail": 0,
"totalDurationMs": 1881,
"totalDecisions": {
"accept": 0,
"reject": 0,
"modify": 0,
"auto_accept": 1
},
"byName": {
"google_web_search": {
"count": 1,
"success": 1,
"fail": 0,
"durationMs": 1881,
"decisions": {
"accept": 0,
"reject": 0,
"modify": 0,
"auto_accept": 1
}
}
}
},
"files": {
"totalLinesAdded": 0,
"totalLinesRemoved": 0
}
"parent_tool_use_id": null
},
{
"type": "result",
"subtype": "success",
"uuid": "...",
"session_id": "...",
"is_error": false,
"duration_ms": 1234,
"result": "The capital of France is Paris.",
"usage": {...}
}
}
]
```
### Stream-JSON Output
Stream-JSON format emits JSON messages immediately as they occur during execution, enabling real-time monitoring. This format uses line-delimited JSON where each message is a complete JSON object on a single line.
```bash
qwen -p "Explain TypeScript" --output-format stream-json
```
Output (streaming as events occur):
```json
{"type":"system","subtype":"session_start","uuid":"...","session_id":"..."}
{"type":"assistant","uuid":"...","session_id":"...","message":{...}}
{"type":"result","subtype":"success","uuid":"...","session_id":"..."}
```
When combined with `--include-partial-messages`, additional stream events are emitted in real-time (message_start, content_block_delta, etc.) for real-time UI updates.
```bash
qwen -p "Write a Python script" --output-format stream-json --include-partial-messages
```
### Input Format
The `--input-format` parameter controls how Qwen Code consumes input from standard input:
- **`text`** (default): Standard text input from stdin or command-line arguments
- **`stream-json`**: JSON message protocol via stdin for bidirectional communication
> **Note:** Stream-json input mode is currently under construction and is intended for SDK integration. It requires `--output-format stream-json` to be set.
### File Redirection
Save output to files or pipe to other commands:
@@ -212,48 +204,55 @@ qwen -p "Add more details" >> docker-explanation.txt
qwen -p "What is Kubernetes?" --output-format json | jq '.response'
qwen -p "Explain microservices" | wc -w
qwen -p "List programming languages" | grep -i "python"
# Stream-JSON output for real-time processing
qwen -p "Explain Docker" --output-format stream-json | jq '.type'
qwen -p "Write code" --output-format stream-json --include-partial-messages | jq '.event.type'
```
## Configuration Options
Key command-line options for headless usage:
| Option | Description | Example |
| ----------------------- | ---------------------------------- | ------------------------------------------------ |
| `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` |
| `--output-format` | Specify output format (text, json) | `qwen -p "query" --output-format json` |
| `--model`, `-m` | Specify the Qwen model | `qwen -p "query" -m qwen3-coder-plus` |
| `--debug`, `-d` | Enable debug mode | `qwen -p "query" --debug` |
| `--all-files`, `-a` | Include all files in context | `qwen -p "query" --all-files` |
| `--include-directories` | Include additional directories | `qwen -p "query" --include-directories src,docs` |
| `--yolo`, `-y` | Auto-approve all actions | `qwen -p "query" --yolo` |
| `--approval-mode` | Set approval mode | `qwen -p "query" --approval-mode auto_edit` |
| Option | Description | Example |
| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------------------------ |
| `--prompt`, `-p` | Run in headless mode | `qwen -p "query"` |
| `--output-format`, `-o` | Specify output format (text, json, stream-json) | `qwen -p "query" --output-format json` |
| `--input-format` | Specify input format (text, stream-json) | `qwen --input-format text --output-format stream-json` |
| `--include-partial-messages` | Include partial messages in stream-json output | `qwen -p "query" --output-format stream-json --include-partial-messages` |
| `--debug`, `-d` | Enable debug mode | `qwen -p "query" --debug` |
| `--all-files`, `-a` | Include all files in context | `qwen -p "query" --all-files` |
| `--include-directories` | Include additional directories | `qwen -p "query" --include-directories src,docs` |
| `--yolo`, `-y` | Auto-approve all actions | `qwen -p "query" --yolo` |
| `--approval-mode` | Set approval mode | `qwen -p "query" --approval-mode auto_edit` |
| `--continue` | Resume the most recent session for this project | `qwen --continue -p "Pick up where we left off"` |
| `--resume [sessionId]` | Resume a specific session (or choose interactively) | `qwen --resume 123e... -p "Finish the refactor"` |
For complete details on all available configuration options, settings files, and environment variables, see the [Configuration Guide](./cli/configuration.md).
## Examples
#### Code review
### Code review
```bash
cat src/auth.py | qwen -p "Review this authentication code for security issues" > security-review.txt
```
#### Generate commit messages
### Generate commit messages
```bash
result=$(git diff --cached | qwen -p "Write a concise commit message for these changes" --output-format json)
echo "$result" | jq -r '.response'
```
#### API documentation
### 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
```
#### Batch code analysis
### Batch code analysis
```bash
for file in src/*.py; do
@@ -264,20 +263,20 @@ for file in src/*.py; do
done
```
#### Code review
### PR code review
```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
```
#### Log analysis
### Log analysis
```bash
grep "ERROR" /var/log/app.log | tail -20 | qwen -p "Analyze these errors and suggest root cause and fixes" > error-analysis.txt
```
#### Release notes generation
### Release notes generation
```bash
result=$(git log --oneline v1.0.0..HEAD | qwen -p "Generate release notes from these commits" --output-format json)
@@ -286,7 +285,7 @@ echo "$response"
echo "$response" >> CHANGELOG.md
```
#### Model and tool usage tracking
### Model and tool usage tracking
```bash
result=$(qwen -p "Explain this database schema" --include-directories db --output-format json)

View File

@@ -106,7 +106,10 @@ Subagents are configured using Markdown files with YAML frontmatter. This format
---
name: agent-name
description: Brief description of when and how to use this agent
tools: tool1, tool2, tool3 # Optional
tools:
- tool1
- tool2
- tool3 # Optional
---
System prompt content goes here.
@@ -167,7 +170,11 @@ Perfect for comprehensive test creation and test-driven development.
---
name: testing-expert
description: Writes comprehensive unit tests, integration tests, and handles test automation with best practices
tools: read_file, write_file, read_many_files, run_shell_command
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a testing specialist focused on creating high-quality, maintainable tests.
@@ -207,7 +214,11 @@ Specialized in creating clear, comprehensive documentation.
---
name: documentation-writer
description: Creates comprehensive documentation, README files, API docs, and user guides
tools: read_file, write_file, read_many_files, web_search
tools:
- read_file
- write_file
- read_many_files
- web_search
---
You are a technical documentation specialist for ${project_name}.
@@ -256,7 +267,9 @@ Focused on code quality, security, and best practices.
---
name: code-reviewer
description: Reviews code for best practices, security issues, performance, and maintainability
tools: read_file, read_many_files
tools:
- read_file
- read_many_files
---
You are an experienced code reviewer focused on quality, security, and maintainability.
@@ -298,7 +311,11 @@ Optimized for React development, hooks, and component patterns.
---
name: react-specialist
description: Expert in React development, hooks, component patterns, and modern React best practices
tools: read_file, write_file, read_many_files, run_shell_command
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a React specialist with deep expertise in modern React development.
@@ -339,7 +356,11 @@ Specialized in Python development, frameworks, and best practices.
---
name: python-expert
description: Expert in Python development, frameworks, testing, and Python-specific best practices
tools: read_file, write_file, read_many_files, run_shell_command
tools:
- read_file
- write_file
- read_many_files
- run_shell_command
---
You are a Python expert with deep knowledge of the Python ecosystem.

View File

@@ -75,20 +75,12 @@ Add to your `.qwen/settings.json`:
### Project Summary Generation
The Welcome Back feature works seamlessly with the `/chat summary` command:
The Welcome Back feature works seamlessly with the `/summary` command:
1. **Generate Summary:** Use `/chat summary` to create a project summary
1. **Generate Summary:** Use `/summary` to create a project summary
2. **Automatic Detection:** Next time you start Qwen Code in this project, Welcome Back will detect the summary
3. **Resume Work:** Choose to continue and the summary will be loaded as context
### Quit Confirmation
When exiting with `/quit-confirm` and choosing "Generate summary and quit":
1. A project summary is automatically created
2. Next session will trigger the Welcome Back dialog
3. You can seamlessly continue your work
## File Structure
The Welcome Back feature creates and uses:

View File

@@ -72,7 +72,7 @@ Create or edit `.qwen/settings.json` in your home directory:
#### Session Commands
- **`/compress`** - Compress conversation history to continue within token limits
- **`/clear`** - Clear all conversation history and start fresh
- **`/clear`** (aliases: `/reset`, `/new`) - Clear conversation history, start a fresh session, and free up context
- **`/stats`** - Check current token usage and limits
> 📝 **Note**: Session token limit applies to a single conversation, not cumulative API calls.
@@ -332,7 +332,7 @@ qwen
### Session Commands
- `/help` - Display available commands
- `/clear` - Clear conversation history
- `/clear` (aliases: `/reset`, `/new`) - Clear conversation history and start a fresh session
- `/compress` - Compress history to save tokens
- `/stats` - Show current session information
- `/exit` or `/quit` - Exit Qwen Code

View File

@@ -14,6 +14,13 @@ This guide provides solutions to common issues and debugging tips, including top
- **Solution:** Set the `NODE_EXTRA_CA_CERTS` environment variable to the absolute path of your corporate root CA certificate file.
- Example: `export NODE_EXTRA_CA_CERTS=/path/to/your/corporate-ca.crt`
- **Issue: Unable to display UI after authentication failure**
- **Cause:** If authentication fails after selecting an authentication type, the `security.auth.selectedType` setting may be persisted in `settings.json`. On restart, the CLI may get stuck trying to authenticate with the failed auth type and fail to display the UI.
- **Solution:** Clear the `security.auth.selectedType` configuration item in your `settings.json` file:
- Open `~/.qwen/settings.json` (or `./.qwen/settings.json` for project-specific settings)
- Remove the `security.auth.selectedType` field
- Restart the CLI to allow it to prompt for authentication again
## Frequently asked questions (FAQs)
- **Q: How do I update Qwen Code to the latest version?**

View File

@@ -4,12 +4,12 @@ Qwen Code provides a comprehensive suite of tools for interacting with the local
**Note:** All file system tools operate within a `rootDirectory` (usually the current working directory where you launched the CLI) for security. Paths that you provide to these tools are generally expected to be absolute or are resolved relative to this root directory.
## 1. `list_directory` (ReadFolder)
## 1. `list_directory` (ListFiles)
`list_directory` lists the names of files and subdirectories directly within a specified directory path. It can optionally ignore entries matching provided glob patterns.
- **Tool name:** `list_directory`
- **Display name:** ReadFolder
- **Display name:** ListFiles
- **File:** `ls.ts`
- **Parameters:**
- `path` (string, required): The absolute path to the directory to list.
@@ -59,86 +59,80 @@ Qwen Code provides a comprehensive suite of tools for interacting with the local
- **Output (`llmContent`):** A success message, e.g., `Successfully overwrote file: /path/to/your/file.txt` or `Successfully created and wrote to new file: /path/to/new/file.txt`.
- **Confirmation:** Yes. Shows a diff of changes and asks for user approval before writing.
## 4. `glob` (FindFiles)
## 4. `glob` (Glob)
`glob` finds files matching specific glob patterns (e.g., `src/**/*.ts`, `*.md`), returning absolute paths sorted by modification time (newest first).
- **Tool name:** `glob`
- **Display name:** FindFiles
- **Display name:** Glob
- **File:** `glob.ts`
- **Parameters:**
- `pattern` (string, required): The glob pattern to match against (e.g., `"*.py"`, `"src/**/*.js"`).
- `path` (string, optional): The absolute path to the directory to search within. If omitted, searches the tool's root directory.
- `case_sensitive` (boolean, optional): Whether the search should be case-sensitive. Defaults to `false`.
- `respect_git_ignore` (boolean, optional): Whether to respect .gitignore patterns when finding files. Defaults to `true`.
- `path` (string, optional): The directory to search in. If not specified, the current working directory will be used.
- **Behavior:**
- Searches for files matching the glob pattern within the specified directory.
- Returns a list of absolute paths, sorted with the most recently modified files first.
- Ignores common nuisance directories like `node_modules` and `.git` by default.
- **Output (`llmContent`):** A message like: `Found 5 file(s) matching "*.ts" within src, sorted by modification time (newest first):\nsrc/file1.ts\nsrc/subdir/file2.ts...`
- Respects .gitignore and .qwenignore patterns by default.
- Limits results to 100 files to prevent context overflow.
- **Output (`llmContent`):** A message like: `Found 5 file(s) matching "*.ts" within /path/to/search/dir, sorted by modification time (newest first):\n---\n/path/to/file1.ts\n/path/to/subdir/file2.ts\n---\n[95 files truncated] ...`
- **Confirmation:** No.
## 5. `search_file_content` (SearchText)
## 5. `grep_search` (Grep)
`search_file_content` searches for a regular expression pattern within the content of files in a specified directory. Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.
`grep_search` searches for a regular expression pattern within the content of files in a specified directory. Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.
- **Tool name:** `search_file_content`
- **Display name:** SearchText
- **File:** `grep.ts`
- **Tool name:** `grep_search`
- **Display name:** Grep
- **File:** `ripGrep.ts` (with `grep.ts` as fallback)
- **Parameters:**
- `pattern` (string, required): The regular expression (regex) to search for (e.g., `"function\s+myFunction"`).
- `path` (string, optional): The absolute path to the directory to search within. Defaults to the current working directory.
- `include` (string, optional): A glob pattern to filter which files are searched (e.g., `"*.js"`, `"src/**/*.{ts,tsx}"`). If omitted, searches most files (respecting common ignores).
- `maxResults` (number, optional): Maximum number of matches to return to prevent context overflow (default: 20, max: 100). Use lower values for broad searches, higher for specific searches.
- `pattern` (string, required): The regular expression pattern to search for in file contents (e.g., `"function\\s+myFunction"`, `"log.*Error"`).
- `path` (string, optional): File or directory to search in. Defaults to current working directory.
- `glob` (string, optional): Glob pattern to filter files (e.g. `"*.js"`, `"src/**/*.{ts,tsx}"`).
- `limit` (number, optional): Limit output to first N matching lines. Optional - shows all matches if not specified.
- **Behavior:**
- Uses `git grep` if available in a Git repository for speed; otherwise, falls back to system `grep` or a JavaScript-based search.
- Returns a list of matching lines, each prefixed with its file path (relative to the search directory) and line number.
- Limits results to a maximum of 20 matches by default to prevent context overflow. When results are truncated, shows a clear warning with guidance on refining searches.
- Uses ripgrep for fast search when available; otherwise falls back to a JavaScript-based search implementation.
- Returns matching lines with file paths and line numbers.
- Case-insensitive by default.
- Respects .gitignore and .qwenignore patterns.
- Limits output to prevent context overflow.
- **Output (`llmContent`):** A formatted string of matches, e.g.:
```
Found 3 matches for pattern "myFunction" in path "." (filter: "*.ts"):
---
File: src/utils.ts
L15: export function myFunction() {
L22: myFunction.call();
---
File: src/index.ts
L5: import { myFunction } from './utils';
src/utils.ts:15:export function myFunction() {
src/utils.ts:22: myFunction.call();
src/index.ts:5:import { myFunction } from './utils';
---
WARNING: Results truncated to prevent context overflow. To see more results:
- Use a more specific pattern to reduce matches
- Add file filters with the 'include' parameter (e.g., "*.js", "src/**")
- Specify a narrower 'path' to search in a subdirectory
- Increase 'maxResults' parameter if you need more matches (current: 20)
[0 lines truncated] ...
```
- **Confirmation:** No.
### `search_file_content` examples
### `grep_search` examples
Search for a pattern with default result limiting:
```
search_file_content(pattern="function\s+myFunction", path="src")
grep_search(pattern="function\\s+myFunction", path="src")
```
Search for a pattern with custom result limiting:
```
search_file_content(pattern="function", path="src", maxResults=50)
grep_search(pattern="function", path="src", limit=50)
```
Search for a pattern with file filtering and custom result limiting:
```
search_file_content(pattern="function", include="*.js", maxResults=10)
grep_search(pattern="function", glob="*.js", limit=10)
```
## 6. `edit` (Edit)
`edit` replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when `expected_replacements` is specified. This tool is designed for precise, targeted changes and requires significant context around the `old_string` to ensure it modifies the correct location.
`edit` replaces text within a file. By default it requires `old_string` to match a single unique location; set `replace_all` to `true` when you intentionally want to change every occurrence. This tool is designed for precise, targeted changes and requires significant context around the `old_string` to ensure it modifies the correct location.
- **Tool name:** `edit`
- **Display name:** Edit
@@ -150,12 +144,12 @@ search_file_content(pattern="function", include="*.js", maxResults=10)
**CRITICAL:** This string must uniquely identify the single instance to change. It should include at least 3 lines of context _before_ and _after_ the target text, matching whitespace and indentation precisely. If `old_string` is empty, the tool attempts to create a new file at `file_path` with `new_string` as content.
- `new_string` (string, required): The exact literal text to replace `old_string` with.
- `expected_replacements` (number, optional): The number of occurrences to replace. Defaults to `1`.
- `replace_all` (boolean, optional): Replace all occurrences of `old_string`. Defaults to `false`.
- **Behavior:**
- If `old_string` is empty and `file_path` does not exist, creates a new file with `new_string` as content.
- If `old_string` is provided, it reads the `file_path` and attempts to find exactly one occurrence of `old_string`.
- If one occurrence is found, it replaces it with `new_string`.
- If `old_string` is provided, it reads the `file_path` and attempts to find exactly one occurrence unless `replace_all` is true.
- If the match is unique (or `replace_all` is true), it replaces the text with `new_string`.
- **Enhanced Reliability (Multi-Stage Edit Correction):** To significantly improve the success rate of edits, especially when the model-provided `old_string` might not be perfectly precise, the tool incorporates a multi-stage edit correction mechanism.
- If the initial `old_string` isn't found or matches multiple locations, the tool can leverage the Qwen model to iteratively refine `old_string` (and potentially `new_string`).
- This self-correction process attempts to identify the unique segment the model intended to modify, making the `edit` operation more robust even with slightly imperfect initial context.
@@ -164,10 +158,10 @@ search_file_content(pattern="function", include="*.js", maxResults=10)
- `old_string` is not empty, but the `file_path` does not exist.
- `old_string` is empty, but the `file_path` already exists.
- `old_string` is not found in the file after attempts to correct it.
- `old_string` is found multiple times, and the self-correction mechanism cannot resolve it to a single, unambiguous match.
- `old_string` is found multiple times, `replace_all` is false, and the self-correction mechanism cannot resolve it to a single, unambiguous match.
- **Output (`llmContent`):**
- On success: `Successfully modified file: /path/to/file.txt (1 replacements).` or `Created new file: /path/to/new_file.txt with provided content.`
- On failure: An error message explaining the reason (e.g., `Failed to edit, 0 occurrences found...`, `Failed to edit, expected 1 occurrences but found 2...`).
- On failure: An error message explaining the reason (e.g., `Failed to edit, 0 occurrences found...`, `Failed to edit because the text matches multiple locations...`).
- **Confirmation:** Yes. Shows a diff of the proposed changes and asks for user approval before writing to the file.
These file system tools provide a foundation for Qwen Code to understand and interact with your local project context.

View File

@@ -1,43 +1,186 @@
# Web Search Tool (`web_search`)
This document describes the `web_search` tool.
This document describes the `web_search` tool for performing web searches using multiple providers.
## Description
Use `web_search` to perform a web search using the Tavily API. The tool returns a concise answer with sources when possible.
Use `web_search` to perform a web search and get information from the internet. The tool supports multiple search providers and returns a concise answer with source citations when available.
### Supported Providers
1. **DashScope** (Official, Free) - Automatically available for Qwen OAuth users (200 requests/minute, 2000 requests/day)
2. **Tavily** - High-quality search API with built-in answer generation
3. **Google Custom Search** - Google's Custom Search JSON API
### Arguments
`web_search` takes one argument:
`web_search` takes two arguments:
- `query` (string, required): The search query.
- `query` (string, required): The search query
- `provider` (string, optional): Specific provider to use ("dashscope", "tavily", "google")
- If not specified, uses the default provider from configuration
## How to use `web_search`
## Configuration
`web_search` calls the Tavily API directly. You must configure the `TAVILY_API_KEY` through one of the following methods:
### Method 1: Settings File (Recommended)
1. **Settings file**: Add `"tavilyApiKey": "your-key-here"` to your `settings.json`
2. **Environment variable**: Set `TAVILY_API_KEY` in your environment or `.env` file
3. **Command line**: Use `--tavily-api-key your-key-here` when running the CLI
Add to your `settings.json`:
If the key is not configured, the tool will be disabled and skipped.
Usage:
```
web_search(query="Your query goes here.")
```json
{
"webSearch": {
"provider": [
{ "type": "dashscope" },
{ "type": "tavily", "apiKey": "tvly-xxxxx" },
{
"type": "google",
"apiKey": "your-google-api-key",
"searchEngineId": "your-search-engine-id"
}
],
"default": "dashscope"
}
}
```
## `web_search` examples
**Notes:**
Get information on a topic:
- DashScope doesn't require an API key (official, free service)
- **Qwen OAuth users:** DashScope is automatically added to your provider list, even if not explicitly configured
- Configure additional providers (Tavily, Google) if you want to use them alongside DashScope
- Set `default` to specify which provider to use by default (if not set, priority order: Tavily > Google > DashScope)
```
web_search(query="latest advancements in AI-powered code generation")
### Method 2: Environment Variables
Set environment variables in your shell or `.env` file:
```bash
# Tavily
export TAVILY_API_KEY="tvly-xxxxx"
# Google
export GOOGLE_API_KEY="your-api-key"
export GOOGLE_SEARCH_ENGINE_ID="your-engine-id"
```
## Important notes
### Method 3: Command Line Arguments
- **Response returned:** The `web_search` tool returns a concise answer when available, with a list of source links.
- **Citations:** Source links are appended as a numbered list.
- **API key:** Configure `TAVILY_API_KEY` via settings.json, environment variables, .env files, or command line arguments. If not configured, the tool is not registered.
Pass API keys when running Qwen Code:
```bash
# Tavily
qwen --tavily-api-key tvly-xxxxx
# Google
qwen --google-api-key your-key --google-search-engine-id your-id
# Specify default provider
qwen --web-search-default tavily
```
### Backward Compatibility (Deprecated)
⚠️ **DEPRECATED:** The legacy `tavilyApiKey` configuration is still supported for backward compatibility but is deprecated:
```json
{
"advanced": {
"tavilyApiKey": "tvly-xxxxx" // ⚠️ Deprecated
}
}
```
**Important:** This configuration is deprecated and will be removed in a future version. Please migrate to the new `webSearch` configuration format shown above. The old configuration will automatically configure Tavily as a provider, but we strongly recommend updating your configuration.
## Disabling Web Search
If you want to disable the web search functionality, you can exclude the `web_search` tool in your `settings.json`:
```json
{
"tools": {
"exclude": ["web_search"]
}
}
```
**Note:** This setting requires a restart of Qwen Code to take effect. Once disabled, the `web_search` tool will not be available to the model, even if web search providers are configured.
## Usage Examples
### Basic search (using default provider)
```
web_search(query="latest advancements in AI")
```
### Search with specific provider
```
web_search(query="latest advancements in AI", provider="tavily")
```
### Real-world examples
```
web_search(query="weather in San Francisco today")
web_search(query="latest Node.js LTS version", provider="google")
web_search(query="best practices for React 19", provider="dashscope")
```
## Provider Details
### DashScope (Official)
- **Cost:** Free
- **Authentication:** Automatically available when using Qwen OAuth authentication
- **Configuration:** No API key required, automatically added to provider list for Qwen OAuth users
- **Quota:** 200 requests/minute, 2000 requests/day
- **Best for:** General queries, always available as fallback for Qwen OAuth users
- **Auto-registration:** If you're using Qwen OAuth, DashScope is automatically added to your provider list even if you don't configure it explicitly
### Tavily
- **Cost:** Requires API key (paid service with free tier)
- **Sign up:** https://tavily.com
- **Features:** High-quality results with AI-generated answers
- **Best for:** Research, comprehensive answers with citations
### Google Custom Search
- **Cost:** Free tier available (100 queries/day)
- **Setup:**
1. Enable Custom Search API in Google Cloud Console
2. Create a Custom Search Engine at https://programmablesearchengine.google.com
- **Features:** Google's search quality
- **Best for:** Specific, factual queries
## Important Notes
- **Response format:** Returns a concise answer with numbered source citations
- **Citations:** Source links are appended as a numbered list: [1], [2], etc.
- **Multiple providers:** If one provider fails, manually specify another using the `provider` parameter
- **DashScope availability:** Automatically available for Qwen OAuth users, no configuration needed
- **Default provider selection:** The system automatically selects a default provider based on availability:
1. Your explicit `default` configuration (highest priority)
2. CLI argument `--web-search-default`
3. First available provider by priority: Tavily > Google > DashScope
## Troubleshooting
**Tool not available?**
- **For Qwen OAuth users:** The tool is automatically registered with DashScope provider, no configuration needed
- **For other authentication types:** Ensure at least one provider (Tavily or Google) is configured
- For Tavily/Google: Verify your API keys are correct
**Provider-specific errors?**
- Use the `provider` parameter to try a different search provider
- Check your API quotas and rate limits
- Verify API keys are properly set in configuration
**Need help?**
- Check your configuration: Run `qwen` and use the settings dialog
- View your current settings in `~/.qwen-code/settings.json` (macOS/Linux) or `%USERPROFILE%\.qwen-code\settings.json` (Windows)

View File

@@ -7,7 +7,7 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import { writeFileSync } from 'node:fs';
import { writeFileSync, rmSync } from 'node:fs';
let esbuild;
try {
@@ -22,6 +22,9 @@ const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const pkg = require(path.resolve(__dirname, 'package.json'));
// Clean dist directory (cross-platform)
rmSync(path.resolve(__dirname, 'dist'), { recursive: true, force: true });
const external = [
'@lydell/node-pty',
'node-pty',

View File

@@ -22,6 +22,7 @@ export default tseslint.config(
'bundle/**',
'package/bundle/**',
'.integration-tests/**',
'packages/**/.integration-test/**',
'dist/**',
],
},
@@ -74,6 +75,8 @@ export default tseslint.config(
},
},
rules: {
// We use TypeScript for React components; prop-types are unnecessary
'react/prop-types': 'off',
// General Best Practice Rules (subset adapted for flat config)
'@typescript-eslint/array-type': ['error', { default: 'array-simple' }],
'arrow-body-style': ['error', 'as-needed'],
@@ -110,10 +113,14 @@ export default tseslint.config(
{
allow: [
'react-dom/test-utils',
'react-dom/client',
'memfs/lib/volume.js',
'yargs/**',
'msw/node',
'**/generated/**'
'**/generated/**',
'./styles/tailwind.css',
'./styles/App.css',
'./styles/style.css'
],
},
],
@@ -150,7 +157,7 @@ export default tseslint.config(
},
},
{
files: ['packages/*/src/**/*.test.{ts,tsx}'],
files: ['packages/*/src/**/*.test.{ts,tsx}', 'packages/**/test/**/*.test.{ts,tsx}'],
plugins: {
vitest,
},
@@ -158,11 +165,19 @@ export default tseslint.config(
...vitest.configs.recommended.rules,
'vitest/expect-expect': 'off',
'vitest/no-commented-out-tests': 'off',
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
},
// extra settings for scripts that we run directly with node
{
files: ['./scripts/**/*.js', 'esbuild.config.js'],
files: ['./scripts/**/*.js', 'esbuild.config.js', 'packages/*/scripts/**/*.js'],
languageOptions: {
globals: {
...globals.node,
@@ -229,7 +244,7 @@ export default tseslint.config(
prettierConfig,
// extra settings for scripts that we run directly with node
{
files: ['./integration-tests/**/*.js'],
files: ['./integration-tests/**/*.{js,ts,tsx}'],
languageOptions: {
globals: {
...globals.node,

View File

@@ -0,0 +1,649 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { spawn } from 'node:child_process';
import { readFileSync, writeFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
import { setTimeout as delay } from 'node:timers/promises';
import { describe, expect, it } from 'vitest';
import { TestRig } from './test-helper.js';
const REQUEST_TIMEOUT_MS = 60_000;
const INITIAL_PROMPT = 'Create a quick note (smoke test).';
const RESUME_PROMPT = 'Continue the note after reload.';
const LIST_SIZE = 5;
const IS_SANDBOX =
process.env['GEMINI_SANDBOX'] &&
process.env['GEMINI_SANDBOX']!.toLowerCase() !== 'false';
type PendingRequest = {
resolve: (value: unknown) => void;
reject: (reason: Error) => void;
timeout: NodeJS.Timeout;
};
type UsageMetadata = {
promptTokens?: number | null;
completionTokens?: number | null;
thoughtsTokens?: number | null;
totalTokens?: number | null;
cachedTokens?: number | null;
};
type SessionUpdateNotification = {
sessionId?: string;
update?: {
sessionUpdate?: string;
availableCommands?: Array<{
name: string;
description: string;
input?: { hint: string } | null;
}>;
content?: {
type: string;
text?: string;
};
modeId?: string;
_meta?: {
usage?: UsageMetadata;
};
};
};
type PermissionRequest = {
id: number;
sessionId?: string;
toolCall?: {
toolCallId: string;
title: string;
kind: string;
status: string;
content?: Array<{
type: string;
text?: string;
path?: string;
oldText?: string;
newText?: string;
}>;
};
options?: Array<{
optionId: string;
name: string;
kind: string;
}>;
};
type PermissionHandler = (
request: PermissionRequest,
) => { optionId: string } | { outcome: 'cancelled' };
/**
* Sets up an ACP test environment with all necessary utilities.
*/
function setupAcpTest(
rig: TestRig,
options?: { permissionHandler?: PermissionHandler },
) {
const pending = new Map<number, PendingRequest>();
let nextRequestId = 1;
const sessionUpdates: SessionUpdateNotification[] = [];
const permissionRequests: PermissionRequest[] = [];
const stderr: string[] = [];
// Default permission handler: auto-approve all
const permissionHandler =
options?.permissionHandler ?? (() => ({ optionId: 'proceed_once' }));
const agent = spawn('node', [rig.bundlePath, '--experimental-acp'], {
cwd: rig.testDir!,
stdio: ['pipe', 'pipe', 'pipe'],
});
agent.stderr?.on('data', (chunk) => {
stderr.push(chunk.toString());
});
const rl = createInterface({ input: agent.stdout });
const send = (json: unknown) => {
agent.stdin.write(`${JSON.stringify(json)}\n`);
};
const sendResponse = (id: number, result: unknown) => {
send({ jsonrpc: '2.0', id, result });
};
const sendRequest = (method: string, params?: unknown) =>
new Promise<unknown>((resolve, reject) => {
const id = nextRequestId++;
const timeout = setTimeout(() => {
pending.delete(id);
reject(new Error(`Request ${id} (${method}) timed out`));
}, REQUEST_TIMEOUT_MS);
pending.set(id, { resolve, reject, timeout });
send({ jsonrpc: '2.0', id, method, params });
});
const handleResponse = (msg: {
id: number;
result?: unknown;
error?: { message?: string };
}) => {
const waiter = pending.get(msg.id);
if (!waiter) {
return;
}
clearTimeout(waiter.timeout);
pending.delete(msg.id);
if (msg.error) {
waiter.reject(new Error(msg.error.message ?? 'Unknown error'));
} else {
waiter.resolve(msg.result);
}
};
const handleMessage = (msg: {
id?: number;
method?: string;
params?: SessionUpdateNotification & {
path?: string;
content?: string;
sessionId?: string;
toolCall?: PermissionRequest['toolCall'];
options?: PermissionRequest['options'];
};
result?: unknown;
error?: { message?: string };
}) => {
if (typeof msg.id !== 'undefined' && ('result' in msg || 'error' in msg)) {
handleResponse(
msg as {
id: number;
result?: unknown;
error?: { message?: string };
},
);
return;
}
if (msg.method === 'session/update') {
sessionUpdates.push({
sessionId: msg.params?.sessionId,
update: msg.params?.update,
});
return;
}
if (
msg.method === 'session/request_permission' &&
typeof msg.id === 'number'
) {
// Track permission request
const permRequest: PermissionRequest = {
id: msg.id,
sessionId: msg.params?.sessionId,
toolCall: msg.params?.toolCall,
options: msg.params?.options,
};
permissionRequests.push(permRequest);
// Use custom handler or default
const response = permissionHandler(permRequest);
if ('outcome' in response) {
sendResponse(msg.id, { outcome: response });
} else {
sendResponse(msg.id, {
outcome: { optionId: response.optionId, outcome: 'selected' },
});
}
return;
}
if (msg.method === 'fs/read_text_file' && typeof msg.id === 'number') {
try {
const content = readFileSync(msg.params?.path ?? '', 'utf8');
sendResponse(msg.id, { content });
} catch (e) {
sendResponse(msg.id, { content: `ERROR: ${(e as Error).message}` });
}
return;
}
if (msg.method === 'fs/write_text_file' && typeof msg.id === 'number') {
try {
writeFileSync(
msg.params?.path ?? '',
msg.params?.content ?? '',
'utf8',
);
sendResponse(msg.id, null);
} catch (e) {
sendResponse(msg.id, { message: (e as Error).message });
}
}
};
rl.on('line', (line) => {
if (!line.trim()) return;
try {
const msg = JSON.parse(line);
handleMessage(msg);
} catch {
// Ignore non-JSON output from the agent.
}
});
const waitForExit = () =>
new Promise<void>((resolve) => {
if (agent.exitCode !== null || agent.signalCode) {
resolve();
return;
}
agent.once('exit', () => resolve());
});
const cleanup = async () => {
rl.close();
agent.kill();
pending.forEach(({ timeout }) => clearTimeout(timeout));
pending.clear();
await waitForExit();
};
return {
sendRequest,
sendResponse,
cleanup,
stderr,
sessionUpdates,
permissionRequests,
};
}
(IS_SANDBOX ? describe.skip : describe)('acp integration', () => {
it('creates, lists, loads, and resumes a session', async () => {
const rig = new TestRig();
rig.setup('acp load session');
const { sendRequest, cleanup, stderr, sessionUpdates } = setupAcpTest(rig);
try {
const initResult = await sendRequest('initialize', {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
},
});
expect(initResult).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((initResult as any).agentInfo.version).toBeDefined();
await sendRequest('authenticate', { methodId: 'openai' });
const newSession = (await sendRequest('session/new', {
cwd: rig.testDir!,
mcpServers: [],
})) as { sessionId: string };
expect(newSession.sessionId).toBeTruthy();
const promptResult = await sendRequest('session/prompt', {
sessionId: newSession.sessionId,
prompt: [{ type: 'text', text: INITIAL_PROMPT }],
});
expect(promptResult).toBeDefined();
await delay(500);
const listResult = (await sendRequest('session/list', {
cwd: rig.testDir!,
size: LIST_SIZE,
})) as { items?: Array<{ sessionId: string }> };
expect(Array.isArray(listResult.items)).toBe(true);
expect(listResult.items?.length ?? 0).toBeGreaterThan(0);
const sessionToLoad = listResult.items![0].sessionId;
await sendRequest('session/load', {
cwd: rig.testDir!,
sessionId: sessionToLoad,
mcpServers: [],
});
const resumeResult = await sendRequest('session/prompt', {
sessionId: sessionToLoad,
prompt: [{ type: 'text', text: RESUME_PROMPT }],
});
expect(resumeResult).toBeDefined();
const sessionsWithUpdates = sessionUpdates
.map((update) => update.sessionId)
.filter(Boolean);
expect(sessionsWithUpdates).toContain(sessionToLoad);
} catch (e) {
if (stderr.length) {
console.error('Agent stderr:', stderr.join(''));
}
throw e;
} finally {
await cleanup();
}
});
it('returns modes on initialize and allows setting approval mode', async () => {
const rig = new TestRig();
rig.setup('acp approval mode');
const { sendRequest, cleanup, stderr } = setupAcpTest(rig);
try {
// Test 1: Initialize and verify modes are returned
const initResult = (await sendRequest('initialize', {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
},
})) as {
protocolVersion: number;
modes: {
currentModeId: string;
availableModes: Array<{
id: string;
name: string;
description: string;
}>;
};
};
expect(initResult).toBeDefined();
expect(initResult.protocolVersion).toBe(1);
// Verify modes data is present
expect(initResult.modes).toBeDefined();
expect(initResult.modes.currentModeId).toBeDefined();
expect(Array.isArray(initResult.modes.availableModes)).toBe(true);
expect(initResult.modes.availableModes.length).toBeGreaterThan(0);
// Verify available modes have expected structure
const modeIds = initResult.modes.availableModes.map((m) => m.id);
expect(modeIds).toContain('default');
expect(modeIds).toContain('yolo');
expect(modeIds).toContain('auto-edit');
expect(modeIds).toContain('plan');
// Verify each mode has required fields
for (const mode of initResult.modes.availableModes) {
expect(mode.id).toBeTruthy();
expect(mode.name).toBeTruthy();
expect(mode.description).toBeTruthy();
}
// Test 2: Authenticate
await sendRequest('authenticate', { methodId: 'openai' });
// Test 3: Create a new session
const newSession = (await sendRequest('session/new', {
cwd: rig.testDir!,
mcpServers: [],
})) as { sessionId: string };
expect(newSession.sessionId).toBeTruthy();
// Test 4: Set approval mode to 'yolo'
const setModeResult = (await sendRequest('session/set_mode', {
sessionId: newSession.sessionId,
modeId: 'yolo',
})) as { modeId: string };
expect(setModeResult).toBeDefined();
expect(setModeResult.modeId).toBe('yolo');
// Test 5: Set approval mode to 'auto-edit'
const setModeResult2 = (await sendRequest('session/set_mode', {
sessionId: newSession.sessionId,
modeId: 'auto-edit',
})) as { modeId: string };
expect(setModeResult2).toBeDefined();
expect(setModeResult2.modeId).toBe('auto-edit');
// Test 6: Set approval mode back to 'default'
const setModeResult3 = (await sendRequest('session/set_mode', {
sessionId: newSession.sessionId,
modeId: 'default',
})) as { modeId: string };
expect(setModeResult3).toBeDefined();
expect(setModeResult3.modeId).toBe('default');
} catch (e) {
if (stderr.length) {
console.error('Agent stderr:', stderr.join(''));
}
throw e;
} finally {
await cleanup();
}
});
it('receives available_commands_update with slash commands after session creation', async () => {
const rig = new TestRig();
rig.setup('acp slash commands');
const { sendRequest, cleanup, stderr, sessionUpdates } = setupAcpTest(rig);
try {
// Initialize
await sendRequest('initialize', {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
},
});
await sendRequest('authenticate', { methodId: 'openai' });
// Create a new session
const newSession = (await sendRequest('session/new', {
cwd: rig.testDir!,
mcpServers: [],
})) as { sessionId: string };
expect(newSession.sessionId).toBeTruthy();
// Wait for available_commands_update to be received
await delay(1000);
// Verify available_commands_update is received
const commandsUpdate = sessionUpdates.find(
(update) =>
update.update?.sessionUpdate === 'available_commands_update',
);
expect(commandsUpdate).toBeDefined();
expect(commandsUpdate?.update?.availableCommands).toBeDefined();
expect(Array.isArray(commandsUpdate?.update?.availableCommands)).toBe(
true,
);
// Verify that the 'init' command is present (the only allowed built-in command for ACP)
const initCommand = commandsUpdate?.update?.availableCommands?.find(
(cmd) => cmd.name === 'init',
);
expect(initCommand).toBeDefined();
expect(initCommand?.description).toBeTruthy();
// Note: We don't test /init execution here because it triggers a complex
// multi-step process (listing files, reading up to 10 files, generating QWEN.md)
// that can take 30-60+ seconds, exceeding the request timeout.
// The slash command execution path is tested via simpler prompts in other tests.
} catch (e) {
if (stderr.length) {
console.error('Agent stderr:', stderr.join(''));
}
throw e;
} finally {
await cleanup();
}
});
it('handles exit plan mode with permission request and mode update notification', async () => {
const rig = new TestRig();
rig.setup('acp exit plan mode');
// Track which permission requests we've seen
const planModeRequests: PermissionRequest[] = [];
const { sendRequest, cleanup, stderr, sessionUpdates, permissionRequests } =
setupAcpTest(rig, {
permissionHandler: (request) => {
// Track all permission requests for later verification
// Auto-approve exit plan mode requests with "proceed_always" to trigger auto-edit mode
if (request.toolCall?.kind === 'switch_mode') {
planModeRequests.push(request);
// Return proceed_always to switch to auto-edit mode
return { optionId: 'proceed_always' };
}
// Auto-approve all other requests
return { optionId: 'proceed_once' };
},
});
try {
// Initialize
await sendRequest('initialize', {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: true },
},
});
await sendRequest('authenticate', { methodId: 'openai' });
// Create a new session
const newSession = (await sendRequest('session/new', {
cwd: rig.testDir!,
mcpServers: [],
})) as { sessionId: string };
expect(newSession.sessionId).toBeTruthy();
// Set mode to 'plan' to enable plan mode
const setModeResult = (await sendRequest('session/set_mode', {
sessionId: newSession.sessionId,
modeId: 'plan',
})) as { modeId: string };
expect(setModeResult.modeId).toBe('plan');
// Send a prompt that should trigger the LLM to call exit_plan_mode
// The prompt is designed to trigger planning behavior
const promptResult = await sendRequest('session/prompt', {
sessionId: newSession.sessionId,
prompt: [
{
type: 'text',
text: 'Create a simple hello world function in Python. Make a brief plan and when ready, use the exit_plan_mode tool to present it for approval.',
},
],
});
expect(promptResult).toBeDefined();
// Give time for all notifications to be processed
await delay(1000);
// Verify: If exit_plan_mode was called, we should have received:
// 1. A permission request with kind: "switch_mode"
// 2. A current_mode_update notification after approval
// Check for switch_mode permission requests
const switchModeRequests = permissionRequests.filter(
(req) => req.toolCall?.kind === 'switch_mode',
);
// Check for current_mode_update notifications
const modeUpdateNotifications = sessionUpdates.filter(
(update) => update.update?.sessionUpdate === 'current_mode_update',
);
// If the LLM called exit_plan_mode, verify the flow
if (switchModeRequests.length > 0) {
// Verify permission request structure
const permReq = switchModeRequests[0];
expect(permReq.toolCall).toBeDefined();
expect(permReq.toolCall?.kind).toBe('switch_mode');
expect(permReq.toolCall?.status).toBe('pending');
expect(permReq.options).toBeDefined();
expect(Array.isArray(permReq.options)).toBe(true);
// Verify options include appropriate choices
const optionKinds = permReq.options?.map((opt) => opt.kind) ?? [];
expect(optionKinds).toContain('allow_once');
expect(optionKinds).toContain('allow_always');
// After approval, should have received current_mode_update
expect(modeUpdateNotifications.length).toBeGreaterThan(0);
// Verify mode update structure
const modeUpdate = modeUpdateNotifications[0];
expect(modeUpdate.sessionId).toBe(newSession.sessionId);
expect(modeUpdate.update?.modeId).toBeDefined();
// Mode should be auto-edit since we approved with proceed_always
expect(modeUpdate.update?.modeId).toBe('auto-edit');
}
// Note: If the LLM didn't call exit_plan_mode, that's acceptable
// since LLM behavior is non-deterministic. The test setup and structure
// is verified regardless.
} catch (e) {
if (stderr.length) {
console.error('Agent stderr:', stderr.join(''));
}
throw e;
} finally {
await cleanup();
}
});
it('receives usage metadata in agent_message_chunk updates', async () => {
const rig = new TestRig();
rig.setup('acp usage metadata');
const { sendRequest, cleanup, stderr, sessionUpdates } = setupAcpTest(rig);
try {
await sendRequest('initialize', {
protocolVersion: 1,
clientCapabilities: { fs: { readTextFile: true, writeTextFile: true } },
});
await sendRequest('authenticate', { methodId: 'openai' });
const newSession = (await sendRequest('session/new', {
cwd: rig.testDir!,
mcpServers: [],
})) as { sessionId: string };
await sendRequest('session/prompt', {
sessionId: newSession.sessionId,
prompt: [{ type: 'text', text: 'Say "hello".' }],
});
await delay(500);
// Find updates with usage metadata
const updatesWithUsage = sessionUpdates.filter(
(u) =>
u.update?.sessionUpdate === 'agent_message_chunk' &&
u.update?._meta?.usage,
);
expect(updatesWithUsage.length).toBeGreaterThan(0);
const usage = updatesWithUsage[0].update?._meta?.usage;
expect(usage).toBeDefined();
expect(
typeof usage?.promptTokens === 'number' ||
typeof usage?.totalTokens === 'number',
).toBe(true);
} catch (e) {
if (stderr.length) console.error('Agent stderr:', stderr.join(''));
throw e;
} finally {
await cleanup();
}
});
});

View File

@@ -21,23 +21,21 @@ describe('Interactive Mode', () => {
it.skipIf(process.platform === 'win32')(
'should trigger chat compression with /compress command',
async () => {
await rig.setup('interactive-compress-test');
await rig.setup('interactive-compress-test', {
settings: {
security: {
auth: {
selectedType: 'openai',
},
},
},
});
const { ptyProcess } = rig.runInteractive();
let fullOutput = '';
ptyProcess.onData((data) => (fullOutput += data));
const authDialogAppeared = await rig.waitForText(
'How would you like to authenticate',
5000,
);
// select the second option if auth dialog come's up
if (authDialogAppeared) {
ptyProcess.write('2');
}
// Wait for the app to be ready
const isReady = await rig.waitForText('Type your message', 15000);
expect(
@@ -68,49 +66,43 @@ describe('Interactive Mode', () => {
},
);
it.skipIf(process.platform === 'win32')(
'should handle compression failure on token inflation',
async () => {
await rig.setup('interactive-compress-test');
it.skip('should handle compression failure on token inflation', async () => {
await rig.setup('interactive-compress-test', {
settings: {
security: {
auth: {
selectedType: 'openai',
},
},
},
});
const { ptyProcess } = rig.runInteractive();
const { ptyProcess } = rig.runInteractive();
let fullOutput = '';
ptyProcess.onData((data) => (fullOutput += data));
let fullOutput = '';
ptyProcess.onData((data) => (fullOutput += data));
const authDialogAppeared = await rig.waitForText(
'How would you like to authenticate',
5000,
);
// Wait for the app to be ready
const isReady = await rig.waitForText('Type your message', 25000);
expect(isReady, 'CLI did not start up in interactive mode correctly').toBe(
true,
);
// select the second option if auth dialog come's up
if (authDialogAppeared) {
ptyProcess.write('2');
}
await type(ptyProcess, '/compress');
await new Promise((resolve) => setTimeout(resolve, 1000));
await type(ptyProcess, '\r');
// Wait for the app to be ready
const isReady = await rig.waitForText('Type your message', 25000);
expect(
isReady,
'CLI did not start up in interactive mode correctly',
).toBe(true);
const foundEvent = await rig.waitForTelemetryEvent(
'chat_compression',
90000,
);
expect(foundEvent).toBe(true);
await type(ptyProcess, '/compress');
await new Promise((resolve) => setTimeout(resolve, 100));
await type(ptyProcess, '\r');
const compressionFailed = await rig.waitForText(
'Nothing to compress.',
25000,
);
const foundEvent = await rig.waitForTelemetryEvent(
'chat_compression',
90000,
);
expect(foundEvent).toBe(true);
const compressionFailed = await rig.waitForText(
'compression was not beneficial',
25000,
);
expect(compressionFailed).toBe(true);
},
);
expect(compressionFailed).toBe(true);
});
});

View File

@@ -6,124 +6,71 @@
import { describe, it, expect } from 'vitest';
import { TestRig } from './test-helper.js';
import * as fs from 'node:fs';
import * as path from 'node:path';
describe('Ctrl+C exit', () => {
// (#9782) Temporarily disabling on windows because it is failing on main and every
// PR, which is potentially hiding other failures
it.skipIf(process.platform === 'win32')(
'should exit gracefully on second Ctrl+C',
async () => {
const rig = new TestRig();
await rig.setup('should exit gracefully on second Ctrl+C');
it.skip('should exit gracefully on second Ctrl+C', async () => {
const rig = new TestRig();
await rig.setup('should exit gracefully on second Ctrl+C');
const { ptyProcess, promise } = rig.runInteractive();
const { ptyProcess, promise } = rig.runInteractive();
let output = '';
ptyProcess.onData((data) => {
output += data;
});
let output = '';
ptyProcess.onData((data) => {
output += data;
});
// Wait for the app to be ready by looking for the initial prompt indicator
await rig.poll(() => output.includes('▶'), 5000, 100);
const isReady = await rig.waitForText('Type your message', 15000);
expect(isReady, 'CLI did not start up in interactive mode correctly').toBe(
true,
);
// Send first Ctrl+C
ptyProcess.write(String.fromCharCode(3));
// Send first Ctrl+C
ptyProcess.write(String.fromCharCode(3));
// Wait for the exit prompt
await rig.poll(
() => output.includes('Press Ctrl+C again to exit'),
1500,
50,
);
// Wait for the exit prompt
const showedExitPrompt = await rig.poll(
() => output.includes('Press Ctrl+C again to exit'),
1500,
50,
);
expect(showedExitPrompt, `Exit prompt not shown. Output: ${output}`).toBe(
true,
);
// Send second Ctrl+C
ptyProcess.write(String.fromCharCode(3));
// Send second Ctrl+C
ptyProcess.write(String.fromCharCode(3));
const result = await promise;
// Wait for process exit with timeout to fail fast
const EXIT_TIMEOUT = 5000;
const result = await Promise.race([
promise,
new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new Error(
`Process did not exit within ${EXIT_TIMEOUT}ms. Output: ${output}`,
),
),
EXIT_TIMEOUT,
),
),
]);
// Expect a graceful exit (code 0)
expect(
result.exitCode,
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
).toBe(0);
// Expect a graceful exit (code 0)
expect(
result.exitCode,
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
).toBe(0);
// Check that the quitting message is displayed
const quittingMessage = 'Agent powering down. Goodbye!';
// The regex below is intentionally matching the ESC control character (\x1b)
// to strip ANSI color codes from the terminal output.
// eslint-disable-next-line no-control-regex
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
expect(cleanOutput).toContain(quittingMessage);
},
);
it.skipIf(process.platform === 'win32')(
'should exit gracefully on second Ctrl+C when calling a tool',
async () => {
const rig = new TestRig();
await rig.setup(
'should exit gracefully on second Ctrl+C when calling a tool',
);
const childProcessFile = 'child_process_file.txt';
rig.createFile(
'wait.js',
`setTimeout(() => require('fs').writeFileSync('${childProcessFile}', 'done'), 5000)`,
);
const { ptyProcess, promise } = rig.runInteractive();
let output = '';
ptyProcess.onData((data) => {
output += data;
});
// Wait for the app to be ready by looking for the initial prompt indicator
await rig.poll(() => output.includes('▶'), 5000, 100);
ptyProcess.write('use the tool to run "node -e wait.js"\n');
await rig.poll(() => output.includes('Shell'), 5000, 100);
// Send first Ctrl+C
ptyProcess.write(String.fromCharCode(3));
// Wait for the exit prompt
await rig.poll(
() => output.includes('Press Ctrl+C again to exit'),
1500,
50,
);
// Send second Ctrl+C
ptyProcess.write(String.fromCharCode(3));
const result = await promise;
// Expect a graceful exit (code 0)
expect(
result.exitCode,
`Process exited with code ${result.exitCode}. Output: ${result.output}`,
).toBe(0);
// Check that the quitting message is displayed
const quittingMessage = 'Agent powering down. Goodbye!';
// The regex below is intentionally matching the ESC control character (\x1b)
// to strip ANSI color codes from the terminal output.
// eslint-disable-next-line no-control-regex
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
expect(cleanOutput).toContain(quittingMessage);
// Check that the child process was terminated and did not create the file.
const childProcessFileExists = fs.existsSync(
path.join(rig.testDir!, childProcessFile),
);
expect(
childProcessFileExists,
'Child process file should not exist',
).toBe(false);
},
);
// Check that the quitting message is displayed
const quittingMessage = 'Agent powering down. Goodbye!';
// The regex below is intentionally matching the ESC control character (\x1b)
// to strip ANSI color codes from the terminal output.
// eslint-disable-next-line no-control-regex
const cleanOutput = output.replace(/\x1b\[[0-9;]*m/g, '');
expect(cleanOutput).toContain(quittingMessage);
});
});

View File

@@ -22,21 +22,19 @@ describe('Interactive file system', () => {
'should perform a read-then-write sequence in interactive mode',
async () => {
const fileName = 'version.txt';
await rig.setup('interactive-read-then-write');
await rig.setup('interactive-read-then-write', {
settings: {
security: {
auth: {
selectedType: 'openai',
},
},
},
});
rig.createFile(fileName, '1.0.0');
const { ptyProcess } = rig.runInteractive();
const authDialogAppeared = await rig.waitForText(
'How would you like to authenticate',
5000,
);
// select the second option if auth dialog come's up
if (authDialogAppeared) {
ptyProcess.write('2');
}
// Wait for the app to be ready
const isReady = await rig.waitForText('Type your message', 15000);
expect(

View File

@@ -1,6 +1,6 @@
/**
* @license
* Copyright 2025 Google LLC
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
@@ -30,6 +30,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = join(__dirname, '..');
const integrationTestsDir = join(rootDir, '.integration-tests');
let runDir = ''; // Make runDir accessible in teardown
let sdkE2eRunDir = ''; // SDK E2E test run directory
const memoryFilePath = join(
os.homedir(),
@@ -48,14 +49,36 @@ export async function setup() {
// File doesn't exist, which is fine.
}
// Setup for CLI integration tests
runDir = join(integrationTestsDir, `${Date.now()}`);
await mkdir(runDir, { recursive: true });
// Setup for SDK E2E tests (separate directory with prefix)
sdkE2eRunDir = join(integrationTestsDir, `sdk-e2e-${Date.now()}`);
await mkdir(sdkE2eRunDir, { recursive: true });
// Clean up old test runs, but keep the latest few for debugging
try {
const testRuns = await readdir(integrationTestsDir);
if (testRuns.length > 5) {
const oldRuns = testRuns.sort().slice(0, testRuns.length - 5);
// Clean up old CLI integration test runs (without sdk-e2e- prefix)
const cliTestRuns = testRuns.filter((run) => !run.startsWith('sdk-e2e-'));
if (cliTestRuns.length > 5) {
const oldRuns = cliTestRuns.sort().slice(0, cliTestRuns.length - 5);
await Promise.all(
oldRuns.map((oldRun) =>
rm(join(integrationTestsDir, oldRun), {
recursive: true,
force: true,
}),
),
);
}
// Clean up old SDK E2E test runs (with sdk-e2e- prefix)
const sdkTestRuns = testRuns.filter((run) => run.startsWith('sdk-e2e-'));
if (sdkTestRuns.length > 5) {
const oldRuns = sdkTestRuns.sort().slice(0, sdkTestRuns.length - 5);
await Promise.all(
oldRuns.map((oldRun) =>
rm(join(integrationTestsDir, oldRun), {
@@ -69,24 +92,37 @@ export async function setup() {
console.error('Error cleaning up old test runs:', e);
}
// Environment variables for CLI integration tests
process.env['INTEGRATION_TEST_FILE_DIR'] = runDir;
process.env['GEMINI_CLI_INTEGRATION_TEST'] = 'true';
process.env['TELEMETRY_LOG_FILE'] = join(runDir, 'telemetry.log');
// Environment variables for SDK E2E tests
process.env['E2E_TEST_FILE_DIR'] = sdkE2eRunDir;
process.env['TEST_CLI_PATH'] = join(rootDir, 'dist/cli.js');
if (process.env['KEEP_OUTPUT']) {
console.log(`Keeping output for test run in: ${runDir}`);
console.log(`Keeping output for SDK E2E test run in: ${sdkE2eRunDir}`);
}
process.env['VERBOSE'] = process.env['VERBOSE'] ?? 'false';
console.log(`\nIntegration test output directory: ${runDir}`);
console.log(`SDK E2E test output directory: ${sdkE2eRunDir}`);
console.log(`CLI path: ${process.env['TEST_CLI_PATH']}`);
}
export async function teardown() {
// Cleanup the test run directory unless KEEP_OUTPUT is set
// Cleanup the CLI test run directory unless KEEP_OUTPUT is set
if (process.env['KEEP_OUTPUT'] !== 'true' && runDir) {
await rm(runDir, { recursive: true, force: true });
}
// Cleanup the SDK E2E test run directory unless KEEP_OUTPUT is set
if (process.env['KEEP_OUTPUT'] !== 'true' && sdkE2eRunDir) {
await rm(sdkE2eRunDir, { recursive: true, force: true });
}
if (originalMemoryContent !== null) {
await mkdir(dirname(memoryFilePath), { recursive: true });
await writeFile(memoryFilePath, originalMemoryContent, 'utf-8');

View File

@@ -19,7 +19,7 @@ describe('JSON output', () => {
await rig.cleanup();
});
it('should return a valid JSON with response and stats', async () => {
it('should return a valid JSON array with result message containing response and stats', async () => {
const result = await rig.run(
'What is the capital of France?',
'--output-format',
@@ -27,19 +27,217 @@ describe('JSON output', () => {
);
const parsed = JSON.parse(result);
expect(parsed).toHaveProperty('response');
expect(typeof parsed.response).toBe('string');
expect(parsed.response.toLowerCase()).toContain('paris');
// The output should be an array of messages
expect(Array.isArray(parsed)).toBe(true);
expect(parsed.length).toBeGreaterThan(0);
expect(parsed).toHaveProperty('stats');
expect(typeof parsed.stats).toBe('object');
// Find the result message (should be the last message)
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage).toBeDefined();
expect(resultMessage).toHaveProperty('is_error');
expect(resultMessage.is_error).toBe(false);
expect(resultMessage).toHaveProperty('result');
expect(typeof resultMessage.result).toBe('string');
expect(resultMessage.result.toLowerCase()).toContain('paris');
// Stats may be present if available
if ('stats' in resultMessage) {
expect(typeof resultMessage.stats).toBe('object');
}
});
it('should return line-delimited JSON messages for stream-json output format', async () => {
const result = await rig.run(
'What is the capital of France?',
'--output-format',
'stream-json',
);
// Stream-json output is line-delimited JSON (one JSON object per line)
const lines = result
.trim()
.split('\n')
.filter((line) => line.trim());
expect(lines.length).toBeGreaterThan(0);
// Parse each line as a JSON object
const messages: unknown[] = [];
for (const line of lines) {
try {
const parsed = JSON.parse(line);
messages.push(parsed);
} catch (parseError) {
throw new Error(
`Failed to parse JSON line: ${line}. Error: ${parseError}`,
);
}
}
// Should have at least system, assistant, and result messages
expect(messages.length).toBeGreaterThanOrEqual(3);
// Find system message
const systemMessage = messages.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'system',
);
expect(systemMessage).toBeDefined();
expect(systemMessage).toHaveProperty('subtype');
expect(systemMessage).toHaveProperty('session_id');
// Find assistant message
const assistantMessage = messages.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'assistant',
);
expect(assistantMessage).toBeDefined();
expect(assistantMessage).toHaveProperty('message');
expect(assistantMessage).toHaveProperty('session_id');
// Find result message (should be the last message)
const resultMessage = messages[messages.length - 1] as {
type: string;
is_error: boolean;
result: string;
};
expect(resultMessage).toBeDefined();
expect(
typeof resultMessage === 'object' &&
resultMessage !== null &&
'type' in resultMessage &&
resultMessage.type === 'result',
).toBe(true);
expect(resultMessage).toHaveProperty('is_error');
expect(resultMessage.is_error).toBe(false);
expect(resultMessage).toHaveProperty('result');
expect(typeof resultMessage.result).toBe('string');
expect(resultMessage.result.toLowerCase()).toContain('paris');
});
it('should include stream events when using stream-json with include-partial-messages', async () => {
const result = await rig.run(
'What is the capital of France?',
'--output-format',
'stream-json',
'--include-partial-messages',
);
// Stream-json output is line-delimited JSON (one JSON object per line)
const lines = result
.trim()
.split('\n')
.filter((line) => line.trim());
expect(lines.length).toBeGreaterThan(0);
// Parse each line as a JSON object
const messages: unknown[] = [];
for (const line of lines) {
try {
const parsed = JSON.parse(line);
messages.push(parsed);
} catch (parseError) {
throw new Error(
`Failed to parse JSON line: ${line}. Error: ${parseError}`,
);
}
}
// Should have more messages than without include-partial-messages
// because we're including stream events
expect(messages.length).toBeGreaterThan(3);
// Find stream_event messages
const streamEvents = messages.filter(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'stream_event',
);
expect(streamEvents.length).toBeGreaterThan(0);
// Verify stream event structure
const firstStreamEvent = streamEvents[0];
expect(firstStreamEvent).toHaveProperty('event');
expect(firstStreamEvent).toHaveProperty('session_id');
expect(firstStreamEvent).toHaveProperty('uuid');
// Check for expected stream event types
const eventTypes = streamEvents.map((event: unknown) =>
typeof event === 'object' &&
event !== null &&
'event' in event &&
typeof event.event === 'object' &&
event.event !== null &&
'type' in event.event
? event.event.type
: null,
);
// Should have message_start event
expect(eventTypes).toContain('message_start');
// Should have content_block_start event
expect(eventTypes).toContain('content_block_start');
// Should have content_block_delta events
expect(eventTypes).toContain('content_block_delta');
// Should have content_block_stop event
expect(eventTypes).toContain('content_block_stop');
// Should have message_stop event
expect(eventTypes).toContain('message_stop');
// Verify that we still have the complete assistant message
const assistantMessage = messages.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'assistant',
);
expect(assistantMessage).toBeDefined();
expect(assistantMessage).toHaveProperty('message');
// Verify that we still have the result message
const resultMessage = messages[messages.length - 1] as {
type: string;
is_error: boolean;
result: string;
};
expect(resultMessage).toBeDefined();
expect(
typeof resultMessage === 'object' &&
resultMessage !== null &&
'type' in resultMessage &&
resultMessage.type === 'result',
).toBe(true);
expect(resultMessage).toHaveProperty('is_error');
expect(resultMessage.is_error).toBe(false);
expect(resultMessage).toHaveProperty('result');
expect(resultMessage.result.toLowerCase()).toContain('paris');
});
it('should return a JSON error for enforced auth mismatch before running', async () => {
process.env['GOOGLE_GENAI_USE_GCA'] = 'true';
const originalOpenaiApiKey = process.env['OPENAI_API_KEY'];
process.env['OPENAI_API_KEY'] = 'test-key';
await rig.setup('json-output-auth-mismatch', {
settings: {
security: { auth: { enforcedType: 'gemini-api-key' } },
security: { auth: { enforcedType: 'qwen-oauth' } },
},
});
@@ -50,40 +248,63 @@ describe('JSON output', () => {
} catch (e) {
thrown = e as Error;
} finally {
delete process.env['GOOGLE_GENAI_USE_GCA'];
process.env['OPENAI_API_KEY'] = originalOpenaiApiKey;
}
expect(thrown).toBeDefined();
const message = (thrown as Error).message;
// Use a regex to find the first complete JSON object in the string
const jsonMatch = message.match(/{[\s\S]*}/);
// Fail if no JSON-like text was found
// The error JSON is written to stdout as a CLIResultMessageError
// Extract stdout from the error message
const stdoutMatch = message.match(/Stdout:\n([\s\S]*?)(?:\n\nStderr:|$)/);
expect(
jsonMatch,
'Expected to find a JSON object in the error output',
stdoutMatch,
'Expected to find stdout in the error message',
).toBeTruthy();
let payload;
const stdout = stdoutMatch![1];
let parsed: unknown[];
try {
// Parse the matched JSON string
payload = JSON.parse(jsonMatch![0]);
// Parse the JSON array from stdout
parsed = JSON.parse(stdout);
} catch (parseError) {
console.error('Failed to parse the following JSON:', jsonMatch![0]);
console.error('Failed to parse the following JSON:', stdout);
throw new Error(
`Test failed: Could not parse JSON from error message. Details: ${parseError}`,
`Test failed: Could not parse JSON from stdout. Details: ${parseError}`,
);
}
expect(payload.error).toBeDefined();
expect(payload.error.type).toBe('Error');
expect(payload.error.code).toBe(1);
expect(payload.error.message).toContain(
'configured auth type is gemini-api-key',
// The output should be an array of messages
expect(Array.isArray(parsed)).toBe(true);
expect(parsed.length).toBeGreaterThan(0);
// Find the result message with error
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result' &&
'is_error' in msg &&
msg.is_error === true,
) as {
type: string;
is_error: boolean;
subtype: string;
error?: { message: string; type?: string };
};
expect(resultMessage).toBeDefined();
expect(resultMessage.is_error).toBe(true);
expect(resultMessage).toHaveProperty('subtype');
expect(resultMessage.subtype).toBe('error_during_execution');
expect(resultMessage).toHaveProperty('error');
expect(resultMessage.error).toBeDefined();
expect(resultMessage.error?.message).toContain(
'configured auth type is qwen-oauth',
);
expect(payload.error.message).toContain(
'current auth type is oauth-personal',
expect(resultMessage.error?.message).toContain(
'current auth type is openai',
);
});
});

View File

@@ -0,0 +1,486 @@
/**
* E2E tests based on abort-and-lifecycle.ts example
* Tests AbortController integration and process lifecycle management
*/
/* eslint-disable @typescript-eslint/no-unused-vars */
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
AbortError,
isAbortError,
isSDKAssistantMessage,
type TextBlock,
type ContentBlock,
} from '@qwen-code/sdk';
import { SDKTestHelper, createSharedTestOptions } from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
describe('AbortController and Process Lifecycle (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('abort-and-lifecycle');
});
afterEach(async () => {
await helper.cleanup();
});
describe('Basic AbortController Usage', () => {
it('should support AbortController cancellation', async () => {
const controller = new AbortController();
// Abort after 5 seconds
setTimeout(() => {
controller.abort();
}, 5000);
const q = query({
prompt: 'Write a very long story about TypeScript programming',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
const textBlocks = message.message.content.filter(
(block): block is TextBlock => block.type === 'text',
);
const text = textBlocks
.map((b) => b.text)
.join('')
.slice(0, 100);
// Should receive some content before abort
expect(text.length).toBeGreaterThan(0);
}
}
// Should not reach here - query should be aborted
expect(false).toBe(true);
} catch (error) {
expect(isAbortError(error)).toBe(true);
} finally {
await q.close();
}
});
it('should handle abort during query execution', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
let receivedFirstMessage = false;
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
if (!receivedFirstMessage) {
// Abort immediately after receiving first assistant message
receivedFirstMessage = true;
controller.abort();
}
}
}
} catch (error) {
expect(isAbortError(error)).toBe(true);
expect(error instanceof AbortError).toBe(true);
// Should have received at least one message before abort
expect(receivedFirstMessage).toBe(true);
} finally {
await q.close();
}
});
it('should handle abort immediately after query starts', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Write a very long essay',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
// Abort immediately after query initialization
setTimeout(() => {
controller.abort();
}, 200);
try {
for await (const _message of q) {
// May or may not receive messages before abort
}
} catch (error) {
expect(isAbortError(error)).toBe(true);
expect(error instanceof AbortError).toBe(true);
} finally {
await q.close();
}
});
});
describe('Process Lifecycle Monitoring', () => {
it('should handle normal process completion', async () => {
const q = query({
prompt: 'Why do we choose to go to the moon?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let completedSuccessfully = false;
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
const textBlocks = message.message.content.filter(
(block): block is TextBlock => block.type === 'text',
);
const text = textBlocks
.map((b) => b.text)
.join('')
.slice(0, 100);
expect(text.length).toBeGreaterThan(0);
}
}
completedSuccessfully = true;
} catch (error) {
// Should not throw for normal completion
expect(false).toBe(true);
} finally {
await q.close();
expect(completedSuccessfully).toBe(true);
}
});
it('should handle process cleanup after error', async () => {
const q = query({
prompt: 'Hello world',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
const textBlocks = message.message.content.filter(
(block): block is TextBlock => block.type === 'text',
);
const text = textBlocks
.map((b) => b.text)
.join('')
.slice(0, 50);
expect(text.length).toBeGreaterThan(0);
}
}
} catch (error) {
// Expected to potentially have errors
} finally {
// Should cleanup successfully even after error
await q.close();
expect(true).toBe(true); // Cleanup completed
}
});
});
describe('Input Stream Control', () => {
it('should support endInput() method', async () => {
const q = query({
prompt: 'What is 2 + 2?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let receivedResponse = false;
let endInputCalled = false;
try {
for await (const message of q) {
if (isSDKAssistantMessage(message) && !endInputCalled) {
const textBlocks = message.message.content.filter(
(block: ContentBlock): block is TextBlock =>
block.type === 'text',
);
const text = textBlocks.map((b: TextBlock) => b.text).join('');
expect(text.length).toBeGreaterThan(0);
receivedResponse = true;
// End input after receiving first response
q.endInput();
endInputCalled = true;
}
}
expect(receivedResponse).toBe(true);
expect(endInputCalled).toBe(true);
} finally {
await q.close();
}
});
});
describe('Error Handling and Recovery', () => {
it('should handle invalid executable path', async () => {
try {
const q = query({
prompt: 'Hello world',
options: {
pathToQwenExecutable: '/nonexistent/path/to/cli',
debug: false,
},
});
// Should not reach here - query() should throw immediately
for await (const _message of q) {
// Should not reach here
}
// Should not reach here
expect(false).toBe(true);
} catch (error) {
expect(error instanceof Error).toBe(true);
expect((error as Error).message).toBeDefined();
expect((error as Error).message).toContain(
'Invalid pathToQwenExecutable',
);
}
});
it('should throw AbortError with correct properties', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Explain the concept of async programming',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
// Abort after allowing query to start
setTimeout(() => controller.abort(), 1000);
try {
for await (const _message of q) {
// May receive some messages before abort
}
} catch (error) {
// Verify error type and helper functions
expect(isAbortError(error)).toBe(true);
expect(error instanceof AbortError).toBe(true);
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toBeDefined();
} finally {
await q.close();
}
});
});
describe('Debugging with stderr callback', () => {
it('should capture stderr messages when debug is enabled', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Why do we choose to go to the moon?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
const textBlocks = message.message.content.filter(
(block): block is TextBlock => block.type === 'text',
);
const text = textBlocks
.map((b) => b.text)
.join('')
.slice(0, 50);
expect(text.length).toBeGreaterThan(0);
}
}
} finally {
await q.close();
expect(stderrMessages.length).toBeGreaterThan(0);
}
});
it('should not capture stderr when debug is disabled', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
try {
for await (const _message of q) {
// Consume all messages
}
} finally {
await q.close();
// Should have minimal or no stderr output when debug is false
expect(stderrMessages.length).toBeLessThan(10);
}
});
});
describe('Abort with Cleanup', () => {
it('should cleanup properly after abort', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Write a very long essay about programming',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
// Abort immediately
setTimeout(() => controller.abort(), 100);
try {
for await (const _message of q) {
// May receive some messages before abort
}
} catch (error) {
if (error instanceof AbortError) {
expect(true).toBe(true); // Expected abort error
} else {
throw error; // Unexpected error
}
} finally {
await q.close();
expect(true).toBe(true); // Cleanup completed after abort
}
});
it('should handle multiple abort calls gracefully', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Count to 100',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
// Multiple abort calls
setTimeout(() => controller.abort(), 100);
setTimeout(() => controller.abort(), 200);
setTimeout(() => controller.abort(), 300);
try {
for await (const _message of q) {
// Should be interrupted
}
} catch (error) {
expect(isAbortError(error)).toBe(true);
} finally {
await q.close();
}
});
});
describe('Resource Management Edge Cases', () => {
it('should handle close() called multiple times', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
// Start the query
const iterator = q[Symbol.asyncIterator]();
await iterator.next();
// Close multiple times
await q.close();
await q.close();
await q.close();
// Should not throw
expect(true).toBe(true);
});
it('should handle abort after close', async () => {
const controller = new AbortController();
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
abortController: controller,
debug: false,
},
});
// Start and close immediately
const iterator = q[Symbol.asyncIterator]();
await iterator.next();
await q.close();
// Abort after close
controller.abort();
// Should not throw
expect(true).toBe(true);
});
});
});

View File

@@ -0,0 +1,640 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* E2E tests for SDK configuration options:
* - logLevel: Controls SDK internal logging verbosity
* - env: Environment variables passed to CLI process
* - authType: Authentication type for AI service
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKAssistantMessage,
isSDKSystemMessage,
type SDKMessage,
} from '@qwen-code/sdk';
import {
SDKTestHelper,
extractText,
createSharedTestOptions,
assertSuccessfulCompletion,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
describe('Configuration Options (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('configuration-options');
});
afterEach(async () => {
await helper.cleanup();
});
describe('logLevel Option', () => {
it('should respect logLevel: debug and capture detailed logs', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'What is 1 + 1? Just answer the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'debug',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Debug level should produce verbose logging
expect(stderrMessages.length).toBeGreaterThan(0);
// Debug logs should contain detailed information like [DEBUG]
const hasDebugLogs = stderrMessages.some(
(msg) => msg.includes('[DEBUG]') || msg.includes('debug'),
);
expect(hasDebugLogs).toBe(true);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should respect logLevel: info and filter out debug messages', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'What is 2 + 2? Just answer the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'info',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Info level should filter out debug messages
// Check that we don't have [DEBUG] level messages from the SDK logger
const sdkDebugLogs = stderrMessages.filter(
(msg) =>
msg.includes('[DEBUG]') && msg.includes('[ProcessTransport]'),
);
expect(sdkDebugLogs.length).toBe(0);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should respect logLevel: warn and only show warnings and errors', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'warn',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Warn level should filter out info and debug messages from SDK
const sdkInfoOrDebugLogs = stderrMessages.filter(
(msg) =>
(msg.includes('[DEBUG]') || msg.includes('[INFO]')) &&
(msg.includes('[ProcessTransport]') ||
msg.includes('[createQuery]') ||
msg.includes('[Query]')),
);
expect(sdkInfoOrDebugLogs.length).toBe(0);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should respect logLevel: error and only show error messages', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello world',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'error',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Error level should filter out all non-error messages from SDK
const sdkNonErrorLogs = stderrMessages.filter(
(msg) =>
(msg.includes('[DEBUG]') ||
msg.includes('[INFO]') ||
msg.includes('[WARN]')) &&
(msg.includes('[ProcessTransport]') ||
msg.includes('[createQuery]') ||
msg.includes('[Query]')),
);
expect(sdkNonErrorLogs.length).toBe(0);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should use logLevel over debug flag when both are provided', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'What is 3 + 3?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: true, // Would normally enable debug logging
logLevel: 'error', // But logLevel should take precedence
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
try {
for await (const _message of q) {
// Consume all messages
}
// logLevel: error should suppress debug/info/warn even with debug: true
const sdkNonErrorLogs = stderrMessages.filter(
(msg) =>
(msg.includes('[DEBUG]') ||
msg.includes('[INFO]') ||
msg.includes('[WARN]')) &&
(msg.includes('[ProcessTransport]') ||
msg.includes('[createQuery]') ||
msg.includes('[Query]')),
);
expect(sdkNonErrorLogs.length).toBe(0);
} finally {
await q.close();
}
});
});
describe('env Option', () => {
it('should pass custom environment variables to CLI process', async () => {
const q = query({
prompt: 'What is 1 + 1? Just the number please.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {
CUSTOM_TEST_VAR: 'test_value_12345',
ANOTHER_VAR: 'another_value',
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// The query should complete successfully with custom env vars
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should allow overriding existing environment variables', async () => {
// Store original value for comparison
const originalPath = process.env['PATH'];
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {
// Override an existing env var (not PATH as it might break things)
MY_TEST_OVERRIDE: 'overridden_value',
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Query should complete successfully
assertSuccessfulCompletion(messages);
// Verify original process env is not modified
expect(process.env['PATH']).toBe(originalPath);
} finally {
await q.close();
}
});
it('should work with empty env object', async () => {
const q = query({
prompt: 'What is 2 + 2?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should support setting model-related environment variables', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {
// Common model-related env vars that CLI might respect
OPENAI_API_KEY: process.env['OPENAI_API_KEY'] || 'test-key',
},
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Should complete (may succeed or fail based on API key validity)
expect(messages.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
it('should not leak env vars between query instances', async () => {
// First query with specific env var
const q1 = query({
prompt: 'Say one',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {
ISOLATED_VAR_1: 'value_1',
},
debug: false,
},
});
try {
for await (const _message of q1) {
// Consume messages
}
} finally {
await q1.close();
}
// Second query with different env var
const q2 = query({
prompt: 'Say two',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
env: {
ISOLATED_VAR_2: 'value_2',
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q2) {
messages.push(message);
}
// Second query should complete successfully
assertSuccessfulCompletion(messages);
// Verify process.env is not polluted by either query
expect(process.env['ISOLATED_VAR_1']).toBeUndefined();
expect(process.env['ISOLATED_VAR_2']).toBeUndefined();
} finally {
await q2.close();
}
});
});
describe('authType Option', () => {
it('should accept authType: openai', async () => {
const q = query({
prompt: 'What is 1 + 1? Just the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
authType: 'openai',
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Query should complete with openai auth type
assertSuccessfulCompletion(messages);
// Verify we got an assistant response
const assistantMessages = messages.filter(isSDKAssistantMessage);
expect(assistantMessages.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
// Skip in containerized sandbox environments - qwen-oauth requires user interaction
// which is not possible in Docker/Podman CI environments
it.skipIf(
process.env['SANDBOX'] === 'sandbox:docker' ||
process.env['SANDBOX'] === 'sandbox:podman',
)('should accept authType: qwen-oauth', async () => {
// Note: qwen-oauth requires credentials in ~/.qwen and user interaction
// Without credentials, the auth process will timeout waiting for user
// This test verifies the option is accepted and passed correctly to CLI
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
authType: 'qwen-oauth',
debug: true,
logLevel: 'debug',
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
// Use a timeout to avoid hanging when credentials are not configured
const timeoutPromise = new Promise<'timeout'>((resolve) =>
setTimeout(() => resolve('timeout'), 20000),
);
const collectMessages = async () => {
for await (const message of q) {
messages.push(message);
}
return 'completed';
};
const result = await Promise.race([collectMessages(), timeoutPromise]);
if (result === 'timeout') {
// Timeout is expected when OAuth credentials are not configured
// Verify that CLI was spawned with correct --auth-type argument
const hasAuthTypeArg = stderrMessages.some((msg) =>
msg.includes('--auth-type'),
);
expect(hasAuthTypeArg).toBe(true);
} else {
// If credentials exist and auth completed, verify we got messages
expect(messages.length).toBeGreaterThan(0);
}
} finally {
await q.close();
}
});
it('should use default auth when authType is not specified', async () => {
const q = query({
prompt: 'What is 2 + 2? Just the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
// authType not specified - should use default
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Query should complete with default auth
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should properly pass authType to CLI process', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Say hi',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
authType: 'openai',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// There should be spawn log containing auth-type
const hasAuthTypeArg = stderrMessages.some((msg) =>
msg.includes('--auth-type'),
);
expect(hasAuthTypeArg).toBe(true);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
});
describe('Combined Options', () => {
it('should work with logLevel, env, and authType together', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'What is 3 + 3? Just the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'debug',
env: {
COMBINED_TEST_VAR: 'combined_value',
},
authType: 'openai',
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// All three options should work together
expect(stderrMessages.length).toBeGreaterThan(0); // logLevel: debug produces logs
expect(assistantText).toMatch(/6/); // Query should work
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should maintain system message consistency with all options', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
logLevel: 'info',
env: {
SYSTEM_MSG_TEST: 'test',
},
authType: 'openai',
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Should have system init message
const systemMessages = messages.filter(isSDKSystemMessage);
const initMessage = systemMessages.find((m) => m.subtype === 'init');
expect(initMessage).toBeDefined();
expect(initMessage!.session_id).toBeDefined();
expect(initMessage!.tools).toBeDefined();
expect(initMessage!.permission_mode).toBeDefined();
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
});
});

View File

@@ -0,0 +1,405 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* E2E tests for MCP (Model Context Protocol) server integration via SDK
* Tests that the SDK can properly interact with MCP servers configured in qwen-code
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKAssistantMessage,
isSDKResultMessage,
isSDKSystemMessage,
isSDKUserMessage,
type SDKMessage,
type ToolUseBlock,
type SDKSystemMessage,
} from '@qwen-code/sdk';
import {
SDKTestHelper,
createMCPServer,
extractText,
findToolUseBlocks,
createSharedTestOptions,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = {
...createSharedTestOptions(),
permissionMode: 'yolo' as const,
};
describe('MCP Server Integration (E2E)', () => {
let helper: SDKTestHelper;
let serverScriptPath: string;
let testDir: string;
beforeEach(async () => {
// Create isolated test environment using SDKTestHelper
helper = new SDKTestHelper();
testDir = await helper.setup('mcp-server-integration');
// Create MCP server using the helper utility
const mcpServer = await createMCPServer(helper, 'math', 'test-math-server');
serverScriptPath = mcpServer.scriptPath;
});
afterEach(async () => {
// Cleanup test directory
await helper.cleanup();
});
describe('Basic MCP Tool Usage', () => {
it('should use MCP add tool to add two numbers', async () => {
const q = query({
prompt:
'Use the add tool to calculate 5 + 10. Just give me the result.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'add');
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate tool was called
expect(foundToolUse).toBe(true);
// Validate result contains expected answer
expect(assistantText).toMatch(/15/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
if (isSDKResultMessage(lastMessage)) {
expect(lastMessage.subtype).toBe('success');
}
} finally {
await q.close();
}
});
it('should use MCP multiply tool to multiply two numbers', async () => {
const q = query({
prompt:
'Use the multiply tool to calculate 6 * 7. Just give me the result.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'multiply');
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate tool was called
expect(foundToolUse).toBe(true);
// Validate result contains expected answer
expect(assistantText).toMatch(/42/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
describe('MCP Server Discovery', () => {
it('should list MCP servers in system init message', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
let systemMessage: SDKSystemMessage | null = null;
try {
for await (const message of q) {
if (isSDKSystemMessage(message) && message.subtype === 'init') {
systemMessage = message;
break;
}
}
// Validate MCP server is listed
expect(systemMessage).not.toBeNull();
expect(systemMessage!.mcp_servers).toBeDefined();
expect(Array.isArray(systemMessage!.mcp_servers)).toBe(true);
// Find our test server
const testServer = systemMessage!.mcp_servers?.find(
(server) => server.name === 'test-math-server',
);
expect(testServer).toBeDefined();
// Note: tools are not exposed in the mcp_servers array in system message
// They are available through the MCP protocol but not in the init message
} finally {
await q.close();
}
});
});
describe('Complex MCP Operations', () => {
it('should chain multiple MCP tool calls', async () => {
const q = query({
prompt:
'First use add to calculate 10 + 5, then multiply the result by 2. Give me the final answer.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
const toolCalls: string[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message);
toolUseBlocks.forEach((block) => {
toolCalls.push(block.name);
});
assistantText += extractText(message.message.content);
}
}
// Validate both tools were called
expect(toolCalls).toContain('add');
expect(toolCalls).toContain('multiply');
// Validate result: (10 + 5) * 2 = 30
expect(assistantText).toMatch(/30/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
it('should handle multiple calls to the same MCP tool', async () => {
const q = query({
prompt:
'Use the add tool twice: first add 1 + 2, then add 3 + 4. Tell me both results.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
const addToolCalls: ToolUseBlock[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'add');
addToolCalls.push(...toolUseBlocks);
assistantText += extractText(message.message.content);
}
}
// Validate add tool was called at least twice
expect(addToolCalls.length).toBeGreaterThanOrEqual(2);
// Validate results contain expected answers: 3 and 7
expect(assistantText).toMatch(/3/);
expect(assistantText).toMatch(/7/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
describe('MCP Tool Message Flow', () => {
it('should receive proper message sequence for MCP tool usage', async () => {
const q = query({
prompt: 'Use add to calculate 2 + 3',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messageTypes: string[] = [];
let foundToolUse = false;
let foundToolResult = false;
try {
for await (const message of q) {
messageTypes.push(message.type);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message);
if (toolUseBlocks.length > 0) {
foundToolUse = true;
expect(toolUseBlocks[0].name).toBe('add');
expect(toolUseBlocks[0].input).toBeDefined();
}
}
if (isSDKUserMessage(message)) {
const content = message.message.content;
const contentArray = Array.isArray(content)
? content
: [{ type: 'text', text: content }];
const toolResultBlock = contentArray.find(
(block) => block.type === 'tool_result',
);
if (toolResultBlock) {
foundToolResult = true;
}
}
}
// Validate message flow
expect(foundToolUse).toBe(true);
expect(foundToolResult).toBe(true);
expect(messageTypes).toContain('system');
expect(messageTypes).toContain('assistant');
expect(messageTypes).toContain('user');
expect(messageTypes).toContain('result');
// Result should be last message
expect(messageTypes[messageTypes.length - 1]).toBe('result');
} finally {
await q.close();
}
});
});
describe('Error Handling', () => {
it('should handle gracefully when MCP tool is not available', async () => {
const q = query({
prompt: 'Use the subtract tool to calculate 10 - 5',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'test-math-server': {
command: 'node',
args: [serverScriptPath],
},
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// Should complete without crashing
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
// Assistant should indicate tool is not available or provide alternative
expect(assistantText.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
});
});

View File

@@ -0,0 +1,559 @@
/**
* E2E tests based on multi-turn.ts example
* Tests multi-turn conversation functionality with real CLI
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKUserMessage,
isSDKAssistantMessage,
isSDKSystemMessage,
isSDKResultMessage,
isSDKPartialAssistantMessage,
isControlRequest,
isControlResponse,
isControlCancel,
type SDKUserMessage,
type SDKAssistantMessage,
type TextBlock,
type ContentBlock,
type SDKMessage,
type ControlMessage,
type ToolUseBlock,
} from '@qwen-code/sdk';
import { SDKTestHelper, createSharedTestOptions } from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
/**
* Determine the message type using protocol type guards
*/
function getMessageType(message: SDKMessage | ControlMessage): string {
if (isSDKUserMessage(message)) {
return '🧑 USER';
} else if (isSDKAssistantMessage(message)) {
return '🤖 ASSISTANT';
} else if (isSDKSystemMessage(message)) {
return `🖥️ SYSTEM(${message.subtype})`;
} else if (isSDKResultMessage(message)) {
return `✅ RESULT(${message.subtype})`;
} else if (isSDKPartialAssistantMessage(message)) {
return '⏳ STREAM_EVENT';
} else if (isControlRequest(message)) {
return `🎮 CONTROL_REQUEST(${message.request.subtype})`;
} else if (isControlResponse(message)) {
return `📭 CONTROL_RESPONSE(${message.response.subtype})`;
} else if (isControlCancel(message)) {
return '🛑 CONTROL_CANCEL';
} else {
return '❓ UNKNOWN';
}
}
/**
* Helper to extract text from ContentBlock array
*/
function extractText(content: ContentBlock[]): string {
return content
.filter((block): block is TextBlock => block.type === 'text')
.map((block) => block.text)
.join('');
}
describe('Multi-Turn Conversations (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('multi-turn');
});
afterEach(async () => {
await helper.cleanup();
});
describe('AsyncIterable Prompt Support', () => {
it('should handle multi-turn conversation using AsyncIterable prompt', async () => {
// Create multi-turn conversation generator
async function* createMultiTurnConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'What is 1 + 1?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 100));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'What is 2 + 2?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 100));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'What is 3 + 3?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
// Create multi-turn query using AsyncIterable prompt
const q = query({
prompt: createMultiTurnConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
const assistantMessages: SDKAssistantMessage[] = [];
const assistantTexts: string[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantMessages.push(message);
const text = extractText(message.message.content);
assistantTexts.push(text);
}
}
expect(messages.length).toBeGreaterThan(0);
expect(assistantMessages.length).toBeGreaterThanOrEqual(3);
// Validate content of responses
expect(assistantTexts[0]).toMatch(/2/);
expect(assistantTexts[1]).toMatch(/4/);
expect(assistantTexts[2]).toMatch(/6/);
} finally {
await q.close();
}
});
it('should maintain session context across turns', async () => {
async function* createContextualConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content:
'Suppose we have 3 rabbits and 4 carrots. How many animals are there?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'How many animals are there? Only output the number',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createContextualConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const assistantMessages: SDKAssistantMessage[] = [];
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
assistantMessages.push(message);
}
}
expect(assistantMessages.length).toBeGreaterThanOrEqual(2);
// The second response should reference the color blue
const secondResponse = extractText(
assistantMessages[1].message.content,
);
expect(secondResponse.toLowerCase()).toContain('3');
} finally {
await q.close();
}
});
});
describe('Tool Usage in Multi-Turn', () => {
it('should handle tool usage across multiple turns', async () => {
async function* createToolConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Create a file named test.txt with content "hello"',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Now read the test.txt file',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createToolConversation(),
options: {
...SHARED_TEST_OPTIONS,
permissionMode: 'yolo',
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
let toolUseCount = 0;
const assistantMessages: SDKAssistantMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantMessages.push(message);
const hasToolUseBlock = message.message.content.some(
(block: ContentBlock): block is ToolUseBlock =>
block.type === 'tool_use',
);
if (hasToolUseBlock) {
toolUseCount++;
}
}
}
expect(messages.length).toBeGreaterThan(0);
expect(toolUseCount).toBeGreaterThan(0);
expect(assistantMessages.length).toBeGreaterThanOrEqual(2);
// Validate second response mentions the file content
const secondResponse = extractText(
assistantMessages[assistantMessages.length - 1].message.content,
);
expect(secondResponse.toLowerCase()).toMatch(/hello|test\.txt/);
} finally {
await q.close();
}
});
});
describe('Message Flow and Sequencing', () => {
it('should process messages in correct sequence', async () => {
async function* createSequentialConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'First question: What is 1 + 1?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 100));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Second question: What is 2 + 2?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createSequentialConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messageSequence: string[] = [];
const assistantResponses: string[] = [];
try {
for await (const message of q) {
const messageType = getMessageType(message);
messageSequence.push(messageType);
if (isSDKAssistantMessage(message)) {
const text = extractText(message.message.content);
assistantResponses.push(text);
}
}
expect(messageSequence.length).toBeGreaterThan(0);
expect(assistantResponses.length).toBeGreaterThanOrEqual(2);
// Should end with result
expect(messageSequence[messageSequence.length - 1]).toContain('RESULT');
// Should have assistant responses
expect(messageSequence.some((type) => type.includes('ASSISTANT'))).toBe(
true,
);
} finally {
await q.close();
}
});
it('should handle conversation completion correctly', async () => {
async function* createSimpleConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Hello',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 100));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Goodbye',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createSimpleConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let completedNaturally = false;
let messageCount = 0;
try {
for await (const message of q) {
messageCount++;
if (isSDKResultMessage(message)) {
completedNaturally = true;
expect(message.subtype).toBe('success');
}
}
expect(messageCount).toBeGreaterThan(0);
expect(completedNaturally).toBe(true);
} finally {
await q.close();
}
});
});
describe('Error Handling in Multi-Turn', () => {
it('should handle empty conversation gracefully', async () => {
async function* createEmptyConversation(): AsyncIterable<SDKUserMessage> {
// Generator that yields nothing
/* eslint-disable no-constant-condition */
if (false) {
yield {} as SDKUserMessage; // Unreachable, but satisfies TypeScript
}
}
const q = query({
prompt: createEmptyConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Should handle empty conversation without crashing
expect(true).toBe(true);
} finally {
await q.close();
}
});
it('should handle conversation with delays', async () => {
async function* createDelayedConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'First message',
},
parent_tool_use_id: null,
} as SDKUserMessage;
// Longer delay to test patience
await new Promise((resolve) => setTimeout(resolve, 500));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'Second message after delay',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createDelayedConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const assistantMessages: SDKAssistantMessage[] = [];
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
assistantMessages.push(message);
}
}
expect(assistantMessages.length).toBeGreaterThanOrEqual(2);
} finally {
await q.close();
}
});
});
describe('Partial Messages in Multi-Turn', () => {
it('should receive partial messages when includePartialMessages is enabled', async () => {
async function* createMultiTurnConversation(): AsyncIterable<SDKUserMessage> {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'What is 1 + 1?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 100));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: 'What is 2 + 2?',
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
const q = query({
prompt: createMultiTurnConversation(),
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
includePartialMessages: true,
debug: false,
},
});
const messages: SDKMessage[] = [];
let partialMessageCount = 0;
let assistantMessageCount = 0;
try {
for await (const message of q) {
messages.push(message);
if (isSDKPartialAssistantMessage(message)) {
partialMessageCount++;
}
if (isSDKAssistantMessage(message)) {
assistantMessageCount++;
}
}
expect(messages.length).toBeGreaterThan(0);
expect(partialMessageCount).toBeGreaterThan(0);
expect(assistantMessageCount).toBeGreaterThanOrEqual(2);
} finally {
await q.close();
}
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,456 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* E2E tests for SDK-embedded MCP servers
*
* Tests that the SDK can create and manage MCP servers running in the SDK process
* using the tool() and createSdkMcpServer() APIs.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { z } from 'zod';
import {
query,
tool,
createSdkMcpServer,
isSDKAssistantMessage,
isSDKResultMessage,
isSDKSystemMessage,
type SDKMessage,
type SDKSystemMessage,
} from '@qwen-code/sdk';
import {
SDKTestHelper,
extractText,
findToolUseBlocks,
createSharedTestOptions,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = {
...createSharedTestOptions(),
permissionMode: 'yolo' as const,
};
describe('SDK MCP Server Integration (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('sdk-mcp-server-integration');
});
afterEach(async () => {
await helper.cleanup();
});
describe('Basic SDK MCP Tool Usage', () => {
it('should use SDK MCP tool to perform a simple calculation', async () => {
// Define a simple calculator tool using the tool() API with Zod schema
const calculatorTool = tool(
'calculate_sum',
'Calculate the sum of two numbers',
z.object({
a: z.number().describe('First number'),
b: z.number().describe('Second number'),
}).shape,
async (args) => ({
content: [{ type: 'text', text: String(args.a + args.b) }],
}),
);
// Create SDK MCP server with the tool
const serverConfig = createSdkMcpServer({
name: 'sdk-calculator',
version: '1.0.0',
tools: [calculatorTool],
});
const q = query({
prompt:
'Use the calculate_sum tool to add 25 and 17. Output the result of tool only.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
mcpServers: {
'sdk-calculator': serverConfig,
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'calculate_sum');
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate tool was called
expect(foundToolUse).toBe(true);
// Validate result contains expected answer: 25 + 17 = 42
expect(assistantText).toMatch(/42/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
if (isSDKResultMessage(lastMessage)) {
expect(lastMessage.subtype).toBe('success');
}
} finally {
await q.close();
}
});
it('should use SDK MCP tool with string operations', async () => {
// Define a string manipulation tool with Zod schema
const stringTool = tool(
'reverse_string',
'Reverse a string',
{
text: z.string().describe('The text to reverse'),
},
async (args) => ({
content: [
{ type: 'text', text: args.text.split('').reverse().join('') },
],
}),
);
const serverConfig = createSdkMcpServer({
name: 'sdk-string-utils',
version: '1.0.0',
tools: [stringTool],
});
const q = query({
prompt: `Use the 'reverse_string' tool to process the word "hello world". Output the tool result only.`,
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
mcpServers: {
'sdk-string-utils': serverConfig,
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'reverse_string');
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate tool was called
expect(foundToolUse).toBe(true);
// Validate result contains reversed string: "olleh"
expect(assistantText.toLowerCase()).toMatch(/olleh/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
describe('Multiple SDK MCP Tools', () => {
it('should use multiple tools from the same SDK MCP server', async () => {
// Define the Zod schema shape for two numbers
const twoNumbersSchema = {
a: z.number().describe('First number'),
b: z.number().describe('Second number'),
};
// Define multiple tools
const addTool = tool(
'sdk_add',
'Add two numbers',
twoNumbersSchema,
async (args) => ({
content: [{ type: 'text', text: String(args.a + args.b) }],
}),
);
const multiplyTool = tool(
'sdk_multiply',
'Multiply two numbers',
twoNumbersSchema,
async (args) => ({
content: [{ type: 'text', text: String(args.a * args.b) }],
}),
);
const serverConfig = createSdkMcpServer({
name: 'sdk-math',
version: '1.0.0',
tools: [addTool, multiplyTool],
});
const q = query({
prompt:
'First use sdk_add to calculate 10 + 5, then use sdk_multiply to multiply the result by 3. Give me the final answer.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'sdk-math': serverConfig,
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
const toolCalls: string[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message);
toolUseBlocks.forEach((block) => {
toolCalls.push(block.name);
});
assistantText += extractText(message.message.content);
}
}
// Validate both tools were called
expect(toolCalls).toContain('sdk_add');
expect(toolCalls).toContain('sdk_multiply');
// Validate result: (10 + 5) * 3 = 45
expect(assistantText).toMatch(/45/);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
describe('SDK MCP Server Discovery', () => {
it('should list SDK MCP servers in system init message', async () => {
// Define echo tool with Zod schema
const echoTool = tool(
'echo',
'Echo a message',
{
message: z.string().describe('Message to echo'),
},
async (args) => ({
content: [{ type: 'text', text: args.message }],
}),
);
const serverConfig = createSdkMcpServer({
name: 'sdk-echo',
version: '1.0.0',
tools: [echoTool],
});
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'sdk-echo': serverConfig,
},
},
});
let systemMessage: SDKSystemMessage | null = null;
try {
for await (const message of q) {
if (isSDKSystemMessage(message) && message.subtype === 'init') {
systemMessage = message;
break;
}
}
// Validate MCP server is listed
expect(systemMessage).not.toBeNull();
expect(systemMessage!.mcp_servers).toBeDefined();
expect(Array.isArray(systemMessage!.mcp_servers)).toBe(true);
// Find our SDK MCP server
const sdkServer = systemMessage!.mcp_servers?.find(
(server) => server.name === 'sdk-echo',
);
expect(sdkServer).toBeDefined();
} finally {
await q.close();
}
});
});
describe('SDK MCP Tool Error Handling', () => {
it('should handle tool errors gracefully', async () => {
// Define a tool that throws an error with Zod schema
const errorTool = tool(
'maybe_fail',
'A tool that may fail based on input',
{
shouldFail: z.boolean().describe('If true, the tool will fail'),
},
async (args) => {
if (args.shouldFail) {
throw new Error('Tool intentionally failed');
}
return { content: [{ type: 'text', text: 'Success!' }] };
},
);
const serverConfig = createSdkMcpServer({
name: 'sdk-error-test',
version: '1.0.0',
tools: [errorTool],
});
const q = query({
prompt:
'Use the maybe_fail tool with shouldFail set to true. Tell me what happens.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'sdk-error-test': serverConfig,
},
},
});
const messages: SDKMessage[] = [];
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, 'maybe_fail');
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
}
}
// Tool should be called
expect(foundToolUse).toBe(true);
// Query should complete (even with tool error)
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
describe('Async Tool Handlers', () => {
it('should handle async tool handlers with delays', async () => {
// Define a tool with async delay using Zod schema
const delayedTool = tool(
'delayed_response',
'Returns a value after a delay',
{
delay: z.number().describe('Delay in milliseconds (max 100)'),
value: z.string().describe('Value to return'),
},
async (args) => {
// Cap delay at 100ms for test performance
const actualDelay = Math.min(args.delay, 100);
await new Promise((resolve) => setTimeout(resolve, actualDelay));
return {
content: [{ type: 'text', text: `Delayed result: ${args.value}` }],
};
},
);
const serverConfig = createSdkMcpServer({
name: 'sdk-async',
version: '1.0.0',
tools: [delayedTool],
});
const q = query({
prompt:
'Use the delayed_response tool with delay=50 and value="test_async". Tell me the result.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
mcpServers: {
'sdk-async': serverConfig,
},
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
let foundToolUse = false;
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(
message,
'delayed_response',
);
if (toolUseBlocks.length > 0) {
foundToolUse = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate tool was called
expect(foundToolUse).toBe(true);
// Validate result contains the delayed response
expect(assistantText.toLowerCase()).toMatch(/test_async/i);
// Validate successful completion
const lastMessage = messages[messages.length - 1];
expect(isSDKResultMessage(lastMessage)).toBe(true);
} finally {
await q.close();
}
});
});
});

View File

@@ -0,0 +1,528 @@
/**
* E2E tests for single-turn query execution
* Tests basic query patterns with simple prompts and clear output expectations
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKAssistantMessage,
isSDKSystemMessage,
isSDKResultMessage,
isSDKPartialAssistantMessage,
type SDKMessage,
type SDKSystemMessage,
type SDKAssistantMessage,
} from '@qwen-code/sdk';
import {
SDKTestHelper,
extractText,
createSharedTestOptions,
assertSuccessfulCompletion,
collectMessagesByType,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
describe('Single-Turn Query (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('single-turn');
});
afterEach(async () => {
await helper.cleanup();
});
describe('Simple Text Queries', () => {
it('should answer basic arithmetic question', async () => {
const q = query({
prompt: 'What is 2 + 2? Just give me the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: true,
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// Validate we got messages
expect(messages.length).toBeGreaterThan(0);
// Validate assistant response content
expect(assistantText.length).toBeGreaterThan(0);
expect(assistantText).toMatch(/4/);
// Validate message flow ends with success
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should answer simple factual question', async () => {
const q = query({
prompt: 'What is the capital of France? One word answer.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// Validate content
expect(assistantText.length).toBeGreaterThan(0);
expect(assistantText.toLowerCase()).toContain('paris');
// Validate completion
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should handle greeting and self-description', async () => {
const q = query({
prompt: 'Say hello and tell me your name in one sentence.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// Validate content contains greeting
expect(assistantText.length).toBeGreaterThan(0);
expect(assistantText.toLowerCase()).toMatch(/hello|hi|greetings/);
// Validate message types
const assistantMessages = collectMessagesByType(
messages,
isSDKAssistantMessage,
);
expect(assistantMessages.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
});
describe('System Initialization', () => {
it('should receive system message with initialization info', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
let systemMessage: SDKSystemMessage | null = null;
try {
for await (const message of q) {
messages.push(message);
if (isSDKSystemMessage(message) && message.subtype === 'init') {
systemMessage = message;
}
}
// Validate system message exists and has required fields
expect(systemMessage).not.toBeNull();
expect(systemMessage!.type).toBe('system');
expect(systemMessage!.subtype).toBe('init');
expect(systemMessage!.uuid).toBeDefined();
expect(systemMessage!.session_id).toBeDefined();
expect(systemMessage!.cwd).toBeDefined();
expect(systemMessage!.tools).toBeDefined();
expect(Array.isArray(systemMessage!.tools)).toBe(true);
expect(systemMessage!.mcp_servers).toBeDefined();
expect(Array.isArray(systemMessage!.mcp_servers)).toBe(true);
expect(systemMessage!.model).toBeDefined();
expect(systemMessage!.permission_mode).toBeDefined();
expect(systemMessage!.qwen_code_version).toBeDefined();
// Validate system message appears early in sequence
const systemMessageIndex = messages.findIndex(
(msg) => isSDKSystemMessage(msg) && msg.subtype === 'init',
);
expect(systemMessageIndex).toBeGreaterThanOrEqual(0);
expect(systemMessageIndex).toBeLessThan(3);
} finally {
await q.close();
}
});
it('should maintain session ID consistency', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let systemMessage: SDKSystemMessage | null = null;
const sessionId = q.getSessionId();
try {
for await (const message of q) {
if (isSDKSystemMessage(message) && message.subtype === 'init') {
systemMessage = message;
}
}
// Validate session IDs are consistent
expect(sessionId).toBeDefined();
expect(systemMessage).not.toBeNull();
expect(systemMessage!.session_id).toBeDefined();
expect(systemMessage!.uuid).toBeDefined();
expect(systemMessage!.session_id).toBe(systemMessage!.uuid);
} finally {
await q.close();
}
});
});
describe('Message Flow', () => {
it('should follow expected message sequence', async () => {
const q = query({
prompt: 'Say hi',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messageTypes: string[] = [];
try {
for await (const message of q) {
messageTypes.push(message.type);
}
// Validate message sequence
expect(messageTypes.length).toBeGreaterThan(0);
expect(messageTypes).toContain('assistant');
expect(messageTypes[messageTypes.length - 1]).toBe('result');
} finally {
await q.close();
}
});
it('should complete iteration naturally', async () => {
const q = query({
prompt: 'Say goodbye',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let completedNaturally = false;
let messageCount = 0;
try {
for await (const message of q) {
messageCount++;
if (isSDKResultMessage(message)) {
completedNaturally = true;
expect(message.subtype).toBe('success');
}
}
expect(messageCount).toBeGreaterThan(0);
expect(completedNaturally).toBe(true);
} finally {
await q.close();
}
});
});
describe('Configuration Options', () => {
it('should respect debug option and capture stderr', async () => {
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
},
});
try {
for await (const _message of q) {
// Consume all messages
}
// Debug mode should produce stderr output
expect(stderrMessages.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
it('should respect cwd option', async () => {
const q = query({
prompt: 'What is 1 + 1?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let hasResponse = false;
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
hasResponse = true;
}
}
expect(hasResponse).toBe(true);
} finally {
await q.close();
}
});
it('should receive partial messages when includePartialMessages is enabled', async () => {
const q = query({
prompt: 'Count from 1 to 5',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
includePartialMessages: true,
debug: false,
},
});
const messages: SDKMessage[] = [];
let partialMessageCount = 0;
let assistantMessageCount = 0;
try {
for await (const message of q) {
messages.push(message);
if (isSDKPartialAssistantMessage(message)) {
partialMessageCount++;
}
if (isSDKAssistantMessage(message)) {
assistantMessageCount++;
}
}
expect(messages.length).toBeGreaterThan(0);
expect(partialMessageCount).toBeGreaterThan(0);
expect(assistantMessageCount).toBeGreaterThan(0);
} finally {
await q.close();
}
});
});
describe('Message Type Recognition', () => {
it('should correctly identify all message types', async () => {
const q = query({
prompt: 'What is 5 + 5?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate type guards work correctly
const assistantMessages = collectMessagesByType(
messages,
isSDKAssistantMessage,
);
const resultMessages = collectMessagesByType(
messages,
isSDKResultMessage,
);
const systemMessages = collectMessagesByType(
messages,
isSDKSystemMessage,
);
expect(assistantMessages.length).toBeGreaterThan(0);
expect(resultMessages.length).toBeGreaterThan(0);
expect(systemMessages.length).toBeGreaterThan(0);
// Validate assistant message structure
const firstAssistant = assistantMessages[0];
expect(firstAssistant.message.content).toBeDefined();
expect(Array.isArray(firstAssistant.message.content)).toBe(true);
// Validate result message structure
const resultMessage = resultMessages[0];
expect(resultMessage.subtype).toBe('success');
} finally {
await q.close();
}
});
it('should extract text content from assistant messages', async () => {
const q = query({
prompt: 'Count from 1 to 3',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
let assistantMessage: SDKAssistantMessage | null = null;
try {
for await (const message of q) {
if (isSDKAssistantMessage(message)) {
assistantMessage = message;
}
}
expect(assistantMessage).not.toBeNull();
expect(assistantMessage!.message.content).toBeDefined();
// Validate content contains expected numbers
const text = extractText(assistantMessage!.message.content);
expect(text.length).toBeGreaterThan(0);
expect(text).toMatch(/1/);
expect(text).toMatch(/2/);
expect(text).toMatch(/3/);
} finally {
await q.close();
}
});
});
describe('Error Handling', () => {
it('should throw if CLI not found', async () => {
try {
const q = query({
prompt: 'Hello',
options: {
pathToQwenExecutable: '/nonexistent/path/to/cli',
debug: false,
},
});
for await (const _message of q) {
// Should not reach here
}
expect(false).toBe(true); // Should have thrown
} catch (error) {
expect(error).toBeDefined();
expect(error instanceof Error).toBe(true);
expect((error as Error).message).toContain(
'Invalid pathToQwenExecutable',
);
}
});
});
describe('Resource Management', () => {
it('should cleanup subprocess on close()', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
// Start and immediately close
const iterator = q[Symbol.asyncIterator]();
await iterator.next();
// Should close without error
await q.close();
expect(true).toBe(true); // Cleanup completed
});
it('should handle close() called multiple times', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
debug: false,
},
});
// Start the query
const iterator = q[Symbol.asyncIterator]();
await iterator.next();
// Close multiple times
await q.close();
await q.close();
await q.close();
// Should not throw
expect(true).toBe(true);
});
});
});

View File

@@ -0,0 +1,614 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* E2E tests for subagent configuration and execution
* Tests subagent delegation and task completion
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKAssistantMessage,
type SDKMessage,
type SubagentConfig,
type ContentBlock,
type ToolUseBlock,
} from '@qwen-code/sdk';
import {
SDKTestHelper,
extractText,
createSharedTestOptions,
findToolUseBlocks,
assertSuccessfulCompletion,
findSystemMessage,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
describe('Subagents (E2E)', () => {
let helper: SDKTestHelper;
let testWorkDir: string;
beforeEach(async () => {
// Create isolated test environment using SDKTestHelper
helper = new SDKTestHelper();
testWorkDir = await helper.setup('subagent-tests');
// Create a simple test file for subagent to work with
await helper.createFile('test.txt', 'Hello from test file\n');
});
afterEach(async () => {
// Cleanup test directory
await helper.cleanup();
});
describe('Subagent Configuration', () => {
it('should accept session-level subagent configuration', async () => {
const simpleSubagent: SubagentConfig = {
name: 'simple-greeter',
description: 'A simple subagent that responds to greetings',
systemPrompt:
'You are a friendly greeter. When given a task, respond with a cheerful greeting.',
level: 'session',
};
const q = query({
prompt: 'Hello, let simple-greeter to say hi back to me.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [simpleSubagent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate system message includes the subagent
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('simple-greeter');
// Validate successful completion
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
});
it('should accept multiple subagent configurations', async () => {
const greeterAgent: SubagentConfig = {
name: 'greeter',
description: 'Responds to greetings',
systemPrompt: 'You are a friendly greeter.',
level: 'session',
};
const mathAgent: SubagentConfig = {
name: 'math-helper',
description: 'Helps with math problems',
systemPrompt: 'You are a math expert. Solve math problems clearly.',
level: 'session',
};
const q = query({
prompt: 'What is 5 + 5?',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [greeterAgent, mathAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate both subagents are registered
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('greeter');
expect(systemMessage!.agents).toContain('math-helper');
expect(systemMessage!.agents!.length).toBeGreaterThanOrEqual(2);
} finally {
await q.close();
}
});
it('should handle subagent with custom model config', async () => {
const customModelAgent: SubagentConfig = {
name: 'custom-model-agent',
description: 'Agent with custom model configuration',
systemPrompt: 'You are a helpful assistant.',
level: 'session',
modelConfig: {
temp: 0.7,
top_p: 0.9,
},
};
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [customModelAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate subagent is registered
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('custom-model-agent');
} finally {
await q.close();
}
});
it('should handle subagent with run config', async () => {
const limitedAgent: SubagentConfig = {
name: 'limited-agent',
description: 'Agent with execution limits',
systemPrompt: 'You are a helpful assistant.',
level: 'session',
runConfig: {
max_turns: 5,
max_time_minutes: 1,
},
};
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [limitedAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate subagent is registered
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('limited-agent');
} finally {
await q.close();
}
});
it('should handle subagent with specific tools', async () => {
const toolRestrictedAgent: SubagentConfig = {
name: 'read-only-agent',
description: 'Agent that can only read files',
systemPrompt:
'You are a file reading assistant. Read files when asked.',
level: 'session',
tools: ['read_file', 'list_directory'],
};
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [toolRestrictedAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate subagent is registered
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('read-only-agent');
} finally {
await q.close();
}
});
});
describe('Subagent Execution', () => {
it('should delegate task to subagent when appropriate', async () => {
const fileReaderAgent: SubagentConfig = {
name: 'file-reader',
description: 'Reads and reports file contents',
systemPrompt: `You are a file reading assistant. When given a task to read a file, use the read_file tool to read it and report its contents back. Be concise in your response.`,
level: 'session',
tools: ['read_file', 'list_directory'],
};
const testFile = helper.getPath('test.txt');
const q = query({
prompt: `Use the file-reader subagent to read the file at ${testFile} and tell me what it contains.`,
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [fileReaderAgent],
debug: false,
permissionMode: 'yolo',
},
});
const messages: SDKMessage[] = [];
let foundTaskTool = false;
let taskToolUseId: string | null = null;
let foundSubagentToolCall = false;
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
// Check for task tool use in content blocks (main agent calling subagent)
const taskToolBlocks = findToolUseBlocks(message, 'task');
if (taskToolBlocks.length > 0) {
foundTaskTool = true;
taskToolUseId = taskToolBlocks[0].id;
}
// Check if this message is from a subagent (has parent_tool_use_id)
if (message.parent_tool_use_id !== null) {
// This is a subagent message
const subagentToolBlocks = findToolUseBlocks(message);
if (subagentToolBlocks.length > 0) {
foundSubagentToolCall = true;
// Verify parent_tool_use_id matches the task tool use id
expect(message.parent_tool_use_id).toBe(taskToolUseId);
}
}
assistantText += extractText(message.message.content);
}
}
// Validate task tool was used (subagent delegation)
expect(foundTaskTool).toBe(true);
expect(taskToolUseId).not.toBeNull();
// Validate subagent actually made tool calls with proper parent_tool_use_id
expect(foundSubagentToolCall).toBe(true);
// Validate we got a response
expect(assistantText.length).toBeGreaterThan(0);
// Validate successful completion
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
}, 60000); // Increase timeout for subagent execution
it('should complete simple task with subagent', async () => {
const simpleTaskAgent: SubagentConfig = {
name: 'simple-calculator',
description: 'Performs simple arithmetic calculations',
systemPrompt:
'You are a calculator. When given a math problem, solve it and provide just the answer.',
level: 'session',
};
const q = query({
prompt: 'Use the simple-calculator subagent to calculate 15 + 27.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [simpleTaskAgent],
debug: false,
permissionMode: 'yolo',
},
});
const messages: SDKMessage[] = [];
let foundTaskTool = false;
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
// Check for task tool use (main agent delegating to subagent)
const toolUseBlock = message.message.content.find(
(block: ContentBlock): block is ToolUseBlock =>
block.type === 'tool_use' && block.name === 'task',
);
if (toolUseBlock) {
foundTaskTool = true;
}
assistantText += extractText(message.message.content);
}
}
// Validate task tool was used (subagent was called)
expect(foundTaskTool).toBe(true);
// Validate we got a response
expect(assistantText.length).toBeGreaterThan(0);
// Validate successful completion
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
}, 60000);
it('should verify subagent execution with comprehensive parent_tool_use_id checks', async () => {
const comprehensiveAgent: SubagentConfig = {
name: 'comprehensive-agent',
description: 'Agent for comprehensive testing',
systemPrompt:
'You are a helpful assistant. When asked to list files, use the list_directory tool.',
level: 'session',
tools: ['list_directory', 'read_file'],
};
const q = query({
prompt: `Use the comprehensive-agent subagent to list the files in ${testWorkDir}.`,
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [comprehensiveAgent],
debug: false,
permissionMode: 'yolo',
},
});
const messages: SDKMessage[] = [];
let taskToolUseId: string | null = null;
const subagentToolCalls: ToolUseBlock[] = [];
const mainAgentToolCalls: ToolUseBlock[] = [];
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
// Collect all tool use blocks
const toolUseBlocks = message.message.content.filter(
(block: ContentBlock): block is ToolUseBlock =>
block.type === 'tool_use',
);
for (const toolUse of toolUseBlocks) {
if (toolUse.name === 'task') {
// This is the main agent calling the subagent
taskToolUseId = toolUse.id;
mainAgentToolCalls.push(toolUse);
}
// If this message has parent_tool_use_id, it's from a subagent
if (message.parent_tool_use_id !== null) {
subagentToolCalls.push(toolUse);
}
}
}
}
// Criterion 1: When a subagent is called, there must be a 'task' tool being called
expect(taskToolUseId).not.toBeNull();
expect(mainAgentToolCalls.length).toBeGreaterThan(0);
expect(mainAgentToolCalls.some((tc) => tc.name === 'task')).toBe(true);
// Criterion 2: A tool call from a subagent is identified by a non-null parent_tool_use_id
// All subagent tool calls should have parent_tool_use_id set to the task tool's id
expect(subagentToolCalls.length).toBeGreaterThan(0);
// Verify all subagent messages have the correct parent_tool_use_id
const subagentMessages = messages.filter(
(msg): msg is SDKMessage & { parent_tool_use_id: string } =>
isSDKAssistantMessage(msg) && msg.parent_tool_use_id !== null,
);
expect(subagentMessages.length).toBeGreaterThan(0);
for (const subagentMsg of subagentMessages) {
expect(subagentMsg.parent_tool_use_id).toBe(taskToolUseId);
}
// Verify no main agent tool calls (except task) have parent_tool_use_id
const mainAgentMessages = messages.filter(
(msg): msg is SDKMessage =>
isSDKAssistantMessage(msg) && msg.parent_tool_use_id === null,
);
for (const mainMsg of mainAgentMessages) {
if (isSDKAssistantMessage(mainMsg)) {
// Main agent messages should not have parent_tool_use_id
expect(mainMsg.parent_tool_use_id).toBeNull();
}
}
// Validate successful completion
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
}, 60000);
});
describe('Subagent Error Handling', () => {
it('should handle empty subagent array', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Should still work with empty agents array
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
} finally {
await q.close();
}
});
it('should handle subagent with minimal configuration', async () => {
const minimalAgent: SubagentConfig = {
name: 'minimal-agent',
description: 'Minimal configuration agent',
systemPrompt: 'You are a helpful assistant.',
level: 'session',
};
const q = query({
prompt: 'Say hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [minimalAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate minimal agent is registered
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('minimal-agent');
} finally {
await q.close();
}
});
});
describe('Subagent Integration', () => {
it('should work with other SDK options', async () => {
const testAgent: SubagentConfig = {
name: 'test-agent',
description: 'Test agent for integration',
systemPrompt: 'You are a test assistant.',
level: 'session',
};
const stderrMessages: string[] = [];
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [testAgent],
debug: true,
stderr: (msg: string) => {
stderrMessages.push(msg);
},
permissionMode: 'default',
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate subagent works with debug mode
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.agents).toBeDefined();
expect(systemMessage!.agents).toContain('test-agent');
expect(stderrMessages.length).toBeGreaterThan(0);
} finally {
await q.close();
}
});
it('should maintain session consistency with subagents', async () => {
const sessionAgent: SubagentConfig = {
name: 'session-agent',
description: 'Agent for session testing',
systemPrompt: 'You are a session test assistant.',
level: 'session',
};
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testWorkDir,
agents: [sessionAgent],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Validate session consistency
const systemMessage = findSystemMessage(messages, 'init');
expect(systemMessage).not.toBeNull();
expect(systemMessage!.session_id).toBeDefined();
expect(systemMessage!.uuid).toBeDefined();
expect(systemMessage!.session_id).toBe(systemMessage!.uuid);
expect(systemMessage!.agents).toContain('session-agent');
} finally {
await q.close();
}
});
});
});

View File

@@ -0,0 +1,317 @@
/**
* E2E tests for system controller features:
* - setModel API for dynamic model switching
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
query,
isSDKAssistantMessage,
isSDKSystemMessage,
type SDKUserMessage,
} from '@qwen-code/sdk';
import { SDKTestHelper, createSharedTestOptions } from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
/**
* Factory function that creates a streaming input with a control point.
* After the first message is yielded, the generator waits for a resume signal,
* allowing the test code to call query instance methods like setModel.
*
* @param firstMessage - The first user message to send
* @param secondMessage - The second user message to send after control operations
* @returns Object containing the async generator and a resume function
*/
function createStreamingInputWithControlPoint(
firstMessage: string,
secondMessage: string,
): {
generator: AsyncIterable<SDKUserMessage>;
resume: () => void;
} {
let resumeResolve: (() => void) | null = null;
const resumePromise = new Promise<void>((resolve) => {
resumeResolve = resolve;
});
const generator = (async function* () {
const sessionId = crypto.randomUUID();
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: firstMessage,
},
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 200));
await resumePromise;
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sessionId,
message: {
role: 'user',
content: secondMessage,
},
parent_tool_use_id: null,
} as SDKUserMessage;
})();
const resume = () => {
if (resumeResolve) {
resumeResolve();
}
};
return { generator, resume };
}
describe('System Control (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('system-control');
});
afterEach(async () => {
await helper.cleanup();
});
describe('setModel API', () => {
it('should change model dynamically during streaming input', async () => {
const { generator, resume } = createStreamingInputWithControlPoint(
'Tell me the model name.',
'Tell me the model name now again.',
);
const q = query({
prompt: generator,
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
model: 'qwen3-max',
debug: false,
},
});
try {
const resolvers: {
first?: () => void;
second?: () => void;
} = {};
const firstResponsePromise = new Promise<void>((resolve) => {
resolvers.first = resolve;
});
const secondResponsePromise = new Promise<void>((resolve) => {
resolvers.second = resolve;
});
let firstResponseReceived = false;
let secondResponseReceived = false;
const systemMessages: Array<{ model?: string }> = [];
// Consume messages in a single loop
(async () => {
for await (const message of q) {
if (isSDKSystemMessage(message)) {
systemMessages.push({ model: message.model });
}
if (isSDKAssistantMessage(message)) {
if (!firstResponseReceived) {
firstResponseReceived = true;
resolvers.first?.();
} else if (!secondResponseReceived) {
secondResponseReceived = true;
resolvers.second?.();
}
}
}
})();
// Wait for first response
await Promise.race([
firstResponsePromise,
new Promise((_, reject) =>
setTimeout(
() => reject(new Error('Timeout waiting for first response')),
15000,
),
),
]);
expect(firstResponseReceived).toBe(true);
// Perform control operation: set model
await q.setModel('qwen3-vl-plus');
// Resume the input stream
resume();
// Wait for second response
await Promise.race([
secondResponsePromise,
new Promise((_, reject) =>
setTimeout(
() => reject(new Error('Timeout waiting for second response')),
10000,
),
),
]);
expect(secondResponseReceived).toBe(true);
// Verify system messages - model should change from qwen3-max to qwen3-vl-plus
expect(systemMessages.length).toBeGreaterThanOrEqual(2);
expect(systemMessages[0].model).toBeOneOf(['qwen3-max', 'coder-model']);
expect(systemMessages[1].model).toBe('qwen3-vl-plus');
} finally {
await q.close();
}
});
it('should handle multiple model changes in sequence', async () => {
const sessionId = crypto.randomUUID();
let resumeResolve1: (() => void) | null = null;
let resumeResolve2: (() => void) | null = null;
const resumePromise1 = new Promise<void>((resolve) => {
resumeResolve1 = resolve;
});
const resumePromise2 = new Promise<void>((resolve) => {
resumeResolve2 = resolve;
});
const generator = (async function* () {
yield {
type: 'user',
session_id: sessionId,
message: { role: 'user', content: 'First message' },
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 200));
await resumePromise1;
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sessionId,
message: { role: 'user', content: 'Second message' },
parent_tool_use_id: null,
} as SDKUserMessage;
await new Promise((resolve) => setTimeout(resolve, 200));
await resumePromise2;
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sessionId,
message: { role: 'user', content: 'Third message' },
parent_tool_use_id: null,
} as SDKUserMessage;
})();
const q = query({
prompt: generator,
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
model: 'qwen3-max',
debug: false,
},
});
try {
const systemMessages: Array<{ model?: string }> = [];
let responseCount = 0;
const resolvers: Array<() => void> = [];
const responsePromises = [
new Promise<void>((resolve) => resolvers.push(resolve)),
new Promise<void>((resolve) => resolvers.push(resolve)),
new Promise<void>((resolve) => resolvers.push(resolve)),
];
(async () => {
for await (const message of q) {
if (isSDKSystemMessage(message)) {
systemMessages.push({ model: message.model });
}
if (isSDKAssistantMessage(message)) {
if (responseCount < resolvers.length) {
resolvers[responseCount]?.();
responseCount++;
}
}
}
})();
// Wait for first response
await Promise.race([
responsePromises[0],
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout 1')), 10000),
),
]);
// First model change
await q.setModel('qwen3-turbo');
resumeResolve1!();
// Wait for second response
await Promise.race([
responsePromises[1],
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout 2')), 10000),
),
]);
// Second model change
await q.setModel('qwen3-vl-plus');
resumeResolve2!();
// Wait for third response
await Promise.race([
responsePromises[2],
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout 3')), 10000),
),
]);
// Verify we received system messages for each model
expect(systemMessages.length).toBeGreaterThanOrEqual(3);
expect(systemMessages[0].model).toBeOneOf(['qwen3-max', 'coder-model']);
expect(systemMessages[1].model).toBe('qwen3-turbo');
expect(systemMessages[2].model).toBe('qwen3-vl-plus');
} finally {
await q.close();
}
});
it('should throw error when setModel is called on closed query', async () => {
const q = query({
prompt: 'Hello',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
model: 'qwen3-max',
},
});
await q.close();
await expect(q.setModel('qwen3-turbo')).rejects.toThrow(
'Query is closed',
);
});
});
});

View File

@@ -0,0 +1,970 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* SDK E2E Test Helper
* Provides utilities for SDK e2e tests including test isolation,
* file management, MCP server setup, and common test utilities.
*/
import { mkdir, writeFile, readFile, rm, chmod } from 'node:fs/promises';
import { join } from 'node:path';
import { existsSync } from 'node:fs';
import type {
SDKMessage,
SDKAssistantMessage,
SDKSystemMessage,
SDKUserMessage,
ContentBlock,
TextBlock,
ToolUseBlock,
} from '@qwen-code/sdk';
import {
isSDKAssistantMessage,
isSDKSystemMessage,
isSDKResultMessage,
} from '@qwen-code/sdk';
// ============================================================================
// Core Test Helper Class
// ============================================================================
export interface SDKTestHelperOptions {
/**
* Optional settings for .qwen/settings.json
*/
settings?: Record<string, unknown>;
/**
* Whether to create .qwen/settings.json
*/
createQwenConfig?: boolean;
}
/**
* Helper class for SDK E2E tests
* Provides isolated test environments for each test case
*/
export class SDKTestHelper {
testDir: string | null = null;
testName?: string;
private baseDir: string;
constructor() {
this.baseDir = process.env['E2E_TEST_FILE_DIR']!;
if (!this.baseDir) {
throw new Error('E2E_TEST_FILE_DIR environment variable not set');
}
}
/**
* Setup an isolated test directory for a specific test
*/
async setup(
testName: string,
options: SDKTestHelperOptions = {},
): Promise<string> {
this.testName = testName;
const sanitizedName = this.sanitizeTestName(testName);
this.testDir = join(this.baseDir, sanitizedName);
await mkdir(this.testDir, { recursive: true });
// Optionally create .qwen/settings.json for CLI configuration
if (options.createQwenConfig) {
const qwenDir = join(this.testDir, '.qwen');
await mkdir(qwenDir, { recursive: true });
const settings = {
telemetry: {
enabled: false, // SDK tests don't need telemetry
},
...options.settings,
};
await writeFile(
join(qwenDir, 'settings.json'),
JSON.stringify(settings, null, 2),
'utf-8',
);
}
return this.testDir;
}
/**
* Create a file in the test directory
*/
async createFile(fileName: string, content: string): Promise<string> {
if (!this.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
const filePath = join(this.testDir, fileName);
await writeFile(filePath, content, 'utf-8');
return filePath;
}
/**
* Read a file from the test directory
*/
async readFile(fileName: string): Promise<string> {
if (!this.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
const filePath = join(this.testDir, fileName);
return await readFile(filePath, 'utf-8');
}
/**
* Create a subdirectory in the test directory
*/
async mkdir(dirName: string): Promise<string> {
if (!this.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
const dirPath = join(this.testDir, dirName);
await mkdir(dirPath, { recursive: true });
return dirPath;
}
/**
* Check if a file exists in the test directory
*/
fileExists(fileName: string): boolean {
if (!this.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
const filePath = join(this.testDir, fileName);
return existsSync(filePath);
}
/**
* Get the full path to a file in the test directory
*/
getPath(fileName: string): string {
if (!this.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
return join(this.testDir, fileName);
}
/**
* Cleanup test directory
*/
async cleanup(): Promise<void> {
if (this.testDir && process.env['KEEP_OUTPUT'] !== 'true') {
try {
await rm(this.testDir, { recursive: true, force: true });
} catch (error) {
if (process.env['VERBOSE'] === 'true') {
console.warn('Cleanup warning:', (error as Error).message);
}
}
}
}
/**
* Sanitize test name to create valid directory name
*/
private sanitizeTestName(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]/g, '-')
.replace(/-+/g, '-')
.substring(0, 100); // Limit length
}
}
// ============================================================================
// MCP Server Utilities
// ============================================================================
export interface MCPServerConfig {
command: string;
args: string[];
}
export interface MCPServerResult {
scriptPath: string;
config: MCPServerConfig;
}
/**
* Built-in MCP server template: Math server with add and multiply tools
*/
const MCP_MATH_SERVER_SCRIPT = `#!/usr/bin/env node
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
const readline = require('readline');
const fs = require('fs');
// Debug logging to stderr (only when MCP_DEBUG or VERBOSE is set)
const debugEnabled = process.env['MCP_DEBUG'] === 'true' || process.env['VERBOSE'] === 'true';
function debug(msg) {
if (debugEnabled) {
fs.writeSync(2, \`[MCP-DEBUG] \${msg}\\n\`);
}
}
debug('MCP server starting...');
// Simple JSON-RPC implementation for MCP
class SimpleJSONRPC {
constructor() {
this.handlers = new Map();
this.rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
this.rl.on('line', (line) => {
debug(\`Received line: \${line}\`);
try {
const message = JSON.parse(line);
debug(\`Parsed message: \${JSON.stringify(message)}\`);
this.handleMessage(message);
} catch (e) {
debug(\`Parse error: \${e.message}\`);
}
});
}
send(message) {
const msgStr = JSON.stringify(message);
debug(\`Sending message: \${msgStr}\`);
process.stdout.write(msgStr + '\\n');
}
async handleMessage(message) {
if (message.method && this.handlers.has(message.method)) {
try {
const result = await this.handlers.get(message.method)(message.params || {});
if (message.id !== undefined) {
this.send({
jsonrpc: '2.0',
id: message.id,
result
});
}
} catch (error) {
if (message.id !== undefined) {
this.send({
jsonrpc: '2.0',
id: message.id,
error: {
code: -32603,
message: error.message
}
});
}
}
} else if (message.id !== undefined) {
this.send({
jsonrpc: '2.0',
id: message.id,
error: {
code: -32601,
message: 'Method not found'
}
});
}
}
on(method, handler) {
this.handlers.set(method, handler);
}
}
// Create MCP server
const rpc = new SimpleJSONRPC();
// Handle initialize
rpc.on('initialize', async (params) => {
debug('Handling initialize request');
return {
protocolVersion: '2024-11-05',
capabilities: {
tools: {}
},
serverInfo: {
name: 'test-math-server',
version: '1.0.0'
}
};
});
// Handle tools/list
rpc.on('tools/list', async () => {
debug('Handling tools/list request');
return {
tools: [
{
name: 'add',
description: 'Add two numbers together',
inputSchema: {
type: 'object',
properties: {
a: { type: 'number', description: 'First number' },
b: { type: 'number', description: 'Second number' }
},
required: ['a', 'b']
}
},
{
name: 'multiply',
description: 'Multiply two numbers together',
inputSchema: {
type: 'object',
properties: {
a: { type: 'number', description: 'First number' },
b: { type: 'number', description: 'Second number' }
},
required: ['a', 'b']
}
}
]
};
});
// Handle tools/call
rpc.on('tools/call', async (params) => {
debug(\`Handling tools/call request for tool: \${params.name}\`);
if (params.name === 'add') {
const { a, b } = params.arguments;
return {
content: [{
type: 'text',
text: String(a + b)
}]
};
}
if (params.name === 'multiply') {
const { a, b } = params.arguments;
return {
content: [{
type: 'text',
text: String(a * b)
}]
};
}
throw new Error('Unknown tool: ' + params.name);
});
// Send initialization notification
rpc.send({
jsonrpc: '2.0',
method: 'initialized'
});
`;
/**
* Create an MCP server script in the test directory
* @param helper - SDKTestHelper instance
* @param type - Type of MCP server ('math' or provide custom script)
* @param serverName - Name of the MCP server (default: 'test-math-server')
* @param customScript - Custom MCP server script (if type is not 'math')
* @returns Object with scriptPath and config
*/
export async function createMCPServer(
helper: SDKTestHelper,
type: 'math' | 'custom' = 'math',
serverName: string = 'test-math-server',
customScript?: string,
): Promise<MCPServerResult> {
if (!helper.testDir) {
throw new Error('Test directory not initialized. Call setup() first.');
}
const script = type === 'math' ? MCP_MATH_SERVER_SCRIPT : customScript;
if (!script) {
throw new Error('Custom script required when type is "custom"');
}
const scriptPath = join(helper.testDir, `${serverName}.cjs`);
await writeFile(scriptPath, script, 'utf-8');
// Make script executable on Unix-like systems
if (process.platform !== 'win32') {
await chmod(scriptPath, 0o755);
}
return {
scriptPath,
config: {
command: 'node',
args: [scriptPath],
},
};
}
// ============================================================================
// Message & Content Utilities
// ============================================================================
/**
* Extract text from ContentBlock array
*/
export function extractText(content: ContentBlock[]): string {
return content
.filter((block): block is TextBlock => block.type === 'text')
.map((block) => block.text)
.join('');
}
/**
* Collect messages by type
*/
export function collectMessagesByType<T extends SDKMessage>(
messages: SDKMessage[],
predicate: (msg: SDKMessage) => msg is T,
): T[] {
return messages.filter(predicate);
}
/**
* Find tool use blocks in a message
*/
export function findToolUseBlocks(
message: SDKAssistantMessage,
toolName?: string,
): ToolUseBlock[] {
const toolUseBlocks = message.message.content.filter(
(block): block is ToolUseBlock => block.type === 'tool_use',
);
if (toolName) {
return toolUseBlocks.filter((block) => block.name === toolName);
}
return toolUseBlocks;
}
/**
* Extract all assistant text from messages
*/
export function getAssistantText(messages: SDKMessage[]): string {
return messages
.filter(isSDKAssistantMessage)
.map((msg) => extractText(msg.message.content))
.join('');
}
/**
* Find system message with optional subtype filter
*/
export function findSystemMessage(
messages: SDKMessage[],
subtype?: string,
): SDKSystemMessage | null {
const systemMessages = messages.filter(isSDKSystemMessage);
if (subtype) {
return systemMessages.find((msg) => msg.subtype === subtype) || null;
}
return systemMessages[0] || null;
}
/**
* Find all tool calls in messages
*/
export function findToolCalls(
messages: SDKMessage[],
toolName?: string,
): Array<{ message: SDKAssistantMessage; toolUse: ToolUseBlock }> {
const results: Array<{
message: SDKAssistantMessage;
toolUse: ToolUseBlock;
}> = [];
for (const message of messages) {
if (isSDKAssistantMessage(message)) {
const toolUseBlocks = findToolUseBlocks(message, toolName);
for (const toolUse of toolUseBlocks) {
results.push({ message, toolUse });
}
}
}
return results;
}
/**
* Find tool result for a specific tool use ID
*/
export function findToolResult(
messages: SDKMessage[],
toolUseId: string,
): { content: string; isError: boolean } | null {
for (const message of messages) {
if (message.type === 'user' && 'message' in message) {
const userMsg = message as SDKUserMessage;
const content = userMsg.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (
block.type === 'tool_result' &&
(block as { tool_use_id?: string }).tool_use_id === toolUseId
) {
const resultBlock = block as {
content?: string | ContentBlock[];
is_error?: boolean;
};
let resultContent = '';
if (typeof resultBlock.content === 'string') {
resultContent = resultBlock.content;
} else if (Array.isArray(resultBlock.content)) {
resultContent = resultBlock.content
.filter((b): b is TextBlock => b.type === 'text')
.map((b) => b.text)
.join('');
}
return {
content: resultContent,
isError: resultBlock.is_error ?? false,
};
}
}
}
}
}
return null;
}
/**
* Find all tool results for a specific tool name
*/
export function findToolResults(
messages: SDKMessage[],
toolName: string,
): Array<{ toolUseId: string; content: string; isError: boolean }> {
const results: Array<{
toolUseId: string;
content: string;
isError: boolean;
}> = [];
// First find all tool calls for this tool
const toolCalls = findToolCalls(messages, toolName);
// Then find the result for each tool call
for (const { toolUse } of toolCalls) {
const result = findToolResult(messages, toolUse.id);
if (result) {
results.push({
toolUseId: toolUse.id,
content: result.content,
isError: result.isError,
});
}
}
return results;
}
/**
* Find all tool result blocks from messages (without requiring tool name)
*/
export function findAllToolResultBlocks(
messages: SDKMessage[],
): Array<{ toolUseId: string; content: string; isError: boolean }> {
const results: Array<{
toolUseId: string;
content: string;
isError: boolean;
}> = [];
for (const message of messages) {
if (message.type === 'user' && 'message' in message) {
const userMsg = message as SDKUserMessage;
const content = userMsg.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'tool_result' && 'tool_use_id' in block) {
const resultBlock = block as {
tool_use_id: string;
content?: string | ContentBlock[];
is_error?: boolean;
};
let resultContent = '';
if (typeof resultBlock.content === 'string') {
resultContent = resultBlock.content;
} else if (Array.isArray(resultBlock.content)) {
resultContent = (resultBlock.content as ContentBlock[])
.filter((b): b is TextBlock => b.type === 'text')
.map((b) => b.text)
.join('');
}
results.push({
toolUseId: resultBlock.tool_use_id,
content: resultContent,
isError: resultBlock.is_error ?? false,
});
}
}
}
}
}
return results;
}
/**
* Check if any tool results exist in messages
*/
export function hasAnyToolResults(messages: SDKMessage[]): boolean {
return findAllToolResultBlocks(messages).length > 0;
}
/**
* Check if any successful (non-error) tool results exist
*/
export function hasSuccessfulToolResults(messages: SDKMessage[]): boolean {
return findAllToolResultBlocks(messages).some((r) => !r.isError);
}
/**
* Check if any error tool results exist
*/
export function hasErrorToolResults(messages: SDKMessage[]): boolean {
return findAllToolResultBlocks(messages).some((r) => r.isError);
}
// ============================================================================
// Streaming Input Utilities
// ============================================================================
/**
* Create a simple streaming input from an array of message contents
*/
export async function* createStreamingInput(
messageContents: string[],
sessionId?: string,
): AsyncIterable<SDKUserMessage> {
const sid = sessionId || crypto.randomUUID();
for (const content of messageContents) {
yield {
type: 'user',
session_id: sid,
message: {
role: 'user',
content: content,
},
parent_tool_use_id: null,
} as SDKUserMessage;
// Small delay between messages
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
/**
* Create a controlled streaming input with pause/resume capability
*/
export function createControlledStreamingInput(
messageContents: string[],
sessionId?: string,
): {
generator: AsyncIterable<SDKUserMessage>;
resume: () => void;
resumeAll: () => void;
} {
const sid = sessionId || crypto.randomUUID();
const resumeResolvers: Array<() => void> = [];
const resumePromises: Array<Promise<void>> = [];
// Create a resume promise for each message after the first
for (let i = 1; i < messageContents.length; i++) {
const promise = new Promise<void>((resolve) => {
resumeResolvers.push(resolve);
});
resumePromises.push(promise);
}
const generator = (async function* () {
// Yield first message immediately
yield {
type: 'user',
session_id: sid,
message: {
role: 'user',
content: messageContents[0],
},
parent_tool_use_id: null,
} as SDKUserMessage;
// For subsequent messages, wait for resume
for (let i = 1; i < messageContents.length; i++) {
await new Promise((resolve) => setTimeout(resolve, 200));
await resumePromises[i - 1];
await new Promise((resolve) => setTimeout(resolve, 200));
yield {
type: 'user',
session_id: sid,
message: {
role: 'user',
content: messageContents[i],
},
parent_tool_use_id: null,
} as SDKUserMessage;
}
})();
let currentResumeIndex = 0;
return {
generator,
resume: () => {
if (currentResumeIndex < resumeResolvers.length) {
resumeResolvers[currentResumeIndex]();
currentResumeIndex++;
}
},
resumeAll: () => {
resumeResolvers.forEach((resolve) => resolve());
currentResumeIndex = resumeResolvers.length;
},
};
}
// ============================================================================
// Assertion Utilities
// ============================================================================
/**
* Assert that messages follow expected type sequence
*/
export function assertMessageSequence(
messages: SDKMessage[],
expectedTypes: string[],
): void {
const actualTypes = messages.map((msg) => msg.type);
if (actualTypes.length < expectedTypes.length) {
throw new Error(
`Expected at least ${expectedTypes.length} messages, got ${actualTypes.length}`,
);
}
for (let i = 0; i < expectedTypes.length; i++) {
if (actualTypes[i] !== expectedTypes[i]) {
throw new Error(
`Expected message ${i} to be type '${expectedTypes[i]}', got '${actualTypes[i]}'`,
);
}
}
}
/**
* Assert that a specific tool was called
*/
export function assertToolCalled(
messages: SDKMessage[],
toolName: string,
): void {
const toolCalls = findToolCalls(messages, toolName);
if (toolCalls.length === 0) {
const allToolCalls = findToolCalls(messages);
const allToolNames = allToolCalls.map((tc) => tc.toolUse.name);
throw new Error(
`Expected tool '${toolName}' to be called. Found tools: ${allToolNames.length > 0 ? allToolNames.join(', ') : 'none'}`,
);
}
}
/**
* Assert that the conversation completed successfully
*/
export function assertSuccessfulCompletion(messages: SDKMessage[]): void {
const lastMessage = messages[messages.length - 1];
if (!isSDKResultMessage(lastMessage)) {
throw new Error(
`Expected last message to be a result message, got '${lastMessage.type}'`,
);
}
if (lastMessage.subtype !== 'success') {
throw new Error(
`Expected successful completion, got result subtype '${lastMessage.subtype}'`,
);
}
}
/**
* Wait for a condition to be true with timeout
*/
export async function waitFor(
predicate: () => boolean | Promise<boolean>,
options: {
timeout?: number;
interval?: number;
errorMessage?: string;
} = {},
): Promise<void> {
const {
timeout = 5000,
interval = 100,
errorMessage = 'Condition not met within timeout',
} = options;
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
const result = await predicate();
if (result) {
return;
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
throw new Error(errorMessage);
}
// ============================================================================
// Debug and Validation Utilities
// ============================================================================
/**
* Validate model output and warn about unexpected content
* Inspired by integration-tests test-helper
*/
export function validateModelOutput(
result: string,
expectedContent: string | (string | RegExp)[] | null = null,
testName = '',
): boolean {
// First, check if there's any output at all
if (!result || result.trim().length === 0) {
throw new Error('Expected model to return some output');
}
// If expectedContent is provided, check for it and warn if missing
if (expectedContent) {
const contents = Array.isArray(expectedContent)
? expectedContent
: [expectedContent];
const missingContent = contents.filter((content) => {
if (typeof content === 'string') {
return !result.toLowerCase().includes(content.toLowerCase());
} else if (content instanceof RegExp) {
return !content.test(result);
}
return false;
});
if (missingContent.length > 0) {
console.warn(
`Warning: Model did not include expected content in response: ${missingContent.join(', ')}.`,
'This is not ideal but not a test failure.',
);
console.warn(
'The tool was called successfully, which is the main requirement.',
);
return false;
} else if (process.env['VERBOSE'] === 'true') {
console.log(`${testName}: Model output validated successfully.`);
}
return true;
}
return true;
}
/**
* Print debug information when tests fail
*/
export function printDebugInfo(
messages: SDKMessage[],
context: Record<string, unknown> = {},
): void {
console.error('Test failed - Debug info:');
console.error('Message count:', messages.length);
// Print message types
const messageTypes = messages.map((m) => m.type);
console.error('Message types:', messageTypes.join(', '));
// Print assistant text
const assistantText = getAssistantText(messages);
console.error(
'Assistant text (first 500 chars):',
assistantText.substring(0, 500),
);
if (assistantText.length > 500) {
console.error(
'Assistant text (last 500 chars):',
assistantText.substring(assistantText.length - 500),
);
}
// Print tool calls
const toolCalls = findToolCalls(messages);
console.error(
'Tool calls found:',
toolCalls.map((tc) => tc.toolUse.name),
);
// Print any additional context provided
Object.entries(context).forEach(([key, value]) => {
console.error(`${key}:`, value);
});
}
/**
* Create detailed error message for tool call expectations
*/
export function createToolCallErrorMessage(
expectedTools: string | string[],
foundTools: string[],
messages: SDKMessage[],
): string {
const expectedStr = Array.isArray(expectedTools)
? expectedTools.join(' or ')
: expectedTools;
const assistantText = getAssistantText(messages);
const preview = assistantText
? assistantText.substring(0, 200) + '...'
: 'no output';
return (
`Expected to find ${expectedStr} tool call(s). ` +
`Found: ${foundTools.length > 0 ? foundTools.join(', ') : 'none'}. ` +
`Output preview: ${preview}`
);
}
// ============================================================================
// Shared Test Options Helper
// ============================================================================
/**
* Create shared test options with CLI path
*/
export function createSharedTestOptions(
overrides: Record<string, unknown> = {},
) {
const TEST_CLI_PATH = process.env['TEST_CLI_PATH'];
if (!TEST_CLI_PATH) {
throw new Error('TEST_CLI_PATH environment variable not set');
}
return {
pathToQwenExecutable: TEST_CLI_PATH,
...overrides,
};
}

View File

@@ -0,0 +1,744 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* E2E tests for tool control parameters:
* - coreTools: Limit available tools to a specific set
* - excludeTools: Block specific tools from execution
* - allowedTools: Auto-approve specific tools without confirmation
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { query, isSDKAssistantMessage, type SDKMessage } from '@qwen-code/sdk';
import {
SDKTestHelper,
extractText,
findToolCalls,
findToolResults,
assertSuccessfulCompletion,
createSharedTestOptions,
} from './test-helper.js';
const SHARED_TEST_OPTIONS = createSharedTestOptions();
const TEST_TIMEOUT = 60000;
describe('Tool Control Parameters (E2E)', () => {
let helper: SDKTestHelper;
let testDir: string;
beforeEach(async () => {
helper = new SDKTestHelper();
testDir = await helper.setup('tool-control', {
createQwenConfig: false,
});
});
afterEach(async () => {
await helper.cleanup();
});
describe('coreTools parameter', () => {
it(
'should only allow specified tools when coreTools is set',
async () => {
// Create a test file
await helper.createFile('test.txt', 'original content');
const q = query({
prompt:
'Read the file test.txt and then write "modified" to test.txt. Finally, list the directory.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Only allow read_file and write_file, exclude list_directory
coreTools: ['read_file', 'write_file'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// Should have read_file and write_file calls
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
// Should NOT have list_directory since it's not in coreTools
expect(toolNames).not.toContain('list_directory');
// Verify file was modified
const content = await helper.readFile('test.txt');
expect(content).toContain('modified');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should work with minimal tool set',
async () => {
const q = query({
prompt: 'What is 2 + 2? Just answer with the number.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
// Only allow thinking, no file operations
coreTools: [],
debug: false,
},
});
const messages: SDKMessage[] = [];
let assistantText = '';
try {
for await (const message of q) {
messages.push(message);
if (isSDKAssistantMessage(message)) {
assistantText += extractText(message.message.content);
}
}
// Should answer without any tool calls
expect(assistantText).toMatch(/4/);
// Should have no tool calls
const toolCalls = findToolCalls(messages);
expect(toolCalls.length).toBe(0);
assertSuccessfulCompletion(messages);
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
});
describe('excludeTools parameter', () => {
it(
'should block excluded tools from execution',
async () => {
await helper.createFile('test.txt', 'test content');
const q = query({
prompt:
'Read test.txt and then write empty content to it to clear it.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
coreTools: ['read_file', 'write_file'],
// Block all write_file tool
excludeTools: ['write_file'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should be able to read the file
expect(toolNames).toContain('read_file');
// The excluded tools should have been called but returned permission declined
// Check if write_file was attempted and got permission denied
const writeFileResults = findToolResults(messages, 'write_file');
if (writeFileResults.length > 0) {
// Tool was called but should have permission declined message
for (const result of writeFileResults) {
expect(result.content).toMatch(/permission.*declined/i);
}
}
// File content should remain unchanged (because write was denied)
const content = await helper.readFile('test.txt');
expect(content).toBe('test content');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should block multiple excluded tools',
async () => {
await helper.createFile('test.txt', 'test content');
const q = query({
prompt: 'Read test.txt, list the directory, and run "echo hello".',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Block multiple tools
excludeTools: ['list_directory', 'run_shell_command'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should be able to read
expect(toolNames).toContain('read_file');
// Excluded tools should have been attempted but returned permission declined
const listDirResults = findToolResults(messages, 'list_directory');
if (listDirResults.length > 0) {
for (const result of listDirResults) {
expect(result.content).toMatch(/permission.*declined/i);
}
}
const shellResults = findToolResults(messages, 'run_shell_command');
if (shellResults.length > 0) {
for (const result of shellResults) {
expect(result.content).toMatch(/permission.*declined/i);
}
}
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should block all shell commands when run_shell_command is excluded',
async () => {
const q = query({
prompt: 'Run "echo hello" and "ls -la" commands.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Block all shell commands - excludeTools blocks entire tools
excludeTools: ['run_shell_command'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// All shell commands should have permission declined
const shellResults = findToolResults(messages, 'run_shell_command');
for (const result of shellResults) {
expect(result.content).toMatch(/permission.*declined/i);
}
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'excludeTools should take priority over allowedTools',
async () => {
await helper.createFile('test.txt', 'test content');
const q = query({
prompt:
'Clear the content of test.txt by writing empty string to it.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
// Conflicting settings: exclude takes priority
excludeTools: ['write_file'],
allowedTools: ['write_file'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
// write_file should have been attempted but returned permission declined
const writeFileResults = findToolResults(messages, 'write_file');
if (writeFileResults.length > 0) {
// Tool was called but should have permission declined message (exclude takes priority)
for (const result of writeFileResults) {
expect(result.content).toMatch(/permission.*declined/i);
}
}
// File content should remain unchanged (because write was denied)
const content = await helper.readFile('test.txt');
expect(content).toBe('test content');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
});
describe('allowedTools parameter', () => {
it(
'should auto-approve allowed tools without canUseTool callback',
async () => {
await helper.createFile('test.txt', 'original');
let canUseToolCalled = false;
const q = query({
prompt: 'Read test.txt and write "modified" to it.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
coreTools: ['read_file', 'write_file'],
// Allow write_file without confirmation
allowedTools: ['read_file', 'write_file'],
canUseTool: async (_toolName) => {
canUseToolCalled = true;
return { behavior: 'deny', message: 'Should not be called' };
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should have executed the tools
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
// canUseTool should NOT have been called (tools are in allowedTools)
expect(canUseToolCalled).toBe(false);
// Verify file was modified
const content = await helper.readFile('test.txt');
expect(content).toContain('modified');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should allow specific shell commands with pattern matching',
async () => {
const q = query({
prompt: 'Run "echo hello" and "ls -la" commands.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
// Allow specific shell commands
allowedTools: ['ShellTool(echo )', 'ShellTool(ls )'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const shellCalls = toolCalls.filter(
(tc) => tc.toolUse.name === 'run_shell_command',
);
// Should have executed shell commands
expect(shellCalls.length).toBeGreaterThan(0);
// All shell commands should be echo or ls
for (const call of shellCalls) {
const input = call.toolUse.input as { command?: string };
if (input.command) {
expect(input.command).toMatch(/^(echo |ls )/);
}
}
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should fall back to canUseTool for non-allowed tools',
async () => {
await helper.createFile('test.txt', 'test');
const canUseToolCalls: string[] = [];
const q = query({
prompt: 'Read test.txt and append an empty line to it.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
// Only allow read_file, list_directory should trigger canUseTool
coreTools: ['read_file', 'write_file'],
allowedTools: ['read_file'],
canUseTool: async (toolName) => {
canUseToolCalls.push(toolName);
return {
behavior: 'allow',
updatedInput: {},
};
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Both tools should have been executed
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
// canUseTool should have been called for write_file (not in allowedTools)
// but NOT for read_file (in allowedTools)
expect(canUseToolCalls).toContain('write_file');
expect(canUseToolCalls).not.toContain('read_file');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should work with permissionMode: auto-edit',
async () => {
await helper.createFile('test.txt', 'test');
const canUseToolCalls: string[] = [];
const q = query({
prompt: 'Read test.txt, write "new" to it, and list the directory.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'auto-edit',
// Allow list_directory in addition to auto-approved edit tools
allowedTools: ['list_directory'],
canUseTool: async (toolName) => {
canUseToolCalls.push(toolName);
return {
behavior: 'deny',
message: 'Should not be called',
};
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// All tools should have been executed
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
expect(toolNames).toContain('list_directory');
// canUseTool should NOT have been called
// (edit tools auto-approved, list_directory in allowedTools)
expect(canUseToolCalls.length).toBe(0);
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
});
describe('Combined tool control scenarios', () => {
it(
'should work with coreTools + allowedTools',
async () => {
await helper.createFile('test.txt', 'test');
const q = query({
prompt: 'Read test.txt and write "modified" to it.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
// Limit to specific tools
coreTools: ['read_file', 'write_file', 'list_directory'],
// Auto-approve write operations
allowedTools: ['write_file'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should use allowed tools from coreTools
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
// Should NOT use tools outside coreTools
expect(toolNames).not.toContain('run_shell_command');
// Verify file was modified
const content = await helper.readFile('test.txt');
expect(content).toContain('modified');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should work with coreTools + excludeTools',
async () => {
await helper.createFile('test.txt', 'test');
const q = query({
prompt:
'Read test.txt, write "new content" to it, and list directory.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Allow file operations
coreTools: ['read_file', 'write_file', 'edit', 'list_directory'],
// But exclude edit
excludeTools: ['edit'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should use non-excluded tools from coreTools
expect(toolNames).toContain('read_file');
// Should NOT use excluded tool
expect(toolNames).not.toContain('edit');
// File should still exist
expect(helper.fileExists('test.txt')).toBe(true);
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should work with all three parameters together',
async () => {
await helper.createFile('test.txt', 'test');
const canUseToolCalls: string[] = [];
const q = query({
prompt:
'Read test.txt, write "modified" to it, and list the directory.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'default',
// Limit available tools
coreTools: ['read_file', 'write_file', 'list_directory', 'edit'],
// Block edit
excludeTools: ['edit'],
// Auto-approve write
allowedTools: ['write_file'],
canUseTool: async (toolName) => {
canUseToolCalls.push(toolName);
return {
behavior: 'allow',
updatedInput: {},
};
},
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should use allowed tools
expect(toolNames).toContain('read_file');
expect(toolNames).toContain('write_file');
// Should NOT use excluded tool
expect(toolNames).not.toContain('edit');
// canUseTool should be called for tools not in allowedTools
// but should NOT be called for write_file (in allowedTools)
expect(canUseToolCalls).not.toContain('write_file');
// Verify file was modified
const content = await helper.readFile('test.txt');
expect(content).toContain('modified');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
});
describe('Edge cases and error handling', () => {
it(
'should handle non-existent tool names in excludeTools',
async () => {
await helper.createFile('test.txt', 'test');
const q = query({
prompt: 'Read test.txt.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Non-existent tool names should be ignored
excludeTools: ['non_existent_tool', 'another_fake_tool'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should work normally
expect(toolNames).toContain('read_file');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
it(
'should handle non-existent tool names in allowedTools',
async () => {
await helper.createFile('test.txt', 'test');
const q = query({
prompt: 'Read test.txt.',
options: {
...SHARED_TEST_OPTIONS,
cwd: testDir,
permissionMode: 'yolo',
// Non-existent tool names should be ignored
allowedTools: ['non_existent_tool', 'read_file'],
debug: false,
},
});
const messages: SDKMessage[] = [];
try {
for await (const message of q) {
messages.push(message);
}
const toolCalls = findToolCalls(messages);
const toolNames = toolCalls.map((tc) => tc.toolUse.name);
// Should work normally
expect(toolNames).toContain('read_file');
} finally {
await q.close();
}
},
TEST_TIMEOUT,
);
});
});

View File

@@ -213,7 +213,7 @@ describe('simple-mcp-server', () => {
it('should add two numbers', async () => {
// Test directory is already set up in before hook
// Just run the command - MCP server config is in settings.json
const output = await rig.run('add 5 and 10');
const output = await rig.run('add 5 and 10, use tool if you can.');
const foundToolCall = await rig.waitForToolCall('add');

View File

@@ -9,7 +9,6 @@ import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { env } from 'node:process';
import { DEFAULT_QWEN_MODEL } from '../packages/core/src/config/models.js';
import fs from 'node:fs';
import { EOL } from 'node:os';
import * as pty from '@lydell/node-pty';
@@ -182,7 +181,6 @@ export class TestRig {
otlpEndpoint: '',
outfile: telemetryPath,
},
model: DEFAULT_QWEN_MODEL,
sandbox: env.GEMINI_SANDBOX !== 'false' ? env.GEMINI_SANDBOX : false,
...options.settings, // Allow tests to override/add settings
};
@@ -342,7 +340,8 @@ export class TestRig {
// as it would corrupt the JSON
const isJsonOutput =
commandArgs.includes('--output-format') &&
commandArgs.includes('json');
(commandArgs.includes('json') ||
commandArgs.includes('stream-json'));
// If we have stderr output and it's not a JSON test, include that also
if (stderr && !isJsonOutput) {
@@ -351,7 +350,23 @@ export class TestRig {
resolve(result);
} else {
reject(new Error(`Process exited with code ${code}:\n${stderr}`));
// Check if this is a JSON output test - for JSON errors, the error is in stdout
const isJsonOutputOnError =
commandArgs.includes('--output-format') &&
(commandArgs.includes('json') ||
commandArgs.includes('stream-json'));
// For JSON output tests, include stdout in the error message
// as the error JSON is written to stdout
if (isJsonOutputOnError && stdout) {
reject(
new Error(
`Process exited with code ${code}:\nStdout:\n${stdout}\n\nStderr:\n${stderr}`,
),
);
} else {
reject(new Error(`Process exited with code ${code}:\n${stderr}`));
}
}
});
});

View File

@@ -2,7 +2,11 @@
"extends": "../tsconfig.json",
"compilerOptions": {
"noEmit": true,
"allowJs": true
"allowJs": true,
"baseUrl": ".",
"paths": {
"@qwen-code/sdk": ["../packages/sdk-typescript/dist/index.d.ts"]
}
},
"include": ["**/*.ts"],
"references": [{ "path": "../packages/core" }]

View File

@@ -1,12 +1,15 @@
/**
* @license
* Copyright 2025 Google LLC
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { defineConfig } from 'vitest/config';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const timeoutMinutes = Number(process.env.TB_TIMEOUT_MINUTES || '5');
const __dirname = dirname(fileURLToPath(import.meta.url));
const timeoutMinutes = Number(process.env['TB_TIMEOUT_MINUTES'] || '5');
const testTimeoutMs = timeoutMinutes * 60 * 1000;
export default defineConfig({
@@ -25,4 +28,13 @@ export default defineConfig({
},
},
},
resolve: {
alias: {
// Use built SDK bundle for e2e tests
'@qwen-code/sdk': resolve(
__dirname,
'../packages/sdk-typescript/dist/index.mjs',
),
},
},
});

View File

@@ -9,14 +9,53 @@ import { TestRig, printDebugInfo, validateModelOutput } from './test-helper.js';
describe('web_search', () => {
it('should be able to search the web', async () => {
// Skip if Tavily key is not configured
if (!process.env['TAVILY_API_KEY']) {
console.warn('Skipping web search test: TAVILY_API_KEY not set');
// Check if any web search provider is available
const hasTavilyKey = !!process.env['TAVILY_API_KEY'];
const hasGoogleKey =
!!process.env['GOOGLE_API_KEY'] &&
!!process.env['GOOGLE_SEARCH_ENGINE_ID'];
// Skip if no provider is configured
// Note: DashScope provider is automatically available for Qwen OAuth users,
// but we can't easily detect that in tests without actual OAuth credentials
if (!hasTavilyKey && !hasGoogleKey) {
console.warn(
'Skipping web search test: No web search provider configured. ' +
'Set TAVILY_API_KEY or GOOGLE_API_KEY+GOOGLE_SEARCH_ENGINE_ID environment variables.',
);
return;
}
const rig = new TestRig();
await rig.setup('should be able to search the web');
// Configure web search in settings if provider keys are available
const webSearchSettings: Record<string, unknown> = {};
const providers: Array<{
type: string;
apiKey?: string;
searchEngineId?: string;
}> = [];
if (hasTavilyKey) {
providers.push({ type: 'tavily', apiKey: process.env['TAVILY_API_KEY'] });
}
if (hasGoogleKey) {
providers.push({
type: 'google',
apiKey: process.env['GOOGLE_API_KEY'],
searchEngineId: process.env['GOOGLE_SEARCH_ENGINE_ID'],
});
}
if (providers.length > 0) {
webSearchSettings.webSearch = {
provider: providers,
default: providers[0]?.type,
};
}
await rig.setup('should be able to search the web', {
settings: webSearchSettings,
});
let result;
try {

4078
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.1.0",
"version": "0.5.0-preview.0",
"engines": {
"node": ">=20.0.0"
},
@@ -13,7 +13,7 @@
"url": "git+https://github.com/QwenLM/qwen-code.git"
},
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.1.0"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.5.0-preview.0"
},
"scripts": {
"start": "cross-env node scripts/start.js",
@@ -28,7 +28,7 @@
"build:all": "npm run build && npm run build:sandbox && npm run build:vscode",
"build:packages": "npm run build --workspaces",
"build:sandbox": "node scripts/build_sandbox.js",
"bundle": "rm -rf dist && npm run generate && node esbuild.config.js && node scripts/copy_bundle_assets.js",
"bundle": "npm run generate && node esbuild.config.js && node scripts/copy_bundle_assets.js",
"test": "npm run test --workspaces --if-present --parallel",
"test:ci": "npm run test:ci --workspaces --if-present --parallel && npm run test:scripts",
"test:scripts": "vitest run --config ./scripts/tests/vitest.config.ts",
@@ -37,6 +37,10 @@
"test:integration:sandbox:none": "cross-env GEMINI_SANDBOX=false vitest run --root ./integration-tests",
"test:integration:sandbox:docker": "cross-env GEMINI_SANDBOX=docker npm run build:sandbox && GEMINI_SANDBOX=docker vitest run --root ./integration-tests",
"test:integration:sandbox:podman": "cross-env GEMINI_SANDBOX=podman vitest run --root ./integration-tests",
"test:integration:sdk:sandbox:none": "cross-env GEMINI_SANDBOX=false vitest run --root ./integration-tests sdk-typescript",
"test:integration:sdk:sandbox:docker": "cross-env GEMINI_SANDBOX=docker npm run build:sandbox && GEMINI_SANDBOX=docker vitest run --root ./integration-tests sdk-typescript",
"test:integration:cli:sandbox:none": "cross-env GEMINI_SANDBOX=false vitest run --root ./integration-tests --exclude '**/sdk-typescript/**'",
"test:integration:cli:sandbox:docker": "cross-env GEMINI_SANDBOX=docker npm run build:sandbox && GEMINI_SANDBOX=docker vitest run --root ./integration-tests --exclude '**/sdk-typescript/**'",
"test:terminal-bench": "cross-env VERBOSE=true KEEP_OUTPUT=true vitest run --config ./vitest.terminal-bench.config.ts --root ./integration-tests",
"test:terminal-bench:oracle": "cross-env VERBOSE=true KEEP_OUTPUT=true vitest run --config ./vitest.terminal-bench.config.ts --root ./integration-tests -t 'oracle'",
"test:terminal-bench:qwen": "cross-env VERBOSE=true KEEP_OUTPUT=true vitest run --config ./vitest.terminal-bench.config.ts --root ./integration-tests -t 'qwen'",
@@ -46,6 +50,7 @@
"lint:all": "node scripts/lint.js",
"format": "prettier --experimental-cli --write .",
"typecheck": "npm run typecheck --workspaces --if-present",
"check-i18n": "npm run check-i18n --workspace=packages/cli",
"preflight": "npm run clean && npm ci && npm run format && npm run lint:ci && npm run build && npm run typecheck && npm run test:ci",
"prepare": "husky && npm run bundle",
"prepare:package": "node scripts/prepare-package.js",
@@ -88,7 +93,7 @@
"eslint-plugin-license-header": "^0.8.0",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
"glob": "^10.4.5",
"glob": "^10.5.0",
"globals": "^16.0.0",
"google-artifactregistry-auth": "^3.4.0",
"husky": "^9.1.7",

View File

@@ -1,6 +1,6 @@
{
"name": "@qwen-code/qwen-code",
"version": "0.1.0",
"version": "0.5.0-preview.0",
"description": "Qwen Code",
"repository": {
"type": "git",
@@ -8,9 +8,16 @@
},
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"qwen": "dist/index.js"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "node ../../scripts/build_package.js",
"start": "node dist/index.js",
@@ -19,13 +26,14 @@
"format": "prettier --write .",
"test": "vitest run",
"test:ci": "vitest run",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"check-i18n": "tsx ../../scripts/check-i18n.ts"
},
"files": [
"dist"
],
"config": {
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.1.0"
"sandboxImageUri": "ghcr.io/qwenlm/qwen-code:0.5.0-preview.0"
},
"dependencies": {
"@google/genai": "1.16.0",
@@ -39,7 +47,7 @@
"diff": "^7.0.0",
"dotenv": "^17.1.0",
"fzf": "^0.5.2",
"glob": "^10.4.5",
"glob": "^10.5.0",
"highlight.js": "^11.11.1",
"ink": "^6.2.3",
"ink-gradient": "^3.0.0",
@@ -55,7 +63,7 @@
"string-width": "^7.1.0",
"strip-ansi": "^7.1.0",
"strip-json-comments": "^3.1.1",
"tar": "^7.5.1",
"tar": "^7.5.2",
"undici": "^7.10.0",
"extract-zip": "^2.0.1",
"update-notifier": "^7.3.1",

View File

@@ -7,7 +7,6 @@
/* ACP defines a schema for a simple (experimental) JSON-RPC protocol that allows GUI applications to interact with agents. */
import { z } from 'zod';
import { EOL } from 'node:os';
import * as schema from './schema.js';
export * from './schema.js';
@@ -43,6 +42,14 @@ export class AgentSideConnection implements Client {
const validatedParams = schema.loadSessionRequestSchema.parse(params);
return agent.loadSession(validatedParams);
}
case schema.AGENT_METHODS.session_list: {
if (!agent.listSessions) {
throw RequestError.methodNotFound();
}
const validatedParams =
schema.listSessionsRequestSchema.parse(params);
return agent.listSessions(validatedParams);
}
case schema.AGENT_METHODS.authenticate: {
const validatedParams =
schema.authenticateRequestSchema.parse(params);
@@ -56,6 +63,13 @@ export class AgentSideConnection implements Client {
const validatedParams = schema.cancelNotificationSchema.parse(params);
return agent.cancel(validatedParams);
}
case schema.AGENT_METHODS.session_set_mode: {
if (!agent.setMode) {
throw RequestError.methodNotFound();
}
const validatedParams = schema.setModeRequestSchema.parse(params);
return agent.setMode(validatedParams);
}
default:
throw RequestError.methodNotFound(method);
}
@@ -74,6 +88,16 @@ export class AgentSideConnection implements Client {
);
}
/**
* Streams authentication updates (e.g. Qwen OAuth authUri) to the client.
*/
async authenticateUpdate(params: schema.AuthenticateUpdate): Promise<void> {
return await this.#connection.sendNotification(
schema.CLIENT_METHODS.authenticate_update,
params,
);
}
/**
* Request permission before running a tool
*
@@ -173,7 +197,7 @@ class Connection {
const decoder = new TextDecoder();
for await (const chunk of output) {
content += decoder.decode(chunk, { stream: true });
const lines = content.split(EOL);
const lines = content.split('\n');
content = lines.pop() || '';
for (const line of lines) {
@@ -227,9 +251,11 @@ class Connection {
).toResult();
}
let errorName;
let details;
if (error instanceof Error) {
errorName = error.name;
details = error.message;
} else if (
typeof error === 'object' &&
@@ -240,6 +266,10 @@ class Connection {
details = error.message;
}
if (errorName === 'TokenManagerError') {
return RequestError.authRequired(details).toResult();
}
return RequestError.internalError(details).toResult();
}
}
@@ -343,6 +373,7 @@ export interface Client {
params: schema.RequestPermissionRequest,
): Promise<schema.RequestPermissionResponse>;
sessionUpdate(params: schema.SessionNotification): Promise<void>;
authenticateUpdate(params: schema.AuthenticateUpdate): Promise<void>;
writeTextFile(
params: schema.WriteTextFileRequest,
): Promise<schema.WriteTextFileResponse>;
@@ -361,7 +392,11 @@ export interface Agent {
loadSession?(
params: schema.LoadSessionRequest,
): Promise<schema.LoadSessionResponse>;
listSessions?(
params: schema.ListSessionsRequest,
): Promise<schema.ListSessionsResponse>;
authenticate(params: schema.AuthenticateRequest): Promise<void>;
prompt(params: schema.PromptRequest): Promise<schema.PromptResponse>;
cancel(params: schema.CancelNotification): Promise<void>;
setMode?(params: schema.SetModeRequest): Promise<schema.SetModeResponse>;
}

View File

@@ -0,0 +1,354 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { ReadableStream, WritableStream } from 'node:stream/web';
import {
APPROVAL_MODE_INFO,
APPROVAL_MODES,
AuthType,
clearCachedCredentialFile,
QwenOAuth2Event,
qwenOAuth2Events,
MCPServerConfig,
SessionService,
buildApiHistoryFromConversation,
type Config,
type ConversationRecord,
type DeviceAuthorizationData,
} from '@qwen-code/qwen-code-core';
import type { ApprovalModeValue } from './schema.js';
import * as acp from './acp.js';
import { AcpFileSystemService } from './service/filesystem.js';
import { Readable, Writable } from 'node:stream';
import type { LoadedSettings } from '../config/settings.js';
import { SettingScope } from '../config/settings.js';
import { z } from 'zod';
import { ExtensionStorage, type Extension } from '../config/extension.js';
import type { CliArgs } from '../config/config.js';
import { loadCliConfig } from '../config/config.js';
import { ExtensionEnablementManager } from '../config/extensions/extensionEnablement.js';
// Import the modular Session class
import { Session } from './session/Session.js';
export async function runAcpAgent(
config: Config,
settings: LoadedSettings,
extensions: Extension[],
argv: CliArgs,
) {
const stdout = Writable.toWeb(process.stdout) as WritableStream;
const stdin = Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>;
// Stdout is used to send messages to the client, so console.log/console.info
// messages to stderr so that they don't interfere with ACP.
console.log = console.error;
console.info = console.error;
console.debug = console.error;
new acp.AgentSideConnection(
(client: acp.Client) =>
new GeminiAgent(config, settings, extensions, argv, client),
stdout,
stdin,
);
}
class GeminiAgent {
private sessions: Map<string, Session> = new Map();
private clientCapabilities: acp.ClientCapabilities | undefined;
constructor(
private config: Config,
private settings: LoadedSettings,
private extensions: Extension[],
private argv: CliArgs,
private client: acp.Client,
) {}
async initialize(
args: acp.InitializeRequest,
): Promise<acp.InitializeResponse> {
this.clientCapabilities = args.clientCapabilities;
const authMethods = [
{
id: AuthType.USE_OPENAI,
name: 'Use OpenAI API key',
description:
'Requires setting the `OPENAI_API_KEY` environment variable',
},
{
id: AuthType.QWEN_OAUTH,
name: 'Qwen OAuth',
description:
'OAuth authentication for Qwen models with 2000 daily requests',
},
];
// Get current approval mode from config
const currentApprovalMode = this.config.getApprovalMode();
// Build available modes from shared APPROVAL_MODE_INFO
const availableModes = APPROVAL_MODES.map((mode) => ({
id: mode as ApprovalModeValue,
name: APPROVAL_MODE_INFO[mode].name,
description: APPROVAL_MODE_INFO[mode].description,
}));
const version = process.env['CLI_VERSION'] || process.version;
return {
protocolVersion: acp.PROTOCOL_VERSION,
agentInfo: {
name: 'qwen-code',
title: 'Qwen Code',
version,
},
authMethods,
modes: {
currentModeId: currentApprovalMode as ApprovalModeValue,
availableModes,
},
agentCapabilities: {
loadSession: true,
promptCapabilities: {
image: true,
audio: true,
embeddedContext: true,
},
},
};
}
async authenticate({ methodId }: acp.AuthenticateRequest): Promise<void> {
const method = z.nativeEnum(AuthType).parse(methodId);
let authUri: string | undefined;
const authUriHandler = (deviceAuth: DeviceAuthorizationData) => {
authUri = deviceAuth.verification_uri_complete;
// Send the auth URL to ACP client as soon as it's available (refreshAuth is blocking).
void this.client.authenticateUpdate({ _meta: { authUri } });
};
if (method === AuthType.QWEN_OAUTH) {
qwenOAuth2Events.once(QwenOAuth2Event.AuthUri, authUriHandler);
}
await clearCachedCredentialFile();
try {
await this.config.refreshAuth(method);
this.settings.setValue(
SettingScope.User,
'security.auth.selectedType',
method,
);
} finally {
// Ensure we don't leak listeners if auth fails early.
if (method === AuthType.QWEN_OAUTH) {
qwenOAuth2Events.off(QwenOAuth2Event.AuthUri, authUriHandler);
}
}
return;
}
async newSession({
cwd,
mcpServers,
}: acp.NewSessionRequest): Promise<acp.NewSessionResponse> {
const config = await this.newSessionConfig(cwd, mcpServers);
await this.ensureAuthenticated(config);
this.setupFileSystem(config);
const session = await this.createAndStoreSession(config);
return {
sessionId: session.getId(),
};
}
async newSessionConfig(
cwd: string,
mcpServers: acp.McpServer[],
sessionId?: string,
): Promise<Config> {
const mergedMcpServers = { ...this.settings.merged.mcpServers };
for (const { command, args, env: rawEnv, name } of mcpServers) {
const env: Record<string, string> = {};
for (const { name: envName, value } of rawEnv) {
env[envName] = value;
}
mergedMcpServers[name] = new MCPServerConfig(command, args, env, cwd);
}
const settings = { ...this.settings.merged, mcpServers: mergedMcpServers };
const argvForSession = {
...this.argv,
resume: sessionId,
continue: false,
};
const config = await loadCliConfig(
settings,
this.extensions,
new ExtensionEnablementManager(
ExtensionStorage.getUserExtensionsDir(),
this.argv.extensions,
),
argvForSession,
cwd,
);
await config.initialize();
return config;
}
async cancel(params: acp.CancelNotification): Promise<void> {
const session = this.sessions.get(params.sessionId);
if (!session) {
throw new Error(`Session not found: ${params.sessionId}`);
}
await session.cancelPendingPrompt();
}
async prompt(params: acp.PromptRequest): Promise<acp.PromptResponse> {
const session = this.sessions.get(params.sessionId);
if (!session) {
throw new Error(`Session not found: ${params.sessionId}`);
}
return session.prompt(params);
}
async loadSession(
params: acp.LoadSessionRequest,
): Promise<acp.LoadSessionResponse> {
const sessionService = new SessionService(params.cwd);
const exists = await sessionService.sessionExists(params.sessionId);
if (!exists) {
throw acp.RequestError.invalidParams(
`Session not found for id: ${params.sessionId}`,
);
}
const config = await this.newSessionConfig(
params.cwd,
params.mcpServers,
params.sessionId,
);
await this.ensureAuthenticated(config);
this.setupFileSystem(config);
const sessionData = config.getResumedSessionData();
if (!sessionData) {
throw acp.RequestError.internalError(
`Failed to load session data for id: ${params.sessionId}`,
);
}
await this.createAndStoreSession(config, sessionData.conversation);
return null;
}
async listSessions(
params: acp.ListSessionsRequest,
): Promise<acp.ListSessionsResponse> {
const sessionService = new SessionService(params.cwd);
const result = await sessionService.listSessions({
cursor: params.cursor,
size: params.size,
});
return {
items: result.items.map((item) => ({
sessionId: item.sessionId,
cwd: item.cwd,
startTime: item.startTime,
mtime: item.mtime,
prompt: item.prompt,
gitBranch: item.gitBranch,
filePath: item.filePath,
messageCount: item.messageCount,
})),
nextCursor: result.nextCursor,
hasMore: result.hasMore,
};
}
async setMode(params: acp.SetModeRequest): Promise<acp.SetModeResponse> {
const session = this.sessions.get(params.sessionId);
if (!session) {
throw new Error(`Session not found: ${params.sessionId}`);
}
return session.setMode(params);
}
private async ensureAuthenticated(config: Config): Promise<void> {
const selectedType = this.settings.merged.security?.auth?.selectedType;
if (!selectedType) {
throw acp.RequestError.authRequired();
}
try {
// Use true for the second argument to ensure only cached credentials are used
await config.refreshAuth(selectedType, true);
} catch (e) {
console.error(`Authentication failed: ${e}`);
throw acp.RequestError.authRequired();
}
}
private setupFileSystem(config: Config): void {
if (!this.clientCapabilities?.fs) {
return;
}
const acpFileSystemService = new AcpFileSystemService(
this.client,
config.getSessionId(),
this.clientCapabilities.fs,
config.getFileSystemService(),
);
config.setFileSystemService(acpFileSystemService);
}
private async createAndStoreSession(
config: Config,
conversation?: ConversationRecord,
): Promise<Session> {
const sessionId = config.getSessionId();
const geminiClient = config.getGeminiClient();
const history = conversation
? buildApiHistoryFromConversation(conversation)
: undefined;
const chat = history
? await geminiClient.startChat(history)
: await geminiClient.startChat();
const session = new Session(
sessionId,
chat,
config,
this.client,
this.settings,
);
this.sessions.set(sessionId, session);
setTimeout(async () => {
await session.sendAvailableCommandsUpdate();
}, 0);
if (conversation && conversation.messages) {
await session.replayHistory(conversation.messages);
}
return session;
}
}

View File

@@ -13,11 +13,14 @@ export const AGENT_METHODS = {
session_load: 'session/load',
session_new: 'session/new',
session_prompt: 'session/prompt',
session_list: 'session/list',
session_set_mode: 'session/set_mode',
};
export const CLIENT_METHODS = {
fs_read_text_file: 'fs/read_text_file',
fs_write_text_file: 'fs/write_text_file',
authenticate_update: 'authenticate/update',
session_request_permission: 'session/request_permission',
session_update: 'session/update',
};
@@ -47,13 +50,14 @@ export type ReadTextFileResponse = z.infer<typeof readTextFileResponseSchema>;
export type RequestPermissionOutcome = z.infer<
typeof requestPermissionOutcomeSchema
>;
export type SessionListItem = z.infer<typeof sessionListItemSchema>;
export type ListSessionsRequest = z.infer<typeof listSessionsRequestSchema>;
export type ListSessionsResponse = z.infer<typeof listSessionsResponseSchema>;
export type CancelNotification = z.infer<typeof cancelNotificationSchema>;
export type AuthenticateRequest = z.infer<typeof authenticateRequestSchema>;
export type AuthenticateResponse = z.infer<typeof authenticateResponseSchema>;
export type NewSessionResponse = z.infer<typeof newSessionResponseSchema>;
export type LoadSessionResponse = z.infer<typeof loadSessionResponseSchema>;
@@ -84,6 +88,12 @@ export type AgentCapabilities = z.infer<typeof agentCapabilitiesSchema>;
export type AuthMethod = z.infer<typeof authMethodSchema>;
export type ModeInfo = z.infer<typeof modeInfoSchema>;
export type ModesData = z.infer<typeof modesDataSchema>;
export type AgentInfo = z.infer<typeof agentInfoSchema>;
export type PromptCapabilities = z.infer<typeof promptCapabilitiesSchema>;
export type ClientResponse = z.infer<typeof clientResponseSchema>;
@@ -128,6 +138,20 @@ export type AgentRequest = z.infer<typeof agentRequestSchema>;
export type AgentNotification = z.infer<typeof agentNotificationSchema>;
export type ApprovalModeValue = z.infer<typeof approvalModeValueSchema>;
export type SetModeRequest = z.infer<typeof setModeRequestSchema>;
export type SetModeResponse = z.infer<typeof setModeResponseSchema>;
export type AvailableCommandInput = z.infer<typeof availableCommandInputSchema>;
export type AvailableCommand = z.infer<typeof availableCommandSchema>;
export type AvailableCommandsUpdate = z.infer<
typeof availableCommandsUpdateSchema
>;
export const writeTextFileRequestSchema = z.object({
content: z.string(),
path: z.string(),
@@ -171,6 +195,7 @@ export const toolKindSchema = z.union([
z.literal('execute'),
z.literal('think'),
z.literal('fetch'),
z.literal('switch_mode'),
z.literal('other'),
]);
@@ -201,11 +226,33 @@ export const cancelNotificationSchema = z.object({
sessionId: z.string(),
});
export const approvalModeValueSchema = z.union([
z.literal('plan'),
z.literal('default'),
z.literal('auto-edit'),
z.literal('yolo'),
]);
export const setModeRequestSchema = z.object({
sessionId: z.string(),
modeId: approvalModeValueSchema,
});
export const setModeResponseSchema = z.object({
modeId: approvalModeValueSchema,
});
export const authenticateRequestSchema = z.object({
methodId: z.string(),
});
export const authenticateResponseSchema = z.null();
export const authenticateUpdateSchema = z.object({
_meta: z.object({
authUri: z.string(),
}),
});
export type AuthenticateUpdate = z.infer<typeof authenticateUpdateSchema>;
export const newSessionResponseSchema = z.object({
sessionId: z.string(),
@@ -213,6 +260,29 @@ export const newSessionResponseSchema = z.object({
export const loadSessionResponseSchema = z.null();
export const sessionListItemSchema = z.object({
cwd: z.string(),
filePath: z.string(),
gitBranch: z.string().optional(),
messageCount: z.number(),
mtime: z.number(),
prompt: z.string(),
sessionId: z.string(),
startTime: z.string(),
});
export const listSessionsResponseSchema = z.object({
hasMore: z.boolean(),
items: z.array(sessionListItemSchema),
nextCursor: z.number().optional(),
});
export const listSessionsRequestSchema = z.object({
cursor: z.number().optional(),
cwd: z.string(),
size: z.number().optional(),
});
export const stopReasonSchema = z.union([
z.literal('end_turn'),
z.literal('max_tokens'),
@@ -251,6 +321,23 @@ export const annotationsSchema = z.object({
priority: z.number().optional().nullable(),
});
export const usageSchema = z.object({
promptTokens: z.number().optional().nullable(),
completionTokens: z.number().optional().nullable(),
thoughtsTokens: z.number().optional().nullable(),
totalTokens: z.number().optional().nullable(),
cachedTokens: z.number().optional().nullable(),
});
export type Usage = z.infer<typeof usageSchema>;
export const sessionUpdateMetaSchema = z.object({
usage: usageSchema.optional().nullable(),
durationMs: z.number().optional().nullable(),
});
export type SessionUpdateMeta = z.infer<typeof sessionUpdateMetaSchema>;
export const requestPermissionResponseSchema = z.object({
outcome: requestPermissionOutcomeSchema,
});
@@ -313,9 +400,28 @@ export const loadSessionRequestSchema = z.object({
sessionId: z.string(),
});
export const modeInfoSchema = z.object({
id: approvalModeValueSchema,
name: z.string(),
description: z.string(),
});
export const modesDataSchema = z.object({
currentModeId: approvalModeValueSchema,
availableModes: z.array(modeInfoSchema),
});
export const agentInfoSchema = z.object({
name: z.string(),
title: z.string(),
version: z.string(),
});
export const initializeResponseSchema = z.object({
agentCapabilities: agentCapabilitiesSchema,
agentInfo: agentInfoSchema,
authMethods: z.array(authMethodSchema),
modes: modesDataSchema,
protocolVersion: z.number(),
});
@@ -386,6 +492,28 @@ export const promptRequestSchema = z.object({
sessionId: z.string(),
});
export const availableCommandInputSchema = z.object({
hint: z.string(),
});
export const availableCommandSchema = z.object({
description: z.string(),
input: availableCommandInputSchema.nullable().optional(),
name: z.string(),
});
export const availableCommandsUpdateSchema = z.object({
availableCommands: z.array(availableCommandSchema),
sessionUpdate: z.literal('available_commands_update'),
});
export const currentModeUpdateSchema = z.object({
sessionUpdate: z.literal('current_mode_update'),
modeId: approvalModeValueSchema,
});
export type CurrentModeUpdate = z.infer<typeof currentModeUpdateSchema>;
export const sessionUpdateSchema = z.union([
z.object({
content: contentBlockSchema,
@@ -394,10 +522,12 @@ export const sessionUpdateSchema = z.union([
z.object({
content: contentBlockSchema,
sessionUpdate: z.literal('agent_message_chunk'),
_meta: sessionUpdateMetaSchema.optional().nullable(),
}),
z.object({
content: contentBlockSchema,
sessionUpdate: z.literal('agent_thought_chunk'),
_meta: sessionUpdateMetaSchema.optional().nullable(),
}),
z.object({
content: z.array(toolCallContentSchema).optional(),
@@ -414,6 +544,7 @@ export const sessionUpdateSchema = z.union([
kind: toolKindSchema.optional().nullable(),
locations: z.array(toolCallLocationSchema).optional().nullable(),
rawInput: z.unknown().optional(),
rawOutput: z.unknown().optional(),
sessionUpdate: z.literal('tool_call_update'),
status: toolCallStatusSchema.optional().nullable(),
title: z.string().optional().nullable(),
@@ -423,14 +554,17 @@ export const sessionUpdateSchema = z.union([
entries: z.array(planEntrySchema),
sessionUpdate: z.literal('plan'),
}),
currentModeUpdateSchema,
availableCommandsUpdateSchema,
]);
export const agentResponseSchema = z.union([
initializeResponseSchema,
authenticateResponseSchema,
newSessionResponseSchema,
loadSessionResponseSchema,
promptResponseSchema,
listSessionsResponseSchema,
setModeResponseSchema,
]);
export const requestPermissionRequestSchema = z.object({
@@ -461,6 +595,8 @@ export const agentRequestSchema = z.union([
newSessionRequestSchema,
loadSessionRequestSchema,
promptRequestSchema,
listSessionsRequestSchema,
setModeRequestSchema,
]);
export const agentNotificationSchema = sessionNotificationSchema;

View File

@@ -0,0 +1,59 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, expect, it, vi } from 'vitest';
import type { FileSystemService } from '@qwen-code/qwen-code-core';
import { AcpFileSystemService } from './filesystem.js';
const createFallback = (): FileSystemService => ({
readTextFile: vi.fn(),
writeTextFile: vi.fn(),
findFiles: vi.fn().mockReturnValue([]),
});
describe('AcpFileSystemService', () => {
describe('readTextFile ENOENT handling', () => {
it('parses path from ACP ENOENT message (quoted)', async () => {
const client = {
readTextFile: vi
.fn()
.mockResolvedValue({ content: 'ERROR: ENOENT: "/remote/file.txt"' }),
} as unknown as import('../acp.js').Client;
const svc = new AcpFileSystemService(
client,
'session-1',
{ readTextFile: true, writeTextFile: true },
createFallback(),
);
await expect(svc.readTextFile('/local/file.txt')).rejects.toMatchObject({
code: 'ENOENT',
path: '/remote/file.txt',
});
});
it('falls back to requested path when none provided', async () => {
const client = {
readTextFile: vi.fn().mockResolvedValue({ content: 'ERROR: ENOENT:' }),
} as unknown as import('../acp.js').Client;
const svc = new AcpFileSystemService(
client,
'session-2',
{ readTextFile: true, writeTextFile: true },
createFallback(),
);
await expect(
svc.readTextFile('/fallback/path.txt'),
).rejects.toMatchObject({
code: 'ENOENT',
path: '/fallback/path.txt',
});
});
});
});

View File

@@ -5,7 +5,7 @@
*/
import type { FileSystemService } from '@qwen-code/qwen-code-core';
import type * as acp from './acp.js';
import type * as acp from '../acp.js';
/**
* ACP client-based implementation of FileSystemService
@@ -30,6 +30,20 @@ export class AcpFileSystemService implements FileSystemService {
limit: null,
});
if (response.content.startsWith('ERROR: ENOENT:')) {
// Treat ACP error strings as structured ENOENT errors without
// assuming a specific platform format.
const match = /^ERROR:\s*ENOENT:\s*(?<path>.*)$/i.exec(response.content);
const err = new Error(response.content) as NodeJS.ErrnoException;
err.code = 'ENOENT';
err.errno = -2;
const rawPath = match?.groups?.['path']?.trim();
err['path'] = rawPath
? rawPath.replace(/^['"]|['"]$/g, '') || filePath
: filePath;
throw err;
}
return response.content;
}

View File

@@ -0,0 +1,458 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HistoryReplayer } from './HistoryReplayer.js';
import type { SessionContext } from './types.js';
import type {
Config,
ChatRecord,
ToolRegistry,
ToolResultDisplay,
TodoResultDisplay,
} from '@qwen-code/qwen-code-core';
describe('HistoryReplayer', () => {
let mockContext: SessionContext;
let sendUpdateSpy: ReturnType<typeof vi.fn>;
let replayer: HistoryReplayer;
beforeEach(() => {
sendUpdateSpy = vi.fn().mockResolvedValue(undefined);
const mockToolRegistry = {
getTool: vi.fn().mockReturnValue(null),
} as unknown as ToolRegistry;
mockContext = {
sessionId: 'test-session-id',
config: {
getToolRegistry: () => mockToolRegistry,
} as unknown as Config,
sendUpdate: sendUpdateSpy,
};
replayer = new HistoryReplayer(mockContext);
});
const createUserRecord = (text: string): ChatRecord => ({
uuid: 'user-uuid',
parentUuid: null,
sessionId: 'test-session',
timestamp: new Date().toISOString(),
type: 'user',
cwd: '/test',
version: '1.0.0',
message: {
role: 'user',
parts: [{ text }],
},
});
const createAssistantRecord = (
text: string,
thought = false,
): ChatRecord => ({
uuid: 'assistant-uuid',
parentUuid: 'user-uuid',
sessionId: 'test-session',
timestamp: new Date().toISOString(),
type: 'assistant',
cwd: '/test',
version: '1.0.0',
message: {
role: 'model',
parts: [{ text, thought }],
},
});
const createToolResultRecord = (
toolName: string,
resultDisplay?: ToolResultDisplay,
hasError = false,
): ChatRecord => ({
uuid: 'tool-uuid',
parentUuid: 'assistant-uuid',
sessionId: 'test-session',
timestamp: new Date().toISOString(),
type: 'tool_result',
cwd: '/test',
version: '1.0.0',
message: {
role: 'user',
parts: [
{
functionResponse: {
name: toolName,
response: { result: 'ok' },
},
},
],
},
toolCallResult: {
callId: 'call-123',
responseParts: [],
resultDisplay,
error: hasError ? new Error('Tool failed') : undefined,
errorType: undefined,
},
});
describe('replay', () => {
it('should replay empty records array', async () => {
await replayer.replay([]);
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
it('should replay records in order', async () => {
const records = [
createUserRecord('Hello'),
createAssistantRecord('Hi there'),
];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledTimes(2);
expect(sendUpdateSpy.mock.calls[0][0].sessionUpdate).toBe(
'user_message_chunk',
);
expect(sendUpdateSpy.mock.calls[1][0].sessionUpdate).toBe(
'agent_message_chunk',
);
});
});
describe('user message replay', () => {
it('should emit user_message_chunk for user records', async () => {
const records = [createUserRecord('Hello, world!')];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'Hello, world!' },
});
});
it('should skip user records without message', async () => {
const record: ChatRecord = {
...createUserRecord('test'),
message: undefined,
};
await replayer.replay([record]);
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
});
describe('assistant message replay', () => {
it('should emit agent_message_chunk for assistant records', async () => {
const records = [createAssistantRecord('I can help with that.')];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'I can help with that.' },
});
});
it('should emit agent_thought_chunk for thought parts', async () => {
const records = [createAssistantRecord('Thinking about this...', true)];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Thinking about this...' },
});
});
it('should handle assistant records with multiple parts', async () => {
const record: ChatRecord = {
...createAssistantRecord('First'),
message: {
role: 'model',
parts: [
{ text: 'First part' },
{ text: 'Second part', thought: true },
{ text: 'Third part' },
],
},
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledTimes(3);
expect(sendUpdateSpy.mock.calls[0][0]).toEqual({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'First part' },
});
expect(sendUpdateSpy.mock.calls[1][0]).toEqual({
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Second part' },
});
expect(sendUpdateSpy.mock.calls[2][0]).toEqual({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'Third part' },
});
});
});
describe('function call replay', () => {
it('should emit tool_call for function call parts', async () => {
const record: ChatRecord = {
...createAssistantRecord(''),
message: {
role: 'model',
parts: [
{
functionCall: {
name: 'read_file',
args: { path: '/test.ts' },
},
},
],
},
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call',
status: 'in_progress',
title: 'read_file',
rawInput: { path: '/test.ts' },
}),
);
});
it('should use function call id as callId when available', async () => {
const record: ChatRecord = {
...createAssistantRecord(''),
message: {
role: 'model',
parts: [
{
functionCall: {
id: 'custom-call-id',
name: 'read_file',
args: {},
},
},
],
},
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
toolCallId: 'custom-call-id',
}),
);
});
});
describe('tool result replay', () => {
it('should emit tool_call_update for tool result records', async () => {
const records = [
createToolResultRecord('read_file', 'File contents here'),
];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'completed',
content: [
{
type: 'content',
// Content comes from functionResponse.response (stringified)
content: { type: 'text', text: '{"result":"ok"}' },
},
],
// resultDisplay is included as rawOutput
rawOutput: 'File contents here',
});
});
it('should emit failed status for tool results with errors', async () => {
const records = [createToolResultRecord('failing_tool', undefined, true)];
await replayer.replay(records);
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
status: 'failed',
}),
);
});
it('should emit plan update for TodoWriteTool results', async () => {
const todoDisplay: TodoResultDisplay = {
type: 'todo_list',
todos: [
{ id: '1', content: 'Task 1', status: 'pending' },
{ id: '2', content: 'Task 2', status: 'completed' },
],
};
const record = createToolResultRecord('todo_write', todoDisplay);
// Override the function response name
record.message = {
role: 'user',
parts: [
{
functionResponse: {
name: 'todo_write',
response: { result: 'ok' },
},
},
],
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [
{ content: 'Task 1', priority: 'medium', status: 'pending' },
{ content: 'Task 2', priority: 'medium', status: 'completed' },
],
});
});
it('should use record uuid as callId when toolCallResult.callId is missing', async () => {
const record: ChatRecord = {
...createToolResultRecord('test_tool'),
uuid: 'fallback-uuid',
toolCallResult: {
callId: undefined as unknown as string,
responseParts: [],
resultDisplay: 'Result',
error: undefined,
errorType: undefined,
},
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
toolCallId: 'fallback-uuid',
}),
);
});
});
describe('system records', () => {
it('should skip system records', async () => {
const systemRecord: ChatRecord = {
uuid: 'system-uuid',
parentUuid: null,
sessionId: 'test-session',
timestamp: new Date().toISOString(),
type: 'system',
subtype: 'chat_compression',
cwd: '/test',
version: '1.0.0',
};
await replayer.replay([systemRecord]);
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
});
describe('mixed record types', () => {
it('should handle a complete conversation replay', async () => {
const records: ChatRecord[] = [
createUserRecord('Read the file test.ts'),
{
...createAssistantRecord(''),
message: {
role: 'model',
parts: [
{ text: "I'll read that file for you.", thought: true },
{
functionCall: {
id: 'call-read',
name: 'read_file',
args: { path: 'test.ts' },
},
},
],
},
},
createToolResultRecord('read_file', 'export const x = 1;'),
createAssistantRecord('The file contains a simple export.'),
];
await replayer.replay(records);
// Verify order and types of updates
const updateTypes = sendUpdateSpy.mock.calls.map(
(call: unknown[]) =>
(call[0] as { sessionUpdate: string }).sessionUpdate,
);
expect(updateTypes).toEqual([
'user_message_chunk',
'agent_thought_chunk',
'tool_call',
'tool_call_update',
'agent_message_chunk',
]);
});
});
describe('usage metadata replay', () => {
it('should emit usage metadata after assistant message content', async () => {
const record: ChatRecord = {
uuid: 'assistant-uuid',
parentUuid: 'user-uuid',
sessionId: 'test-session',
timestamp: new Date().toISOString(),
type: 'assistant',
cwd: '/test',
version: '1.0.0',
message: {
role: 'model',
parts: [{ text: 'Hello!' }],
},
usageMetadata: {
promptTokenCount: 100,
candidatesTokenCount: 50,
totalTokenCount: 150,
},
};
await replayer.replay([record]);
expect(sendUpdateSpy).toHaveBeenCalledTimes(2);
expect(sendUpdateSpy).toHaveBeenNthCalledWith(1, {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'Hello!' },
});
expect(sendUpdateSpy).toHaveBeenNthCalledWith(2, {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: '' },
_meta: {
usage: {
promptTokens: 100,
completionTokens: 50,
thoughtsTokens: undefined,
totalTokens: 150,
cachedTokens: undefined,
},
},
});
});
});
});

View File

@@ -0,0 +1,202 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { ChatRecord, TaskResultDisplay } from '@qwen-code/qwen-code-core';
import type {
Content,
GenerateContentResponseUsageMetadata,
} from '@google/genai';
import type { SessionContext } from './types.js';
import { MessageEmitter } from './emitters/MessageEmitter.js';
import { ToolCallEmitter } from './emitters/ToolCallEmitter.js';
/**
* Handles replaying session history on session load.
*
* Uses the unified emitters to ensure consistency with normal flow.
* This ensures that replayed history looks identical to how it would
* have appeared during the original session.
*/
export class HistoryReplayer {
private readonly messageEmitter: MessageEmitter;
private readonly toolCallEmitter: ToolCallEmitter;
constructor(ctx: SessionContext) {
this.messageEmitter = new MessageEmitter(ctx);
this.toolCallEmitter = new ToolCallEmitter(ctx);
}
/**
* Replays all chat records from a loaded session.
*
* @param records - Array of chat records to replay
*/
async replay(records: ChatRecord[]): Promise<void> {
for (const record of records) {
await this.replayRecord(record);
}
}
/**
* Replays a single chat record.
*/
private async replayRecord(record: ChatRecord): Promise<void> {
switch (record.type) {
case 'user':
if (record.message) {
await this.replayContent(record.message, 'user');
}
break;
case 'assistant':
if (record.message) {
await this.replayContent(record.message, 'assistant');
}
if (record.usageMetadata) {
await this.replayUsageMetadata(record.usageMetadata);
}
break;
case 'tool_result':
await this.replayToolResult(record);
break;
default:
// Skip system records (compression, telemetry, slash commands)
break;
}
}
/**
* Replays content from a message (user or assistant).
* Handles text parts, thought parts, and function calls.
*/
private async replayContent(
content: Content,
role: 'user' | 'assistant',
): Promise<void> {
for (const part of content.parts ?? []) {
// Text content
if ('text' in part && part.text) {
const isThought = (part as { thought?: boolean }).thought ?? false;
await this.messageEmitter.emitMessage(part.text, role, isThought);
}
// Function call (tool start)
if ('functionCall' in part && part.functionCall) {
const functionName = part.functionCall.name ?? '';
const callId = part.functionCall.id ?? `${functionName}-${Date.now()}`;
await this.toolCallEmitter.emitStart({
toolName: functionName,
callId,
args: part.functionCall.args as Record<string, unknown>,
status: 'in_progress',
});
}
}
}
/**
* Replays usage metadata.
* @param usageMetadata - The usage metadata to replay
*/
private async replayUsageMetadata(
usageMetadata: GenerateContentResponseUsageMetadata,
): Promise<void> {
await this.messageEmitter.emitUsageMetadata(usageMetadata);
}
/**
* Replays a tool result record.
*/
private async replayToolResult(record: ChatRecord): Promise<void> {
// message is required - skip if not present
if (!record.message?.parts) {
return;
}
const result = record.toolCallResult;
const callId = result?.callId ?? record.uuid;
// Extract tool name from the function response in message if available
const toolName = this.extractToolNameFromRecord(record);
await this.toolCallEmitter.emitResult({
toolName,
callId,
success: !result?.error,
message: record.message.parts,
resultDisplay: result?.resultDisplay,
// For TodoWriteTool fallback, try to extract args from the record
// Note: args aren't stored in tool_result records by default
args: undefined,
});
// Special handling: Task tool execution summary contains token usage
const { resultDisplay } = result ?? {};
if (
!!resultDisplay &&
typeof resultDisplay === 'object' &&
'type' in resultDisplay &&
(resultDisplay as { type?: unknown }).type === 'task_execution'
) {
await this.emitTaskUsageFromResultDisplay(
resultDisplay as TaskResultDisplay,
);
}
}
/**
* Emits token usage from a TaskResultDisplay execution summary, if present.
*/
private async emitTaskUsageFromResultDisplay(
resultDisplay: TaskResultDisplay,
): Promise<void> {
const summary = resultDisplay.executionSummary;
if (!summary) {
return;
}
const usageMetadata: GenerateContentResponseUsageMetadata = {};
if (Number.isFinite(summary.inputTokens)) {
usageMetadata.promptTokenCount = summary.inputTokens;
}
if (Number.isFinite(summary.outputTokens)) {
usageMetadata.candidatesTokenCount = summary.outputTokens;
}
if (Number.isFinite(summary.thoughtTokens)) {
usageMetadata.thoughtsTokenCount = summary.thoughtTokens;
}
if (Number.isFinite(summary.cachedTokens)) {
usageMetadata.cachedContentTokenCount = summary.cachedTokens;
}
if (Number.isFinite(summary.totalTokens)) {
usageMetadata.totalTokenCount = summary.totalTokens;
}
// Only emit if we captured at least one token metric
if (Object.keys(usageMetadata).length > 0) {
await this.messageEmitter.emitUsageMetadata(usageMetadata);
}
}
/**
* Extracts tool name from a chat record's function response.
*/
private extractToolNameFromRecord(record: ChatRecord): string {
// Try to get from functionResponse in message
if (record.message?.parts) {
for (const part of record.message.parts) {
if ('functionResponse' in part && part.functionResponse?.name) {
return part.functionResponse.name;
}
}
}
return '';
}
}

View File

@@ -0,0 +1,525 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { SubAgentTracker } from './SubAgentTracker.js';
import type { SessionContext } from './types.js';
import type {
Config,
ToolRegistry,
SubAgentEventEmitter,
SubAgentToolCallEvent,
SubAgentToolResultEvent,
SubAgentApprovalRequestEvent,
ToolEditConfirmationDetails,
ToolInfoConfirmationDetails,
} from '@qwen-code/qwen-code-core';
import {
SubAgentEventType,
ToolConfirmationOutcome,
TodoWriteTool,
} from '@qwen-code/qwen-code-core';
import type * as acp from '../acp.js';
import { EventEmitter } from 'node:events';
// Helper to create a mock SubAgentToolCallEvent with required fields
function createToolCallEvent(
overrides: Partial<SubAgentToolCallEvent> & { name: string; callId: string },
): SubAgentToolCallEvent {
return {
subagentId: 'test-subagent',
round: 1,
timestamp: Date.now(),
description: `Calling ${overrides.name}`,
args: {},
...overrides,
};
}
// Helper to create a mock SubAgentToolResultEvent with required fields
function createToolResultEvent(
overrides: Partial<SubAgentToolResultEvent> & {
name: string;
callId: string;
success: boolean;
},
): SubAgentToolResultEvent {
return {
subagentId: 'test-subagent',
round: 1,
timestamp: Date.now(),
...overrides,
};
}
// Helper to create a mock SubAgentApprovalRequestEvent with required fields
function createApprovalEvent(
overrides: Partial<SubAgentApprovalRequestEvent> & {
name: string;
callId: string;
confirmationDetails: SubAgentApprovalRequestEvent['confirmationDetails'];
respond: SubAgentApprovalRequestEvent['respond'];
},
): SubAgentApprovalRequestEvent {
return {
subagentId: 'test-subagent',
round: 1,
timestamp: Date.now(),
description: `Awaiting approval for ${overrides.name}`,
...overrides,
};
}
// Helper to create edit confirmation details
function createEditConfirmation(
overrides: Partial<Omit<ToolEditConfirmationDetails, 'onConfirm' | 'type'>>,
): Omit<ToolEditConfirmationDetails, 'onConfirm'> {
return {
type: 'edit',
title: 'Edit file',
fileName: '/test.ts',
filePath: '/test.ts',
fileDiff: '',
originalContent: '',
newContent: '',
...overrides,
};
}
// Helper to create info confirmation details
function createInfoConfirmation(
overrides?: Partial<Omit<ToolInfoConfirmationDetails, 'onConfirm' | 'type'>>,
): Omit<ToolInfoConfirmationDetails, 'onConfirm'> {
return {
type: 'info',
title: 'Tool requires approval',
prompt: 'Allow this action?',
...overrides,
};
}
describe('SubAgentTracker', () => {
let mockContext: SessionContext;
let mockClient: acp.Client;
let sendUpdateSpy: ReturnType<typeof vi.fn>;
let requestPermissionSpy: ReturnType<typeof vi.fn>;
let tracker: SubAgentTracker;
let eventEmitter: SubAgentEventEmitter;
let abortController: AbortController;
beforeEach(() => {
sendUpdateSpy = vi.fn().mockResolvedValue(undefined);
requestPermissionSpy = vi.fn().mockResolvedValue({
outcome: { optionId: ToolConfirmationOutcome.ProceedOnce },
});
const mockToolRegistry = {
getTool: vi.fn().mockReturnValue(null),
} as unknown as ToolRegistry;
mockContext = {
sessionId: 'test-session-id',
config: {
getToolRegistry: () => mockToolRegistry,
} as unknown as Config,
sendUpdate: sendUpdateSpy,
};
mockClient = {
requestPermission: requestPermissionSpy,
} as unknown as acp.Client;
tracker = new SubAgentTracker(mockContext, mockClient);
eventEmitter = new EventEmitter() as unknown as SubAgentEventEmitter;
abortController = new AbortController();
});
describe('setup', () => {
it('should return cleanup function', () => {
const cleanups = tracker.setup(eventEmitter, abortController.signal);
expect(cleanups).toHaveLength(1);
expect(typeof cleanups[0]).toBe('function');
});
it('should register event listeners', () => {
const onSpy = vi.spyOn(eventEmitter, 'on');
tracker.setup(eventEmitter, abortController.signal);
expect(onSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_CALL,
expect.any(Function),
);
expect(onSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_RESULT,
expect.any(Function),
);
expect(onSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_WAITING_APPROVAL,
expect.any(Function),
);
});
it('should remove event listeners on cleanup', () => {
const offSpy = vi.spyOn(eventEmitter, 'off');
const cleanups = tracker.setup(eventEmitter, abortController.signal);
cleanups[0]();
expect(offSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_CALL,
expect.any(Function),
);
expect(offSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_RESULT,
expect.any(Function),
);
expect(offSpy).toHaveBeenCalledWith(
SubAgentEventType.TOOL_WAITING_APPROVAL,
expect.any(Function),
);
});
});
describe('tool call handling', () => {
it('should emit tool_call on TOOL_CALL event', async () => {
tracker.setup(eventEmitter, abortController.signal);
const event = createToolCallEvent({
name: 'read_file',
callId: 'call-123',
args: { path: '/test.ts' },
description: 'Reading file',
});
eventEmitter.emit(SubAgentEventType.TOOL_CALL, event);
// Allow async operations to complete
await vi.waitFor(() => {
expect(sendUpdateSpy).toHaveBeenCalled();
});
// ToolCallEmitter resolves metadata from registry - uses toolName when tool not found
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call',
toolCallId: 'call-123',
status: 'pending',
title: 'read_file',
content: [],
locations: [],
kind: 'other',
rawInput: { path: '/test.ts' },
}),
);
});
it('should skip tool_call for TodoWriteTool', async () => {
tracker.setup(eventEmitter, abortController.signal);
const event = createToolCallEvent({
name: TodoWriteTool.Name,
callId: 'call-todo',
args: { todos: [] },
});
eventEmitter.emit(SubAgentEventType.TOOL_CALL, event);
// Give time for any async operation
await new Promise((resolve) => setTimeout(resolve, 10));
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
it('should not emit when aborted', async () => {
tracker.setup(eventEmitter, abortController.signal);
abortController.abort();
const event = createToolCallEvent({
name: 'read_file',
callId: 'call-123',
args: {},
});
eventEmitter.emit(SubAgentEventType.TOOL_CALL, event);
await new Promise((resolve) => setTimeout(resolve, 10));
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
});
describe('tool result handling', () => {
it('should emit tool_call_update on TOOL_RESULT event', async () => {
tracker.setup(eventEmitter, abortController.signal);
// First emit tool call to store state
eventEmitter.emit(
SubAgentEventType.TOOL_CALL,
createToolCallEvent({
name: 'read_file',
callId: 'call-123',
args: { path: '/test.ts' },
}),
);
// Then emit result
const resultEvent = createToolResultEvent({
name: 'read_file',
callId: 'call-123',
success: true,
resultDisplay: 'File contents',
});
eventEmitter.emit(SubAgentEventType.TOOL_RESULT, resultEvent);
await vi.waitFor(() => {
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'completed',
}),
);
});
});
it('should emit failed status on unsuccessful result', async () => {
tracker.setup(eventEmitter, abortController.signal);
const resultEvent = createToolResultEvent({
name: 'read_file',
callId: 'call-fail',
success: false,
resultDisplay: undefined,
});
eventEmitter.emit(SubAgentEventType.TOOL_RESULT, resultEvent);
await vi.waitFor(() => {
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
status: 'failed',
}),
);
});
});
it('should emit plan update for TodoWriteTool results', async () => {
tracker.setup(eventEmitter, abortController.signal);
// Store args via tool call
eventEmitter.emit(
SubAgentEventType.TOOL_CALL,
createToolCallEvent({
name: TodoWriteTool.Name,
callId: 'call-todo',
args: {
todos: [{ id: '1', content: 'Task 1', status: 'pending' }],
},
}),
);
// Emit result with todo_list display
const resultEvent = createToolResultEvent({
name: TodoWriteTool.Name,
callId: 'call-todo',
success: true,
resultDisplay: JSON.stringify({
type: 'todo_list',
todos: [{ id: '1', content: 'Task 1', status: 'completed' }],
}),
});
eventEmitter.emit(SubAgentEventType.TOOL_RESULT, resultEvent);
await vi.waitFor(() => {
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [
{ content: 'Task 1', priority: 'medium', status: 'completed' },
],
});
});
});
it('should clean up state after result', async () => {
tracker.setup(eventEmitter, abortController.signal);
eventEmitter.emit(
SubAgentEventType.TOOL_CALL,
createToolCallEvent({
name: 'test_tool',
callId: 'call-cleanup',
args: { test: true },
}),
);
eventEmitter.emit(
SubAgentEventType.TOOL_RESULT,
createToolResultEvent({
name: 'test_tool',
callId: 'call-cleanup',
success: true,
}),
);
// Emit another result for same callId - should not have stored args
sendUpdateSpy.mockClear();
eventEmitter.emit(
SubAgentEventType.TOOL_RESULT,
createToolResultEvent({
name: 'test_tool',
callId: 'call-cleanup',
success: true,
}),
);
await vi.waitFor(() => {
expect(sendUpdateSpy).toHaveBeenCalled();
});
// Second call should not have args from first call
// (state was cleaned up)
});
});
describe('approval handling', () => {
it('should request permission from client', async () => {
tracker.setup(eventEmitter, abortController.signal);
const respondSpy = vi.fn().mockResolvedValue(undefined);
const event = createApprovalEvent({
name: 'edit_file',
callId: 'call-edit',
description: 'Editing file',
confirmationDetails: createEditConfirmation({
fileName: '/test.ts',
originalContent: 'old',
newContent: 'new',
}),
respond: respondSpy,
});
eventEmitter.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, event);
await vi.waitFor(() => {
expect(requestPermissionSpy).toHaveBeenCalled();
});
expect(requestPermissionSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionId: 'test-session-id',
toolCall: expect.objectContaining({
toolCallId: 'call-edit',
status: 'pending',
content: [
{
type: 'diff',
path: '/test.ts',
oldText: 'old',
newText: 'new',
},
],
}),
}),
);
});
it('should respond to subagent with permission outcome', async () => {
tracker.setup(eventEmitter, abortController.signal);
const respondSpy = vi.fn().mockResolvedValue(undefined);
const event = createApprovalEvent({
name: 'test_tool',
callId: 'call-123',
confirmationDetails: createInfoConfirmation(),
respond: respondSpy,
});
eventEmitter.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, event);
await vi.waitFor(() => {
expect(respondSpy).toHaveBeenCalledWith(
ToolConfirmationOutcome.ProceedOnce,
);
});
});
it('should cancel on permission request failure', async () => {
requestPermissionSpy.mockRejectedValue(new Error('Network error'));
tracker.setup(eventEmitter, abortController.signal);
const respondSpy = vi.fn().mockResolvedValue(undefined);
const event = createApprovalEvent({
name: 'test_tool',
callId: 'call-123',
confirmationDetails: createInfoConfirmation(),
respond: respondSpy,
});
eventEmitter.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, event);
await vi.waitFor(() => {
expect(respondSpy).toHaveBeenCalledWith(ToolConfirmationOutcome.Cancel);
});
});
it('should handle cancelled outcome from client', async () => {
requestPermissionSpy.mockResolvedValue({
outcome: { outcome: 'cancelled' },
});
tracker.setup(eventEmitter, abortController.signal);
const respondSpy = vi.fn().mockResolvedValue(undefined);
const event = createApprovalEvent({
name: 'test_tool',
callId: 'call-123',
confirmationDetails: createInfoConfirmation(),
respond: respondSpy,
});
eventEmitter.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, event);
await vi.waitFor(() => {
expect(respondSpy).toHaveBeenCalledWith(ToolConfirmationOutcome.Cancel);
});
});
});
describe('permission options', () => {
it('should include "Allow All Edits" for edit type', async () => {
tracker.setup(eventEmitter, abortController.signal);
const event = createApprovalEvent({
name: 'edit_file',
callId: 'call-123',
confirmationDetails: createEditConfirmation({
fileName: '/test.ts',
originalContent: '',
newContent: 'new',
}),
respond: vi.fn(),
});
eventEmitter.emit(SubAgentEventType.TOOL_WAITING_APPROVAL, event);
await vi.waitFor(() => {
expect(requestPermissionSpy).toHaveBeenCalled();
});
const call = requestPermissionSpy.mock.calls[0][0];
expect(call.options).toContainEqual(
expect.objectContaining({
optionId: ToolConfirmationOutcome.ProceedAlways,
name: 'Allow All Edits',
}),
);
});
});
});

View File

@@ -0,0 +1,339 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type {
SubAgentEventEmitter,
SubAgentToolCallEvent,
SubAgentToolResultEvent,
SubAgentApprovalRequestEvent,
SubAgentUsageEvent,
ToolCallConfirmationDetails,
AnyDeclarativeTool,
AnyToolInvocation,
} from '@qwen-code/qwen-code-core';
import {
SubAgentEventType,
ToolConfirmationOutcome,
} from '@qwen-code/qwen-code-core';
import { z } from 'zod';
import type { SessionContext } from './types.js';
import { ToolCallEmitter } from './emitters/ToolCallEmitter.js';
import { MessageEmitter } from './emitters/MessageEmitter.js';
import type * as acp from '../acp.js';
/**
* Permission option kind type matching ACP schema.
*/
type PermissionKind =
| 'allow_once'
| 'reject_once'
| 'allow_always'
| 'reject_always';
/**
* Configuration for permission options displayed to users.
*/
interface PermissionOptionConfig {
optionId: ToolConfirmationOutcome;
name: string;
kind: PermissionKind;
}
const basicPermissionOptions: readonly PermissionOptionConfig[] = [
{
optionId: ToolConfirmationOutcome.ProceedOnce,
name: 'Allow',
kind: 'allow_once',
},
{
optionId: ToolConfirmationOutcome.Cancel,
name: 'Reject',
kind: 'reject_once',
},
] as const;
/**
* Tracks and emits events for sub-agent tool calls within TaskTool execution.
*
* Uses the unified ToolCallEmitter for consistency with normal flow
* and history replay. Also handles permission requests for tools that
* require user approval.
*/
export class SubAgentTracker {
private readonly toolCallEmitter: ToolCallEmitter;
private readonly messageEmitter: MessageEmitter;
private readonly toolStates = new Map<
string,
{
tool?: AnyDeclarativeTool;
invocation?: AnyToolInvocation;
args?: Record<string, unknown>;
}
>();
constructor(
private readonly ctx: SessionContext,
private readonly client: acp.Client,
) {
this.toolCallEmitter = new ToolCallEmitter(ctx);
this.messageEmitter = new MessageEmitter(ctx);
}
/**
* Sets up event listeners for a sub-agent's tool events.
*
* @param eventEmitter - The SubAgentEventEmitter from TaskTool
* @param abortSignal - Signal to abort tracking if parent is cancelled
* @returns Array of cleanup functions to remove listeners
*/
setup(
eventEmitter: SubAgentEventEmitter,
abortSignal: AbortSignal,
): Array<() => void> {
const onToolCall = this.createToolCallHandler(abortSignal);
const onToolResult = this.createToolResultHandler(abortSignal);
const onApproval = this.createApprovalHandler(abortSignal);
const onUsageMetadata = this.createUsageMetadataHandler(abortSignal);
eventEmitter.on(SubAgentEventType.TOOL_CALL, onToolCall);
eventEmitter.on(SubAgentEventType.TOOL_RESULT, onToolResult);
eventEmitter.on(SubAgentEventType.TOOL_WAITING_APPROVAL, onApproval);
eventEmitter.on(SubAgentEventType.USAGE_METADATA, onUsageMetadata);
return [
() => {
eventEmitter.off(SubAgentEventType.TOOL_CALL, onToolCall);
eventEmitter.off(SubAgentEventType.TOOL_RESULT, onToolResult);
eventEmitter.off(SubAgentEventType.TOOL_WAITING_APPROVAL, onApproval);
eventEmitter.off(SubAgentEventType.USAGE_METADATA, onUsageMetadata);
// Clean up any remaining states
this.toolStates.clear();
},
];
}
/**
* Creates a handler for tool call start events.
*/
private createToolCallHandler(
abortSignal: AbortSignal,
): (...args: unknown[]) => void {
return (...args: unknown[]) => {
const event = args[0] as SubAgentToolCallEvent;
if (abortSignal.aborted) return;
// Look up tool and build invocation for metadata
const toolRegistry = this.ctx.config.getToolRegistry();
const tool = toolRegistry.getTool(event.name);
let invocation: AnyToolInvocation | undefined;
if (tool) {
try {
invocation = tool.build(event.args);
} catch (e) {
// If building fails, continue with defaults
console.warn(`Failed to build subagent tool ${event.name}:`, e);
}
}
// Store tool, invocation, and args for result handling
this.toolStates.set(event.callId, {
tool,
invocation,
args: event.args,
});
// Use unified emitter - handles TodoWriteTool skipping internally
void this.toolCallEmitter.emitStart({
toolName: event.name,
callId: event.callId,
args: event.args,
});
};
}
/**
* Creates a handler for tool result events.
*/
private createToolResultHandler(
abortSignal: AbortSignal,
): (...args: unknown[]) => void {
return (...args: unknown[]) => {
const event = args[0] as SubAgentToolResultEvent;
if (abortSignal.aborted) return;
const state = this.toolStates.get(event.callId);
// Use unified emitter - handles TodoWriteTool plan updates internally
void this.toolCallEmitter.emitResult({
toolName: event.name,
callId: event.callId,
success: event.success,
message: event.responseParts ?? [],
resultDisplay: event.resultDisplay,
args: state?.args,
});
// Clean up state
this.toolStates.delete(event.callId);
};
}
/**
* Creates a handler for tool approval request events.
*/
private createApprovalHandler(
abortSignal: AbortSignal,
): (...args: unknown[]) => Promise<void> {
return async (...args: unknown[]) => {
const event = args[0] as SubAgentApprovalRequestEvent;
if (abortSignal.aborted) return;
const state = this.toolStates.get(event.callId);
const content: acp.ToolCallContent[] = [];
// Handle edit confirmation type - show diff
if (event.confirmationDetails.type === 'edit') {
const editDetails = event.confirmationDetails as unknown as {
type: 'edit';
fileName: string;
originalContent: string | null;
newContent: string;
};
content.push({
type: 'diff',
path: editDetails.fileName,
oldText: editDetails.originalContent ?? '',
newText: editDetails.newContent,
});
}
// Build permission request
const fullConfirmationDetails = {
...event.confirmationDetails,
onConfirm: async () => {
// Placeholder - actual response handled via event.respond
},
} as unknown as ToolCallConfirmationDetails;
const { title, locations, kind } =
this.toolCallEmitter.resolveToolMetadata(event.name, state?.args);
const params: acp.RequestPermissionRequest = {
sessionId: this.ctx.sessionId,
options: this.toPermissionOptions(fullConfirmationDetails),
toolCall: {
toolCallId: event.callId,
status: 'pending',
title,
content,
locations,
kind,
rawInput: state?.args,
},
};
try {
// Request permission from client
const output = await this.client.requestPermission(params);
const outcome =
output.outcome.outcome === 'cancelled'
? ToolConfirmationOutcome.Cancel
: z
.nativeEnum(ToolConfirmationOutcome)
.parse(output.outcome.optionId);
// Respond to subagent with the outcome
await event.respond(outcome);
} catch (error) {
// If permission request fails, cancel the tool call
console.error(
`Permission request failed for subagent tool ${event.name}:`,
error,
);
await event.respond(ToolConfirmationOutcome.Cancel);
}
};
}
/**
* Creates a handler for usage metadata events.
*/
private createUsageMetadataHandler(
abortSignal: AbortSignal,
): (...args: unknown[]) => void {
return (...args: unknown[]) => {
const event = args[0] as SubAgentUsageEvent;
if (abortSignal.aborted) return;
this.messageEmitter.emitUsageMetadata(event.usage, '', event.durationMs);
};
}
/**
* Converts confirmation details to permission options for the client.
*/
private toPermissionOptions(
confirmation: ToolCallConfirmationDetails,
): acp.PermissionOption[] {
switch (confirmation.type) {
case 'edit':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: 'Allow All Edits',
kind: 'allow_always',
},
...basicPermissionOptions,
];
case 'exec':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: `Always Allow ${(confirmation as { rootCommand?: string }).rootCommand ?? 'command'}`,
kind: 'allow_always',
},
...basicPermissionOptions,
];
case 'mcp':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlwaysServer,
name: `Always Allow ${(confirmation as { serverName?: string }).serverName ?? 'server'}`,
kind: 'allow_always',
},
{
optionId: ToolConfirmationOutcome.ProceedAlwaysTool,
name: `Always Allow ${(confirmation as { toolName?: string }).toolName ?? 'tool'}`,
kind: 'allow_always',
},
...basicPermissionOptions,
];
case 'info':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: 'Always Allow',
kind: 'allow_always',
},
...basicPermissionOptions,
];
case 'plan':
return [
{
optionId: ToolConfirmationOutcome.ProceedAlways,
name: 'Always Allow Plans',
kind: 'allow_always',
},
...basicPermissionOptions,
];
default: {
// Fallback for unknown types
return [...basicPermissionOptions];
}
}
}
}

View File

@@ -0,0 +1,37 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { SessionContext } from '../types.js';
import type * as acp from '../../acp.js';
/**
* Abstract base class for all session event emitters.
* Provides common functionality and access to session context.
*/
export abstract class BaseEmitter {
constructor(protected readonly ctx: SessionContext) {}
/**
* Sends a session update to the ACP client.
*/
protected async sendUpdate(update: acp.SessionUpdate): Promise<void> {
return this.ctx.sendUpdate(update);
}
/**
* Gets the session configuration.
*/
protected get config() {
return this.ctx.config;
}
/**
* Gets the session ID.
*/
protected get sessionId() {
return this.ctx.sessionId;
}
}

View File

@@ -0,0 +1,206 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MessageEmitter } from './MessageEmitter.js';
import type { SessionContext } from '../types.js';
import type { Config } from '@qwen-code/qwen-code-core';
describe('MessageEmitter', () => {
let mockContext: SessionContext;
let sendUpdateSpy: ReturnType<typeof vi.fn>;
let emitter: MessageEmitter;
beforeEach(() => {
sendUpdateSpy = vi.fn().mockResolvedValue(undefined);
mockContext = {
sessionId: 'test-session-id',
config: {} as Config,
sendUpdate: sendUpdateSpy,
};
emitter = new MessageEmitter(mockContext);
});
describe('emitUserMessage', () => {
it('should send user_message_chunk update with text content', async () => {
await emitter.emitUserMessage('Hello, world!');
expect(sendUpdateSpy).toHaveBeenCalledTimes(1);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'Hello, world!' },
});
});
it('should handle empty text', async () => {
await emitter.emitUserMessage('');
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: '' },
});
});
it('should handle multiline text', async () => {
const multilineText = 'Line 1\nLine 2\nLine 3';
await emitter.emitUserMessage(multilineText);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: multilineText },
});
});
});
describe('emitAgentMessage', () => {
it('should send agent_message_chunk update with text content', async () => {
await emitter.emitAgentMessage('I can help you with that.');
expect(sendUpdateSpy).toHaveBeenCalledTimes(1);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'I can help you with that.' },
});
});
});
describe('emitAgentThought', () => {
it('should send agent_thought_chunk update with text content', async () => {
await emitter.emitAgentThought('Let me think about this...');
expect(sendUpdateSpy).toHaveBeenCalledTimes(1);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Let me think about this...' },
});
});
});
describe('emitMessage', () => {
it('should emit user message when role is user', async () => {
await emitter.emitMessage('User input', 'user');
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'User input' },
});
});
it('should emit agent message when role is assistant and isThought is false', async () => {
await emitter.emitMessage('Agent response', 'assistant', false);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'Agent response' },
});
});
it('should emit agent message when role is assistant and isThought is not provided', async () => {
await emitter.emitMessage('Agent response', 'assistant');
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'Agent response' },
});
});
it('should emit agent thought when role is assistant and isThought is true', async () => {
await emitter.emitAgentThought('Thinking...');
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Thinking...' },
});
});
it('should ignore isThought when role is user', async () => {
// Even if isThought is true, user messages should still be user_message_chunk
await emitter.emitMessage('User input', 'user', true);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'User input' },
});
});
});
describe('multiple emissions', () => {
it('should handle multiple sequential emissions', async () => {
await emitter.emitUserMessage('First');
await emitter.emitAgentMessage('Second');
await emitter.emitAgentThought('Third');
expect(sendUpdateSpy).toHaveBeenCalledTimes(3);
expect(sendUpdateSpy).toHaveBeenNthCalledWith(1, {
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text: 'First' },
});
expect(sendUpdateSpy).toHaveBeenNthCalledWith(2, {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'Second' },
});
expect(sendUpdateSpy).toHaveBeenNthCalledWith(3, {
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text: 'Third' },
});
});
});
describe('emitUsageMetadata', () => {
it('should emit agent_message_chunk with _meta.usage containing token counts', async () => {
const usageMetadata = {
promptTokenCount: 100,
candidatesTokenCount: 50,
thoughtsTokenCount: 25,
totalTokenCount: 175,
cachedContentTokenCount: 10,
};
await emitter.emitUsageMetadata(usageMetadata);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: '' },
_meta: {
usage: {
promptTokens: 100,
completionTokens: 50,
thoughtsTokens: 25,
totalTokens: 175,
cachedTokens: 10,
},
},
});
});
it('should include durationMs in _meta when provided', async () => {
const usageMetadata = {
promptTokenCount: 10,
candidatesTokenCount: 5,
thoughtsTokenCount: 2,
totalTokenCount: 17,
cachedContentTokenCount: 1,
};
await emitter.emitUsageMetadata(usageMetadata, 'done', 1234);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: 'done' },
_meta: {
usage: {
promptTokens: 10,
completionTokens: 5,
thoughtsTokens: 2,
totalTokens: 17,
cachedTokens: 1,
},
durationMs: 1234,
},
});
});
});
});

View File

@@ -0,0 +1,95 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { GenerateContentResponseUsageMetadata } from '@google/genai';
import type { Usage } from '../../schema.js';
import { BaseEmitter } from './BaseEmitter.js';
/**
* Handles emission of text message chunks (user, agent, thought).
*
* This emitter is responsible for sending message content to the ACP client
* in a consistent format, regardless of whether the message comes from
* normal flow, history replay, or other sources.
*/
export class MessageEmitter extends BaseEmitter {
/**
* Emits a user message chunk.
*/
async emitUserMessage(text: string): Promise<void> {
await this.sendUpdate({
sessionUpdate: 'user_message_chunk',
content: { type: 'text', text },
});
}
/**
* Emits an agent thought chunk.
*/
async emitAgentThought(text: string): Promise<void> {
await this.sendUpdate({
sessionUpdate: 'agent_thought_chunk',
content: { type: 'text', text },
});
}
/**
* Emits an agent message chunk.
*/
async emitAgentMessage(text: string): Promise<void> {
await this.sendUpdate({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text },
});
}
/**
* Emits usage metadata.
*/
async emitUsageMetadata(
usageMetadata: GenerateContentResponseUsageMetadata,
text: string = '',
durationMs?: number,
): Promise<void> {
const usage: Usage = {
promptTokens: usageMetadata.promptTokenCount,
completionTokens: usageMetadata.candidatesTokenCount,
thoughtsTokens: usageMetadata.thoughtsTokenCount,
totalTokens: usageMetadata.totalTokenCount,
cachedTokens: usageMetadata.cachedContentTokenCount,
};
const meta =
typeof durationMs === 'number' ? { usage, durationMs } : { usage };
await this.sendUpdate({
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text },
_meta: meta,
});
}
/**
* Emits a message chunk based on role and thought flag.
* This is the unified method that handles all message types.
*
* @param text - The message text content
* @param role - Whether this is a user or assistant message
* @param isThought - Whether this is an assistant thought (only applies to assistant role)
*/
async emitMessage(
text: string,
role: 'user' | 'assistant',
isThought: boolean = false,
): Promise<void> {
if (role === 'user') {
return this.emitUserMessage(text);
}
return isThought
? this.emitAgentThought(text)
: this.emitAgentMessage(text);
}
}

View File

@@ -0,0 +1,228 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { PlanEmitter } from './PlanEmitter.js';
import type { SessionContext, TodoItem } from '../types.js';
import type { Config } from '@qwen-code/qwen-code-core';
describe('PlanEmitter', () => {
let mockContext: SessionContext;
let sendUpdateSpy: ReturnType<typeof vi.fn>;
let emitter: PlanEmitter;
beforeEach(() => {
sendUpdateSpy = vi.fn().mockResolvedValue(undefined);
mockContext = {
sessionId: 'test-session-id',
config: {} as Config,
sendUpdate: sendUpdateSpy,
};
emitter = new PlanEmitter(mockContext);
});
describe('emitPlan', () => {
it('should send plan update with converted todo entries', async () => {
const todos: TodoItem[] = [
{ id: '1', content: 'First task', status: 'pending' },
{ id: '2', content: 'Second task', status: 'in_progress' },
{ id: '3', content: 'Third task', status: 'completed' },
];
await emitter.emitPlan(todos);
expect(sendUpdateSpy).toHaveBeenCalledTimes(1);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [
{ content: 'First task', priority: 'medium', status: 'pending' },
{ content: 'Second task', priority: 'medium', status: 'in_progress' },
{ content: 'Third task', priority: 'medium', status: 'completed' },
],
});
});
it('should handle empty todos array', async () => {
await emitter.emitPlan([]);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [],
});
});
it('should set default priority to medium for all entries', async () => {
const todos: TodoItem[] = [
{ id: '1', content: 'Task', status: 'pending' },
];
await emitter.emitPlan(todos);
const call = sendUpdateSpy.mock.calls[0][0];
expect(call.entries[0].priority).toBe('medium');
});
});
describe('extractTodos', () => {
describe('from resultDisplay object', () => {
it('should extract todos from valid todo_list object', () => {
const resultDisplay = {
type: 'todo_list',
todos: [
{ id: '1', content: 'Task 1', status: 'pending' as const },
{ id: '2', content: 'Task 2', status: 'completed' as const },
],
};
const result = emitter.extractTodos(resultDisplay);
expect(result).toEqual([
{ id: '1', content: 'Task 1', status: 'pending' },
{ id: '2', content: 'Task 2', status: 'completed' },
]);
});
it('should return null for object without type todo_list', () => {
const resultDisplay = {
type: 'other',
todos: [],
};
const result = emitter.extractTodos(resultDisplay);
expect(result).toBeNull();
});
it('should return null for object without todos array', () => {
const resultDisplay = {
type: 'todo_list',
items: [], // wrong key
};
const result = emitter.extractTodos(resultDisplay);
expect(result).toBeNull();
});
});
describe('from resultDisplay JSON string', () => {
it('should extract todos from valid JSON string', () => {
const resultDisplay = JSON.stringify({
type: 'todo_list',
todos: [{ id: '1', content: 'Task', status: 'pending' }],
});
const result = emitter.extractTodos(resultDisplay);
expect(result).toEqual([
{ id: '1', content: 'Task', status: 'pending' },
]);
});
it('should return null for invalid JSON string', () => {
const resultDisplay = 'not valid json';
const result = emitter.extractTodos(resultDisplay);
expect(result).toBeNull();
});
it('should return null for JSON without todo_list type', () => {
const resultDisplay = JSON.stringify({
type: 'other',
data: {},
});
const result = emitter.extractTodos(resultDisplay);
expect(result).toBeNull();
});
});
describe('from args fallback', () => {
it('should extract todos from args when resultDisplay is null', () => {
const args = {
todos: [{ id: '1', content: 'From args', status: 'pending' }],
};
const result = emitter.extractTodos(null, args);
expect(result).toEqual([
{ id: '1', content: 'From args', status: 'pending' },
]);
});
it('should extract todos from args when resultDisplay is undefined', () => {
const args = {
todos: [{ id: '1', content: 'From args', status: 'pending' }],
};
const result = emitter.extractTodos(undefined, args);
expect(result).toEqual([
{ id: '1', content: 'From args', status: 'pending' },
]);
});
it('should prefer resultDisplay over args', () => {
const resultDisplay = {
type: 'todo_list',
todos: [{ id: '1', content: 'From display', status: 'completed' }],
};
const args = {
todos: [{ id: '2', content: 'From args', status: 'pending' }],
};
const result = emitter.extractTodos(resultDisplay, args);
expect(result).toEqual([
{ id: '1', content: 'From display', status: 'completed' },
]);
});
it('should return null when args has no todos array', () => {
const args = { other: 'value' };
const result = emitter.extractTodos(null, args);
expect(result).toBeNull();
});
it('should return null when args.todos is not an array', () => {
const args = { todos: 'not an array' };
const result = emitter.extractTodos(null, args);
expect(result).toBeNull();
});
});
describe('edge cases', () => {
it('should return null when both resultDisplay and args are undefined', () => {
const result = emitter.extractTodos(undefined, undefined);
expect(result).toBeNull();
});
it('should return null when resultDisplay is empty object', () => {
const result = emitter.extractTodos({});
expect(result).toBeNull();
});
it('should handle resultDisplay with todos but wrong type', () => {
const resultDisplay = {
type: 'not_todo_list',
todos: [{ id: '1', content: 'Task', status: 'pending' }],
};
const result = emitter.extractTodos(resultDisplay);
expect(result).toBeNull();
});
});
});
});

View File

@@ -0,0 +1,96 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { BaseEmitter } from './BaseEmitter.js';
import type { TodoItem } from '../types.js';
import type * as acp from '../../acp.js';
/**
* Handles emission of plan/todo updates.
*
* This emitter is responsible for converting todo items to ACP plan entries
* and sending plan updates to the client. It also provides utilities for
* extracting todos from various sources (tool result displays, args, etc.).
*/
export class PlanEmitter extends BaseEmitter {
/**
* Emits a plan update with the given todo items.
*
* @param todos - Array of todo items to send as plan entries
*/
async emitPlan(todos: TodoItem[]): Promise<void> {
const entries: acp.PlanEntry[] = todos.map((todo) => ({
content: todo.content,
priority: 'medium' as const, // Default priority since todos don't have priority
status: todo.status,
}));
await this.sendUpdate({
sessionUpdate: 'plan',
entries,
});
}
/**
* Extracts todos from tool result display or args.
* Tries multiple sources in priority order:
* 1. Result display object with type 'todo_list'
* 2. Result display as JSON string
* 3. Args with 'todos' array
*
* @param resultDisplay - The tool result display (object, string, or undefined)
* @param args - The tool call arguments (fallback source)
* @returns Array of todos if found, null otherwise
*/
extractTodos(
resultDisplay: unknown,
args?: Record<string, unknown>,
): TodoItem[] | null {
// Try resultDisplay first (final state from tool execution)
const fromDisplay = this.extractFromResultDisplay(resultDisplay);
if (fromDisplay) return fromDisplay;
// Fallback to args (initial state)
if (args && Array.isArray(args['todos'])) {
return args['todos'] as TodoItem[];
}
return null;
}
/**
* Extracts todos from a result display value.
* Handles both object and JSON string formats.
*/
private extractFromResultDisplay(resultDisplay: unknown): TodoItem[] | null {
if (!resultDisplay) return null;
// Handle direct object with type 'todo_list'
if (typeof resultDisplay === 'object') {
const obj = resultDisplay as Record<string, unknown>;
if (obj['type'] === 'todo_list' && Array.isArray(obj['todos'])) {
return obj['todos'] as TodoItem[];
}
}
// Handle JSON string (from subagent events)
if (typeof resultDisplay === 'string') {
try {
const parsed = JSON.parse(resultDisplay) as Record<string, unknown>;
if (
parsed?.['type'] === 'todo_list' &&
Array.isArray(parsed['todos'])
) {
return parsed['todos'] as TodoItem[];
}
} catch {
// Not JSON, ignore
}
}
return null;
}
}

View File

@@ -0,0 +1,662 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ToolCallEmitter } from './ToolCallEmitter.js';
import type { SessionContext } from '../types.js';
import type {
Config,
ToolRegistry,
AnyDeclarativeTool,
AnyToolInvocation,
} from '@qwen-code/qwen-code-core';
import { Kind, TodoWriteTool } from '@qwen-code/qwen-code-core';
import type { Part } from '@google/genai';
// Helper to create mock message parts for tests
const createMockMessage = (text?: string): Part[] =>
text
? [{ functionResponse: { name: 'test', response: { output: text } } }]
: [];
describe('ToolCallEmitter', () => {
let mockContext: SessionContext;
let sendUpdateSpy: ReturnType<typeof vi.fn>;
let mockToolRegistry: ToolRegistry;
let emitter: ToolCallEmitter;
// Helper to create mock tool
const createMockTool = (
overrides: Partial<AnyDeclarativeTool> = {},
): AnyDeclarativeTool =>
({
name: 'test_tool',
kind: Kind.Other,
build: vi.fn().mockReturnValue({
getDescription: () => 'Test tool description',
toolLocations: () => [{ path: '/test/file.ts', line: 10 }],
} as unknown as AnyToolInvocation),
...overrides,
}) as unknown as AnyDeclarativeTool;
beforeEach(() => {
sendUpdateSpy = vi.fn().mockResolvedValue(undefined);
mockToolRegistry = {
getTool: vi.fn().mockReturnValue(null),
} as unknown as ToolRegistry;
mockContext = {
sessionId: 'test-session-id',
config: {
getToolRegistry: () => mockToolRegistry,
} as unknown as Config,
sendUpdate: sendUpdateSpy,
};
emitter = new ToolCallEmitter(mockContext);
});
describe('emitStart', () => {
it('should emit tool_call update with basic params when tool not in registry', async () => {
const result = await emitter.emitStart({
toolName: 'unknown_tool',
callId: 'call-123',
args: { arg1: 'value1' },
});
expect(result).toBe(true);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call',
toolCallId: 'call-123',
status: 'pending',
title: 'unknown_tool', // Falls back to tool name
content: [],
locations: [],
kind: 'other',
rawInput: { arg1: 'value1' },
});
});
it('should emit tool_call with resolved metadata when tool is in registry', async () => {
const mockTool = createMockTool({ kind: Kind.Edit });
vi.mocked(mockToolRegistry.getTool).mockReturnValue(mockTool);
const result = await emitter.emitStart({
toolName: 'edit_file',
callId: 'call-456',
args: { path: '/test.ts' },
});
expect(result).toBe(true);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call',
toolCallId: 'call-456',
status: 'pending',
title: 'edit_file: Test tool description',
content: [],
locations: [{ path: '/test/file.ts', line: 10 }],
kind: 'edit',
rawInput: { path: '/test.ts' },
});
});
it('should skip emit for TodoWriteTool and return false', async () => {
const result = await emitter.emitStart({
toolName: TodoWriteTool.Name,
callId: 'call-todo',
args: { todos: [] },
});
expect(result).toBe(false);
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
it('should handle empty args', async () => {
await emitter.emitStart({
toolName: 'test_tool',
callId: 'call-empty',
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
rawInput: {},
}),
);
});
it('should fall back gracefully when tool build fails', async () => {
const mockTool = createMockTool();
vi.mocked(mockTool.build).mockImplementation(() => {
throw new Error('Build failed');
});
vi.mocked(mockToolRegistry.getTool).mockReturnValue(mockTool);
await emitter.emitStart({
toolName: 'failing_tool',
callId: 'call-fail',
args: { invalid: true },
});
// Should use fallback values
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call',
toolCallId: 'call-fail',
status: 'pending',
title: 'failing_tool', // Fallback to tool name
content: [],
locations: [], // Fallback to empty
kind: 'other', // Fallback to other
rawInput: { invalid: true },
});
});
});
describe('emitResult', () => {
it('should emit tool_call_update with completed status on success', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-123',
success: true,
message: createMockMessage('Tool completed successfully'),
resultDisplay: 'Tool completed successfully',
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'completed',
rawOutput: 'Tool completed successfully',
}),
);
});
it('should emit tool_call_update with failed status on failure', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-123',
success: false,
message: [],
error: new Error('Something went wrong'),
});
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'failed',
content: [
{
type: 'content',
content: { type: 'text', text: 'Something went wrong' },
},
],
});
});
it('should handle diff display format', async () => {
await emitter.emitResult({
toolName: 'edit_file',
callId: 'call-edit',
success: true,
message: [],
resultDisplay: {
fileName: '/test/file.ts',
originalContent: 'old content',
newContent: 'new content',
},
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-edit',
status: 'completed',
content: [
{
type: 'diff',
path: '/test/file.ts',
oldText: 'old content',
newText: 'new content',
},
],
}),
);
});
it('should transform message parts to content', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-123',
success: true,
message: [{ text: 'Some text output' }],
resultDisplay: 'raw output',
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'completed',
content: [
{
type: 'content',
content: { type: 'text', text: 'Some text output' },
},
],
rawOutput: 'raw output',
}),
);
});
it('should handle empty message parts', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-empty',
success: true,
message: [],
});
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-empty',
status: 'completed',
content: [],
});
});
describe('TodoWriteTool handling', () => {
it('should emit plan update instead of tool_call_update for TodoWriteTool', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo',
success: true,
message: [],
resultDisplay: {
type: 'todo_list',
todos: [
{ id: '1', content: 'Task 1', status: 'pending' },
{ id: '2', content: 'Task 2', status: 'in_progress' },
],
},
});
expect(sendUpdateSpy).toHaveBeenCalledTimes(1);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [
{ content: 'Task 1', priority: 'medium', status: 'pending' },
{ content: 'Task 2', priority: 'medium', status: 'in_progress' },
],
});
});
it('should use args as fallback for TodoWriteTool todos', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo',
success: true,
message: [],
resultDisplay: null,
args: {
todos: [{ id: '1', content: 'From args', status: 'completed' }],
},
});
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [
{ content: 'From args', priority: 'medium', status: 'completed' },
],
});
});
it('should not emit anything for TodoWriteTool with empty todos', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo',
success: true,
message: [],
resultDisplay: { type: 'todo_list', todos: [] },
});
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
it('should not emit anything for TodoWriteTool with no extractable todos', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo',
success: true,
message: [],
resultDisplay: 'Some string result',
});
expect(sendUpdateSpy).not.toHaveBeenCalled();
});
});
});
describe('emitError', () => {
it('should emit tool_call_update with failed status and error message', async () => {
const error = new Error('Connection timeout');
await emitter.emitError('call-123', error);
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-123',
status: 'failed',
content: [
{
type: 'content',
content: { type: 'text', text: 'Connection timeout' },
},
],
});
});
});
describe('isTodoWriteTool', () => {
it('should return true for TodoWriteTool.Name', () => {
expect(emitter.isTodoWriteTool(TodoWriteTool.Name)).toBe(true);
});
it('should return false for other tool names', () => {
expect(emitter.isTodoWriteTool('read_file')).toBe(false);
expect(emitter.isTodoWriteTool('edit_file')).toBe(false);
expect(emitter.isTodoWriteTool('')).toBe(false);
});
});
describe('mapToolKind', () => {
it('should map all Kind values correctly', () => {
expect(emitter.mapToolKind(Kind.Read)).toBe('read');
expect(emitter.mapToolKind(Kind.Edit)).toBe('edit');
expect(emitter.mapToolKind(Kind.Delete)).toBe('delete');
expect(emitter.mapToolKind(Kind.Move)).toBe('move');
expect(emitter.mapToolKind(Kind.Search)).toBe('search');
expect(emitter.mapToolKind(Kind.Execute)).toBe('execute');
expect(emitter.mapToolKind(Kind.Think)).toBe('think');
expect(emitter.mapToolKind(Kind.Fetch)).toBe('fetch');
expect(emitter.mapToolKind(Kind.Other)).toBe('other');
});
it('should map exit_plan_mode tool to switch_mode kind', () => {
// exit_plan_mode uses Kind.Think internally, but should map to switch_mode per ACP spec
expect(emitter.mapToolKind(Kind.Think, 'exit_plan_mode')).toBe(
'switch_mode',
);
});
it('should not affect other tools with Kind.Think', () => {
// Other tools with Kind.Think should still map to think
expect(emitter.mapToolKind(Kind.Think, 'todo_write')).toBe('think');
expect(emitter.mapToolKind(Kind.Think, 'some_other_tool')).toBe('think');
});
});
describe('isExitPlanModeTool', () => {
it('should return true for exit_plan_mode tool name', () => {
expect(emitter.isExitPlanModeTool('exit_plan_mode')).toBe(true);
});
it('should return false for other tool names', () => {
expect(emitter.isExitPlanModeTool('read_file')).toBe(false);
expect(emitter.isExitPlanModeTool('edit_file')).toBe(false);
expect(emitter.isExitPlanModeTool('todo_write')).toBe(false);
expect(emitter.isExitPlanModeTool('')).toBe(false);
});
});
describe('resolveToolMetadata', () => {
it('should return defaults when tool not found', () => {
const metadata = emitter.resolveToolMetadata('unknown_tool', {
arg: 'value',
});
expect(metadata).toEqual({
title: 'unknown_tool',
locations: [],
kind: 'other',
});
});
it('should return tool metadata when tool found and built successfully', () => {
const mockTool = createMockTool({ kind: Kind.Search });
vi.mocked(mockToolRegistry.getTool).mockReturnValue(mockTool);
const metadata = emitter.resolveToolMetadata('search_tool', {
query: 'test',
});
expect(metadata).toEqual({
title: 'search_tool: Test tool description',
locations: [{ path: '/test/file.ts', line: 10 }],
kind: 'search',
});
});
});
describe('integration: consistent behavior across flows', () => {
it('should handle the same params consistently regardless of source', async () => {
// This test verifies that the emitter produces consistent output
// whether called from normal flow, replay, or subagent
const params = {
toolName: 'read_file',
callId: 'consistent-call',
args: { path: '/test.ts' },
};
// First call (e.g., from normal flow)
await emitter.emitStart(params);
const firstCall = sendUpdateSpy.mock.calls[0][0];
// Reset and call again (e.g., from replay)
sendUpdateSpy.mockClear();
await emitter.emitStart(params);
const secondCall = sendUpdateSpy.mock.calls[0][0];
// Both should produce identical output
expect(firstCall).toEqual(secondCall);
});
});
describe('fixes verification', () => {
describe('Fix 2: functionResponse parts are stringified', () => {
it('should stringify functionResponse parts in message', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-func',
success: true,
message: [
{
functionResponse: {
name: 'test',
response: { output: 'test output' },
},
},
],
resultDisplay: { unknownField: 'value', nested: { data: 123 } },
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-func',
status: 'completed',
content: [
{
type: 'content',
content: {
type: 'text',
text: 'test output',
},
},
],
rawOutput: { unknownField: 'value', nested: { data: 123 } },
}),
);
});
});
describe('Fix 3: rawOutput is included in emitResult', () => {
it('should include rawOutput when resultDisplay is provided', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-extra',
success: true,
message: [{ text: 'Result text' }],
resultDisplay: 'Result text',
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-extra',
status: 'completed',
rawOutput: 'Result text',
}),
);
});
it('should not include rawOutput when resultDisplay is undefined', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-null',
success: true,
message: [],
});
const call = sendUpdateSpy.mock.calls[0][0];
expect(call.rawOutput).toBeUndefined();
});
});
describe('Fix 5: Line null mapping in resolveToolMetadata', () => {
it('should map undefined line to null in locations', () => {
const mockTool = createMockTool();
// Override toolLocations to return undefined line
vi.mocked(mockTool.build).mockReturnValue({
getDescription: () => 'Description',
toolLocations: () => [
{ path: '/file1.ts', line: 10 },
{ path: '/file2.ts', line: undefined },
{ path: '/file3.ts' }, // no line property
],
} as unknown as AnyToolInvocation);
vi.mocked(mockToolRegistry.getTool).mockReturnValue(mockTool);
const metadata = emitter.resolveToolMetadata('test_tool', {
arg: 'value',
});
expect(metadata.locations).toEqual([
{ path: '/file1.ts', line: 10 },
{ path: '/file2.ts', line: null },
{ path: '/file3.ts', line: null },
]);
});
});
describe('Fix 6: Empty plan emission when args has todos', () => {
it('should emit empty plan when args had todos but result has none', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo-empty',
success: true,
message: [],
resultDisplay: null, // No result display
args: {
todos: [], // Empty array in args
},
});
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [],
});
});
it('should emit empty plan when result todos is empty but args had todos', async () => {
await emitter.emitResult({
toolName: TodoWriteTool.Name,
callId: 'call-todo-cleared',
success: true,
message: [],
resultDisplay: {
type: 'todo_list',
todos: [], // Empty result
},
args: {
todos: [{ id: '1', content: 'Was here', status: 'pending' }],
},
});
// Should still emit empty plan (result takes precedence but we emit empty)
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'plan',
entries: [],
});
});
});
describe('Message transformation', () => {
it('should transform text parts from message', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-text',
success: true,
message: [{ text: 'Text content from message' }],
});
expect(sendUpdateSpy).toHaveBeenCalledWith({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-text',
status: 'completed',
content: [
{
type: 'content',
content: { type: 'text', text: 'Text content from message' },
},
],
});
});
it('should transform functionResponse parts from message', async () => {
await emitter.emitResult({
toolName: 'test_tool',
callId: 'call-func-resp',
success: true,
message: [
{
functionResponse: {
name: 'test_tool',
response: { output: 'Function output' },
},
},
],
resultDisplay: 'raw result',
});
expect(sendUpdateSpy).toHaveBeenCalledWith(
expect.objectContaining({
sessionUpdate: 'tool_call_update',
toolCallId: 'call-func-resp',
status: 'completed',
content: [
{
type: 'content',
content: { type: 'text', text: 'Function output' },
},
],
rawOutput: 'raw result',
}),
);
});
});
});
});

View File

@@ -0,0 +1,302 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { BaseEmitter } from './BaseEmitter.js';
import { PlanEmitter } from './PlanEmitter.js';
import type {
SessionContext,
ToolCallStartParams,
ToolCallResultParams,
ResolvedToolMetadata,
} from '../types.js';
import type * as acp from '../../acp.js';
import type { Part } from '@google/genai';
import {
TodoWriteTool,
Kind,
ExitPlanModeTool,
} from '@qwen-code/qwen-code-core';
/**
* Unified tool call event emitter.
*
* Handles tool_call and tool_call_update for ALL flows:
* - Normal tool execution in runTool()
* - History replay in HistoryReplayer
* - SubAgent tool tracking in SubAgentTracker
*
* This ensures consistent behavior across all tool event sources,
* including special handling for tools like TodoWriteTool.
*/
export class ToolCallEmitter extends BaseEmitter {
private readonly planEmitter: PlanEmitter;
constructor(ctx: SessionContext) {
super(ctx);
this.planEmitter = new PlanEmitter(ctx);
}
/**
* Emits a tool call start event.
*
* @param params - Tool call start parameters
* @returns true if event was emitted, false if skipped (e.g., TodoWriteTool)
*/
async emitStart(params: ToolCallStartParams): Promise<boolean> {
// Skip tool_call for TodoWriteTool - plan updates sent on result
if (this.isTodoWriteTool(params.toolName)) {
return false;
}
const { title, locations, kind } = this.resolveToolMetadata(
params.toolName,
params.args,
);
await this.sendUpdate({
sessionUpdate: 'tool_call',
toolCallId: params.callId,
status: params.status || 'pending',
title,
content: [],
locations,
kind,
rawInput: params.args ?? {},
});
return true;
}
/**
* Emits a tool call result event.
* Handles TodoWriteTool specially by routing to plan updates.
*
* @param params - Tool call result parameters
*/
async emitResult(params: ToolCallResultParams): Promise<void> {
// Handle TodoWriteTool specially - send plan update instead
if (this.isTodoWriteTool(params.toolName)) {
const todos = this.planEmitter.extractTodos(
params.resultDisplay,
params.args,
);
// Match original behavior: send plan even if empty when args['todos'] exists
// This ensures the UI is updated even when all todos are removed
if (todos && todos.length > 0) {
await this.planEmitter.emitPlan(todos);
} else if (params.args && Array.isArray(params.args['todos'])) {
// Send empty plan when args had todos but result has none
await this.planEmitter.emitPlan([]);
}
return; // Skip tool_call_update for TodoWriteTool
}
// Determine content for the update
let contentArray: acp.ToolCallContent[] = [];
// Special case: diff result from edit tools (format from resultDisplay)
const diffContent = this.extractDiffContent(params.resultDisplay);
if (diffContent) {
contentArray = [diffContent];
} else if (params.error) {
// Error case: show error message
contentArray = [
{
type: 'content',
content: { type: 'text', text: params.error.message },
},
];
} else {
// Normal case: transform message parts to ToolCallContent[]
contentArray = this.transformPartsToToolCallContent(params.message);
}
// Build the update
const update: Parameters<typeof this.sendUpdate>[0] = {
sessionUpdate: 'tool_call_update',
toolCallId: params.callId,
status: params.success ? 'completed' : 'failed',
content: contentArray,
};
// Add rawOutput from resultDisplay
if (params.resultDisplay !== undefined) {
(update as Record<string, unknown>)['rawOutput'] = params.resultDisplay;
}
await this.sendUpdate(update);
}
/**
* Emits a tool call error event.
* Use this for explicit error handling when not using emitResult.
*
* @param callId - The tool call ID
* @param error - The error that occurred
*/
async emitError(callId: string, error: Error): Promise<void> {
await this.sendUpdate({
sessionUpdate: 'tool_call_update',
toolCallId: callId,
status: 'failed',
content: [
{ type: 'content', content: { type: 'text', text: error.message } },
],
});
}
// ==================== Public Utilities ====================
/**
* Checks if a tool name is the TodoWriteTool.
* Exposed for external use in components that need to check this.
*/
isTodoWriteTool(toolName: string): boolean {
return toolName === TodoWriteTool.Name;
}
/**
* Checks if a tool name is the ExitPlanModeTool.
*/
isExitPlanModeTool(toolName: string): boolean {
return toolName === ExitPlanModeTool.Name;
}
/**
* Resolves tool metadata from the registry.
* Falls back to defaults if tool not found or build fails.
*
* @param toolName - Name of the tool
* @param args - Tool call arguments (used to build invocation)
*/
resolveToolMetadata(
toolName: string,
args?: Record<string, unknown>,
): ResolvedToolMetadata {
const toolRegistry = this.config.getToolRegistry();
const tool = toolRegistry.getTool(toolName);
let title = tool?.displayName ?? toolName;
let locations: acp.ToolCallLocation[] = [];
let kind: acp.ToolKind = 'other';
if (tool && args) {
try {
const invocation = tool.build(args);
title = `${title}: ${invocation.getDescription()}`;
// Map locations to ensure line is null instead of undefined (for ACP consistency)
locations = invocation.toolLocations().map((loc) => ({
path: loc.path,
line: loc.line ?? null,
}));
// Pass tool name to handle special cases like exit_plan_mode -> switch_mode
kind = this.mapToolKind(tool.kind, toolName);
} catch {
// Use defaults on build failure
}
}
return { title, locations, kind };
}
/**
* Maps core Tool Kind enum to ACP ToolKind string literals.
*
* @param kind - The core Kind enum value
* @param toolName - Optional tool name to handle special cases like exit_plan_mode
*/
mapToolKind(kind: Kind, toolName?: string): acp.ToolKind {
// Special case: exit_plan_mode uses 'switch_mode' kind per ACP spec
if (toolName && this.isExitPlanModeTool(toolName)) {
return 'switch_mode';
}
const kindMap: Record<Kind, acp.ToolKind> = {
[Kind.Read]: 'read',
[Kind.Edit]: 'edit',
[Kind.Delete]: 'delete',
[Kind.Move]: 'move',
[Kind.Search]: 'search',
[Kind.Execute]: 'execute',
[Kind.Think]: 'think',
[Kind.Fetch]: 'fetch',
[Kind.Other]: 'other',
};
return kindMap[kind] ?? 'other';
}
// ==================== Private Helpers ====================
/**
* Extracts diff content from resultDisplay if it's a diff type (edit tool result).
* Returns null if not a diff.
*/
private extractDiffContent(
resultDisplay: unknown,
): acp.ToolCallContent | null {
if (!resultDisplay || typeof resultDisplay !== 'object') return null;
const obj = resultDisplay as Record<string, unknown>;
// Check if this is a diff display (edit tool result)
if ('fileName' in obj && 'newContent' in obj) {
return {
type: 'diff',
path: obj['fileName'] as string,
oldText: (obj['originalContent'] as string) ?? '',
newText: obj['newContent'] as string,
};
}
return null;
}
/**
* Transforms Part[] to ToolCallContent[].
* Extracts text from functionResponse parts and text parts.
*/
private transformPartsToToolCallContent(
parts: Part[],
): acp.ToolCallContent[] {
const result: acp.ToolCallContent[] = [];
for (const part of parts) {
// Handle text parts
if ('text' in part && part.text) {
result.push({
type: 'content',
content: { type: 'text', text: part.text },
});
}
// Handle functionResponse parts - stringify the response
if ('functionResponse' in part && part.functionResponse) {
try {
const resp = part.functionResponse.response as Record<
string,
unknown
>;
const outputField = resp['output'];
const errorField = resp['error'];
const responseText =
typeof outputField === 'string'
? outputField
: typeof errorField === 'string'
? errorField
: JSON.stringify(resp);
result.push({
type: 'content',
content: { type: 'text', text: responseText },
});
} catch {
// Ignore serialization errors
}
}
}
return result;
}
}

View File

@@ -0,0 +1,10 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
export { BaseEmitter } from './BaseEmitter.js';
export { MessageEmitter } from './MessageEmitter.js';
export { PlanEmitter } from './PlanEmitter.js';
export { ToolCallEmitter } from './ToolCallEmitter.js';

View File

@@ -0,0 +1,40 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Session module for ACP/Zed integration.
*
* This module provides a modular architecture for handling session events:
* - **Emitters**: Unified event emission (MessageEmitter, ToolCallEmitter, PlanEmitter)
* - **HistoryReplayer**: Replays session history using unified emitters
* - **SubAgentTracker**: Tracks sub-agent tool events using unified emitters
*
* The key benefit is that all event emission goes through the same emitters,
* ensuring consistency between normal flow, history replay, and sub-agent events.
*/
// Types
export type {
SessionContext,
SessionUpdateSender,
ToolCallStartParams,
ToolCallResultParams,
TodoItem,
ResolvedToolMetadata,
} from './types.js';
// Emitters
export { BaseEmitter } from './emitters/BaseEmitter.js';
export { MessageEmitter } from './emitters/MessageEmitter.js';
export { PlanEmitter } from './emitters/PlanEmitter.js';
export { ToolCallEmitter } from './emitters/ToolCallEmitter.js';
// Components
export { HistoryReplayer } from './HistoryReplayer.js';
export { SubAgentTracker } from './SubAgentTracker.js';
// Main Session class
export { Session } from './Session.js';

View File

@@ -0,0 +1,78 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { Config } from '@qwen-code/qwen-code-core';
import type { Part } from '@google/genai';
import type * as acp from '../acp.js';
/**
* Interface for sending session updates to the ACP client.
* Implemented by Session class and used by all emitters.
*/
export interface SessionUpdateSender {
sendUpdate(update: acp.SessionUpdate): Promise<void>;
}
/**
* Session context shared across all emitters.
* Provides access to session state and configuration.
*/
export interface SessionContext extends SessionUpdateSender {
readonly sessionId: string;
readonly config: Config;
}
/**
* Parameters for emitting a tool call start event.
*/
export interface ToolCallStartParams {
/** Name of the tool being called */
toolName: string;
/** Unique identifier for this tool call */
callId: string;
/** Arguments passed to the tool */
args?: Record<string, unknown>;
/** Status of the tool call */
status?: 'pending' | 'in_progress' | 'completed' | 'failed';
}
/**
* Parameters for emitting a tool call result event.
*/
export interface ToolCallResultParams {
/** Name of the tool that was called */
toolName: string;
/** Unique identifier for this tool call */
callId: string;
/** Whether the tool execution succeeded */
success: boolean;
/** The response parts from tool execution (maps to content in update event) */
message: Part[];
/** Display result from tool execution (maps to rawOutput in update event) */
resultDisplay?: unknown;
/** Error if tool execution failed */
error?: Error;
/** Original args (fallback for TodoWriteTool todos extraction) */
args?: Record<string, unknown>;
}
/**
* Todo item structure for plan updates.
*/
export interface TodoItem {
id: string;
content: string;
status: 'pending' | 'in_progress' | 'completed';
}
/**
* Resolved tool metadata from the registry.
*/
export interface ResolvedToolMetadata {
title: string;
locations: acp.ToolCallLocation[];
kind: acp.ToolKind;
}

View File

@@ -18,60 +18,26 @@ vi.mock('./settings.js', () => ({
describe('validateAuthMethod', () => {
beforeEach(() => {
vi.resetModules();
vi.stubEnv('GEMINI_API_KEY', undefined);
vi.stubEnv('GOOGLE_CLOUD_PROJECT', undefined);
vi.stubEnv('GOOGLE_CLOUD_LOCATION', undefined);
vi.stubEnv('GOOGLE_API_KEY', undefined);
});
afterEach(() => {
vi.unstubAllEnvs();
});
it('should return null for LOGIN_WITH_GOOGLE', () => {
expect(validateAuthMethod(AuthType.LOGIN_WITH_GOOGLE)).toBeNull();
it('should return null for USE_OPENAI', () => {
process.env['OPENAI_API_KEY'] = 'fake-key';
expect(validateAuthMethod(AuthType.USE_OPENAI)).toBeNull();
});
it('should return null for CLOUD_SHELL', () => {
expect(validateAuthMethod(AuthType.CLOUD_SHELL)).toBeNull();
it('should return an error message for USE_OPENAI if OPENAI_API_KEY is not set', () => {
delete process.env['OPENAI_API_KEY'];
expect(validateAuthMethod(AuthType.USE_OPENAI)).toBe(
'OPENAI_API_KEY environment variable not found. You can enter it interactively or add it to your .env file.',
);
});
describe('USE_GEMINI', () => {
it('should return null if GEMINI_API_KEY is set', () => {
vi.stubEnv('GEMINI_API_KEY', 'test-key');
expect(validateAuthMethod(AuthType.USE_GEMINI)).toBeNull();
});
it('should return an error message if GEMINI_API_KEY is not set', () => {
vi.stubEnv('GEMINI_API_KEY', undefined);
expect(validateAuthMethod(AuthType.USE_GEMINI)).toBe(
'GEMINI_API_KEY environment variable not found. Add that to your environment and try again (no reload needed if using .env)!',
);
});
});
describe('USE_VERTEX_AI', () => {
it('should return null if GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION are set', () => {
vi.stubEnv('GOOGLE_CLOUD_PROJECT', 'test-project');
vi.stubEnv('GOOGLE_CLOUD_LOCATION', 'test-location');
expect(validateAuthMethod(AuthType.USE_VERTEX_AI)).toBeNull();
});
it('should return null if GOOGLE_API_KEY is set', () => {
vi.stubEnv('GOOGLE_API_KEY', 'test-api-key');
expect(validateAuthMethod(AuthType.USE_VERTEX_AI)).toBeNull();
});
it('should return an error message if no required environment variables are set', () => {
vi.stubEnv('GOOGLE_CLOUD_PROJECT', undefined);
vi.stubEnv('GOOGLE_CLOUD_LOCATION', undefined);
expect(validateAuthMethod(AuthType.USE_VERTEX_AI)).toBe(
'When using Vertex AI, you must specify either:\n' +
'• GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION environment variables.\n' +
'• GOOGLE_API_KEY environment variable (if using express mode).\n' +
'Update your environment and try again (no reload needed if using .env)!',
);
});
it('should return null for QWEN_OAUTH', () => {
expect(validateAuthMethod(AuthType.QWEN_OAUTH)).toBeNull();
});
it('should return an error message for an invalid auth method', () => {

View File

@@ -8,39 +8,13 @@ import { AuthType } from '@qwen-code/qwen-code-core';
import { loadEnvironment, loadSettings } from './settings.js';
export function validateAuthMethod(authMethod: string): string | null {
loadEnvironment(loadSettings().merged);
if (
authMethod === AuthType.LOGIN_WITH_GOOGLE ||
authMethod === AuthType.CLOUD_SHELL
) {
return null;
}
if (authMethod === AuthType.USE_GEMINI) {
if (!process.env['GEMINI_API_KEY']) {
return 'GEMINI_API_KEY environment variable not found. Add that to your environment and try again (no reload needed if using .env)!';
}
return null;
}
if (authMethod === AuthType.USE_VERTEX_AI) {
const hasVertexProjectLocationConfig =
!!process.env['GOOGLE_CLOUD_PROJECT'] &&
!!process.env['GOOGLE_CLOUD_LOCATION'];
const hasGoogleApiKey = !!process.env['GOOGLE_API_KEY'];
if (!hasVertexProjectLocationConfig && !hasGoogleApiKey) {
return (
'When using Vertex AI, you must specify either:\n' +
'• GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION environment variables.\n' +
'• GOOGLE_API_KEY environment variable (if using express mode).\n' +
'Update your environment and try again (no reload needed if using .env)!'
);
}
return null;
}
const settings = loadSettings();
loadEnvironment(settings.merged);
if (authMethod === AuthType.USE_OPENAI) {
if (!process.env['OPENAI_API_KEY']) {
const hasApiKey =
process.env['OPENAI_API_KEY'] || settings.merged.security?.auth?.apiKey;
if (!hasApiKey) {
return 'OPENAI_API_KEY environment variable not found. You can enter it interactively or add it to your .env file.';
}
return null;
@@ -54,15 +28,3 @@ export function validateAuthMethod(authMethod: string): string | null {
return 'Invalid auth method selected.';
}
export const setOpenAIApiKey = (apiKey: string): void => {
process.env['OPENAI_API_KEY'] = apiKey;
};
export const setOpenAIBaseUrl = (baseUrl: string): void => {
process.env['OPENAI_BASE_URL'] = baseUrl;
};
export const setOpenAIModel = (model: string): void => {
process.env['OPENAI_MODEL'] = model;
};

View File

@@ -15,6 +15,7 @@ import type {
import { Config } from '@qwen-code/qwen-code-core';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import type { Settings } from './settings.js';
export const server = setupServer();
@@ -73,12 +74,10 @@ describe('Configuration Integration Tests', () => {
it('should load default file filtering settings', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFilteringRespectGitIgnore: undefined, // Should default to true
};
const config = new Config(configParams);
@@ -89,9 +88,8 @@ describe('Configuration Integration Tests', () => {
it('should load custom file filtering settings from configuration', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFiltering: {
@@ -107,12 +105,10 @@ describe('Configuration Integration Tests', () => {
it('should merge user and workspace file filtering settings', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFilteringRespectGitIgnore: true,
};
const config = new Config(configParams);
@@ -125,9 +121,8 @@ describe('Configuration Integration Tests', () => {
it('should handle partial configuration objects gracefully', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFiltering: {
@@ -144,12 +139,10 @@ describe('Configuration Integration Tests', () => {
it('should handle empty configuration objects gracefully', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFilteringRespectGitIgnore: undefined,
};
const config = new Config(configParams);
@@ -161,9 +154,8 @@ describe('Configuration Integration Tests', () => {
it('should handle missing configuration sections gracefully', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
// Missing fileFiltering configuration
@@ -180,12 +172,10 @@ describe('Configuration Integration Tests', () => {
it('should handle a security-focused configuration', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFilteringRespectGitIgnore: true,
};
const config = new Config(configParams);
@@ -196,9 +186,8 @@ describe('Configuration Integration Tests', () => {
it('should handle a CI/CD environment configuration', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
fileFiltering: {
@@ -216,9 +205,8 @@ describe('Configuration Integration Tests', () => {
it('should enable checkpointing when the setting is true', async () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
checkpointing: true,
@@ -234,9 +222,8 @@ describe('Configuration Integration Tests', () => {
it('should have an empty array for extension context files by default', () => {
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
};
@@ -248,9 +235,8 @@ describe('Configuration Integration Tests', () => {
const contextFiles = ['/path/to/file1.txt', '/path/to/file2.js'];
const configParams: ConfigParameters = {
cwd: '/tmp',
contentGeneratorConfig: TEST_CONTENT_GENERATOR_CONFIG,
generationConfig: TEST_CONTENT_GENERATOR_CONFIG,
embeddingModel: 'test-embedding-model',
sandbox: false,
targetDir: tempDir,
debugMode: false,
extensionContextFilePaths: contextFiles,
@@ -261,11 +247,11 @@ describe('Configuration Integration Tests', () => {
});
describe('Approval Mode Integration Tests', () => {
let parseArguments: typeof import('./config').parseArguments;
let parseArguments: typeof import('./config.js').parseArguments;
beforeEach(async () => {
// Import the argument parsing function for integration testing
const { parseArguments: parseArgs } = await import('./config');
const { parseArguments: parseArgs } = await import('./config.js');
parseArguments = parseArgs;
});

File diff suppressed because it is too large Load Diff

View File

@@ -4,16 +4,10 @@
* SPDX-License-Identifier: Apache-2.0
*/
import type {
FileFilteringOptions,
MCPServerConfig,
OutputFormat,
} from '@qwen-code/qwen-code-core';
import { extensionsCommand } from '../commands/extensions.js';
import {
ApprovalMode,
AuthType,
Config,
DEFAULT_QWEN_MODEL,
DEFAULT_QWEN_EMBEDDING_MODEL,
DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
EditTool,
@@ -25,7 +19,15 @@ import {
WriteFileTool,
resolveTelemetrySettings,
FatalConfigError,
Storage,
InputFormat,
OutputFormat,
SessionService,
type ResumedSessionData,
type FileFilteringOptions,
type MCPServerConfig,
} from '@qwen-code/qwen-code-core';
import { extensionsCommand } from '../commands/extensions.js';
import type { Settings } from './settings.js';
import yargs, { type Argv } from 'yargs';
import { hideBin } from 'yargs/helpers';
@@ -43,6 +45,7 @@ import { mcpCommand } from '../commands/mcp.js';
import { isWorkspaceTrusted } from './trustedFolders.js';
import type { ExtensionEnablementManager } from './extensions/extensionEnablement.js';
import { buildWebSearchConfig } from './webSearch.js';
// Simple console logger for now - replace with actual logger if available
const logger = {
@@ -114,13 +117,43 @@ export interface CliArgs {
openaiLogging: boolean | undefined;
openaiApiKey: string | undefined;
openaiBaseUrl: string | undefined;
openaiLoggingDir: string | undefined;
proxy: string | undefined;
includeDirectories: string[] | undefined;
tavilyApiKey: string | undefined;
googleApiKey: string | undefined;
googleSearchEngineId: string | undefined;
webSearchDefault: string | undefined;
screenReader: boolean | undefined;
vlmSwitchMode: string | undefined;
useSmartEdit: boolean | undefined;
inputFormat?: string | undefined;
outputFormat: string | undefined;
includePartialMessages?: boolean;
/** Resume the most recent session for the current project */
continue: boolean | undefined;
/** Resume a specific session by its ID */
resume: string | undefined;
maxSessionTurns: number | undefined;
coreTools: string[] | undefined;
excludeTools: string[] | undefined;
authType: string | undefined;
channel: string | undefined;
}
function normalizeOutputFormat(
format: string | OutputFormat | undefined,
): OutputFormat | undefined {
if (!format) {
return undefined;
}
if (format === OutputFormat.STREAM_JSON) {
return OutputFormat.STREAM_JSON;
}
if (format === 'json' || format === OutputFormat.JSON) {
return OutputFormat.JSON;
}
return OutputFormat.TEXT;
}
export async function parseArguments(settings: Settings): Promise<CliArgs> {
@@ -194,14 +227,13 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
})
.option('proxy', {
type: 'string',
description:
'Proxy for gemini client, like schema://user:password@host:port',
description: 'Proxy for Qwen Code, like schema://user:password@host:port',
})
.deprecateOption(
'proxy',
'Use the "proxy" setting in settings.json instead. This flag will be removed in a future version.',
)
.command('$0 [query..]', 'Launch Gemini CLI', (yargsInstance: Argv) =>
.command('$0 [query..]', 'Launch Qwen Code CLI', (yargsInstance: Argv) =>
yargsInstance
.positional('query', {
description:
@@ -266,6 +298,11 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
type: 'boolean',
description: 'Starts the agent in ACP mode',
})
.option('channel', {
type: 'string',
choices: ['VSCode', 'ACP', 'SDK', 'CI'],
description: 'Channel identifier (VSCode, ACP, SDK, CI)',
})
.option('allowed-mcp-server-names', {
type: 'array',
string: true,
@@ -315,6 +352,11 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
description:
'Enable logging of OpenAI API calls for debugging and analysis',
})
.option('openai-logging-dir', {
type: 'string',
description:
'Custom directory path for OpenAI API logs. Overrides settings files.',
})
.option('openai-api-key', {
type: 'string',
description: 'OpenAI API key to use for authentication',
@@ -325,7 +367,20 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
})
.option('tavily-api-key', {
type: 'string',
description: 'Tavily API key for web search functionality',
description: 'Tavily API key for web search',
})
.option('google-api-key', {
type: 'string',
description: 'Google Custom Search API key',
})
.option('google-search-engine-id', {
type: 'string',
description: 'Google Custom Search Engine ID',
})
.option('web-search-default', {
type: 'string',
description:
'Default web search provider (dashscope, tavily, google)',
})
.option('screen-reader', {
type: 'boolean',
@@ -338,11 +393,64 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
'Default behavior when images are detected in input. Values: once (one-time switch), session (switch for entire session), persist (continue with current model). Overrides settings files.',
default: process.env['VLM_SWITCH_MODE'],
})
.option('input-format', {
type: 'string',
choices: ['text', 'stream-json'],
description: 'The format consumed from standard input.',
default: 'text',
})
.option('output-format', {
alias: 'o',
type: 'string',
description: 'The format of the CLI output.',
choices: ['text', 'json'],
choices: ['text', 'json', 'stream-json'],
})
.option('include-partial-messages', {
type: 'boolean',
description:
'Include partial assistant messages when using stream-json output.',
default: false,
})
.option('continue', {
type: 'boolean',
description:
'Resume the most recent session for the current project.',
default: false,
})
.option('resume', {
type: 'string',
description:
'Resume a specific session by its ID. Use without an ID to show session picker.',
})
.option('max-session-turns', {
type: 'number',
description: 'Maximum number of session turns',
})
.option('core-tools', {
type: 'array',
string: true,
description: 'Core tool paths',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('exclude-tools', {
type: 'array',
string: true,
description: 'Tools to exclude',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('allowed-tools', {
type: 'array',
string: true,
description: 'Tools to allow, will bypass confirmation',
coerce: (tools: string[]) =>
tools.flatMap((tool) => tool.split(',').map((t) => t.trim())),
})
.option('auth-type', {
type: 'string',
choices: [AuthType.USE_OPENAI, AuthType.QWEN_OAUTH],
description: 'Authentication type',
})
.deprecateOption(
'show-memory-usage',
@@ -387,6 +495,21 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
if (argv['yolo'] && argv['approvalMode']) {
return 'Cannot use both --yolo (-y) and --approval-mode together. Use --approval-mode=yolo instead.';
}
if (
argv['includePartialMessages'] &&
argv['outputFormat'] !== OutputFormat.STREAM_JSON
) {
return '--include-partial-messages requires --output-format stream-json';
}
if (
argv['inputFormat'] === 'stream-json' &&
argv['outputFormat'] !== OutputFormat.STREAM_JSON
) {
return '--input-format stream-json requires --output-format stream-json';
}
if (argv['continue'] && argv['resume']) {
return 'Cannot use both --continue and --resume together. Use --continue to resume the latest session, or --resume <sessionId> to resume a specific session.';
}
return true;
}),
)
@@ -442,6 +565,12 @@ export async function parseArguments(settings: Settings): Promise<CliArgs> {
// The import format is now only controlled by settings.memoryImportFormat
// We no longer accept it as a CLI argument
// Apply ACP fallback: if experimental-acp is present but no explicit --channel, treat as ACP
if (result['experimentalAcp'] && !result['channel']) {
(result as Record<string, unknown>)['channel'] = 'ACP';
}
return result as unknown as CliArgs;
}
@@ -501,7 +630,6 @@ export async function loadCliConfig(
settings: Settings,
extensions: Extension[],
extensionEnablementManager: ExtensionEnablementManager,
sessionId: string,
argv: CliArgs,
cwd: string = process.cwd(),
): Promise<Config> {
@@ -539,6 +667,20 @@ export async function loadCliConfig(
(e) => e.contextFiles,
);
// Automatically load output-language.md if it exists
const outputLanguageFilePath = path.join(
Storage.getGlobalQwenDir(),
'output-language.md',
);
if (fs.existsSync(outputLanguageFilePath)) {
extensionContextFilePaths.push(outputLanguageFilePath);
if (debugMode) {
logger.debug(
`Found output-language.md, adding to context files: ${outputLanguageFilePath}`,
);
}
}
const fileService = new FileDiscoveryService(cwd);
const fileFiltering = {
@@ -567,6 +709,22 @@ export async function loadCliConfig(
let mcpServers = mergeMcpServers(settings, activeExtensions);
const question = argv.promptInteractive || argv.prompt || '';
const inputFormat: InputFormat =
(argv.inputFormat as InputFormat | undefined) ?? InputFormat.TEXT;
const argvOutputFormat = normalizeOutputFormat(
argv.outputFormat as string | OutputFormat | undefined,
);
const settingsOutputFormat = normalizeOutputFormat(settings.output?.format);
const outputFormat =
argvOutputFormat ?? settingsOutputFormat ?? OutputFormat.TEXT;
const outputSettingsFormat: OutputFormat =
outputFormat === OutputFormat.STREAM_JSON
? settingsOutputFormat &&
settingsOutputFormat !== OutputFormat.STREAM_JSON
? settingsOutputFormat
: OutputFormat.TEXT
: (outputFormat as OutputFormat);
const includePartialMessages = Boolean(argv.includePartialMessages);
// Determine approval mode with backward compatibility
let approvalMode: ApprovalMode;
@@ -608,14 +766,40 @@ export async function loadCliConfig(
throw err;
}
// Interactive mode: explicit -i flag or (TTY + no args + no -p flag)
// Interactive mode determination with priority:
// 1. If promptInteractive (-i flag) is provided, it is explicitly interactive
// 2. If outputFormat is stream-json or json (no matter input-format) along with query or prompt, it is non-interactive
// 3. If no query or prompt is provided, check isTTY: TTY means interactive, non-TTY means non-interactive
const hasQuery = !!argv.query;
const interactive =
!!argv.promptInteractive ||
(process.stdin.isTTY && !hasQuery && !argv.prompt);
const hasPrompt = !!argv.prompt;
let interactive: boolean;
if (argv.promptInteractive) {
// Priority 1: Explicit -i flag means interactive
interactive = true;
} else if (
(outputFormat === OutputFormat.STREAM_JSON ||
outputFormat === OutputFormat.JSON) &&
(hasQuery || hasPrompt)
) {
// Priority 2: JSON/stream-json output with query/prompt means non-interactive
interactive = false;
} else if (!hasQuery && !hasPrompt) {
// Priority 3: No query or prompt means interactive only if TTY (format arguments ignored)
interactive = process.stdin.isTTY ?? false;
} else {
// Default: If we have query/prompt but output format is TEXT, assume non-interactive
// (fallback for edge cases where query/prompt is provided with TEXT output)
interactive = false;
}
// In non-interactive mode, exclude tools that require a prompt.
// However, if stream-json input is used, control can be requested via JSON messages,
// so tools should not be excluded in that case.
const extraExcludes: string[] = [];
if (!interactive && !argv.experimentalAcp) {
if (
!interactive &&
!argv.experimentalAcp &&
inputFormat !== InputFormat.STREAM_JSON
) {
switch (approvalMode) {
case ApprovalMode.PLAN:
case ApprovalMode.DEFAULT:
@@ -639,6 +823,7 @@ export async function loadCliConfig(
settings,
activeExtensions,
extraExcludes.length > 0 ? extraExcludes : undefined,
argv.excludeTools,
);
const blockedMcpServers: Array<{ name: string; extensionName: string }> = [];
@@ -669,13 +854,11 @@ export async function loadCliConfig(
);
}
const defaultModel = DEFAULT_QWEN_MODEL;
const resolvedModel: string =
const resolvedModel =
argv.model ||
process.env['OPENAI_MODEL'] ||
process.env['QWEN_MODEL'] ||
settings.model?.name ||
defaultModel;
settings.model?.name;
const sandboxConfig = await loadSandboxConfig(settings, argv);
const screenReader =
@@ -685,8 +868,33 @@ export async function loadCliConfig(
const vlmSwitchMode =
argv.vlmSwitchMode || settings.experimental?.vlmSwitchMode;
let sessionId: string | undefined;
let sessionData: ResumedSessionData | undefined;
if (argv.continue || argv.resume) {
const sessionService = new SessionService(cwd);
if (argv.continue) {
sessionData = await sessionService.loadLastSession();
if (sessionData) {
sessionId = sessionData.conversation.sessionId;
}
}
if (argv.resume) {
sessionId = argv.resume;
sessionData = await sessionService.loadSession(argv.resume);
if (!sessionData) {
const message = `No saved session found with ID ${argv.resume}. Run \`qwen --resume\` without an ID to choose from existing sessions.`;
console.log(message);
process.exit(1);
}
}
}
return new Config({
sessionId,
sessionData,
embeddingModel: DEFAULT_QWEN_EMBEDDING_MODEL,
sandbox: sandboxConfig,
targetDir: cwd,
@@ -696,7 +904,7 @@ export async function loadCliConfig(
debugMode,
question,
fullContext: argv.allFiles || false,
coreTools: settings.tools?.core || undefined,
coreTools: argv.coreTools || settings.tools?.core || undefined,
allowedTools: argv.allowedTools || settings.tools?.allowed || undefined,
excludeTools,
toolDiscoveryCommand: settings.tools?.discoveryCommand,
@@ -729,28 +937,43 @@ export async function loadCliConfig(
model: resolvedModel,
extensionContextFilePaths,
sessionTokenLimit: settings.model?.sessionTokenLimit ?? -1,
maxSessionTurns: settings.model?.maxSessionTurns ?? -1,
maxSessionTurns:
argv.maxSessionTurns ?? settings.model?.maxSessionTurns ?? -1,
experimentalZedIntegration: argv.experimentalAcp || false,
listExtensions: argv.listExtensions || false,
extensions: allExtensions,
blockedMcpServers,
noBrowser: !!process.env['NO_BROWSER'],
authType: settings.security?.auth?.selectedType,
authType:
(argv.authType as AuthType | undefined) ||
settings.security?.auth?.selectedType,
inputFormat,
outputFormat,
includePartialMessages,
generationConfig: {
...(settings.model?.generationConfig || {}),
model: resolvedModel,
apiKey: argv.openaiApiKey || process.env['OPENAI_API_KEY'],
baseUrl: argv.openaiBaseUrl || process.env['OPENAI_BASE_URL'],
apiKey:
argv.openaiApiKey ||
process.env['OPENAI_API_KEY'] ||
settings.security?.auth?.apiKey,
baseUrl:
argv.openaiBaseUrl ||
process.env['OPENAI_BASE_URL'] ||
settings.security?.auth?.baseUrl,
enableOpenAILogging:
(typeof argv.openaiLogging === 'undefined'
? settings.model?.enableOpenAILogging
: argv.openaiLogging) ?? false,
openAILoggingDir:
argv.openaiLoggingDir || settings.model?.openAILoggingDir,
},
cliVersion: await getCliVersion(),
tavilyApiKey:
argv.tavilyApiKey ||
settings.advanced?.tavilyApiKey ||
process.env['TAVILY_API_KEY'],
webSearch: buildWebSearchConfig(
argv,
settings,
settings.security?.auth?.selectedType,
),
summarizeToolOutput: settings.model?.summarizeToolOutput,
ideMode,
chatCompression: settings.model?.chatCompression,
@@ -758,10 +981,11 @@ export async function loadCliConfig(
interactive,
trustedFolder,
useRipgrep: settings.tools?.useRipgrep,
useBuiltinRipgrep: settings.tools?.useBuiltinRipgrep,
shouldUseNodePtyShell: settings.tools?.shell?.enableInteractiveShell,
skipNextSpeakerCheck: settings.model?.skipNextSpeakerCheck,
enablePromptCompletion: settings.general?.enablePromptCompletion ?? false,
skipLoopDetection: settings.model?.skipLoopDetection ?? false,
skipStartupContext: settings.model?.skipStartupContext ?? false,
vlmSwitchMode,
truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
truncateToolOutputLines: settings.tools?.truncateToolOutputLines,
@@ -769,8 +993,9 @@ export async function loadCliConfig(
eventEmitter: appEvents,
useSmartEdit: argv.useSmartEdit ?? settings.useSmartEdit,
output: {
format: (argv.outputFormat ?? settings.output?.format) as OutputFormat,
format: outputSettingsFormat,
},
channel: argv.channel,
});
}
@@ -830,8 +1055,10 @@ function mergeExcludeTools(
settings: Settings,
extensions: Extension[],
extraExcludes?: string[] | undefined,
cliExcludeTools?: string[] | undefined,
): string[] {
const allExcludeTools = new Set([
...(cliExcludeTools || []),
...(settings.tools?.exclude || []),
...(extraExcludes || []),
]);

View File

@@ -30,7 +30,6 @@ import { getErrorMessage } from '../utils/errors.js';
import { recursivelyHydrateStrings } from './extensions/variables.js';
import { isWorkspaceTrusted } from './trustedFolders.js';
import { resolveEnvVarsInObject } from '../utils/envVarResolver.js';
import { randomUUID } from 'node:crypto';
import {
cloneFromGit,
downloadFromGitHubRelease,
@@ -134,7 +133,6 @@ function getTelemetryConfig(cwd: string) {
const config = new Config({
telemetry: settings.merged.telemetry,
interactive: false,
sessionId: randomUUID(),
targetDir: cwd,
cwd,
model: '',

View File

@@ -66,6 +66,8 @@ import {
loadEnvironment,
migrateDeprecatedSettings,
SettingScope,
SETTINGS_VERSION,
SETTINGS_VERSION_KEY,
} from './settings.js';
import { FatalConfigError, QWEN_DIR } from '@qwen-code/qwen-code-core';
@@ -94,6 +96,7 @@ vi.mock('fs', async (importOriginal) => {
existsSync: vi.fn(),
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
renameSync: vi.fn(),
mkdirSync: vi.fn(),
realpathSync: (p: string) => p,
};
@@ -171,11 +174,15 @@ describe('Settings Loading and Merging', () => {
getSystemSettingsPath(),
'utf-8',
);
expect(settings.system.settings).toEqual(systemSettingsContent);
expect(settings.system.settings).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.user.settings).toEqual({});
expect(settings.workspace.settings).toEqual({});
expect(settings.merged).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
});
@@ -207,10 +214,14 @@ describe('Settings Loading and Merging', () => {
expectedUserSettingsPath,
'utf-8',
);
expect(settings.user.settings).toEqual(userSettingsContent);
expect(settings.user.settings).toEqual({
...userSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.workspace.settings).toEqual({});
expect(settings.merged).toEqual({
...userSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
});
@@ -241,9 +252,13 @@ describe('Settings Loading and Merging', () => {
'utf-8',
);
expect(settings.user.settings).toEqual({});
expect(settings.workspace.settings).toEqual(workspaceSettingsContent);
expect(settings.workspace.settings).toEqual({
...workspaceSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.merged).toEqual({
...workspaceSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
});
@@ -304,10 +319,20 @@ describe('Settings Loading and Merging', () => {
const settings = loadSettings(MOCK_WORKSPACE_DIR);
expect(settings.system.settings).toEqual(systemSettingsContent);
expect(settings.user.settings).toEqual(userSettingsContent);
expect(settings.workspace.settings).toEqual(workspaceSettingsContent);
expect(settings.system.settings).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.user.settings).toEqual({
...userSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.workspace.settings).toEqual({
...workspaceSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.merged).toEqual({
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
ui: {
theme: 'system-theme',
},
@@ -361,6 +386,7 @@ describe('Settings Loading and Merging', () => {
const settings = loadSettings(MOCK_WORKSPACE_DIR);
expect(settings.merged).toEqual({
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
ui: {
theme: 'legacy-dark',
},
@@ -413,6 +439,132 @@ describe('Settings Loading and Merging', () => {
expect((settings.merged as TestSettings)['allowedTools']).toBeUndefined();
});
it('should add version field to migrated settings file', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
const legacySettingsContent = {
theme: 'dark',
model: 'qwen-coder',
};
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(legacySettingsContent);
return '{}';
},
);
loadSettings(MOCK_WORKSPACE_DIR);
// Verify that fs.writeFileSync was called with migrated settings including version
expect(fs.writeFileSync).toHaveBeenCalled();
const writeCall = (fs.writeFileSync as Mock).mock.calls[0];
const writtenContent = JSON.parse(writeCall[1] as string);
expect(writtenContent[SETTINGS_VERSION_KEY]).toBe(SETTINGS_VERSION);
});
it('should not re-migrate settings that have version field', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
const migratedSettingsContent = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
ui: {
theme: 'dark',
},
model: {
name: 'qwen-coder',
},
};
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(migratedSettingsContent);
return '{}';
},
);
loadSettings(MOCK_WORKSPACE_DIR);
// Verify that fs.renameSync and fs.writeFileSync were NOT called
// (because no migration was needed)
expect(fs.renameSync).not.toHaveBeenCalled();
expect(fs.writeFileSync).not.toHaveBeenCalled();
});
it('should add version field to V2 settings without version and write to disk', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
// V2 format but no version field
const v2SettingsWithoutVersion = {
ui: {
theme: 'dark',
},
model: {
name: 'qwen-coder',
},
};
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(v2SettingsWithoutVersion);
return '{}';
},
);
loadSettings(MOCK_WORKSPACE_DIR);
// Verify that fs.writeFileSync was called (to add version)
// but NOT fs.renameSync (no backup needed, just adding version)
expect(fs.renameSync).not.toHaveBeenCalled();
expect(fs.writeFileSync).toHaveBeenCalledTimes(1);
const writeCall = (fs.writeFileSync as Mock).mock.calls[0];
const writtenPath = writeCall[0];
const writtenContent = JSON.parse(writeCall[1] as string);
expect(writtenPath).toBe(USER_SETTINGS_PATH);
expect(writtenContent[SETTINGS_VERSION_KEY]).toBe(SETTINGS_VERSION);
expect(writtenContent.ui?.theme).toBe('dark');
expect(writtenContent.model?.name).toBe('qwen-coder');
});
it('should correctly handle partially migrated settings without version field', () => {
(mockFsExistsSync as Mock).mockImplementation(
(p: fs.PathLike) => p === USER_SETTINGS_PATH,
);
// Edge case: model already in V2 format (object), but autoAccept in V1 format
const partiallyMigratedContent = {
model: {
name: 'qwen-coder',
},
autoAccept: false, // V1 key
};
(fs.readFileSync as Mock).mockImplementation(
(p: fs.PathOrFileDescriptor) => {
if (p === USER_SETTINGS_PATH)
return JSON.stringify(partiallyMigratedContent);
return '{}';
},
);
loadSettings(MOCK_WORKSPACE_DIR);
// Verify that the migrated settings preserve the model object correctly
expect(fs.writeFileSync).toHaveBeenCalled();
const writeCall = (fs.writeFileSync as Mock).mock.calls[0];
const writtenContent = JSON.parse(writeCall[1] as string);
// Model should remain as an object, not double-nested
expect(writtenContent.model).toEqual({ name: 'qwen-coder' });
// autoAccept should be migrated to tools.autoAccept
expect(writtenContent.tools?.autoAccept).toBe(false);
// Version field should be added
expect(writtenContent[SETTINGS_VERSION_KEY]).toBe(SETTINGS_VERSION);
});
it('should correctly merge and migrate legacy array properties from multiple scopes', () => {
(mockFsExistsSync as Mock).mockReturnValue(true);
const legacyUserSettings = {
@@ -515,11 +667,24 @@ describe('Settings Loading and Merging', () => {
const settings = loadSettings(MOCK_WORKSPACE_DIR);
expect(settings.systemDefaults.settings).toEqual(systemDefaultsContent);
expect(settings.system.settings).toEqual(systemSettingsContent);
expect(settings.user.settings).toEqual(userSettingsContent);
expect(settings.workspace.settings).toEqual(workspaceSettingsContent);
expect(settings.systemDefaults.settings).toEqual({
...systemDefaultsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.system.settings).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.user.settings).toEqual({
...userSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.workspace.settings).toEqual({
...workspaceSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.merged).toEqual({
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
context: {
fileName: 'WORKSPACE_CONTEXT.md',
includeDirectories: [
@@ -866,8 +1031,14 @@ describe('Settings Loading and Merging', () => {
const settings = loadSettings(MOCK_WORKSPACE_DIR);
expect(settings.user.settings).toEqual(userSettingsContent);
expect(settings.workspace.settings).toEqual(workspaceSettingsContent);
expect(settings.user.settings).toEqual({
...userSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.workspace.settings).toEqual({
...workspaceSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.merged.mcpServers).toEqual({
'user-server': {
command: 'user-command',
@@ -1696,9 +1867,13 @@ describe('Settings Loading and Merging', () => {
'utf-8',
);
expect(settings.system.path).toBe(MOCK_ENV_SYSTEM_SETTINGS_PATH);
expect(settings.system.settings).toEqual(systemSettingsContent);
expect(settings.system.settings).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
expect(settings.merged).toEqual({
...systemSettingsContent,
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
});
});
});
@@ -2248,6 +2423,44 @@ describe('Settings Loading and Merging', () => {
customWittyPhrases: ['test phrase'],
});
});
it('should remove version field when migrating to V1', () => {
const v2Settings = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
ui: {
theme: 'dark',
},
model: {
name: 'qwen-coder',
},
};
const v1Settings = migrateSettingsToV1(v2Settings);
// Version field should not be present in V1 settings
expect(v1Settings[SETTINGS_VERSION_KEY]).toBeUndefined();
// Other fields should be properly migrated
expect(v1Settings).toEqual({
theme: 'dark',
model: 'qwen-coder',
});
});
it('should handle version field in unrecognized properties', () => {
const v2Settings = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
general: {
vimMode: true,
},
someUnrecognizedKey: 'value',
};
const v1Settings = migrateSettingsToV1(v2Settings);
// Version field should be filtered out
expect(v1Settings[SETTINGS_VERSION_KEY]).toBeUndefined();
// Unrecognized keys should be preserved
expect(v1Settings['someUnrecognizedKey']).toBe('value');
expect(v1Settings['vimMode']).toBe(true);
});
});
describe('loadEnvironment', () => {
@@ -2368,6 +2581,73 @@ describe('Settings Loading and Merging', () => {
};
expect(needsMigration(settings)).toBe(false);
});
describe('with version field', () => {
it('should return false when version field indicates current or newer version', () => {
const settingsWithVersion = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
theme: 'dark', // Even though this is a V1 key, version field takes precedence
};
expect(needsMigration(settingsWithVersion)).toBe(false);
});
it('should return false when version field indicates a newer version', () => {
const settingsWithNewerVersion = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION + 1,
theme: 'dark',
};
expect(needsMigration(settingsWithNewerVersion)).toBe(false);
});
it('should return true when version field indicates an older version', () => {
const settingsWithOldVersion = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION - 1,
theme: 'dark',
};
expect(needsMigration(settingsWithOldVersion)).toBe(true);
});
it('should use fallback logic when version field is not a number', () => {
const settingsWithInvalidVersion = {
[SETTINGS_VERSION_KEY]: 'not-a-number',
theme: 'dark',
};
expect(needsMigration(settingsWithInvalidVersion)).toBe(true);
});
it('should use fallback logic when version field is missing', () => {
const settingsWithoutVersion = {
theme: 'dark',
};
expect(needsMigration(settingsWithoutVersion)).toBe(true);
});
});
describe('edge case: partially migrated settings', () => {
it('should return true for partially migrated settings without version field', () => {
// This simulates the dangerous edge case: model already in V2 format,
// but other fields in V1 format
const partiallyMigrated = {
model: {
name: 'qwen-coder',
},
autoAccept: false, // V1 key
};
expect(needsMigration(partiallyMigrated)).toBe(true);
});
it('should return false for partially migrated settings WITH version field', () => {
// With version field, we trust that it's been properly migrated
const partiallyMigratedWithVersion = {
[SETTINGS_VERSION_KEY]: SETTINGS_VERSION,
model: {
name: 'qwen-coder',
},
autoAccept: false, // This would look like V1 but version says it's V2
};
expect(needsMigration(partiallyMigratedWithVersion)).toBe(false);
});
});
});
describe('migrateDeprecatedSettings', () => {

View File

@@ -56,6 +56,10 @@ export const DEFAULT_EXCLUDED_ENV_VARS = ['DEBUG', 'DEBUG_MODE'];
const MIGRATE_V2_OVERWRITE = true;
// Settings version to track migration state
export const SETTINGS_VERSION = 2;
export const SETTINGS_VERSION_KEY = '$version';
const MIGRATION_MAP: Record<string, string> = {
accessibility: 'ui.accessibility',
allowedTools: 'tools.allowed',
@@ -73,7 +77,6 @@ const MIGRATION_MAP: Record<string, string> = {
disableAutoUpdate: 'general.disableAutoUpdate',
disableUpdateNag: 'general.disableUpdateNag',
dnsResolutionOrder: 'advanced.dnsResolutionOrder',
enablePromptCompletion: 'general.enablePromptCompletion',
enforcedAuthType: 'security.auth.enforcedType',
excludeTools: 'tools.exclude',
excludeMCPServers: 'mcp.excluded',
@@ -127,6 +130,7 @@ const MIGRATION_MAP: Record<string, string> = {
sessionTokenLimit: 'model.sessionTokenLimit',
contentGenerator: 'model.generationConfig',
skipLoopDetection: 'model.skipLoopDetection',
skipStartupContext: 'model.skipStartupContext',
enableOpenAILogging: 'model.enableOpenAILogging',
tavilyApiKey: 'advanced.tavilyApiKey',
vlmSwitchMode: 'experimental.vlmSwitchMode',
@@ -216,8 +220,16 @@ function setNestedProperty(
}
export function needsMigration(settings: Record<string, unknown>): boolean {
// A file needs migration if it contains any top-level key that is moved to a
// nested location in V2.
// Check version field first - if present and matches current version, no migration needed
if (SETTINGS_VERSION_KEY in settings) {
const version = settings[SETTINGS_VERSION_KEY];
if (typeof version === 'number' && version >= SETTINGS_VERSION) {
return false;
}
}
// Fallback to legacy detection: A file needs migration if it contains any
// top-level key that is moved to a nested location in V2.
const hasV1Keys = Object.entries(MIGRATION_MAP).some(([v1Key, v2Path]) => {
if (v1Key === v2Path || !(v1Key in settings)) {
return false;
@@ -250,6 +262,21 @@ function migrateSettingsToV2(
for (const [oldKey, newPath] of Object.entries(MIGRATION_MAP)) {
if (flatKeys.has(oldKey)) {
// Safety check: If this key is a V2 container (like 'model') and it's
// already an object, it's likely already in V2 format. Skip migration
// to prevent double-nesting (e.g., model.name.name).
if (
KNOWN_V2_CONTAINERS.has(oldKey) &&
typeof flatSettings[oldKey] === 'object' &&
flatSettings[oldKey] !== null &&
!Array.isArray(flatSettings[oldKey])
) {
// This is already a V2 container, carry it over as-is
v2Settings[oldKey] = flatSettings[oldKey];
flatKeys.delete(oldKey);
continue;
}
setNestedProperty(v2Settings, newPath, flatSettings[oldKey]);
flatKeys.delete(oldKey);
}
@@ -287,6 +314,9 @@ function migrateSettingsToV2(
}
}
// Set version field to indicate this is a V2 settings file
v2Settings[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
return v2Settings;
}
@@ -336,6 +366,11 @@ export function migrateSettingsToV1(
// Carry over any unrecognized keys
for (const remainingKey of v2Keys) {
// Skip the version field - it's only for V2 format
if (remainingKey === SETTINGS_VERSION_KEY) {
continue;
}
const value = v2Settings[remainingKey];
if (value === undefined) {
continue;
@@ -448,6 +483,27 @@ export class LoadedSettings {
}
}
/**
* Creates a minimal LoadedSettings instance with empty settings.
* Used in stream-json mode where settings are ignored.
*/
export function createMinimalSettings(): LoadedSettings {
const emptySettingsFile: SettingsFile = {
path: '',
settings: {},
originalSettings: {},
rawJson: '{}',
};
return new LoadedSettings(
emptySettingsFile,
emptySettingsFile,
emptySettingsFile,
emptySettingsFile,
false,
new Set(),
);
}
function findEnvFile(startDir: string): string | null {
let currentDir = path.resolve(startDir);
while (true) {
@@ -621,6 +677,22 @@ export function loadSettings(
}
settingsObject = migratedSettings;
}
} else if (!(SETTINGS_VERSION_KEY in settingsObject)) {
// No migration needed, but version field is missing - add it for future optimizations
settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
if (MIGRATE_V2_OVERWRITE) {
try {
fs.writeFileSync(
filePath,
JSON.stringify(settingsObject, null, 2),
'utf-8',
);
} catch (e) {
console.error(
`Error adding version to settings file: ${getErrorMessage(e)}`,
);
}
}
}
return { settings: settingsObject as Settings, rawJson: content };
}
@@ -787,5 +859,6 @@ export function saveSettings(settingsFile: SettingsFile): void {
);
} catch (error) {
console.error('Error saving user settings file:', error);
throw error;
}
}

View File

@@ -12,6 +12,7 @@ import type {
ChatCompressionSettings,
} from '@qwen-code/qwen-code-core';
import {
ApprovalMode,
DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
} from '@qwen-code/qwen-code-core';
@@ -166,16 +167,6 @@ const SETTINGS_SCHEMA = {
},
},
},
enablePromptCompletion: {
type: 'boolean',
label: 'Enable Prompt Completion',
category: 'General',
requiresRestart: true,
default: false,
description:
'Enable AI-powered prompt completion suggestions while typing.',
showInDialog: true,
},
debugKeystrokeLogging: {
type: 'boolean',
label: 'Debug Keystroke Logging',
@@ -185,6 +176,24 @@ const SETTINGS_SCHEMA = {
description: 'Enable debug logging of keystrokes to the console.',
showInDialog: true,
},
language: {
type: 'enum',
label: 'Language',
category: 'General',
requiresRestart: false,
default: 'auto',
description:
'The language for the user interface. Use "auto" to detect from system settings. ' +
'You can also use custom language codes (e.g., "es", "fr") by placing JS language files ' +
'in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js).',
showInDialog: true,
options: [
{ value: 'auto', label: 'Auto (detect from system)' },
{ value: 'en', label: 'English' },
{ value: 'zh', label: '中文 (Chinese)' },
{ value: 'ru', label: 'Русский (Russian)' },
],
},
},
},
output: {
@@ -549,6 +558,16 @@ const SETTINGS_SCHEMA = {
description: 'Disable all loop detection checks (streaming and LLM).',
showInDialog: true,
},
skipStartupContext: {
type: 'boolean',
label: 'Skip Startup Context',
category: 'Model',
requiresRestart: true,
default: false,
description:
'Avoid sending the workspace startup context at the beginning of each session.',
showInDialog: true,
},
enableOpenAILogging: {
type: 'boolean',
label: 'Enable OpenAI Logging',
@@ -558,6 +577,16 @@ const SETTINGS_SCHEMA = {
description: 'Enable OpenAI logging.',
showInDialog: true,
},
openAILoggingDir: {
type: 'string',
label: 'OpenAI Logging Directory',
category: 'Model',
requiresRestart: false,
default: undefined as string | undefined,
description:
'Custom directory path for OpenAI API logs. If not specified, defaults to logs/openai in the current working directory.',
showInDialog: true,
},
generationConfig: {
type: 'object',
label: 'Generation Configuration',
@@ -810,14 +839,20 @@ const SETTINGS_SCHEMA = {
mergeStrategy: MergeStrategy.UNION,
},
approvalMode: {
type: 'string',
label: 'Default Approval Mode',
type: 'enum',
label: 'Approval Mode',
category: 'Tools',
requiresRestart: false,
default: 'default',
default: ApprovalMode.DEFAULT,
description:
'Default approval mode for tool usage. Valid values: plan, default, auto-edit, yolo.',
'Approval mode for tool usage. Controls how tools are approved before execution.',
showInDialog: true,
options: [
{ value: ApprovalMode.PLAN, label: 'Plan' },
{ value: ApprovalMode.DEFAULT, label: 'Default' },
{ value: ApprovalMode.AUTO_EDIT, label: 'Auto Edit' },
{ value: ApprovalMode.YOLO, label: 'YOLO' },
],
},
discoveryCommand: {
type: 'string',
@@ -847,6 +882,16 @@ const SETTINGS_SCHEMA = {
'Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance.',
showInDialog: true,
},
useBuiltinRipgrep: {
type: 'boolean',
label: 'Use Builtin Ripgrep',
category: 'Tools',
requiresRestart: false,
default: true,
description:
'Use the bundled ripgrep binary. When set to false, the system-level "rg" command will be used instead. This setting is only effective when useRipgrep is true.',
showInDialog: true,
},
enableToolOutputTruncation: {
type: 'boolean',
label: 'Enable Tool Output Truncation',
@@ -991,6 +1036,24 @@ const SETTINGS_SCHEMA = {
description: 'Whether to use an external authentication flow.',
showInDialog: false,
},
apiKey: {
type: 'string',
label: 'API Key',
category: 'Security',
requiresRestart: true,
default: undefined as string | undefined,
description: 'API key for OpenAI compatible authentication.',
showInDialog: false,
},
baseUrl: {
type: 'string',
label: 'Base URL',
category: 'Security',
requiresRestart: true,
default: undefined as string | undefined,
description: 'Base URL for OpenAI compatible API.',
showInDialog: false,
},
},
},
},
@@ -1044,17 +1107,36 @@ const SETTINGS_SCHEMA = {
},
tavilyApiKey: {
type: 'string',
label: 'Tavily API Key',
label: 'Tavily API Key (Deprecated)',
category: 'Advanced',
requiresRestart: false,
default: undefined as string | undefined,
description:
'The API key for the Tavily API. Required to enable the web_search tool functionality.',
'⚠️ DEPRECATED: Please use webSearch.provider configuration instead. Legacy API key for the Tavily API.',
showInDialog: false,
},
},
},
webSearch: {
type: 'object',
label: 'Web Search',
category: 'Advanced',
requiresRestart: true,
default: undefined as
| {
provider: Array<{
type: 'tavily' | 'google' | 'dashscope';
apiKey?: string;
searchEngineId?: string;
}>;
default: string;
}
| undefined,
description: 'Configuration for web search providers.',
showInDialog: false,
},
experimental: {
type: 'object',
label: 'Experimental',

View File

@@ -0,0 +1,121 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import { AuthType } from '@qwen-code/qwen-code-core';
import type { WebSearchProviderConfig } from '@qwen-code/qwen-code-core';
import type { Settings } from './settings.js';
/**
* CLI arguments related to web search configuration
*/
export interface WebSearchCliArgs {
tavilyApiKey?: string;
googleApiKey?: string;
googleSearchEngineId?: string;
webSearchDefault?: string;
}
/**
* Web search configuration structure
*/
export interface WebSearchConfig {
provider: WebSearchProviderConfig[];
default: string;
}
/**
* Build webSearch configuration from multiple sources with priority:
* 1. settings.json (new format) - highest priority
* 2. Command line args + environment variables
* 3. Legacy tavilyApiKey (backward compatibility)
*
* @param argv - Command line arguments
* @param settings - User settings from settings.json
* @param authType - Authentication type (e.g., 'qwen-oauth')
* @returns WebSearch configuration or undefined if no providers available
*/
export function buildWebSearchConfig(
argv: WebSearchCliArgs,
settings: Settings,
authType?: string,
): WebSearchConfig | undefined {
const isQwenOAuth = authType === AuthType.QWEN_OAUTH;
// Step 1: Collect providers from settings or command line/env
let providers: WebSearchProviderConfig[] = [];
let userDefault: string | undefined;
if (settings.webSearch) {
// Use providers from settings.json
providers = [...settings.webSearch.provider];
userDefault = settings.webSearch.default;
} else {
// Build providers from command line args and environment variables
const tavilyKey =
argv.tavilyApiKey ||
settings.advanced?.tavilyApiKey ||
process.env['TAVILY_API_KEY'];
if (tavilyKey) {
providers.push({
type: 'tavily',
apiKey: tavilyKey,
} as WebSearchProviderConfig);
}
const googleKey = argv.googleApiKey || process.env['GOOGLE_API_KEY'];
const googleEngineId =
argv.googleSearchEngineId || process.env['GOOGLE_SEARCH_ENGINE_ID'];
if (googleKey && googleEngineId) {
providers.push({
type: 'google',
apiKey: googleKey,
searchEngineId: googleEngineId,
} as WebSearchProviderConfig);
}
}
// Step 2: Ensure dashscope is available for qwen-oauth users
if (isQwenOAuth) {
const hasDashscope = providers.some((p) => p.type === 'dashscope');
if (!hasDashscope) {
providers.push({ type: 'dashscope' } as WebSearchProviderConfig);
}
}
// Step 3: If no providers available, return undefined
if (providers.length === 0) {
return undefined;
}
// Step 4: Determine default provider
// Priority: user explicit config > CLI arg > first available provider (tavily > google > dashscope)
const providerPriority: Array<'tavily' | 'google' | 'dashscope'> = [
'tavily',
'google',
'dashscope',
];
// Determine default provider based on availability
let defaultProvider = userDefault || argv.webSearchDefault;
if (!defaultProvider) {
// Find first available provider by priority order
for (const providerType of providerPriority) {
if (providers.some((p) => p.type === providerType)) {
defaultProvider = providerType;
break;
}
}
// Fallback to first available provider if none found in priority list
if (!defaultProvider) {
defaultProvider = providers[0]?.type || 'dashscope';
}
}
return {
provider: providers,
default: defaultProvider,
};
}

View File

@@ -8,6 +8,8 @@ import {
type AuthType,
type Config,
getErrorMessage,
logAuth,
AuthEvent,
} from '@qwen-code/qwen-code-core';
/**
@@ -25,11 +27,21 @@ export async function performInitialAuth(
}
try {
await config.refreshAuth(authType);
await config.refreshAuth(authType, true);
// The console.log is intentionally left out here.
// We can add a dedicated startup message later if needed.
// Log authentication success
const authEvent = new AuthEvent(authType, 'auto', 'success');
logAuth(config, authEvent);
} catch (e) {
return `Failed to login. Message: ${getErrorMessage(e)}`;
const errorMessage = `Failed to login. Message: ${getErrorMessage(e)}`;
// Log authentication failure
const authEvent = new AuthEvent(authType, 'auto', 'error', errorMessage);
logAuth(config, authEvent);
return errorMessage;
}
return null;

View File

@@ -11,9 +11,10 @@ import {
logIdeConnection,
type Config,
} from '@qwen-code/qwen-code-core';
import { type LoadedSettings } from '../config/settings.js';
import { type LoadedSettings, SettingScope } from '../config/settings.js';
import { performInitialAuth } from './auth.js';
import { validateTheme } from './theme.js';
import { initializeI18n } from '../i18n/index.js';
export interface InitializationResult {
authError: string | null;
@@ -33,10 +34,24 @@ export async function initializeApp(
config: Config,
settings: LoadedSettings,
): Promise<InitializationResult> {
const authError = await performInitialAuth(
config,
settings.merged.security?.auth?.selectedType,
);
// Initialize i18n system
const languageSetting =
process.env['QWEN_CODE_LANG'] ||
settings.merged.general?.language ||
'auto';
await initializeI18n(languageSetting);
const authType = settings.merged.security?.auth?.selectedType;
const authError = await performInitialAuth(config, authType);
// Fallback to user select when initial authentication fails
if (authError) {
settings.setValue(
SettingScope.User,
'security.auth.selectedType',
undefined,
);
}
const themeError = validateTheme(settings);
const shouldOpenAuthDialog =

View File

@@ -6,6 +6,7 @@
import { themeManager } from '../ui/themes/theme-manager.js';
import { type LoadedSettings } from '../config/settings.js';
import { t } from '../i18n/index.js';
/**
* Validates the configured theme.
@@ -15,7 +16,9 @@ import { type LoadedSettings } from '../config/settings.js';
export function validateTheme(settings: LoadedSettings): string | null {
const effectiveTheme = settings.merged.ui?.theme;
if (effectiveTheme && !themeManager.findThemeByName(effectiveTheme)) {
return `Theme "${effectiveTheme}" not found.`;
return t('Theme "{{themeName}}" not found.', {
themeName: effectiveTheme,
});
}
return null;
}

View File

@@ -22,6 +22,7 @@ import {
import { type LoadedSettings } from './config/settings.js';
import { appEvents, AppEvent } from './utils/events.js';
import type { Config } from '@qwen-code/qwen-code-core';
import { OutputFormat } from '@qwen-code/qwen-code-core';
// Custom error to identify mock process.exit calls
class MockProcessExitError extends Error {
@@ -158,6 +159,7 @@ describe('gemini.tsx main function', () => {
getScreenReader: () => false,
getGeminiMdFileCount: () => 0,
getProjectRoot: () => '/',
getOutputFormat: () => OutputFormat.TEXT,
} as unknown as Config;
});
vi.mocked(loadSettings).mockReturnValue({
@@ -230,6 +232,143 @@ describe('gemini.tsx main function', () => {
// Avoid the process.exit error from being thrown.
processExitSpy.mockRestore();
});
it('invokes runNonInteractiveStreamJson and performs cleanup in stream-json mode', async () => {
const originalIsTTY = Object.getOwnPropertyDescriptor(
process.stdin,
'isTTY',
);
const originalIsRaw = Object.getOwnPropertyDescriptor(
process.stdin,
'isRaw',
);
Object.defineProperty(process.stdin, 'isTTY', {
value: true,
configurable: true,
});
Object.defineProperty(process.stdin, 'isRaw', {
value: false,
configurable: true,
});
const processExitSpy = vi
.spyOn(process, 'exit')
.mockImplementation((code) => {
throw new MockProcessExitError(code);
});
const { loadCliConfig, parseArguments } = await import(
'./config/config.js'
);
const { loadSettings } = await import('./config/settings.js');
const cleanupModule = await import('./utils/cleanup.js');
const extensionModule = await import('./config/extension.js');
const validatorModule = await import('./validateNonInterActiveAuth.js');
const streamJsonModule = await import('./nonInteractive/session.js');
const initializerModule = await import('./core/initializer.js');
const startupWarningsModule = await import('./utils/startupWarnings.js');
const userStartupWarningsModule = await import(
'./utils/userStartupWarnings.js'
);
vi.mocked(cleanupModule.cleanupCheckpoints).mockResolvedValue(undefined);
vi.mocked(cleanupModule.registerCleanup).mockImplementation(() => {});
const runExitCleanupMock = vi.mocked(cleanupModule.runExitCleanup);
runExitCleanupMock.mockResolvedValue(undefined);
vi.spyOn(extensionModule, 'loadExtensions').mockReturnValue([]);
vi.spyOn(
extensionModule.ExtensionStorage,
'getUserExtensionsDir',
).mockReturnValue('/tmp/extensions');
vi.spyOn(initializerModule, 'initializeApp').mockResolvedValue({
authError: null,
themeError: null,
shouldOpenAuthDialog: false,
geminiMdFileCount: 0,
});
vi.spyOn(startupWarningsModule, 'getStartupWarnings').mockResolvedValue([]);
vi.spyOn(
userStartupWarningsModule,
'getUserStartupWarnings',
).mockResolvedValue([]);
const validatedConfig = { validated: true } as unknown as Config;
const validateAuthSpy = vi
.spyOn(validatorModule, 'validateNonInteractiveAuth')
.mockResolvedValue(validatedConfig);
const runStreamJsonSpy = vi
.spyOn(streamJsonModule, 'runNonInteractiveStreamJson')
.mockResolvedValue(undefined);
vi.mocked(loadSettings).mockReturnValue({
errors: [],
merged: {
advanced: {},
security: { auth: {} },
ui: {},
},
setValue: vi.fn(),
forScope: () => ({ settings: {}, originalSettings: {}, path: '' }),
} as never);
vi.mocked(parseArguments).mockResolvedValue({
extensions: [],
} as never);
const configStub = {
isInteractive: () => false,
getQuestion: () => ' hello stream ',
getSandbox: () => false,
getDebugMode: () => false,
getListExtensions: () => false,
getMcpServers: () => ({}),
initialize: vi.fn().mockResolvedValue(undefined),
getIdeMode: () => false,
getExperimentalZedIntegration: () => false,
getScreenReader: () => false,
getGeminiMdFileCount: () => 0,
getProjectRoot: () => '/',
getInputFormat: () => 'stream-json',
getContentGeneratorConfig: () => ({ authType: 'test-auth' }),
} as unknown as Config;
vi.mocked(loadCliConfig).mockResolvedValue(configStub);
process.env['SANDBOX'] = '1';
try {
await main();
} catch (error) {
if (!(error instanceof MockProcessExitError)) {
throw error;
}
} finally {
processExitSpy.mockRestore();
if (originalIsTTY) {
Object.defineProperty(process.stdin, 'isTTY', originalIsTTY);
} else {
delete (process.stdin as { isTTY?: unknown }).isTTY;
}
if (originalIsRaw) {
Object.defineProperty(process.stdin, 'isRaw', originalIsRaw);
} else {
delete (process.stdin as { isRaw?: unknown }).isRaw;
}
delete process.env['SANDBOX'];
}
expect(runStreamJsonSpy).toHaveBeenCalledTimes(1);
const [configArg, inputArg] = runStreamJsonSpy.mock.calls[0];
expect(configArg).toBe(validatedConfig);
expect(inputArg).toBe('hello stream');
expect(validateAuthSpy).toHaveBeenCalledWith(
undefined,
undefined,
configStub,
expect.any(Object),
);
expect(runExitCleanupMock).toHaveBeenCalledTimes(1);
});
});
describe('gemini.tsx main function kitty protocol', () => {
@@ -327,13 +466,26 @@ describe('gemini.tsx main function kitty protocol', () => {
openaiLogging: undefined,
openaiApiKey: undefined,
openaiBaseUrl: undefined,
openaiLoggingDir: undefined,
proxy: undefined,
includeDirectories: undefined,
tavilyApiKey: undefined,
googleApiKey: undefined,
googleSearchEngineId: undefined,
webSearchDefault: undefined,
screenReader: undefined,
vlmSwitchMode: undefined,
useSmartEdit: undefined,
inputFormat: undefined,
outputFormat: undefined,
includePartialMessages: undefined,
continue: undefined,
resume: undefined,
coreTools: undefined,
excludeTools: undefined,
authType: undefined,
maxSessionTurns: undefined,
channel: undefined,
});
await main();
@@ -408,6 +560,7 @@ describe('startInteractiveUI', () => {
vi.mock('./utils/cleanup.js', () => ({
cleanupCheckpoints: vi.fn(() => Promise.resolve()),
registerCleanup: vi.fn(),
runExitCleanup: vi.fn(() => Promise.resolve()),
}));
vi.mock('ink', () => ({

View File

@@ -4,63 +4,61 @@
* SPDX-License-Identifier: Apache-2.0
*/
import React from 'react';
import type { Config } from '@qwen-code/qwen-code-core';
import {
AuthType,
getOauthClient,
InputFormat,
logUserPrompt,
} from '@qwen-code/qwen-code-core';
import { render } from 'ink';
import { AppContainer } from './ui/AppContainer.js';
import { loadCliConfig, parseArguments } from './config/config.js';
import * as cliConfig from './config/config.js';
import { readStdin } from './utils/readStdin.js';
import dns from 'node:dns';
import os from 'node:os';
import { basename } from 'node:path';
import v8 from 'node:v8';
import os from 'node:os';
import dns from 'node:dns';
import { randomUUID } from 'node:crypto';
import { start_sandbox } from './utils/sandbox.js';
import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js';
import {
loadSettings,
migrateDeprecatedSettings,
SettingScope,
} from './config/settings.js';
import { themeManager } from './ui/themes/theme-manager.js';
import { getStartupWarnings } from './utils/startupWarnings.js';
import { getUserStartupWarnings } from './utils/userStartupWarnings.js';
import { ConsolePatcher } from './ui/utils/ConsolePatcher.js';
import { runNonInteractive } from './nonInteractiveCli.js';
import React from 'react';
import { validateAuthMethod } from './config/auth.js';
import * as cliConfig from './config/config.js';
import { loadCliConfig, parseArguments } from './config/config.js';
import { ExtensionStorage, loadExtensions } from './config/extension.js';
import type { DnsResolutionOrder, LoadedSettings } from './config/settings.js';
import { loadSettings, migrateDeprecatedSettings } from './config/settings.js';
import {
initializeApp,
type InitializationResult,
} from './core/initializer.js';
import { runNonInteractive } from './nonInteractiveCli.js';
import { runNonInteractiveStreamJson } from './nonInteractive/session.js';
import { AppContainer } from './ui/AppContainer.js';
import { setMaxSizedBoxDebugging } from './ui/components/shared/MaxSizedBox.js';
import { KeypressProvider } from './ui/contexts/KeypressContext.js';
import { SessionStatsProvider } from './ui/contexts/SessionContext.js';
import { SettingsContext } from './ui/contexts/SettingsContext.js';
import { VimModeProvider } from './ui/contexts/VimModeContext.js';
import { useKittyKeyboardProtocol } from './ui/hooks/useKittyKeyboardProtocol.js';
import { themeManager } from './ui/themes/theme-manager.js';
import { ConsolePatcher } from './ui/utils/ConsolePatcher.js';
import { detectAndEnableKittyProtocol } from './ui/utils/kittyProtocolDetector.js';
import { checkForUpdates } from './ui/utils/updateCheck.js';
import {
cleanupCheckpoints,
registerCleanup,
runExitCleanup,
} from './utils/cleanup.js';
import { getCliVersion } from './utils/version.js';
import type { Config } from '@qwen-code/qwen-code-core';
import {
AuthType,
getOauthClient,
logUserPrompt,
} from '@qwen-code/qwen-code-core';
import {
initializeApp,
type InitializationResult,
} from './core/initializer.js';
import { validateAuthMethod } from './config/auth.js';
import { setMaxSizedBoxDebugging } from './ui/components/shared/MaxSizedBox.js';
import { SettingsContext } from './ui/contexts/SettingsContext.js';
import { detectAndEnableKittyProtocol } from './ui/utils/kittyProtocolDetector.js';
import { checkForUpdates } from './ui/utils/updateCheck.js';
import { AppEvent, appEvents } from './utils/events.js';
import { handleAutoUpdate } from './utils/handleAutoUpdate.js';
import { computeWindowTitle } from './utils/windowTitle.js';
import { SessionStatsProvider } from './ui/contexts/SessionContext.js';
import { VimModeProvider } from './ui/contexts/VimModeContext.js';
import { KeypressProvider } from './ui/contexts/KeypressContext.js';
import { appEvents, AppEvent } from './utils/events.js';
import { useKittyKeyboardProtocol } from './ui/hooks/useKittyKeyboardProtocol.js';
import { readStdin } from './utils/readStdin.js';
import {
relaunchOnExitCode,
relaunchAppInChildProcess,
relaunchOnExitCode,
} from './utils/relaunch.js';
import { start_sandbox } from './utils/sandbox.js';
import { getStartupWarnings } from './utils/startupWarnings.js';
import { getUserStartupWarnings } from './utils/userStartupWarnings.js';
import { getCliVersion } from './utils/version.js';
import { computeWindowTitle } from './utils/windowTitle.js';
import { validateNonInteractiveAuth } from './validateNonInterActiveAuth.js';
import { showResumeSessionPicker } from './ui/components/ResumeSessionPicker.js';
export function validateDnsResolutionOrder(
order: string | undefined,
@@ -110,9 +108,9 @@ function getNodeMemoryArgs(isDebugMode: boolean): string[] {
return [];
}
import { runZedIntegration } from './zed-integration/zedIntegration.js';
import { loadSandboxConfig } from './config/sandboxConfig.js';
import { ExtensionEnablementManager } from './config/extensions/extensionEnablement.js';
import { loadSandboxConfig } from './config/sandboxConfig.js';
import { runAcpAgent } from './acp-integration/acpAgent.js';
export function setupUnhandledRejectionHandler() {
let unhandledRejectionOccurred = false;
@@ -160,7 +158,7 @@ export async function startInteractiveUI(
process.platform === 'win32' || nodeMajorVersion < 20
}
>
<SessionStatsProvider>
<SessionStatsProvider sessionId={config.getSessionId()}>
<VimModeProvider settings={settings}>
<AppContainer
config={config}
@@ -209,9 +207,8 @@ export async function main() {
const settings = loadSettings();
migrateDeprecatedSettings(settings);
await cleanupCheckpoints();
const sessionId = randomUUID();
const argv = await parseArguments(settings.merged);
let argv = await parseArguments(settings.merged);
// Check for invalid input combinations early to prevent crashes
if (argv.promptInteractive && !process.stdin.isTTY) {
@@ -222,28 +219,11 @@ export async function main() {
}
const isDebugMode = cliConfig.isDebugMode(argv);
const consolePatcher = new ConsolePatcher({
stderr: true,
debugMode: isDebugMode,
});
consolePatcher.patch();
registerCleanup(consolePatcher.cleanup);
dns.setDefaultResultOrder(
validateDnsResolutionOrder(settings.merged.advanced?.dnsResolutionOrder),
);
// Set a default auth type if one isn't set.
if (!settings.merged.security?.auth?.selectedType) {
if (process.env['CLOUD_SHELL'] === 'true') {
settings.setValue(
SettingScope.User,
'selectedAuthType',
AuthType.CLOUD_SHELL,
);
}
}
// Load custom themes from settings
themeManager.loadCustomThemes(settings.merged.ui?.customThemes);
@@ -272,7 +252,6 @@ export async function main() {
settings.merged,
[],
new ExtensionEnablementManager(ExtensionStorage.getUserExtensionsDir()),
sessionId,
argv,
);
@@ -297,8 +276,11 @@ export async function main() {
process.exit(1);
}
}
// For stream-json mode, don't read stdin here - it should be forwarded to the sandbox
// and consumed by StreamJsonInputReader inside the container
const inputFormat = argv.inputFormat as string | undefined;
let stdinData = '';
if (!process.stdin.isTTY) {
if (!process.stdin.isTTY && inputFormat !== 'stream-json') {
stdinData = await readStdin();
}
@@ -338,6 +320,18 @@ export async function main() {
}
}
// Handle --resume without a session ID by showing the session picker
if (argv.resume === '') {
const selectedSessionId = await showResumeSessionPicker();
if (!selectedSessionId) {
// User cancelled or no sessions available
process.exit(0);
}
// Update argv with the selected session ID
argv = { ...argv, resume: selectedSessionId };
}
// We are now past the logic handling potentially launching a child process
// to run Gemini CLI. It is now safe to perform expensive initialization that
// may have side effects.
@@ -351,7 +345,6 @@ export async function main() {
settings.merged,
extensions,
extensionEnablementManager,
sessionId,
argv,
);
@@ -363,6 +356,15 @@ export async function main() {
process.exit(0);
}
// Setup unified ConsolePatcher based on interactive mode
const isInteractive = config.isInteractive();
const consolePatcher = new ConsolePatcher({
stderr: isInteractive,
debugMode: isDebugMode,
});
consolePatcher.patch();
registerCleanup(consolePatcher.cleanup);
const wasRaw = process.stdin.isRaw;
let kittyProtocolDetectionComplete: Promise<boolean> | undefined;
if (config.isInteractive() && !wasRaw && process.stdin.isTTY) {
@@ -384,7 +386,18 @@ export async function main() {
setMaxSizedBoxDebugging(isDebugMode);
const initializationResult = await initializeApp(config, settings);
// Check input format early to determine initialization flow
const inputFormat =
typeof config.getInputFormat === 'function'
? config.getInputFormat()
: InputFormat.TEXT;
// For stream-json mode, defer config.initialize() until after the initialize control request
// For other modes, initialize normally
let initializationResult: InitializationResult | undefined;
if (inputFormat !== InputFormat.STREAM_JSON) {
initializationResult = await initializeApp(config, settings);
}
if (
settings.merged.security?.auth?.selectedType ===
@@ -396,13 +409,17 @@ export async function main() {
}
if (config.getExperimentalZedIntegration()) {
return runZedIntegration(config, settings, extensions, argv);
return runAcpAgent(config, settings, extensions, argv);
}
let input = config.getQuestion();
const startupWarnings = [
...(await getStartupWarnings()),
...(await getUserStartupWarnings()),
...(await getUserStartupWarnings({
workspaceRoot: process.cwd(),
useRipgrep: settings.merged.tools?.useRipgrep ?? true,
useBuiltinRipgrep: settings.merged.tools?.useBuiltinRipgrep ?? true,
})),
];
// Render UI, passing necessary config values. Check that there is no command line question.
@@ -414,21 +431,47 @@ export async function main() {
settings,
startupWarnings,
process.cwd(),
initializationResult,
initializationResult!,
);
return;
}
await config.initialize();
// For non-stream-json mode, initialize config here
if (inputFormat !== InputFormat.STREAM_JSON) {
await config.initialize();
}
// If not a TTY, read from stdin
// This is for cases where the user pipes input directly into the command
if (!process.stdin.isTTY) {
// Only read stdin if NOT in stream-json mode
// In stream-json mode, stdin is used for protocol messages (control requests, etc.)
// and should be consumed by StreamJsonInputReader instead
if (inputFormat !== InputFormat.STREAM_JSON && !process.stdin.isTTY) {
const stdinData = await readStdin();
if (stdinData) {
input = `${stdinData}\n\n${input}`;
}
}
const nonInteractiveConfig = await validateNonInteractiveAuth(
(argv.authType as AuthType) ||
settings.merged.security?.auth?.selectedType,
settings.merged.security?.auth?.useExternal,
config,
settings,
);
const prompt_id = Math.random().toString(16).slice(2);
if (inputFormat === InputFormat.STREAM_JSON) {
const trimmedInput = (input ?? '').trim();
await runNonInteractiveStreamJson(
nonInteractiveConfig,
trimmedInput.length > 0 ? trimmedInput : '',
);
await runExitCleanup();
process.exit(0);
}
if (!input) {
console.error(
`No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`,
@@ -436,7 +479,6 @@ export async function main() {
process.exit(1);
}
const prompt_id = Math.random().toString(16).slice(2);
logUserPrompt(config, {
'event.name': 'user_prompt',
'event.timestamp': new Date().toISOString(),
@@ -446,15 +488,8 @@ export async function main() {
prompt_length: input.length,
});
const nonInteractiveConfig = await validateNonInteractiveAuth(
settings.merged.security?.auth?.selectedType,
settings.merged.security?.auth?.useExternal,
config,
settings,
);
if (config.getDebugMode()) {
console.log('Session ID: %s', sessionId);
console.log('Session ID: %s', config.getSessionId());
}
await runNonInteractive(nonInteractiveConfig, settings, input, prompt_id);

View File

@@ -0,0 +1,234 @@
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { homedir } from 'node:os';
export type SupportedLanguage = 'en' | 'zh' | 'ru' | string; // Allow custom language codes
// State
let currentLanguage: SupportedLanguage = 'en';
let translations: Record<string, string> = {};
// Cache
type TranslationDict = Record<string, string>;
const translationCache: Record<string, TranslationDict> = {};
const loadingPromises: Record<string, Promise<TranslationDict>> = {};
// Path helpers
const getBuiltinLocalesDir = (): string => {
const __filename = fileURLToPath(import.meta.url);
return path.join(path.dirname(__filename), 'locales');
};
const getUserLocalesDir = (): string =>
path.join(homedir(), '.qwen', 'locales');
/**
* Get the path to the user's custom locales directory.
* Users can place custom language packs (e.g., es.js, fr.js) in this directory.
* @returns The path to ~/.qwen/locales
*/
export function getUserLocalesDirectory(): string {
return getUserLocalesDir();
}
const getLocalePath = (
lang: SupportedLanguage,
useUserDir: boolean = false,
): string => {
const baseDir = useUserDir ? getUserLocalesDir() : getBuiltinLocalesDir();
return path.join(baseDir, `${lang}.js`);
};
// Language detection
export function detectSystemLanguage(): SupportedLanguage {
const envLang = process.env['QWEN_CODE_LANG'] || process.env['LANG'];
if (envLang?.startsWith('zh')) return 'zh';
if (envLang?.startsWith('en')) return 'en';
if (envLang?.startsWith('ru')) return 'ru';
try {
const locale = Intl.DateTimeFormat().resolvedOptions().locale;
if (locale.startsWith('zh')) return 'zh';
if (locale.startsWith('ru')) return 'ru';
} catch {
// Fallback to default
}
return 'en';
}
// Translation loading
async function loadTranslationsAsync(
lang: SupportedLanguage,
): Promise<TranslationDict> {
if (translationCache[lang]) {
return translationCache[lang];
}
const existingPromise = loadingPromises[lang];
if (existingPromise) {
return existingPromise;
}
const loadPromise = (async () => {
// Try user directory first (for custom language packs), then builtin directory
const searchDirs = [
{ dir: getUserLocalesDir(), isUser: true },
{ dir: getBuiltinLocalesDir(), isUser: false },
];
for (const { dir, isUser } of searchDirs) {
// Ensure directory exists
if (!fs.existsSync(dir)) {
continue;
}
const jsPath = getLocalePath(lang, isUser);
if (!fs.existsSync(jsPath)) {
continue;
}
try {
// Convert file path to file:// URL for cross-platform compatibility
const fileUrl = pathToFileURL(jsPath).href;
try {
const module = await import(fileUrl);
const result = module.default || module;
if (
result &&
typeof result === 'object' &&
Object.keys(result).length > 0
) {
translationCache[lang] = result;
return result;
} else {
throw new Error('Module loaded but result is empty or invalid');
}
} catch {
// For builtin locales, try alternative import method (relative path)
if (!isUser) {
try {
const module = await import(`./locales/${lang}.js`);
const result = module.default || module;
if (
result &&
typeof result === 'object' &&
Object.keys(result).length > 0
) {
translationCache[lang] = result;
return result;
}
} catch {
// Continue to next directory
}
}
// If import failed, continue to next directory
continue;
}
} catch (error) {
// Log warning but continue to next directory
if (isUser) {
console.warn(
`Failed to load translations from user directory for ${lang}:`,
error,
);
} else {
console.warn(`Failed to load JS translations for ${lang}:`, error);
if (error instanceof Error) {
console.warn(`Error details: ${error.message}`);
console.warn(`Stack: ${error.stack}`);
}
}
// Continue to next directory
continue;
}
}
// Return empty object if both directories fail
// Cache it to avoid repeated failed attempts
translationCache[lang] = {};
return {};
})();
loadingPromises[lang] = loadPromise;
// Clean up promise after completion to allow retry on next call if needed
loadPromise.finally(() => {
delete loadingPromises[lang];
});
return loadPromise;
}
function loadTranslations(lang: SupportedLanguage): TranslationDict {
// Only return from cache (JS files require async loading)
return translationCache[lang] || {};
}
// String interpolation
function interpolate(
template: string,
params?: Record<string, string>,
): string {
if (!params) return template;
return template.replace(
/\{\{(\w+)\}\}/g,
(match, key) => params[key] ?? match,
);
}
// Language setting helpers
function resolveLanguage(lang: SupportedLanguage | 'auto'): SupportedLanguage {
return lang === 'auto' ? detectSystemLanguage() : lang;
}
// Public API
export function setLanguage(lang: SupportedLanguage | 'auto'): void {
const resolvedLang = resolveLanguage(lang);
currentLanguage = resolvedLang;
// Try to load translations synchronously (from cache only)
const loaded = loadTranslations(resolvedLang);
translations = loaded;
// Warn if translations are empty and JS file exists (requires async loading)
if (Object.keys(loaded).length === 0) {
const userJsPath = getLocalePath(resolvedLang, true);
const builtinJsPath = getLocalePath(resolvedLang, false);
if (fs.existsSync(userJsPath) || fs.existsSync(builtinJsPath)) {
console.warn(
`Language file for ${resolvedLang} requires async loading. ` +
`Use setLanguageAsync() instead, or call initializeI18n() first.`,
);
}
}
}
export async function setLanguageAsync(
lang: SupportedLanguage | 'auto',
): Promise<void> {
currentLanguage = resolveLanguage(lang);
translations = await loadTranslationsAsync(currentLanguage);
}
export function getCurrentLanguage(): SupportedLanguage {
return currentLanguage;
}
export function t(key: string, params?: Record<string, string>): string {
const translation = translations[key] ?? key;
return interpolate(translation, params);
}
export async function initializeI18n(
lang?: SupportedLanguage | 'auto',
): Promise<void> {
await setLanguageAsync(lang ?? 'auto');
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,76 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Control Context
*
* Layer 1 of the control plane architecture. Provides shared, session-scoped
* state for all controllers and services, eliminating the need for prop
* drilling. Mutable fields are intentionally exposed so controllers can track
* runtime state (e.g. permission mode, active MCP clients).
*/
import type { Config, MCPServerConfig } from '@qwen-code/qwen-code-core';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
import type { StreamJsonOutputAdapter } from '../io/StreamJsonOutputAdapter.js';
import type { PermissionMode } from '../types.js';
/**
* Control Context interface
*
* Provides shared access to session-scoped resources and mutable state
* for all controllers across both ControlDispatcher (protocol routing) and
* ControlService (programmatic API).
*/
export interface IControlContext {
readonly config: Config;
readonly streamJson: StreamJsonOutputAdapter;
readonly sessionId: string;
readonly abortSignal: AbortSignal;
readonly debugMode: boolean;
permissionMode: PermissionMode;
sdkMcpServers: Set<string>;
mcpClients: Map<string, { client: Client; config: MCPServerConfig }>;
onInterrupt?: () => void;
}
/**
* Control Context implementation
*/
export class ControlContext implements IControlContext {
readonly config: Config;
readonly streamJson: StreamJsonOutputAdapter;
readonly sessionId: string;
readonly abortSignal: AbortSignal;
readonly debugMode: boolean;
permissionMode: PermissionMode;
sdkMcpServers: Set<string>;
mcpClients: Map<string, { client: Client; config: MCPServerConfig }>;
onInterrupt?: () => void;
constructor(options: {
config: Config;
streamJson: StreamJsonOutputAdapter;
sessionId: string;
abortSignal: AbortSignal;
permissionMode?: PermissionMode;
onInterrupt?: () => void;
}) {
this.config = options.config;
this.streamJson = options.streamJson;
this.sessionId = options.sessionId;
this.abortSignal = options.abortSignal;
this.debugMode = options.config.getDebugMode();
this.permissionMode = options.permissionMode || 'default';
this.sdkMcpServers = new Set();
this.mcpClients = new Map();
this.onInterrupt = options.onInterrupt;
}
}

View File

@@ -0,0 +1,924 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ControlDispatcher } from './ControlDispatcher.js';
import type { IControlContext } from './ControlContext.js';
import type { SystemController } from './controllers/systemController.js';
import type { StreamJsonOutputAdapter } from '../io/StreamJsonOutputAdapter.js';
import type {
CLIControlRequest,
CLIControlResponse,
ControlResponse,
ControlRequestPayload,
CLIControlInitializeRequest,
CLIControlInterruptRequest,
CLIControlSetModelRequest,
CLIControlSupportedCommandsRequest,
} from '../types.js';
/**
* Creates a mock control context for testing
*/
function createMockContext(debugMode: boolean = false): IControlContext {
const abortController = new AbortController();
const mockStreamJson = {
send: vi.fn(),
} as unknown as StreamJsonOutputAdapter;
const mockConfig = {
getDebugMode: vi.fn().mockReturnValue(debugMode),
};
return {
config: mockConfig as unknown as IControlContext['config'],
streamJson: mockStreamJson,
sessionId: 'test-session-id',
abortSignal: abortController.signal,
debugMode,
permissionMode: 'default',
sdkMcpServers: new Set<string>(),
mcpClients: new Map(),
};
}
/**
* Creates a mock system controller for testing
*/
function createMockSystemController() {
return {
handleRequest: vi.fn(),
sendControlRequest: vi.fn(),
cleanup: vi.fn(),
} as unknown as SystemController;
}
describe('ControlDispatcher', () => {
let dispatcher: ControlDispatcher;
let mockContext: IControlContext;
let mockSystemController: SystemController;
beforeEach(() => {
mockContext = createMockContext();
mockSystemController = createMockSystemController();
// Mock SystemController constructor
vi.doMock('./controllers/systemController.js', () => ({
SystemController: vi.fn().mockImplementation(() => mockSystemController),
}));
dispatcher = new ControlDispatcher(mockContext);
// Replace with mock controller for easier testing
(
dispatcher as unknown as { systemController: SystemController }
).systemController = mockSystemController;
});
describe('constructor', () => {
it('should initialize with context and create controllers', () => {
expect(dispatcher).toBeDefined();
expect(dispatcher.systemController).toBeDefined();
});
it('should listen to abort signal and shutdown when aborted', () => {
const abortController = new AbortController();
const context = {
...createMockContext(),
abortSignal: abortController.signal,
};
const newDispatcher = new ControlDispatcher(context);
vi.spyOn(newDispatcher, 'shutdown');
abortController.abort();
// Give event loop a chance to process
return new Promise<void>((resolve) => {
setImmediate(() => {
expect(newDispatcher.shutdown).toHaveBeenCalled();
resolve();
});
});
});
});
describe('dispatch', () => {
it('should route initialize request to system controller', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-1',
request: {
subtype: 'initialize',
} as CLIControlInitializeRequest,
};
const mockResponse = {
subtype: 'initialize',
capabilities: { test: true },
};
vi.mocked(mockSystemController.handleRequest).mockResolvedValue(
mockResponse,
);
await dispatcher.dispatch(request);
expect(mockSystemController.handleRequest).toHaveBeenCalledWith(
request.request,
'req-1',
);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'success',
request_id: 'req-1',
response: mockResponse,
},
});
});
it('should route interrupt request to system controller', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-2',
request: {
subtype: 'interrupt',
} as CLIControlInterruptRequest,
};
const mockResponse = { subtype: 'interrupt' };
vi.mocked(mockSystemController.handleRequest).mockResolvedValue(
mockResponse,
);
await dispatcher.dispatch(request);
expect(mockSystemController.handleRequest).toHaveBeenCalledWith(
request.request,
'req-2',
);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'success',
request_id: 'req-2',
response: mockResponse,
},
});
});
it('should route set_model request to system controller', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-3',
request: {
subtype: 'set_model',
model: 'test-model',
} as CLIControlSetModelRequest,
};
const mockResponse = {
subtype: 'set_model',
model: 'test-model',
};
vi.mocked(mockSystemController.handleRequest).mockResolvedValue(
mockResponse,
);
await dispatcher.dispatch(request);
expect(mockSystemController.handleRequest).toHaveBeenCalledWith(
request.request,
'req-3',
);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'success',
request_id: 'req-3',
response: mockResponse,
},
});
});
it('should route supported_commands request to system controller', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-4',
request: {
subtype: 'supported_commands',
} as CLIControlSupportedCommandsRequest,
};
const mockResponse = {
subtype: 'supported_commands',
commands: ['initialize', 'interrupt'],
};
vi.mocked(mockSystemController.handleRequest).mockResolvedValue(
mockResponse,
);
await dispatcher.dispatch(request);
expect(mockSystemController.handleRequest).toHaveBeenCalledWith(
request.request,
'req-4',
);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'success',
request_id: 'req-4',
response: mockResponse,
},
});
});
it('should send error response when controller throws error', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-5',
request: {
subtype: 'initialize',
} as CLIControlInitializeRequest,
};
const error = new Error('Test error');
vi.mocked(mockSystemController.handleRequest).mockRejectedValue(error);
await dispatcher.dispatch(request);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: 'req-5',
error: 'Test error',
},
});
});
it('should handle non-Error thrown values', async () => {
const request: CLIControlRequest = {
type: 'control_request',
request_id: 'req-6',
request: {
subtype: 'initialize',
} as CLIControlInitializeRequest,
};
vi.mocked(mockSystemController.handleRequest).mockRejectedValue(
'String error',
);
await dispatcher.dispatch(request);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: 'req-6',
error: 'String error',
},
});
});
it('should send error response for unknown request subtype', async () => {
const request = {
type: 'control_request' as const,
request_id: 'req-7',
request: {
subtype: 'unknown_subtype',
} as unknown as ControlRequestPayload,
};
await dispatcher.dispatch(request);
// Dispatch catches errors and sends error response instead of throwing
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: 'req-7',
error: 'Unknown control request subtype: unknown_subtype',
},
});
});
});
describe('handleControlResponse', () => {
it('should resolve pending outgoing request on success response', () => {
const requestId = 'outgoing-req-1';
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response: { result: 'success' },
},
};
// Register a pending outgoing request
const resolve = vi.fn();
const reject = vi.fn();
const timeoutId = setTimeout(() => {}, 1000);
// Access private method through type casting
(
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerOutgoingRequest(
requestId,
'SystemController',
resolve,
reject,
timeoutId,
);
dispatcher.handleControlResponse(response);
expect(resolve).toHaveBeenCalledWith(response.response);
expect(reject).not.toHaveBeenCalled();
});
it('should reject pending outgoing request on error response', () => {
const requestId = 'outgoing-req-2';
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId,
error: 'Request failed',
},
};
const resolve = vi.fn();
const reject = vi.fn();
const timeoutId = setTimeout(() => {}, 1000);
(
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerOutgoingRequest(
requestId,
'SystemController',
resolve,
reject,
timeoutId,
);
dispatcher.handleControlResponse(response);
expect(reject).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Request failed',
}),
);
expect(resolve).not.toHaveBeenCalled();
});
it('should handle error object in error response', () => {
const requestId = 'outgoing-req-3';
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId,
error: { message: 'Detailed error', code: 500 },
},
};
const resolve = vi.fn();
const reject = vi.fn();
const timeoutId = setTimeout(() => {}, 1000);
(
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerOutgoingRequest(
requestId,
'SystemController',
resolve,
reject,
timeoutId,
);
dispatcher.handleControlResponse(response);
expect(reject).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Detailed error',
}),
);
});
it('should handle response for non-existent pending request gracefully', () => {
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: 'non-existent',
response: {},
},
};
// Should not throw
expect(() => dispatcher.handleControlResponse(response)).not.toThrow();
});
it('should handle response for non-existent request in debug mode', () => {
const context = createMockContext(true);
const consoleSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const dispatcherWithDebug = new ControlDispatcher(context);
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: 'non-existent',
response: {},
},
};
dispatcherWithDebug.handleControlResponse(response);
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining(
'[ControlDispatcher] No pending outgoing request for: non-existent',
),
);
consoleSpy.mockRestore();
});
});
describe('sendControlRequest', () => {
it('should delegate to system controller sendControlRequest', async () => {
const payload: ControlRequestPayload = {
subtype: 'initialize',
} as CLIControlInitializeRequest;
const expectedResponse: ControlResponse = {
subtype: 'success',
request_id: 'test-id',
response: {},
};
vi.mocked(mockSystemController.sendControlRequest).mockResolvedValue(
expectedResponse,
);
const result = await dispatcher.sendControlRequest(payload, 5000);
expect(mockSystemController.sendControlRequest).toHaveBeenCalledWith(
payload,
5000,
);
expect(result).toBe(expectedResponse);
});
});
describe('handleCancel', () => {
it('should cancel specific incoming request', () => {
const requestId = 'cancel-req-1';
const abortController = new AbortController();
const timeoutId = setTimeout(() => {}, 1000);
const abortSpy = vi.spyOn(abortController, 'abort');
(
dispatcher as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerIncomingRequest(
requestId,
'SystemController',
abortController,
timeoutId,
);
dispatcher.handleCancel(requestId);
expect(abortSpy).toHaveBeenCalled();
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId,
error: 'Request cancelled',
},
});
});
it('should cancel all incoming requests when no requestId provided', () => {
const requestId1 = 'cancel-req-2';
const requestId2 = 'cancel-req-3';
const abortController1 = new AbortController();
const abortController2 = new AbortController();
const timeoutId1 = setTimeout(() => {}, 1000);
const timeoutId2 = setTimeout(() => {}, 1000);
const abortSpy1 = vi.spyOn(abortController1, 'abort');
const abortSpy2 = vi.spyOn(abortController2, 'abort');
const register = (
dispatcher as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerIncomingRequest.bind(dispatcher);
register(requestId1, 'SystemController', abortController1, timeoutId1);
register(requestId2, 'SystemController', abortController2, timeoutId2);
dispatcher.handleCancel();
expect(abortSpy1).toHaveBeenCalled();
expect(abortSpy2).toHaveBeenCalled();
expect(mockContext.streamJson.send).toHaveBeenCalledTimes(2);
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId1,
error: 'All requests cancelled',
},
});
expect(mockContext.streamJson.send).toHaveBeenCalledWith({
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId2,
error: 'All requests cancelled',
},
});
});
it('should handle cancel of non-existent request gracefully', () => {
expect(() => dispatcher.handleCancel('non-existent')).not.toThrow();
});
it('should log cancellation in debug mode', () => {
const context = createMockContext(true);
const consoleSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const dispatcherWithDebug = new ControlDispatcher(context);
const requestId = 'cancel-req-debug';
const abortController = new AbortController();
const timeoutId = setTimeout(() => {}, 1000);
(
dispatcherWithDebug as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerIncomingRequest(
requestId,
'SystemController',
abortController,
timeoutId,
);
dispatcherWithDebug.handleCancel(requestId);
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining(
'[ControlDispatcher] Cancelled incoming request: cancel-req-debug',
),
);
consoleSpy.mockRestore();
});
});
describe('shutdown', () => {
it('should cancel all pending incoming requests', () => {
const requestId1 = 'shutdown-req-1';
const requestId2 = 'shutdown-req-2';
const abortController1 = new AbortController();
const abortController2 = new AbortController();
const timeoutId1 = setTimeout(() => {}, 1000);
const timeoutId2 = setTimeout(() => {}, 1000);
const abortSpy1 = vi.spyOn(abortController1, 'abort');
const abortSpy2 = vi.spyOn(abortController2, 'abort');
const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
const register = (
dispatcher as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerIncomingRequest.bind(dispatcher);
register(requestId1, 'SystemController', abortController1, timeoutId1);
register(requestId2, 'SystemController', abortController2, timeoutId2);
dispatcher.shutdown();
expect(abortSpy1).toHaveBeenCalled();
expect(abortSpy2).toHaveBeenCalled();
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId1);
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId2);
});
it('should reject all pending outgoing requests', () => {
const requestId1 = 'outgoing-shutdown-1';
const requestId2 = 'outgoing-shutdown-2';
const reject1 = vi.fn();
const reject2 = vi.fn();
const timeoutId1 = setTimeout(() => {}, 1000);
const timeoutId2 = setTimeout(() => {}, 1000);
const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
const register = (
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerOutgoingRequest.bind(dispatcher);
register(requestId1, 'SystemController', vi.fn(), reject1, timeoutId1);
register(requestId2, 'SystemController', vi.fn(), reject2, timeoutId2);
dispatcher.shutdown();
expect(reject1).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Dispatcher shutdown',
}),
);
expect(reject2).toHaveBeenCalledWith(
expect.objectContaining({
message: 'Dispatcher shutdown',
}),
);
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId1);
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId2);
});
it('should cleanup all controllers', () => {
vi.mocked(mockSystemController.cleanup).mockImplementation(() => {});
dispatcher.shutdown();
expect(mockSystemController.cleanup).toHaveBeenCalled();
});
it('should log shutdown in debug mode', () => {
const context = createMockContext(true);
const consoleSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => {});
const dispatcherWithDebug = new ControlDispatcher(context);
dispatcherWithDebug.shutdown();
expect(consoleSpy).toHaveBeenCalledWith(
'[ControlDispatcher] Shutting down',
);
consoleSpy.mockRestore();
});
});
describe('pending request registry', () => {
describe('registerIncomingRequest', () => {
it('should register incoming request', () => {
const requestId = 'reg-incoming-1';
const abortController = new AbortController();
const timeoutId = setTimeout(() => {}, 1000);
(
dispatcher as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerIncomingRequest(
requestId,
'SystemController',
abortController,
timeoutId,
);
// Verify it was registered by trying to cancel it
dispatcher.handleCancel(requestId);
expect(abortController.signal.aborted).toBe(true);
});
});
describe('deregisterIncomingRequest', () => {
it('should deregister incoming request', () => {
const requestId = 'dereg-incoming-1';
const abortController = new AbortController();
const timeoutId = setTimeout(() => {}, 1000);
const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
(
dispatcher as unknown as {
registerIncomingRequest: (
id: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
) => void;
deregisterIncomingRequest: (id: string) => void;
}
).registerIncomingRequest(
requestId,
'SystemController',
abortController,
timeoutId,
);
(
dispatcher as unknown as {
deregisterIncomingRequest: (id: string) => void;
}
).deregisterIncomingRequest(requestId);
// Verify it was deregistered - cancel should not find it
const sendMock = vi.mocked(mockContext.streamJson.send);
const sendCallCount = sendMock.mock.calls.length;
dispatcher.handleCancel(requestId);
// Should not send cancel response for non-existent request
expect(sendMock.mock.calls.length).toBe(sendCallCount);
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId);
});
it('should handle deregister of non-existent request gracefully', () => {
expect(() => {
(
dispatcher as unknown as {
deregisterIncomingRequest: (id: string) => void;
}
).deregisterIncomingRequest('non-existent');
}).not.toThrow();
});
});
describe('registerOutgoingRequest', () => {
it('should register outgoing request', () => {
const requestId = 'reg-outgoing-1';
const resolve = vi.fn();
const reject = vi.fn();
const timeoutId = setTimeout(() => {}, 1000);
(
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
}
).registerOutgoingRequest(
requestId,
'SystemController',
resolve,
reject,
timeoutId,
);
// Verify it was registered by handling a response
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response: {},
},
};
dispatcher.handleControlResponse(response);
expect(resolve).toHaveBeenCalled();
});
});
describe('deregisterOutgoingRequest', () => {
it('should deregister outgoing request', () => {
const requestId = 'dereg-outgoing-1';
const resolve = vi.fn();
const reject = vi.fn();
const timeoutId = setTimeout(() => {}, 1000);
const clearTimeoutSpy = vi.spyOn(global, 'clearTimeout');
(
dispatcher as unknown as {
registerOutgoingRequest: (
id: string,
controller: string,
resolve: (r: ControlResponse) => void,
reject: (e: Error) => void,
timeoutId: NodeJS.Timeout,
) => void;
deregisterOutgoingRequest: (id: string) => void;
}
).registerOutgoingRequest(
requestId,
'SystemController',
resolve,
reject,
timeoutId,
);
(
dispatcher as unknown as {
deregisterOutgoingRequest: (id: string) => void;
}
).deregisterOutgoingRequest(requestId);
// Verify it was deregistered - response should not find it
const response: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response: {},
},
};
dispatcher.handleControlResponse(response);
expect(resolve).not.toHaveBeenCalled();
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutId);
});
it('should handle deregister of non-existent request gracefully', () => {
expect(() => {
(
dispatcher as unknown as {
deregisterOutgoingRequest: (id: string) => void;
}
).deregisterOutgoingRequest('non-existent');
}).not.toThrow();
});
});
});
});

View File

@@ -0,0 +1,400 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Control Dispatcher
*
* Layer 2 of the control plane architecture. Routes control requests between
* SDK and CLI to appropriate controllers, manages pending request registries,
* and handles cancellation/cleanup. Application code MUST NOT depend on
* controller instances exposed by this class; instead, use ControlService,
* which wraps these controllers with a stable programmatic API.
*
* Controllers:
* - SystemController: initialize, interrupt, set_model, supported_commands
* - PermissionController: can_use_tool, set_permission_mode
* - SdkMcpController: mcp_server_status (mcp_message handled via callback)
* - HookController: hook_callback
*
* Note: mcp_message requests are NOT routed through the dispatcher. CLI MCP
* clients send messages via SdkMcpController.createSendSdkMcpMessage() callback.
*
* Note: Control request types are centrally defined in the ControlRequestType
* enum in packages/sdk/typescript/src/types/controlRequests.ts
*/
import type { IControlContext } from './ControlContext.js';
import type { IPendingRequestRegistry } from './controllers/baseController.js';
import { SystemController } from './controllers/systemController.js';
import { PermissionController } from './controllers/permissionController.js';
import { SdkMcpController } from './controllers/sdkMcpController.js';
// import { HookController } from './controllers/hookController.js';
import type {
CLIControlRequest,
CLIControlResponse,
ControlResponse,
ControlRequestPayload,
} from '../types.js';
/**
* Tracks an incoming request from SDK awaiting CLI response
*/
interface PendingIncomingRequest {
controller: string;
abortController: AbortController;
timeoutId: NodeJS.Timeout;
}
/**
* Tracks an outgoing request from CLI awaiting SDK response
*/
interface PendingOutgoingRequest {
controller: string;
resolve: (response: ControlResponse) => void;
reject: (error: Error) => void;
timeoutId: NodeJS.Timeout;
}
/**
* Central coordinator for control plane communication.
* Routes requests to controllers and manages request lifecycle.
*/
export class ControlDispatcher implements IPendingRequestRegistry {
private context: IControlContext;
// Make controllers publicly accessible
readonly systemController: SystemController;
readonly permissionController: PermissionController;
readonly sdkMcpController: SdkMcpController;
// readonly hookController: HookController;
// Central pending request registries
private pendingIncomingRequests: Map<string, PendingIncomingRequest> =
new Map();
private pendingOutgoingRequests: Map<string, PendingOutgoingRequest> =
new Map();
constructor(context: IControlContext) {
this.context = context;
// Create domain controllers with context and registry
this.systemController = new SystemController(
context,
this,
'SystemController',
);
this.permissionController = new PermissionController(
context,
this,
'PermissionController',
);
this.sdkMcpController = new SdkMcpController(
context,
this,
'SdkMcpController',
);
// this.hookController = new HookController(context, this, 'HookController');
// Listen for main abort signal
this.context.abortSignal.addEventListener('abort', () => {
this.shutdown();
});
}
/**
* Routes an incoming request to the appropriate controller and sends response
*/
async dispatch(request: CLIControlRequest): Promise<void> {
const { request_id, request: payload } = request;
try {
// Route to appropriate controller
const controller = this.getControllerForRequest(payload.subtype);
const response = await controller.handleRequest(payload, request_id);
// Send success response
this.sendSuccessResponse(request_id, response);
} catch (error) {
// Send error response
const errorMessage =
error instanceof Error ? error.message : String(error);
this.sendErrorResponse(request_id, errorMessage);
}
}
/**
* Processes response from SDK for an outgoing request
*/
handleControlResponse(response: CLIControlResponse): void {
const responsePayload = response.response;
const requestId = responsePayload.request_id;
const pending = this.pendingOutgoingRequests.get(requestId);
if (!pending) {
// No pending request found - may have timed out or been cancelled
if (this.context.debugMode) {
console.error(
`[ControlDispatcher] No pending outgoing request for: ${requestId}`,
);
}
return;
}
// Deregister
this.deregisterOutgoingRequest(requestId);
// Resolve or reject based on response type
if (responsePayload.subtype === 'success') {
pending.resolve(responsePayload);
} else {
const errorMessage =
typeof responsePayload.error === 'string'
? responsePayload.error
: (responsePayload.error?.message ?? 'Unknown error');
pending.reject(new Error(errorMessage));
}
}
/**
* Sends a control request to SDK and waits for response
*/
async sendControlRequest(
payload: ControlRequestPayload,
timeoutMs?: number,
): Promise<ControlResponse> {
// Delegate to system controller (or any controller, they all have the same method)
return this.systemController.sendControlRequest(payload, timeoutMs);
}
/**
* Cancels a specific request or all pending requests
*/
handleCancel(requestId?: string): void {
if (requestId) {
// Cancel specific incoming request
const pending = this.pendingIncomingRequests.get(requestId);
if (pending) {
pending.abortController.abort();
this.deregisterIncomingRequest(requestId);
this.sendErrorResponse(requestId, 'Request cancelled');
if (this.context.debugMode) {
console.error(
`[ControlDispatcher] Cancelled incoming request: ${requestId}`,
);
}
}
} else {
// Cancel ALL pending incoming requests
const requestIds = Array.from(this.pendingIncomingRequests.keys());
for (const id of requestIds) {
const pending = this.pendingIncomingRequests.get(id);
if (pending) {
pending.abortController.abort();
this.deregisterIncomingRequest(id);
this.sendErrorResponse(id, 'All requests cancelled');
}
}
if (this.context.debugMode) {
console.error(
`[ControlDispatcher] Cancelled all ${requestIds.length} pending incoming requests`,
);
}
}
}
/**
* Stops all pending requests and cleans up all controllers
*/
shutdown(): void {
if (this.context.debugMode) {
console.error('[ControlDispatcher] Shutting down');
}
// Cancel all incoming requests
for (const [
_requestId,
pending,
] of this.pendingIncomingRequests.entries()) {
pending.abortController.abort();
clearTimeout(pending.timeoutId);
}
this.pendingIncomingRequests.clear();
// Cancel all outgoing requests
for (const [
_requestId,
pending,
] of this.pendingOutgoingRequests.entries()) {
clearTimeout(pending.timeoutId);
pending.reject(new Error('Dispatcher shutdown'));
}
this.pendingOutgoingRequests.clear();
// Cleanup controllers
this.systemController.cleanup();
this.permissionController.cleanup();
this.sdkMcpController.cleanup();
// this.hookController.cleanup();
}
/**
* Registers an incoming request in the pending registry
*/
registerIncomingRequest(
requestId: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
): void {
this.pendingIncomingRequests.set(requestId, {
controller,
abortController,
timeoutId,
});
}
/**
* Removes an incoming request from the pending registry
*/
deregisterIncomingRequest(requestId: string): void {
const pending = this.pendingIncomingRequests.get(requestId);
if (pending) {
clearTimeout(pending.timeoutId);
this.pendingIncomingRequests.delete(requestId);
}
}
/**
* Registers an outgoing request in the pending registry
*/
registerOutgoingRequest(
requestId: string,
controller: string,
resolve: (response: ControlResponse) => void,
reject: (error: Error) => void,
timeoutId: NodeJS.Timeout,
): void {
this.pendingOutgoingRequests.set(requestId, {
controller,
resolve,
reject,
timeoutId,
});
}
/**
* Removes an outgoing request from the pending registry
*/
deregisterOutgoingRequest(requestId: string): void {
const pending = this.pendingOutgoingRequests.get(requestId);
if (pending) {
clearTimeout(pending.timeoutId);
this.pendingOutgoingRequests.delete(requestId);
}
}
/**
* Get count of pending incoming requests (for debugging)
*/
getPendingIncomingRequestCount(): number {
return this.pendingIncomingRequests.size;
}
/**
* Wait for all incoming request handlers to complete.
*
* Uses polling since we don't have direct Promise references to handlers.
* The pendingIncomingRequests map is managed by BaseController:
* - Registered when handler starts (in handleRequest)
* - Deregistered when handler completes (success or error)
*
* @param pollIntervalMs - How often to check (default 50ms)
* @param timeoutMs - Maximum wait time (default 30s)
*/
async waitForPendingIncomingRequests(
pollIntervalMs: number = 50,
timeoutMs: number = 30000,
): Promise<void> {
const startTime = Date.now();
while (this.pendingIncomingRequests.size > 0) {
if (Date.now() - startTime > timeoutMs) {
if (this.context.debugMode) {
console.error(
`[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`,
);
}
break;
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
if (this.context.debugMode && this.pendingIncomingRequests.size === 0) {
console.error('[ControlDispatcher] All incoming requests completed');
}
}
/**
* Returns the controller that handles the given request subtype
*/
private getControllerForRequest(subtype: string) {
switch (subtype) {
case 'initialize':
case 'interrupt':
case 'set_model':
case 'supported_commands':
return this.systemController;
case 'can_use_tool':
case 'set_permission_mode':
return this.permissionController;
case 'mcp_server_status':
return this.sdkMcpController;
// case 'hook_callback':
// return this.hookController;
default:
throw new Error(`Unknown control request subtype: ${subtype}`);
}
}
/**
* Sends a success response back to SDK
*/
private sendSuccessResponse(
requestId: string,
response: Record<string, unknown>,
): void {
const controlResponse: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'success',
request_id: requestId,
response,
},
};
this.context.streamJson.send(controlResponse);
}
/**
* Sends an error response back to SDK
*/
private sendErrorResponse(requestId: string, error: string): void {
const controlResponse: CLIControlResponse = {
type: 'control_response',
response: {
subtype: 'error',
request_id: requestId,
error,
},
};
this.context.streamJson.send(controlResponse);
}
}

View File

@@ -0,0 +1,179 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Control Service - Public Programmatic API
*
* Provides type-safe access to control plane functionality for internal
* CLI code. This is the ONLY programmatic interface that should be used by:
* - nonInteractiveCli
* - Session managers
* - Tool execution handlers
* - Internal CLI logic
*
* DO NOT use ControlDispatcher or controllers directly from application code.
*
* Architecture:
* - ControlContext stores shared session state (Layer 1)
* - ControlDispatcher handles protocol-level routing (Layer 2)
* - ControlService provides programmatic API for internal CLI usage (Layer 3)
*
* ControlService and ControlDispatcher share controller instances to ensure
* a single source of truth. All higher level code MUST access the control
* plane exclusively through ControlService.
*/
import type { IControlContext } from './ControlContext.js';
import type { ControlDispatcher } from './ControlDispatcher.js';
import type {
PermissionServiceAPI,
SystemServiceAPI,
// McpServiceAPI,
// HookServiceAPI,
} from './types/serviceAPIs.js';
/**
* Control Service
*
* Facade layer providing domain-grouped APIs for control plane operations.
* Shares controller instances with ControlDispatcher to ensure single source
* of truth and state consistency.
*/
export class ControlService {
private dispatcher: ControlDispatcher;
/**
* Construct ControlService
*
* @param context - Control context (unused directly, passed to dispatcher)
* @param dispatcher - Control dispatcher that owns the controller instances
*/
constructor(context: IControlContext, dispatcher: ControlDispatcher) {
this.dispatcher = dispatcher;
}
/**
* Permission Domain API
*
* Handles tool execution permissions, approval checks, and callbacks.
* Delegates to the shared PermissionController instance.
*/
get permission(): PermissionServiceAPI {
const controller = this.dispatcher.permissionController;
return {
/**
* Build UI suggestions for tool confirmation dialogs
*
* Creates actionable permission suggestions based on tool confirmation details.
*
* @param confirmationDetails - Tool confirmation details
* @returns Array of permission suggestions or null
*/
buildPermissionSuggestions:
controller.buildPermissionSuggestions.bind(controller),
/**
* Get callback for monitoring tool call status updates
*
* Returns callback function for integration with CoreToolScheduler.
*
* @returns Callback function for tool call updates
*/
getToolCallUpdateCallback:
controller.getToolCallUpdateCallback.bind(controller),
};
}
/**
* System Domain API
*
* Handles system-level operations and session management.
* Delegates to the shared SystemController instance.
*/
get system(): SystemServiceAPI {
const controller = this.dispatcher.systemController;
return {
/**
* Get control capabilities
*
* Returns the control capabilities object indicating what control
* features are available. Used exclusively for the initialize
* control response. System messages do not include capabilities.
*
* @returns Control capabilities object
*/
getControlCapabilities: () => controller.buildControlCapabilities(),
};
}
/**
* MCP Domain API
*
* Handles Model Context Protocol server interactions.
* Delegates to the shared MCPController instance.
*/
// get mcp(): McpServiceAPI {
// return {
// /**
// * Get or create MCP client for a server (lazy initialization)
// *
// * Returns existing client or creates new connection.
// *
// * @param serverName - Name of the MCP server
// * @returns Promise with client and config
// */
// getMcpClient: async (serverName: string) => {
// // MCPController has a private method getOrCreateMcpClient
// // We need to expose it via the API
// // For now, throw error as placeholder
// // The actual implementation will be added when we update MCPController
// throw new Error(
// `getMcpClient not yet implemented in ControlService. Server: ${serverName}`,
// );
// },
//
// /**
// * List all available MCP servers
// *
// * Returns names of configured/connected MCP servers.
// *
// * @returns Array of server names
// */
// listServers: () => {
// // Get servers from context
// const sdkServers = Array.from(
// this.dispatcher.mcpController['context'].sdkMcpServers,
// );
// const cliServers = Array.from(
// this.dispatcher.mcpController['context'].mcpClients.keys(),
// );
// return [...new Set([...sdkServers, ...cliServers])];
// },
// };
// }
/**
* Hook Domain API
*
* Handles hook callback processing (placeholder for future expansion).
* Delegates to the shared HookController instance.
*/
// get hook(): HookServiceAPI {
// // HookController has no public methods yet - controller access reserved for future use
// return {};
// }
/**
* Cleanup all controllers
*
* Should be called on session shutdown. Delegates to dispatcher's shutdown
* method to ensure all controllers are properly cleaned up.
*/
cleanup(): void {
// Delegate to dispatcher which manages controller cleanup
this.dispatcher.shutdown();
}
}

View File

@@ -0,0 +1,221 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Base Controller
*
* Abstract base class for domain-specific control plane controllers.
* Provides common functionality for:
* - Handling incoming control requests (SDK -> CLI)
* - Sending outgoing control requests (CLI -> SDK)
* - Request lifecycle management with timeout and cancellation
* - Integration with central pending request registry
*/
import { randomUUID } from 'node:crypto';
import type { IControlContext } from '../ControlContext.js';
import type {
ControlRequestPayload,
ControlResponse,
CLIControlRequest,
} from '../../types.js';
const DEFAULT_REQUEST_TIMEOUT_MS = 30000; // 30 seconds
/**
* Registry interface for controllers to register/deregister pending requests
*/
export interface IPendingRequestRegistry {
registerIncomingRequest(
requestId: string,
controller: string,
abortController: AbortController,
timeoutId: NodeJS.Timeout,
): void;
deregisterIncomingRequest(requestId: string): void;
registerOutgoingRequest(
requestId: string,
controller: string,
resolve: (response: ControlResponse) => void,
reject: (error: Error) => void,
timeoutId: NodeJS.Timeout,
): void;
deregisterOutgoingRequest(requestId: string): void;
}
/**
* Abstract base controller class
*
* Subclasses should implement handleRequestPayload() to process specific
* control request types.
*/
export abstract class BaseController {
protected context: IControlContext;
protected registry: IPendingRequestRegistry;
protected controllerName: string;
constructor(
context: IControlContext,
registry: IPendingRequestRegistry,
controllerName: string,
) {
this.context = context;
this.registry = registry;
this.controllerName = controllerName;
}
/**
* Handle an incoming control request
*
* Manages lifecycle: register -> process -> deregister
*/
async handleRequest(
payload: ControlRequestPayload,
requestId: string,
): Promise<Record<string, unknown>> {
const requestAbortController = new AbortController();
// Setup timeout
const timeoutId = setTimeout(() => {
requestAbortController.abort();
this.registry.deregisterIncomingRequest(requestId);
if (this.context.debugMode) {
console.error(`[${this.controllerName}] Request timeout: ${requestId}`);
}
}, DEFAULT_REQUEST_TIMEOUT_MS);
// Register with central registry
this.registry.registerIncomingRequest(
requestId,
this.controllerName,
requestAbortController,
timeoutId,
);
try {
const response = await this.handleRequestPayload(
payload,
requestAbortController.signal,
);
// Success - deregister
this.registry.deregisterIncomingRequest(requestId);
return response;
} catch (error) {
// Error - deregister
this.registry.deregisterIncomingRequest(requestId);
throw error;
}
}
/**
* Send an outgoing control request to SDK
*
* Manages lifecycle: register -> send -> wait for response -> deregister
* Respects the provided AbortSignal for cancellation.
*/
async sendControlRequest(
payload: ControlRequestPayload,
timeoutMs: number = DEFAULT_REQUEST_TIMEOUT_MS,
signal?: AbortSignal,
): Promise<ControlResponse> {
// Check if already aborted
if (signal?.aborted) {
throw new Error('Request aborted');
}
const requestId = randomUUID();
return new Promise<ControlResponse>((resolve, reject) => {
// Setup abort handler
const abortHandler = () => {
this.registry.deregisterOutgoingRequest(requestId);
reject(new Error('Request aborted'));
if (this.context.debugMode) {
console.error(
`[${this.controllerName}] Outgoing request aborted: ${requestId}`,
);
}
};
if (signal) {
signal.addEventListener('abort', abortHandler, { once: true });
}
// Setup timeout
const timeoutId = setTimeout(() => {
if (signal) {
signal.removeEventListener('abort', abortHandler);
}
this.registry.deregisterOutgoingRequest(requestId);
reject(new Error('Control request timeout'));
if (this.context.debugMode) {
console.error(
`[${this.controllerName}] Outgoing request timeout: ${requestId}`,
);
}
}, timeoutMs);
// Wrap resolve/reject to clean up abort listener
const wrappedResolve = (response: ControlResponse) => {
if (signal) {
signal.removeEventListener('abort', abortHandler);
}
resolve(response);
};
const wrappedReject = (error: Error) => {
if (signal) {
signal.removeEventListener('abort', abortHandler);
}
reject(error);
};
// Register with central registry
this.registry.registerOutgoingRequest(
requestId,
this.controllerName,
wrappedResolve,
wrappedReject,
timeoutId,
);
// Send control request
const request: CLIControlRequest = {
type: 'control_request',
request_id: requestId,
request: payload,
};
try {
this.context.streamJson.send(request);
} catch (error) {
if (signal) {
signal.removeEventListener('abort', abortHandler);
}
this.registry.deregisterOutgoingRequest(requestId);
reject(error);
}
});
}
/**
* Abstract method: Handle specific request payload
*
* Subclasses must implement this to process their domain-specific requests.
*/
protected abstract handleRequestPayload(
payload: ControlRequestPayload,
signal: AbortSignal,
): Promise<Record<string, unknown>>;
/**
* Cleanup resources
*/
cleanup(): void {}
}

View File

@@ -0,0 +1,56 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Hook Controller
*
* Handles hook-related control requests:
* - hook_callback: Process hook callbacks (placeholder for future)
*/
import { BaseController } from './baseController.js';
import type {
ControlRequestPayload,
CLIHookCallbackRequest,
} from '../../types.js';
export class HookController extends BaseController {
/**
* Handle hook control requests
*/
protected async handleRequestPayload(
payload: ControlRequestPayload,
_signal: AbortSignal,
): Promise<Record<string, unknown>> {
switch (payload.subtype) {
case 'hook_callback':
return this.handleHookCallback(payload as CLIHookCallbackRequest);
default:
throw new Error(`Unsupported request subtype in HookController`);
}
}
/**
* Handle hook_callback request
*
* Processes hook callbacks (placeholder implementation)
*/
private async handleHookCallback(
payload: CLIHookCallbackRequest,
): Promise<Record<string, unknown>> {
if (this.context.debugMode) {
console.error(`[HookController] Hook callback: ${payload.callback_id}`);
}
// Hook callback processing not yet implemented
return {
result: 'Hook callback processing not yet implemented',
callback_id: payload.callback_id,
tool_use_id: payload.tool_use_id,
};
}
}

View File

@@ -0,0 +1,493 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Permission Controller
*
* Handles permission-related control requests:
* - can_use_tool: Check if tool usage is allowed
* - set_permission_mode: Change permission mode at runtime
*
* Abstracts all permission logic from the session manager to keep it clean.
*/
import type {
WaitingToolCall,
ToolExecuteConfirmationDetails,
ToolMcpConfirmationDetails,
ApprovalMode,
} from '@qwen-code/qwen-code-core';
import {
InputFormat,
ToolConfirmationOutcome,
} from '@qwen-code/qwen-code-core';
import type {
CLIControlPermissionRequest,
CLIControlSetPermissionModeRequest,
ControlRequestPayload,
PermissionMode,
PermissionSuggestion,
} from '../../types.js';
import { BaseController } from './baseController.js';
// Import ToolCallConfirmationDetails types for type alignment
type ToolConfirmationType = 'edit' | 'exec' | 'mcp' | 'info' | 'plan';
export class PermissionController extends BaseController {
private pendingOutgoingRequests = new Set<string>();
/**
* Handle permission control requests
*/
protected async handleRequestPayload(
payload: ControlRequestPayload,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
switch (payload.subtype) {
case 'can_use_tool':
return this.handleCanUseTool(
payload as CLIControlPermissionRequest,
signal,
);
case 'set_permission_mode':
return this.handleSetPermissionMode(
payload as CLIControlSetPermissionModeRequest,
signal,
);
default:
throw new Error(`Unsupported request subtype in PermissionController`);
}
}
/**
* Handle can_use_tool request
*
* Comprehensive permission evaluation based on:
* - Permission mode (approval level)
* - Tool registry validation
* - Error handling with safe defaults
*/
private async handleCanUseTool(
payload: CLIControlPermissionRequest,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
const toolName = payload.tool_name;
if (
!toolName ||
typeof toolName !== 'string' ||
toolName.trim().length === 0
) {
return {
subtype: 'can_use_tool',
behavior: 'deny',
message: 'Missing or invalid tool_name in can_use_tool request',
};
}
let behavior: 'allow' | 'deny' = 'allow';
let message: string | undefined;
try {
// Check permission mode first
const permissionResult = this.checkPermissionMode();
if (!permissionResult.allowed) {
behavior = 'deny';
message = permissionResult.message;
}
// Check tool registry if permission mode allows
if (behavior === 'allow') {
const registryResult = this.checkToolRegistry(toolName);
if (!registryResult.allowed) {
behavior = 'deny';
message = registryResult.message;
}
}
} catch (error) {
behavior = 'deny';
message =
error instanceof Error
? `Failed to evaluate tool permission: ${error.message}`
: 'Failed to evaluate tool permission';
}
const response: Record<string, unknown> = {
subtype: 'can_use_tool',
behavior,
};
if (message) {
response['message'] = message;
}
return response;
}
/**
* Check permission mode for tool execution
*/
private checkPermissionMode(): { allowed: boolean; message?: string } {
const mode = this.context.permissionMode;
// Map permission modes to approval logic (aligned with VALID_APPROVAL_MODE_VALUES)
switch (mode) {
case 'yolo': // Allow all tools
case 'auto-edit': // Auto-approve edit operations
case 'plan': // Auto-approve planning operations
return { allowed: true };
case 'default': // TODO: allow all tools for test
default:
return {
allowed: false,
message:
'Tool execution requires manual approval. Update permission mode or approve via host.',
};
}
}
/**
* Check if tool exists in registry
*/
private checkToolRegistry(toolName: string): {
allowed: boolean;
message?: string;
} {
try {
// Access tool registry through config
const config = this.context.config;
const registryProvider = config as unknown as {
getToolRegistry?: () => {
getTool?: (name: string) => unknown;
};
};
if (typeof registryProvider.getToolRegistry === 'function') {
const registry = registryProvider.getToolRegistry();
if (
registry &&
typeof registry.getTool === 'function' &&
!registry.getTool(toolName)
) {
return {
allowed: false,
message: `Tool "${toolName}" is not registered.`,
};
}
}
return { allowed: true };
} catch (error) {
return {
allowed: false,
message: `Failed to check tool registry: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}
/**
* Handle set_permission_mode request
*
* Updates the permission mode in the context
*/
private async handleSetPermissionMode(
payload: CLIControlSetPermissionModeRequest,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
const mode = payload.mode;
const validModes: PermissionMode[] = [
'default',
'plan',
'auto-edit',
'yolo',
];
if (!validModes.includes(mode)) {
throw new Error(
`Invalid permission mode: ${mode}. Valid values are: ${validModes.join(', ')}`,
);
}
this.context.permissionMode = mode;
this.context.config.setApprovalMode(mode as ApprovalMode);
if (this.context.debugMode) {
console.error(
`[PermissionController] Permission mode updated to: ${mode}`,
);
}
return { status: 'updated', mode };
}
/**
* Build permission suggestions for tool confirmation UI
*
* This method creates UI suggestions based on tool confirmation details,
* helping the host application present appropriate permission options.
*/
buildPermissionSuggestions(
confirmationDetails: unknown,
): PermissionSuggestion[] | null {
if (
!confirmationDetails ||
typeof confirmationDetails !== 'object' ||
!('type' in confirmationDetails)
) {
return null;
}
const details = confirmationDetails as Record<string, unknown>;
const type = String(details['type'] ?? '');
const title =
typeof details['title'] === 'string' ? details['title'] : undefined;
// Ensure type matches ToolCallConfirmationDetails union
const confirmationType = type as ToolConfirmationType;
switch (confirmationType) {
case 'exec': // ToolExecuteConfirmationDetails
return [
{
type: 'allow',
label: 'Allow Command',
description: `Execute: ${details['command']}`,
},
{
type: 'deny',
label: 'Deny',
description: 'Block this command execution',
},
];
case 'edit': // ToolEditConfirmationDetails
return [
{
type: 'allow',
label: 'Allow Edit',
description: `Edit file: ${details['fileName']}`,
},
{
type: 'deny',
label: 'Deny',
description: 'Block this file edit',
},
{
type: 'modify',
label: 'Review Changes',
description: 'Review the proposed changes before applying',
},
];
case 'plan': // ToolPlanConfirmationDetails
return [
{
type: 'allow',
label: 'Approve Plan',
description: title || 'Execute the proposed plan',
},
{
type: 'deny',
label: 'Reject Plan',
description: 'Do not execute this plan',
},
];
case 'mcp': // ToolMcpConfirmationDetails
return [
{
type: 'allow',
label: 'Allow MCP Call',
description: `${details['serverName']}: ${details['toolName']}`,
},
{
type: 'deny',
label: 'Deny',
description: 'Block this MCP server call',
},
];
case 'info': // ToolInfoConfirmationDetails
return [
{
type: 'allow',
label: 'Allow Info Request',
description: title || 'Allow information request',
},
{
type: 'deny',
label: 'Deny',
description: 'Block this information request',
},
];
default:
// Fallback for unknown types
return [
{
type: 'allow',
label: 'Allow',
description: title || `Allow ${type} operation`,
},
{
type: 'deny',
label: 'Deny',
description: `Block ${type} operation`,
},
];
}
}
/**
* Get callback for monitoring tool calls and handling outgoing permission requests
* This is passed to executeToolCall to hook into CoreToolScheduler updates
*/
getToolCallUpdateCallback(): (toolCalls: unknown[]) => void {
return (toolCalls: unknown[]) => {
for (const call of toolCalls) {
if (
call &&
typeof call === 'object' &&
(call as { status?: string }).status === 'awaiting_approval'
) {
const awaiting = call as WaitingToolCall;
if (
typeof awaiting.confirmationDetails?.onConfirm === 'function' &&
!this.pendingOutgoingRequests.has(awaiting.request.callId)
) {
this.pendingOutgoingRequests.add(awaiting.request.callId);
void this.handleOutgoingPermissionRequest(awaiting);
}
}
}
};
}
/**
* Handle outgoing permission request
*
* Behavior depends on input format:
* - stream-json mode: Send can_use_tool to SDK and await response
* - Other modes: Check local approval mode and decide immediately
*/
private async handleOutgoingPermissionRequest(
toolCall: WaitingToolCall,
): Promise<void> {
try {
// Check if already aborted
if (this.context.abortSignal?.aborted) {
await toolCall.confirmationDetails.onConfirm(
ToolConfirmationOutcome.Cancel,
);
return;
}
const inputFormat = this.context.config.getInputFormat?.();
const isStreamJsonMode = inputFormat === InputFormat.STREAM_JSON;
if (!isStreamJsonMode) {
// No SDK available - use local permission check
const modeCheck = this.checkPermissionMode();
const outcome = modeCheck.allowed
? ToolConfirmationOutcome.ProceedOnce
: ToolConfirmationOutcome.Cancel;
await toolCall.confirmationDetails.onConfirm(outcome);
return;
}
// Stream-json mode: ask SDK for permission
const permissionSuggestions = this.buildPermissionSuggestions(
toolCall.confirmationDetails,
);
const response = await this.sendControlRequest(
{
subtype: 'can_use_tool',
tool_name: toolCall.request.name,
tool_use_id: toolCall.request.callId,
input: toolCall.request.args,
permission_suggestions: permissionSuggestions,
blocked_path: null,
} as CLIControlPermissionRequest,
undefined, // use default timeout
this.context.abortSignal,
);
if (response.subtype !== 'success') {
await toolCall.confirmationDetails.onConfirm(
ToolConfirmationOutcome.Cancel,
);
return;
}
const payload = (response.response || {}) as Record<string, unknown>;
const behavior = String(payload['behavior'] || '').toLowerCase();
if (behavior === 'allow') {
// Handle updated input if provided
const updatedInput = payload['updatedInput'];
if (updatedInput && typeof updatedInput === 'object') {
toolCall.request.args = updatedInput as Record<string, unknown>;
}
await toolCall.confirmationDetails.onConfirm(
ToolConfirmationOutcome.ProceedOnce,
);
} else {
// Extract cancel message from response if available
const cancelMessage =
typeof payload['message'] === 'string'
? payload['message']
: undefined;
await toolCall.confirmationDetails.onConfirm(
ToolConfirmationOutcome.Cancel,
cancelMessage ? { cancelMessage } : undefined,
);
}
} catch (error) {
if (this.context.debugMode) {
console.error(
'[PermissionController] Outgoing permission failed:',
error,
);
}
// On error, use default cancel message
// Only pass payload for exec and mcp types that support it
const confirmationType = toolCall.confirmationDetails.type;
if (['edit', 'exec', 'mcp'].includes(confirmationType)) {
const execOrMcpDetails = toolCall.confirmationDetails as
| ToolExecuteConfirmationDetails
| ToolMcpConfirmationDetails;
await execOrMcpDetails.onConfirm(
ToolConfirmationOutcome.Cancel,
undefined,
);
} else {
// For other types, don't pass payload (backward compatible)
await toolCall.confirmationDetails.onConfirm(
ToolConfirmationOutcome.Cancel,
);
}
} finally {
this.pendingOutgoingRequests.delete(toolCall.request.callId);
}
}
}

View File

@@ -0,0 +1,138 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* SDK MCP Controller
*
* Handles MCP communication between CLI MCP clients and SDK MCP servers:
* - Provides sendSdkMcpMessage callback for CLI → SDK MCP message routing
* - mcp_server_status: Returns status of SDK MCP servers
*
* Message Flow (CLI MCP Client → SDK MCP Server):
* CLI MCP Client → SdkControlClientTransport.send() →
* sendSdkMcpMessage callback → control_request (mcp_message) → SDK →
* SDK MCP Server processes → control_response → CLI MCP Client
*/
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import { BaseController } from './baseController.js';
import type {
ControlRequestPayload,
CLIControlMcpMessageRequest,
} from '../../types.js';
const MCP_REQUEST_TIMEOUT = 30_000; // 30 seconds
export class SdkMcpController extends BaseController {
/**
* Handle SDK MCP control requests from ControlDispatcher
*
* Note: mcp_message requests are NOT handled here. CLI MCP clients
* send messages via the sendSdkMcpMessage callback directly, not
* through the control dispatcher.
*/
protected async handleRequestPayload(
payload: ControlRequestPayload,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
switch (payload.subtype) {
case 'mcp_server_status':
return this.handleMcpStatus();
default:
throw new Error(`Unsupported request subtype in SdkMcpController`);
}
}
/**
* Handle mcp_server_status request
*
* Returns status of all registered SDK MCP servers.
* SDK servers are considered "connected" if they are registered.
*/
private async handleMcpStatus(): Promise<Record<string, unknown>> {
const status: Record<string, string> = {};
for (const serverName of this.context.sdkMcpServers) {
// SDK MCP servers are "connected" once registered since they run in SDK process
status[serverName] = 'connected';
}
return {
subtype: 'mcp_server_status',
status,
};
}
/**
* Send MCP message to SDK server via control plane
*
* @param serverName - Name of the SDK MCP server
* @param message - MCP JSON-RPC message to send
* @returns MCP JSON-RPC response from SDK server
*/
private async sendMcpMessageToSdk(
serverName: string,
message: JSONRPCMessage,
): Promise<JSONRPCMessage> {
if (this.context.debugMode) {
console.error(
`[SdkMcpController] Sending MCP message to SDK server '${serverName}':`,
JSON.stringify(message),
);
}
// Send control request to SDK with the MCP message
const response = await this.sendControlRequest(
{
subtype: 'mcp_message',
server_name: serverName,
message: message as CLIControlMcpMessageRequest['message'],
},
MCP_REQUEST_TIMEOUT,
this.context.abortSignal,
);
// Extract MCP response from control response
const responsePayload = response.response as Record<string, unknown>;
const mcpResponse = responsePayload?.['mcp_response'] as JSONRPCMessage;
if (!mcpResponse) {
throw new Error(
`Invalid MCP response from SDK for server '${serverName}'`,
);
}
if (this.context.debugMode) {
console.error(
`[SdkMcpController] Received MCP response from SDK server '${serverName}':`,
JSON.stringify(mcpResponse),
);
}
return mcpResponse;
}
/**
* Create a callback function for sending MCP messages to SDK servers.
*
* This callback is used by McpClientManager/SdkControlClientTransport to send
* MCP messages from CLI MCP clients to SDK MCP servers via the control plane.
*
* @returns A function that sends MCP messages to SDK and returns the response
*/
createSendSdkMcpMessage(): (
serverName: string,
message: JSONRPCMessage,
) => Promise<JSONRPCMessage> {
return (serverName: string, message: JSONRPCMessage) =>
this.sendMcpMessageToSdk(serverName, message);
}
}

View File

@@ -0,0 +1,451 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* System Controller
*
* Handles system-level control requests:
* - initialize: Setup session and return system info
* - interrupt: Cancel current operations
* - set_model: Switch model (placeholder)
*/
import { BaseController } from './baseController.js';
import type {
ControlRequestPayload,
CLIControlInitializeRequest,
CLIControlSetModelRequest,
CLIMcpServerConfig,
} from '../../types.js';
import { CommandService } from '../../../services/CommandService.js';
import { BuiltinCommandLoader } from '../../../services/BuiltinCommandLoader.js';
import {
MCPServerConfig,
AuthProviderType,
type MCPOAuthConfig,
} from '@qwen-code/qwen-code-core';
export class SystemController extends BaseController {
/**
* Handle system control requests
*/
protected async handleRequestPayload(
payload: ControlRequestPayload,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
switch (payload.subtype) {
case 'initialize':
return this.handleInitialize(
payload as CLIControlInitializeRequest,
signal,
);
case 'interrupt':
return this.handleInterrupt();
case 'set_model':
return this.handleSetModel(
payload as CLIControlSetModelRequest,
signal,
);
case 'supported_commands':
return this.handleSupportedCommands(signal);
default:
throw new Error(`Unsupported request subtype in SystemController`);
}
}
/**
* Handle initialize request
*
* Processes SDK MCP servers config.
* SDK servers are registered in context.sdkMcpServers
* and added to config.mcpServers with the sdk type flag.
* External MCP servers are configured separately in settings.
*/
private async handleInitialize(
payload: CLIControlInitializeRequest,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
this.context.config.setSdkMode(true);
// Process SDK MCP servers
if (
payload.sdkMcpServers &&
typeof payload.sdkMcpServers === 'object' &&
payload.sdkMcpServers !== null
) {
const sdkServers: Record<string, MCPServerConfig> = {};
for (const [key, wireConfig] of Object.entries(payload.sdkMcpServers)) {
const name =
typeof wireConfig?.name === 'string' && wireConfig.name.trim().length
? wireConfig.name
: key;
this.context.sdkMcpServers.add(name);
sdkServers[name] = new MCPServerConfig(
undefined, // command
undefined, // args
undefined, // env
undefined, // cwd
undefined, // url
undefined, // httpUrl
undefined, // headers
undefined, // tcp
undefined, // timeout
true, // trust - SDK servers are trusted
undefined, // description
undefined, // includeTools
undefined, // excludeTools
undefined, // extensionName
undefined, // oauth
undefined, // authProviderType
undefined, // targetAudience
undefined, // targetServiceAccount
'sdk', // type
);
}
const sdkServerCount = Object.keys(sdkServers).length;
if (sdkServerCount > 0) {
try {
this.context.config.addMcpServers(sdkServers);
if (this.context.debugMode) {
console.error(
`[SystemController] Added ${sdkServerCount} SDK MCP servers to config`,
);
}
} catch (error) {
if (this.context.debugMode) {
console.error(
'[SystemController] Failed to add SDK MCP servers:',
error,
);
}
}
}
}
if (
payload.mcpServers &&
typeof payload.mcpServers === 'object' &&
payload.mcpServers !== null
) {
const externalServers: Record<string, MCPServerConfig> = {};
for (const [name, serverConfig] of Object.entries(payload.mcpServers)) {
const normalized = this.normalizeMcpServerConfig(
name,
serverConfig as CLIMcpServerConfig | undefined,
);
if (normalized) {
externalServers[name] = normalized;
}
}
const externalCount = Object.keys(externalServers).length;
if (externalCount > 0) {
try {
this.context.config.addMcpServers(externalServers);
if (this.context.debugMode) {
console.error(
`[SystemController] Added ${externalCount} external MCP servers to config`,
);
}
} catch (error) {
if (this.context.debugMode) {
console.error(
'[SystemController] Failed to add external MCP servers:',
error,
);
}
}
}
}
if (payload.agents && Array.isArray(payload.agents)) {
try {
this.context.config.setSessionSubagents(payload.agents);
if (this.context.debugMode) {
console.error(
`[SystemController] Added ${payload.agents.length} session subagents to config`,
);
}
} catch (error) {
if (this.context.debugMode) {
console.error(
'[SystemController] Failed to add session subagents:',
error,
);
}
}
}
// Build capabilities for response
const capabilities = this.buildControlCapabilities();
if (this.context.debugMode) {
console.error(
`[SystemController] Initialized with ${this.context.sdkMcpServers.size} SDK MCP servers`,
);
}
return {
subtype: 'initialize',
capabilities,
};
}
/**
* Build control capabilities for initialize control response
*
* This method constructs the control capabilities object that indicates
* what control features are available. It is used exclusively in the
* initialize control response.
*/
buildControlCapabilities(): Record<string, unknown> {
const capabilities: Record<string, unknown> = {
can_handle_can_use_tool: true,
can_handle_hook_callback: false,
can_set_permission_mode:
typeof this.context.config.setApprovalMode === 'function',
can_set_model: typeof this.context.config.setModel === 'function',
// SDK MCP servers are supported - messages routed through control plane
can_handle_mcp_message: true,
};
return capabilities;
}
private normalizeMcpServerConfig(
serverName: string,
config?: CLIMcpServerConfig,
): MCPServerConfig | null {
if (!config || typeof config !== 'object') {
if (this.context.debugMode) {
console.error(
`[SystemController] Ignoring invalid MCP server config for '${serverName}'`,
);
}
return null;
}
const authProvider = this.normalizeAuthProviderType(
config.authProviderType,
);
const oauthConfig = this.normalizeOAuthConfig(config.oauth);
return new MCPServerConfig(
config.command,
config.args,
config.env,
config.cwd,
config.url,
config.httpUrl,
config.headers,
config.tcp,
config.timeout,
config.trust,
config.description,
config.includeTools,
config.excludeTools,
config.extensionName,
oauthConfig,
authProvider,
config.targetAudience,
config.targetServiceAccount,
);
}
private normalizeAuthProviderType(
value?: string,
): AuthProviderType | undefined {
if (!value) {
return undefined;
}
switch (value) {
case AuthProviderType.DYNAMIC_DISCOVERY:
case AuthProviderType.GOOGLE_CREDENTIALS:
case AuthProviderType.SERVICE_ACCOUNT_IMPERSONATION:
return value;
default:
if (this.context.debugMode) {
console.error(
`[SystemController] Unsupported authProviderType '${value}', skipping`,
);
}
return undefined;
}
}
private normalizeOAuthConfig(
oauth?: CLIMcpServerConfig['oauth'],
): MCPOAuthConfig | undefined {
if (!oauth) {
return undefined;
}
return {
enabled: oauth.enabled,
clientId: oauth.clientId,
clientSecret: oauth.clientSecret,
authorizationUrl: oauth.authorizationUrl,
tokenUrl: oauth.tokenUrl,
scopes: oauth.scopes,
audiences: oauth.audiences,
redirectUri: oauth.redirectUri,
tokenParamName: oauth.tokenParamName,
registrationUrl: oauth.registrationUrl,
};
}
/**
* Handle interrupt request
*
* Triggers the interrupt callback to cancel current operations
*/
private async handleInterrupt(): Promise<Record<string, unknown>> {
// Trigger interrupt callback if available
if (this.context.onInterrupt) {
this.context.onInterrupt();
}
// Abort the main signal to cancel ongoing operations
if (this.context.abortSignal && !this.context.abortSignal.aborted) {
// Note: We can't directly abort the signal, but the onInterrupt callback should handle this
if (this.context.debugMode) {
console.error('[SystemController] Interrupt signal triggered');
}
}
if (this.context.debugMode) {
console.error('[SystemController] Interrupt handled');
}
return { subtype: 'interrupt' };
}
/**
* Handle set_model request
*
* Implements actual model switching with validation and error handling
*/
private async handleSetModel(
payload: CLIControlSetModelRequest,
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
const model = payload.model;
// Validate model parameter
if (typeof model !== 'string' || model.trim() === '') {
throw new Error('Invalid model specified for set_model request');
}
try {
// Attempt to set the model using config
await this.context.config.setModel(model);
if (this.context.debugMode) {
console.error(`[SystemController] Model switched to: ${model}`);
}
return {
subtype: 'set_model',
model,
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : 'Failed to set model';
if (this.context.debugMode) {
console.error(
`[SystemController] Failed to set model ${model}:`,
error,
);
}
throw new Error(errorMessage);
}
}
/**
* Handle supported_commands request
*
* Returns list of supported slash commands loaded dynamically
*/
private async handleSupportedCommands(
signal: AbortSignal,
): Promise<Record<string, unknown>> {
if (signal.aborted) {
throw new Error('Request aborted');
}
const slashCommands = await this.loadSlashCommandNames(signal);
return {
subtype: 'supported_commands',
commands: slashCommands,
};
}
/**
* Load slash command names using CommandService
*
* @param signal - AbortSignal to respect for cancellation
* @returns Promise resolving to array of slash command names
*/
private async loadSlashCommandNames(signal: AbortSignal): Promise<string[]> {
if (signal.aborted) {
return [];
}
try {
const service = await CommandService.create(
[new BuiltinCommandLoader(this.context.config)],
signal,
);
if (signal.aborted) {
return [];
}
const names = new Set<string>();
const commands = service.getCommands();
for (const command of commands) {
names.add(command.name);
}
return Array.from(names).sort();
} catch (error) {
// Check if the error is due to abort
if (signal.aborted) {
return [];
}
if (this.context.debugMode) {
console.error(
'[SystemController] Failed to load slash commands:',
error,
);
}
return [];
}
}
}

View File

@@ -0,0 +1,117 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Service API Types
*
* These interfaces define the public API contract for the ControlService facade.
* They provide type-safe, domain-grouped access to control plane functionality
* for internal CLI code (nonInteractiveCli, session managers, etc.).
*/
import type { Client } from '@modelcontextprotocol/sdk/client/index.js';
import type { MCPServerConfig } from '@qwen-code/qwen-code-core';
import type { PermissionSuggestion } from '../../types.js';
/**
* Permission Service API
*
* Provides permission-related operations including tool execution approval,
* permission suggestions, and tool call monitoring callbacks.
*/
export interface PermissionServiceAPI {
/**
* Build UI suggestions for tool confirmation dialogs
*
* Creates actionable permission suggestions based on tool confirmation details,
* helping host applications present appropriate approval/denial options.
*
* @param confirmationDetails - Tool confirmation details (type, title, metadata)
* @returns Array of permission suggestions or null if details are invalid
*/
buildPermissionSuggestions(
confirmationDetails: unknown,
): PermissionSuggestion[] | null;
/**
* Get callback for monitoring tool call status updates
*
* Returns a callback function that should be passed to executeToolCall
* to enable integration with CoreToolScheduler updates. This callback
* handles outgoing permission requests for tools awaiting approval.
*
* @returns Callback function that processes tool call updates
*/
getToolCallUpdateCallback(): (toolCalls: unknown[]) => void;
}
/**
* System Service API
*
* Provides system-level operations for the control system.
*
* Note: System messages and slash commands are NOT part of the control system API.
* They are handled independently via buildSystemMessage() from nonInteractiveHelpers.ts,
* regardless of whether the control system is available.
*/
export interface SystemServiceAPI {
/**
* Get control capabilities
*
* Returns the control capabilities object indicating what control
* features are available. Used exclusively for the initialize control
* response. System messages do not include capabilities as they are
* independent of the control system.
*
* @returns Control capabilities object
*/
getControlCapabilities(): Record<string, unknown>;
}
/**
* MCP Service API
*
* Provides Model Context Protocol server interaction including
* lazy client initialization and server discovery.
*/
export interface McpServiceAPI {
/**
* Get or create MCP client for a server (lazy initialization)
*
* Returns an existing client from cache or creates a new connection
* if this is the first request for the server. Handles connection
* lifecycle and error recovery.
*
* @param serverName - Name of the MCP server to connect to
* @returns Promise resolving to client instance and server configuration
* @throws Error if server is not configured or connection fails
*/
getMcpClient(serverName: string): Promise<{
client: Client;
config: MCPServerConfig;
}>;
/**
* List all available MCP servers
*
* Returns names of both SDK-managed and CLI-managed MCP servers
* that are currently configured or connected.
*
* @returns Array of server names
*/
listServers(): string[];
}
/**
* Hook Service API
*
* Provides hook callback processing (placeholder for future expansion).
*/
export interface HookServiceAPI {
// Future: Hook-related methods will be added here
// For now, hook functionality is handled only via control requests
registerHookCallback(callback: unknown): void;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,791 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type {
Config,
ServerGeminiStreamEvent,
} from '@qwen-code/qwen-code-core';
import { GeminiEventType } from '@qwen-code/qwen-code-core';
import type { Part } from '@google/genai';
import { JsonOutputAdapter } from './JsonOutputAdapter.js';
function createMockConfig(): Config {
return {
getSessionId: vi.fn().mockReturnValue('test-session-id'),
getModel: vi.fn().mockReturnValue('test-model'),
} as unknown as Config;
}
describe('JsonOutputAdapter', () => {
let adapter: JsonOutputAdapter;
let mockConfig: Config;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let stdoutWriteSpy: any;
beforeEach(() => {
mockConfig = createMockConfig();
adapter = new JsonOutputAdapter(mockConfig);
stdoutWriteSpy = vi
.spyOn(process.stdout, 'write')
.mockImplementation(() => true);
});
afterEach(() => {
stdoutWriteSpy.mockRestore();
});
describe('startAssistantMessage', () => {
it('should reset state for new message', () => {
adapter.startAssistantMessage();
adapter.startAssistantMessage(); // Start second message
// Should not throw
expect(() => adapter.finalizeAssistantMessage()).not.toThrow();
});
});
describe('processEvent', () => {
beforeEach(() => {
adapter.startAssistantMessage();
});
it('should append text content from Content events', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Content,
value: 'Hello',
};
adapter.processEvent(event);
const event2: ServerGeminiStreamEvent = {
type: GeminiEventType.Content,
value: ' World',
};
adapter.processEvent(event2);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: 'Hello World',
});
});
it('should append citation content from Citation events', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Citation,
value: 'Citation text',
};
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: expect.stringContaining('Citation text'),
});
});
it('should ignore non-string citation values', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Citation,
value: 123,
} as unknown as ServerGeminiStreamEvent;
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(0);
});
it('should append thinking from Thought events', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: 'Thinking about the task',
},
};
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'thinking',
thinking: 'Planning: Thinking about the task',
signature: 'Planning',
});
});
it('should handle thinking with only subject', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: '',
},
};
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content[0]).toMatchObject({
type: 'thinking',
signature: 'Planning',
});
});
it('should append tool use from ToolCallRequest events', () => {
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
};
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'tool_use',
id: 'tool-call-1',
name: 'test_tool',
input: { param1: 'value1' },
});
});
it('should set stop_reason to tool_use when message contains only tool_use blocks', () => {
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBe('tool_use');
});
it('should set stop_reason to null when message contains text blocks', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Some text',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBeNull();
});
it('should set stop_reason to null when message contains thinking blocks', () => {
adapter.processEvent({
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: 'Thinking about the task',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBeNull();
});
it('should set stop_reason to tool_use when message contains multiple tool_use blocks', () => {
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool_1',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-2',
name: 'test_tool_2',
args: { param2: 'value2' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(2);
expect(
message.message.content.every((block) => block.type === 'tool_use'),
).toBe(true);
expect(message.message.stop_reason).toBe('tool_use');
});
it('should update usage from Finished event', () => {
const usageMetadata = {
promptTokenCount: 100,
candidatesTokenCount: 50,
cachedContentTokenCount: 10,
totalTokenCount: 160,
};
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Finished,
value: {
reason: undefined,
usageMetadata,
},
};
adapter.processEvent(event);
const message = adapter.finalizeAssistantMessage();
expect(message.message.usage).toMatchObject({
input_tokens: 100,
output_tokens: 50,
cache_read_input_tokens: 10,
total_tokens: 160,
});
});
it('should finalize pending blocks on Finished event', () => {
// Add some text first
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Some text',
});
const event: ServerGeminiStreamEvent = {
type: GeminiEventType.Finished,
value: { reason: undefined, usageMetadata: undefined },
};
adapter.processEvent(event);
// Should not throw when finalizing
expect(() => adapter.finalizeAssistantMessage()).not.toThrow();
});
it('should ignore events after finalization', () => {
adapter.finalizeAssistantMessage();
const originalContent =
adapter.finalizeAssistantMessage().message.content;
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Should be ignored',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toEqual(originalContent);
});
});
describe('finalizeAssistantMessage', () => {
beforeEach(() => {
adapter.startAssistantMessage();
});
it('should build and emit a complete assistant message', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test response',
});
const message = adapter.finalizeAssistantMessage();
expect(message.type).toBe('assistant');
expect(message.uuid).toBeTruthy();
expect(message.session_id).toBe('test-session-id');
expect(message.parent_tool_use_id).toBeNull();
expect(message.message.role).toBe('assistant');
expect(message.message.model).toBe('test-model');
expect(message.message.content).toHaveLength(1);
});
it('should return same message on subsequent calls', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test',
});
const message1 = adapter.finalizeAssistantMessage();
const message2 = adapter.finalizeAssistantMessage();
expect(message1).toEqual(message2);
});
it('should split different block types into separate assistant messages', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
adapter.processEvent({
type: GeminiEventType.Thought,
value: { subject: 'Thinking', description: 'Thought' },
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0].type).toBe('thinking');
const storedMessages = (adapter as unknown as { messages: unknown[] })
.messages;
const assistantMessages = storedMessages.filter(
(
msg,
): msg is {
type: string;
message: { content: Array<{ type: string }> };
} => {
if (
typeof msg !== 'object' ||
msg === null ||
!('type' in msg) ||
(msg as { type?: string }).type !== 'assistant' ||
!('message' in msg)
) {
return false;
}
const message = (msg as { message?: unknown }).message;
return (
typeof message === 'object' &&
message !== null &&
'content' in message &&
Array.isArray((message as { content?: unknown }).content)
);
},
);
expect(assistantMessages).toHaveLength(2);
for (const assistant of assistantMessages) {
const uniqueTypes = new Set(
assistant.message.content.map((block) => block.type),
);
expect(uniqueTypes.size).toBeLessThanOrEqual(1);
}
});
it('should throw if message not started', () => {
adapter = new JsonOutputAdapter(mockConfig);
expect(() => adapter.finalizeAssistantMessage()).toThrow(
'Message not started',
);
});
});
describe('emitResult', () => {
beforeEach(() => {
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Response text',
});
adapter.finalizeAssistantMessage();
});
it('should emit success result as JSON array', () => {
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(Array.isArray(parsed)).toBe(true);
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage).toBeDefined();
expect(resultMessage.is_error).toBe(false);
expect(resultMessage.subtype).toBe('success');
expect(resultMessage.result).toBe('Response text');
expect(resultMessage.duration_ms).toBe(1000);
expect(resultMessage.num_turns).toBe(1);
});
it('should emit error result', () => {
adapter.emitResult({
isError: true,
errorMessage: 'Test error',
durationMs: 500,
apiDurationMs: 300,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage.is_error).toBe(true);
expect(resultMessage.subtype).toBe('error_during_execution');
expect(resultMessage.error?.message).toBe('Test error');
});
it('should use provided summary over extracted text', () => {
adapter.emitResult({
isError: false,
summary: 'Custom summary',
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage.result).toBe('Custom summary');
});
it('should include usage information', () => {
const usage = {
input_tokens: 100,
output_tokens: 50,
total_tokens: 150,
};
adapter.emitResult({
isError: false,
usage,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage.usage).toEqual(usage);
});
it('should include stats when provided', () => {
const stats = {
models: {},
tools: {
totalCalls: 5,
totalSuccess: 4,
totalFail: 1,
totalDurationMs: 1000,
totalDecisions: {
accept: 3,
reject: 1,
modify: 0,
auto_accept: 1,
},
byName: {},
},
files: {
totalLinesAdded: 10,
totalLinesRemoved: 5,
},
};
adapter.emitResult({
isError: false,
stats,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const resultMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'result',
);
expect(resultMessage.stats).toEqual(stats);
});
});
describe('emitUserMessage', () => {
it('should add user message to collection', () => {
const parts: Part[] = [{ text: 'Hello user' }];
adapter.emitUserMessage(parts);
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const userMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'user',
);
expect(userMessage).toBeDefined();
expect(Array.isArray(userMessage.message.content)).toBe(true);
if (Array.isArray(userMessage.message.content)) {
expect(userMessage.message.content).toHaveLength(1);
expect(userMessage.message.content[0]).toEqual({
type: 'text',
text: 'Hello user',
});
}
});
it('should handle parent_tool_use_id', () => {
const parts: Part[] = [{ text: 'Tool response' }];
adapter.emitUserMessage(parts);
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const userMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'user',
);
// emitUserMessage currently sets parent_tool_use_id to null
expect(userMessage.parent_tool_use_id).toBeNull();
});
});
describe('emitToolResult', () => {
it('should emit tool result message', () => {
const request = {
callId: 'tool-1',
name: 'test_tool',
args: {},
isClientInitiated: false,
prompt_id: 'prompt-1',
};
const response = {
callId: 'tool-1',
responseParts: [],
resultDisplay: 'Tool executed successfully',
error: undefined,
errorType: undefined,
};
adapter.emitToolResult(request, response);
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const toolResult = parsed.find(
(
msg: unknown,
): msg is { type: 'user'; message: { content: unknown[] } } =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'user' &&
'message' in msg &&
typeof msg.message === 'object' &&
msg.message !== null &&
'content' in msg.message &&
Array.isArray(msg.message.content) &&
msg.message.content[0] &&
typeof msg.message.content[0] === 'object' &&
'type' in msg.message.content[0] &&
msg.message.content[0].type === 'tool_result',
);
expect(toolResult).toBeDefined();
const block = toolResult.message.content[0] as {
type: 'tool_result';
tool_use_id: string;
content?: string;
is_error?: boolean;
};
expect(block).toMatchObject({
type: 'tool_result',
tool_use_id: 'tool-1',
content: 'Tool executed successfully',
is_error: false,
});
});
it('should mark error tool results', () => {
const request = {
callId: 'tool-1',
name: 'test_tool',
args: {},
isClientInitiated: false,
prompt_id: 'prompt-1',
};
const response = {
callId: 'tool-1',
responseParts: [],
resultDisplay: undefined,
error: new Error('Tool failed'),
errorType: undefined,
};
adapter.emitToolResult(request, response);
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const toolResult = parsed.find(
(
msg: unknown,
): msg is { type: 'user'; message: { content: unknown[] } } =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'user' &&
'message' in msg &&
typeof msg.message === 'object' &&
msg.message !== null &&
'content' in msg.message &&
Array.isArray(msg.message.content),
);
const block = toolResult.message.content[0] as {
is_error?: boolean;
};
expect(block.is_error).toBe(true);
});
});
describe('emitSystemMessage', () => {
it('should add system message to collection', () => {
adapter.emitSystemMessage('test_subtype', { data: 'value' });
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const systemMessage = parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
msg.type === 'system',
);
expect(systemMessage).toBeDefined();
expect(systemMessage.subtype).toBe('test_subtype');
expect(systemMessage.data).toEqual({ data: 'value' });
});
});
describe('getSessionId and getModel', () => {
it('should return session ID from config', () => {
expect(adapter.getSessionId()).toBe('test-session-id');
expect(mockConfig.getSessionId).toHaveBeenCalled();
});
it('should return model from config', () => {
expect(adapter.getModel()).toBe('test-model');
expect(mockConfig.getModel).toHaveBeenCalled();
});
});
describe('multiple messages in collection', () => {
it('should collect all messages and emit as array', () => {
adapter.emitSystemMessage('init', {});
adapter.emitUserMessage([{ text: 'User input' }]);
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Assistant response',
});
adapter.finalizeAssistantMessage();
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(Array.isArray(parsed)).toBe(true);
expect(parsed.length).toBeGreaterThanOrEqual(3);
const systemMsg = parsed[0] as { type?: string };
const userMsg = parsed[1] as { type?: string };
expect(systemMsg.type).toBe('system');
expect(userMsg.type).toBe('user');
expect(
parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
(msg as { type?: string }).type === 'assistant',
),
).toBeDefined();
expect(
parsed.find(
(msg: unknown) =>
typeof msg === 'object' &&
msg !== null &&
'type' in msg &&
(msg as { type?: string }).type === 'result',
),
).toBeDefined();
});
});
});

View File

@@ -0,0 +1,81 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import type { Config } from '@qwen-code/qwen-code-core';
import type { CLIAssistantMessage, CLIMessage } from '../types.js';
import {
BaseJsonOutputAdapter,
type JsonOutputAdapterInterface,
type ResultOptions,
} from './BaseJsonOutputAdapter.js';
/**
* JSON output adapter that collects all messages and emits them
* as a single JSON array at the end of the turn.
* Supports both main agent and subagent messages through distinct APIs.
*/
export class JsonOutputAdapter
extends BaseJsonOutputAdapter
implements JsonOutputAdapterInterface
{
private readonly messages: CLIMessage[] = [];
constructor(config: Config) {
super(config);
}
/**
* Emits message to the messages array (batch mode).
* Tracks the last assistant message for efficient result text extraction.
*/
protected emitMessageImpl(message: CLIMessage): void {
this.messages.push(message);
// Track assistant messages for result generation
if (
typeof message === 'object' &&
message !== null &&
'type' in message &&
message.type === 'assistant'
) {
this.updateLastAssistantMessage(message as CLIAssistantMessage);
}
}
/**
* JSON mode does not emit stream events.
*/
protected shouldEmitStreamEvents(): boolean {
return false;
}
finalizeAssistantMessage(): CLIAssistantMessage {
const message = this.finalizeAssistantMessageInternal(
this.mainAgentMessageState,
null,
);
this.updateLastAssistantMessage(message);
return message;
}
emitResult(options: ResultOptions): void {
const resultMessage = this.buildResultMessage(
options,
this.lastAssistantMessage,
);
this.messages.push(resultMessage);
// Emit the entire messages array as JSON (includes all main agent + subagent messages)
const json = JSON.stringify(this.messages);
process.stdout.write(`${json}\n`);
}
emitMessage(message: CLIMessage): void {
// In JSON mode, messages are collected in the messages array
// This is called by the base class's finalizeAssistantMessageInternal
// but can also be called directly for user/tool/system messages
this.messages.push(message);
}
}

View File

@@ -0,0 +1,215 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { PassThrough } from 'node:stream';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
StreamJsonInputReader,
StreamJsonParseError,
type StreamJsonInputMessage,
} from './StreamJsonInputReader.js';
describe('StreamJsonInputReader', () => {
afterEach(() => {
vi.restoreAllMocks();
});
describe('read', () => {
/**
* Test parsing all supported message types in a single test
*/
it('should parse valid messages of all types', async () => {
const input = new PassThrough();
const reader = new StreamJsonInputReader(input);
const messages = [
{
type: 'user',
session_id: 'test-session',
message: {
role: 'user',
content: [{ type: 'text', text: 'hello world' }],
},
parent_tool_use_id: null,
},
{
type: 'control_request',
request_id: 'req-1',
request: { subtype: 'initialize' },
},
{
type: 'control_response',
response: {
subtype: 'success',
request_id: 'req-1',
response: { initialized: true },
},
},
{
type: 'control_cancel_request',
request_id: 'req-1',
},
];
for (const msg of messages) {
input.write(JSON.stringify(msg) + '\n');
}
input.end();
const parsed: StreamJsonInputMessage[] = [];
for await (const msg of reader.read()) {
parsed.push(msg);
}
expect(parsed).toHaveLength(messages.length);
expect(parsed).toEqual(messages);
});
it('should parse multiple messages', async () => {
const input = new PassThrough();
const reader = new StreamJsonInputReader(input);
const message1 = {
type: 'control_request',
request_id: 'req-1',
request: { subtype: 'initialize' },
};
const message2 = {
type: 'user',
session_id: 'test-session',
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
},
parent_tool_use_id: null,
};
input.write(JSON.stringify(message1) + '\n');
input.write(JSON.stringify(message2) + '\n');
input.end();
const messages: StreamJsonInputMessage[] = [];
for await (const msg of reader.read()) {
messages.push(msg);
}
expect(messages).toHaveLength(2);
expect(messages[0]).toEqual(message1);
expect(messages[1]).toEqual(message2);
});
it('should skip empty lines and trim whitespace', async () => {
const input = new PassThrough();
const reader = new StreamJsonInputReader(input);
const message = {
type: 'user',
session_id: 'test-session',
message: {
role: 'user',
content: [{ type: 'text', text: 'hello' }],
},
parent_tool_use_id: null,
};
input.write('\n');
input.write(' ' + JSON.stringify(message) + ' \n');
input.write(' \n');
input.write('\t\n');
input.end();
const messages: StreamJsonInputMessage[] = [];
for await (const msg of reader.read()) {
messages.push(msg);
}
expect(messages).toHaveLength(1);
expect(messages[0]).toEqual(message);
});
/**
* Consolidated error handling test cases
*/
it.each([
{
name: 'invalid JSON',
input: '{"invalid": json}\n',
expectedError: 'Failed to parse stream-json line',
},
{
name: 'missing type field',
input:
JSON.stringify({ session_id: 'test-session', message: 'hello' }) +
'\n',
expectedError: 'Missing required "type" field',
},
{
name: 'non-object value (string)',
input: '"just a string"\n',
expectedError: 'Parsed value is not an object',
},
{
name: 'non-object value (null)',
input: 'null\n',
expectedError: 'Parsed value is not an object',
},
{
name: 'array value',
input: '[1, 2, 3]\n',
expectedError: 'Missing required "type" field',
},
{
name: 'type field not a string',
input: JSON.stringify({ type: 123, session_id: 'test-session' }) + '\n',
expectedError: 'Missing required "type" field',
},
])(
'should throw StreamJsonParseError for $name',
async ({ input: inputLine, expectedError }) => {
const input = new PassThrough();
const reader = new StreamJsonInputReader(input);
input.write(inputLine);
input.end();
const messages: StreamJsonInputMessage[] = [];
let error: unknown;
try {
for await (const msg of reader.read()) {
messages.push(msg);
}
} catch (e) {
error = e;
}
expect(messages).toHaveLength(0);
expect(error).toBeInstanceOf(StreamJsonParseError);
expect((error as StreamJsonParseError).message).toContain(
expectedError,
);
},
);
it('should use process.stdin as default input', () => {
const reader = new StreamJsonInputReader();
// Access private field for testing constructor default parameter
expect((reader as unknown as { input: typeof process.stdin }).input).toBe(
process.stdin,
);
});
it('should use provided input stream', () => {
const customInput = new PassThrough();
const reader = new StreamJsonInputReader(customInput);
// Access private field for testing constructor parameter
expect((reader as unknown as { input: typeof customInput }).input).toBe(
customInput,
);
});
});
});

View File

@@ -0,0 +1,73 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { createInterface } from 'node:readline/promises';
import type { Readable } from 'node:stream';
import process from 'node:process';
import type {
CLIControlRequest,
CLIControlResponse,
CLIMessage,
ControlCancelRequest,
} from '../types.js';
export type StreamJsonInputMessage =
| CLIMessage
| CLIControlRequest
| CLIControlResponse
| ControlCancelRequest;
export class StreamJsonParseError extends Error {}
export class StreamJsonInputReader {
private readonly input: Readable;
constructor(input: Readable = process.stdin) {
this.input = input;
}
async *read(): AsyncGenerator<StreamJsonInputMessage> {
const rl = createInterface({
input: this.input,
crlfDelay: Number.POSITIVE_INFINITY,
terminal: false,
});
try {
for await (const rawLine of rl) {
const line = rawLine.trim();
if (!line) {
continue;
}
yield this.parse(line);
}
} finally {
rl.close();
}
}
private parse(line: string): StreamJsonInputMessage {
try {
const parsed = JSON.parse(line) as StreamJsonInputMessage;
if (!parsed || typeof parsed !== 'object') {
throw new StreamJsonParseError('Parsed value is not an object');
}
if (!('type' in parsed) || typeof parsed.type !== 'string') {
throw new StreamJsonParseError('Missing required "type" field');
}
return parsed;
} catch (error) {
if (error instanceof StreamJsonParseError) {
throw error;
}
const reason = error instanceof Error ? error.message : String(error);
throw new StreamJsonParseError(
`Failed to parse stream-json line: ${reason}`,
);
}
}
}

View File

@@ -0,0 +1,997 @@
/**
* @license
* Copyright 2025 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type {
Config,
ServerGeminiStreamEvent,
} from '@qwen-code/qwen-code-core';
import { GeminiEventType } from '@qwen-code/qwen-code-core';
import type { Part } from '@google/genai';
import { StreamJsonOutputAdapter } from './StreamJsonOutputAdapter.js';
function createMockConfig(): Config {
return {
getSessionId: vi.fn().mockReturnValue('test-session-id'),
getModel: vi.fn().mockReturnValue('test-model'),
} as unknown as Config;
}
describe('StreamJsonOutputAdapter', () => {
let adapter: StreamJsonOutputAdapter;
let mockConfig: Config;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let stdoutWriteSpy: any;
beforeEach(() => {
mockConfig = createMockConfig();
stdoutWriteSpy = vi
.spyOn(process.stdout, 'write')
.mockImplementation(() => true);
});
afterEach(() => {
stdoutWriteSpy.mockRestore();
});
describe('with partial messages enabled', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, true);
});
describe('startAssistantMessage', () => {
it('should reset state for new message', () => {
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'First',
});
adapter.finalizeAssistantMessage();
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Second',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: 'Second',
});
});
});
describe('processEvent with stream events', () => {
beforeEach(() => {
adapter.startAssistantMessage();
});
it('should emit stream events for text deltas', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Hello',
});
const calls = stdoutWriteSpy.mock.calls;
expect(calls.length).toBeGreaterThan(0);
const deltaEventCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'content_block_delta'
);
} catch {
return false;
}
});
expect(deltaEventCall).toBeDefined();
const parsed = JSON.parse(deltaEventCall![0] as string);
expect(parsed.event.type).toBe('content_block_delta');
expect(parsed.event.delta).toMatchObject({
type: 'text_delta',
text: 'Hello',
});
});
it('should emit message_start event on first content', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'First',
});
const calls = stdoutWriteSpy.mock.calls;
const messageStartCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'message_start'
);
} catch {
return false;
}
});
expect(messageStartCall).toBeDefined();
});
it('should emit content_block_start for new blocks', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
const calls = stdoutWriteSpy.mock.calls;
const blockStartCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'content_block_start'
);
} catch {
return false;
}
});
expect(blockStartCall).toBeDefined();
});
it('should emit thinking delta events', () => {
adapter.processEvent({
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: 'Thinking',
},
});
const calls = stdoutWriteSpy.mock.calls;
const deltaCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'content_block_delta' &&
parsed.event.delta.type === 'thinking_delta'
);
} catch {
return false;
}
});
expect(deltaCall).toBeDefined();
});
it('should emit message_stop on finalization', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
adapter.finalizeAssistantMessage();
const calls = stdoutWriteSpy.mock.calls;
const messageStopCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'message_stop'
);
} catch {
return false;
}
});
expect(messageStopCall).toBeDefined();
});
});
});
describe('with partial messages disabled', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
});
it('should not emit stream events', () => {
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
const calls = stdoutWriteSpy.mock.calls;
const streamEventCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return parsed.type === 'stream_event';
} catch {
return false;
}
});
expect(streamEventCall).toBeUndefined();
});
it('should still emit final assistant message', () => {
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
adapter.finalizeAssistantMessage();
const calls = stdoutWriteSpy.mock.calls;
const assistantCall = calls.find((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return parsed.type === 'assistant';
} catch {
return false;
}
});
expect(assistantCall).toBeDefined();
});
});
describe('processEvent', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
adapter.startAssistantMessage();
});
it('should append text content from Content events', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Hello',
});
adapter.processEvent({
type: GeminiEventType.Content,
value: ' World',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: 'Hello World',
});
});
it('should append citation content from Citation events', () => {
adapter.processEvent({
type: GeminiEventType.Citation,
value: 'Citation text',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: expect.stringContaining('Citation text'),
});
});
it('should ignore non-string citation values', () => {
adapter.processEvent({
type: GeminiEventType.Citation,
value: 123,
} as unknown as ServerGeminiStreamEvent);
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(0);
});
it('should append thinking from Thought events', () => {
adapter.processEvent({
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: 'Thinking about the task',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'thinking',
thinking: 'Planning: Thinking about the task',
signature: 'Planning',
});
});
it('should handle thinking with only subject', () => {
adapter.processEvent({
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: '',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content[0]).toMatchObject({
type: 'thinking',
signature: 'Planning',
});
});
it('should append tool use from ToolCallRequest events', () => {
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'tool_use',
id: 'tool-call-1',
name: 'test_tool',
input: { param1: 'value1' },
});
});
it('should set stop_reason to tool_use when message contains only tool_use blocks', () => {
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBe('tool_use');
});
it('should set stop_reason to null when message contains text blocks', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Some text',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBeNull();
});
it('should set stop_reason to null when message contains thinking blocks', () => {
adapter.processEvent({
type: GeminiEventType.Thought,
value: {
subject: 'Planning',
description: 'Thinking about the task',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.stop_reason).toBeNull();
});
it('should set stop_reason to tool_use when message contains multiple tool_use blocks', () => {
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-1',
name: 'test_tool_1',
args: { param1: 'value1' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
adapter.processEvent({
type: GeminiEventType.ToolCallRequest,
value: {
callId: 'tool-call-2',
name: 'test_tool_2',
args: { param2: 'value2' },
isClientInitiated: false,
prompt_id: 'prompt-1',
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(2);
expect(
message.message.content.every((block) => block.type === 'tool_use'),
).toBe(true);
expect(message.message.stop_reason).toBe('tool_use');
});
it('should update usage from Finished event', () => {
const usageMetadata = {
promptTokenCount: 100,
candidatesTokenCount: 50,
cachedContentTokenCount: 10,
totalTokenCount: 160,
};
adapter.processEvent({
type: GeminiEventType.Finished,
value: {
reason: undefined,
usageMetadata,
},
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.usage).toMatchObject({
input_tokens: 100,
output_tokens: 50,
cache_read_input_tokens: 10,
total_tokens: 160,
});
});
it('should ignore events after finalization', () => {
adapter.finalizeAssistantMessage();
const originalContent =
adapter.finalizeAssistantMessage().message.content;
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Should be ignored',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toEqual(originalContent);
});
});
describe('finalizeAssistantMessage', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
adapter.startAssistantMessage();
});
it('should build and emit a complete assistant message', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test response',
});
const message = adapter.finalizeAssistantMessage();
expect(message.type).toBe('assistant');
expect(message.uuid).toBeTruthy();
expect(message.session_id).toBe('test-session-id');
expect(message.parent_tool_use_id).toBeNull();
expect(message.message.role).toBe('assistant');
expect(message.message.model).toBe('test-model');
expect(message.message.content).toHaveLength(1);
});
it('should emit message to stdout immediately', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test',
});
stdoutWriteSpy.mockClear();
adapter.finalizeAssistantMessage();
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.type).toBe('assistant');
});
it('should store message in lastAssistantMessage', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test',
});
const message = adapter.finalizeAssistantMessage();
// Access protected property for testing
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((adapter as any).lastAssistantMessage).toEqual(message);
});
it('should return same message on subsequent calls', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Test',
});
const message1 = adapter.finalizeAssistantMessage();
const message2 = adapter.finalizeAssistantMessage();
expect(message1).toEqual(message2);
});
it('should split different block types into separate assistant messages', () => {
stdoutWriteSpy.mockClear();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
adapter.processEvent({
type: GeminiEventType.Thought,
value: { subject: 'Thinking', description: 'Thought' },
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0].type).toBe('thinking');
const assistantMessages = stdoutWriteSpy.mock.calls
.map((call: unknown[]) => JSON.parse(call[0] as string))
.filter(
(
payload: unknown,
): payload is {
type: string;
message: { content: Array<{ type: string }> };
} => {
if (
typeof payload !== 'object' ||
payload === null ||
!('type' in payload) ||
(payload as { type?: string }).type !== 'assistant' ||
!('message' in payload)
) {
return false;
}
const message = (payload as { message?: unknown }).message;
if (
typeof message !== 'object' ||
message === null ||
!('content' in message)
) {
return false;
}
const content = (message as { content?: unknown }).content;
return (
Array.isArray(content) &&
content.length > 0 &&
content.every(
(block: unknown) =>
typeof block === 'object' &&
block !== null &&
'type' in block,
)
);
},
);
expect(assistantMessages).toHaveLength(2);
const observedTypes = assistantMessages.map(
(payload: {
type: string;
message: { content: Array<{ type: string }> };
}) => payload.message.content[0]?.type ?? '',
);
expect(observedTypes).toEqual(['text', 'thinking']);
for (const payload of assistantMessages) {
const uniqueTypes = new Set(
payload.message.content.map((block: { type: string }) => block.type),
);
expect(uniqueTypes.size).toBeLessThanOrEqual(1);
}
});
it('should throw if message not started', () => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
expect(() => adapter.finalizeAssistantMessage()).toThrow(
'Message not started',
);
});
});
describe('emitResult', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
adapter.startAssistantMessage();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Response text',
});
adapter.finalizeAssistantMessage();
});
it('should emit success result immediately', () => {
stdoutWriteSpy.mockClear();
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.type).toBe('result');
expect(parsed.is_error).toBe(false);
expect(parsed.subtype).toBe('success');
expect(parsed.result).toBe('Response text');
expect(parsed.duration_ms).toBe(1000);
expect(parsed.num_turns).toBe(1);
});
it('should emit error result', () => {
stdoutWriteSpy.mockClear();
adapter.emitResult({
isError: true,
errorMessage: 'Test error',
durationMs: 500,
apiDurationMs: 300,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.is_error).toBe(true);
expect(parsed.subtype).toBe('error_during_execution');
expect(parsed.error?.message).toBe('Test error');
});
it('should use provided summary over extracted text', () => {
stdoutWriteSpy.mockClear();
adapter.emitResult({
isError: false,
summary: 'Custom summary',
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.result).toBe('Custom summary');
});
it('should include usage information', () => {
const usage = {
input_tokens: 100,
output_tokens: 50,
total_tokens: 150,
};
stdoutWriteSpy.mockClear();
adapter.emitResult({
isError: false,
usage,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.usage).toEqual(usage);
});
it('should handle result without assistant message', () => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
stdoutWriteSpy.mockClear();
adapter.emitResult({
isError: false,
durationMs: 1000,
apiDurationMs: 800,
numTurns: 1,
});
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.result).toBe('');
});
});
describe('emitUserMessage', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
});
it('should emit user message immediately', () => {
stdoutWriteSpy.mockClear();
const parts: Part[] = [{ text: 'Hello user' }];
adapter.emitUserMessage(parts);
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.type).toBe('user');
expect(Array.isArray(parsed.message.content)).toBe(true);
if (Array.isArray(parsed.message.content)) {
expect(parsed.message.content).toHaveLength(1);
expect(parsed.message.content[0]).toEqual({
type: 'text',
text: 'Hello user',
});
}
});
it('should handle parent_tool_use_id', () => {
const parts: Part[] = [{ text: 'Tool response' }];
adapter.emitUserMessage(parts);
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
// emitUserMessage currently sets parent_tool_use_id to null
expect(parsed.parent_tool_use_id).toBeNull();
});
});
describe('emitToolResult', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
});
it('should emit tool result message immediately', () => {
stdoutWriteSpy.mockClear();
const request = {
callId: 'tool-1',
name: 'test_tool',
args: {},
isClientInitiated: false,
prompt_id: 'prompt-1',
};
const response = {
callId: 'tool-1',
responseParts: [],
resultDisplay: 'Tool executed successfully',
error: undefined,
errorType: undefined,
};
adapter.emitToolResult(request, response);
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.type).toBe('user');
expect(parsed.parent_tool_use_id).toBeNull();
const block = parsed.message.content[0];
expect(block).toMatchObject({
type: 'tool_result',
tool_use_id: 'tool-1',
content: 'Tool executed successfully',
is_error: false,
});
});
it('should mark error tool results', () => {
const request = {
callId: 'tool-1',
name: 'test_tool',
args: {},
isClientInitiated: false,
prompt_id: 'prompt-1',
};
const response = {
callId: 'tool-1',
responseParts: [],
resultDisplay: undefined,
error: new Error('Tool failed'),
errorType: undefined,
};
adapter.emitToolResult(request, response);
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
const block = parsed.message.content[0];
expect(block.is_error).toBe(true);
});
});
describe('emitSystemMessage', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
});
it('should emit system message immediately', () => {
stdoutWriteSpy.mockClear();
adapter.emitSystemMessage('test_subtype', { data: 'value' });
expect(stdoutWriteSpy).toHaveBeenCalled();
const output = stdoutWriteSpy.mock.calls[0][0] as string;
const parsed = JSON.parse(output);
expect(parsed.type).toBe('system');
expect(parsed.subtype).toBe('test_subtype');
expect(parsed.data).toEqual({ data: 'value' });
});
});
describe('getSessionId and getModel', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
});
it('should return session ID from config', () => {
expect(adapter.getSessionId()).toBe('test-session-id');
expect(mockConfig.getSessionId).toHaveBeenCalled();
});
it('should return model from config', () => {
expect(adapter.getModel()).toBe('test-model');
expect(mockConfig.getModel).toHaveBeenCalled();
});
});
describe('message_id in stream events', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, true);
adapter.startAssistantMessage();
});
it('should include message_id in stream events after message starts', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text',
});
// Process another event to ensure messageStarted is true
adapter.processEvent({
type: GeminiEventType.Content,
value: 'More',
});
const calls = stdoutWriteSpy.mock.calls;
// Find all delta events
const deltaCalls = calls.filter((call: unknown[]) => {
try {
const parsed = JSON.parse(call[0] as string);
return (
parsed.type === 'stream_event' &&
parsed.event.type === 'content_block_delta'
);
} catch {
return false;
}
});
expect(deltaCalls.length).toBeGreaterThan(0);
// The second delta event should have message_id (after messageStarted becomes true)
// message_id is added to the event object, so check parsed.event.message_id
if (deltaCalls.length > 1) {
const secondDelta = JSON.parse(
(deltaCalls[1] as unknown[])[0] as string,
);
// message_id is on the enriched event object
expect(
secondDelta.event.message_id || secondDelta.message_id,
).toBeTruthy();
} else {
// If only one delta, check if message_id exists
const delta = JSON.parse((deltaCalls[0] as unknown[])[0] as string);
// message_id is added when messageStarted is true
// First event may or may not have it, but subsequent ones should
expect(delta.event.message_id || delta.message_id).toBeTruthy();
}
});
});
describe('multiple text blocks', () => {
beforeEach(() => {
adapter = new StreamJsonOutputAdapter(mockConfig, false);
adapter.startAssistantMessage();
});
it('should split assistant messages when block types change repeatedly', () => {
stdoutWriteSpy.mockClear();
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Text content',
});
adapter.processEvent({
type: GeminiEventType.Thought,
value: { subject: 'Thinking', description: 'Thought' },
});
adapter.processEvent({
type: GeminiEventType.Content,
value: 'More text',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: 'More text',
});
const assistantMessages = stdoutWriteSpy.mock.calls
.map((call: unknown[]) => JSON.parse(call[0] as string))
.filter(
(
payload: unknown,
): payload is {
type: string;
message: { content: Array<{ type: string; text?: string }> };
} => {
if (
typeof payload !== 'object' ||
payload === null ||
!('type' in payload) ||
(payload as { type?: string }).type !== 'assistant' ||
!('message' in payload)
) {
return false;
}
const message = (payload as { message?: unknown }).message;
if (
typeof message !== 'object' ||
message === null ||
!('content' in message)
) {
return false;
}
const content = (message as { content?: unknown }).content;
return (
Array.isArray(content) &&
content.length > 0 &&
content.every(
(block: unknown) =>
typeof block === 'object' &&
block !== null &&
'type' in block,
)
);
},
);
expect(assistantMessages).toHaveLength(3);
const observedTypes = assistantMessages.map(
(msg: {
type: string;
message: { content: Array<{ type: string; text?: string }> };
}) => msg.message.content[0]?.type ?? '',
);
expect(observedTypes).toEqual(['text', 'thinking', 'text']);
for (const msg of assistantMessages) {
const uniqueTypes = new Set(
msg.message.content.map((block: { type: string }) => block.type),
);
expect(uniqueTypes.size).toBeLessThanOrEqual(1);
}
});
it('should merge consecutive text fragments', () => {
adapter.processEvent({
type: GeminiEventType.Content,
value: 'Hello',
});
adapter.processEvent({
type: GeminiEventType.Content,
value: ' ',
});
adapter.processEvent({
type: GeminiEventType.Content,
value: 'World',
});
const message = adapter.finalizeAssistantMessage();
expect(message.message.content).toHaveLength(1);
expect(message.message.content[0]).toMatchObject({
type: 'text',
text: 'Hello World',
});
});
});
});

Some files were not shown because too many files have changed in this diff Show More