Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

[fix] chat CLI Windows signal handling, REPL exit, and total timeout

haowenzhong171ec753d2187
diff --git a/docs/en/CLI.md b/docs/en/CLI.md
index 5bd0ba6b08..f3687363ff 100644
--- a/docs/en/CLI.md
+++ b/docs/en/CLI.md
@@ -235,7 +235,7 @@ Cancel operation:
## Terminal CLI: `jiuwenswarm chat`
-Starting from v0.2.1, JiuwenSwarm provides a first-party command-line chat entry point to interact with JiuwenSwarm directly from the terminal.
+Starting from v0.2.3, JiuwenSwarm provides a first-party command-line chat entry point to interact with JiuwenSwarm directly from the terminal.
### Quick Start
@@ -274,7 +274,7 @@ jiuwenswarm chat "Hello, introduce yourself"
| `--jsonl` | — | Print each Gateway event frame as JSON Lines |
| `--show-reasoning` | — | Include reasoning output (to stderr) |
| `--show-tools` | — | Include compact tool call/result status (to stderr) |
-| `--timeout <seconds>` | 300 | Per-recv timeout in seconds |
+| `--timeout <seconds>` | — | Total response timeout in seconds |
### Modes (`--mode`)
@@ -319,11 +319,17 @@ jiuwenswarm chat
# Session: cli-20260616-120500-abc12345
# > show me the files in the current directory
# > analyze main.py
-# > Ctrl+D to exit
+# > /exit
```
All messages in REPL mode share the same session, maintaining continuous context.
+**Exit the REPL** with any of:
+
+- `/exit`, `/quit`, or `/q`
+- `Ctrl+D` (Unix) / `Ctrl+Z`+Enter (Windows)
+- `Ctrl+C` at the input prompt
+
### Loading Spinner
While waiting for the first response, a dynamic loading indicator displays on stderr:
@@ -359,8 +365,10 @@ jiuwenswarm chat --jsonl "analyze README" | jq
| Action | Behavior |
|---|---|
-| First Ctrl+C | Sends `chat.interrupt` to Agent, graceful cancel |
-| Second Ctrl+C | Immediate exit (`os._exit(130)`) |
+| First Ctrl+C | Sends `chat.interrupt` to Agent, graceful cancel. In REPL, stays in the loop for the next prompt |
+| Second Ctrl+C | Force exit (exit code 130) |
+
+> **Windows note**: `loop.add_signal_handler` is not supported on Windows. The CLI falls back to `signal.signal(SIGINT, ...)` so Ctrl+C still triggers graceful cancel (sends `chat.interrupt`) instead of raising an unhandled `KeyboardInterrupt`. Two rapid Ctrl+C presses force-exit on Windows as well.
### Exit Codes
diff --git "a/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md" "b/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
index ee4aaa60e0..ba55326f87 100644
--- "a/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
+++ "b/docs/zh/\345\221\275\344\273\244\350\241\214\346\214\207\344\273\244.md"
@@ -197,7 +197,7 @@ Gateway 会回复确认提示,要求用户确认:
## 终端 CLI:`jiuwenswarm chat`
-从 v0.2.1 开始,JiuwenSwarm 提供了原生命令行聊天入口,可以在终端中直接与 JiuwenSwarm 对话。
+从 v0.2.3 开始,JiuwenSwarm 提供了原生命令行聊天入口,可以在终端中直接与 JiuwenSwarm 对话。
### 快速开始
@@ -236,7 +236,7 @@ jiuwenswarm chat "你好,介绍一下你自己"
| `--jsonl` | — | 逐行输出 JSON 事件帧 |
| `--show-reasoning` | — | 显示推理过程(输出到 stderr) |
| `--show-tools` | — | 显示工具调用/结果(输出到 stderr) |
-| `--timeout <seconds>` | 300 | 单次 recv 超时(秒) |
+| `--timeout <seconds>` | — | 总响应超时(秒) |
### 模式(`--mode`)
@@ -281,11 +281,17 @@ jiuwenswarm chat
# Session: cli-20260616-120500-abc12345
# > 帮我看看当前目录的文件
# > 分析 main.py
-# > 按 Ctrl+D 退出
+# > /exit
```
REPL 中所有消息复用同一个 session,保持上下文连续。
+**退出 REPL** 的方式:
+
+- `/exit`、`/quit` 或 `/q`
+- `Ctrl+D`(Unix)/ `Ctrl+Z`+Enter(Windows)
+- 在输入提示符下按 `Ctrl+C`
+
### 加载动画
发送请求后,在等待第一个回复期间,终端会显示动态加载提示(输出到 stderr,不影响内容重定向):
@@ -321,8 +327,10 @@ jiuwenswarm chat --jsonl "分析 README" | jq
| 操作 | 行为 |
|---|---|
-| 第一次 Ctrl+C | 发送 `chat.interrupt` 给 Agent,尝试优雅取消 |
-| 第二次 Ctrl+C | 立即退出(`os._exit(130)`) |
+| 第一次 Ctrl+C | 发送 `chat.interrupt` 给 Agent,尝试优雅取消。在 REPL 模式下,取消后留在循环中等待下一个输入 |
+| 第二次 Ctrl+C | 强制退出(退出码 130) |
+
+> **Windows 注意**:Windows 不支持 `loop.add_signal_handler`。CLI 会回退到 `signal.signal(SIGINT, ...)`,使 Ctrl+C 仍能触发优雅取消(发送 `chat.interrupt`),而不是抛出未处理的 `KeyboardInterrupt`。连续两次快速 Ctrl+C 在 Windows 上同样会强制退出。
### 退出码
diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.py
index 88587f9760..fce5dca11f 100644
--- a/jiuwenswarm/cli/chat.py
+++ b/jiuwenswarm/cli/chat.py
@@ -11,6 +11,7 @@ import logging
import os
import signal
import sys
+import time
import uuid as uuid_module
from pathlib import Path
@@ -182,7 +183,15 @@ async def _run_interactive_loop(
timeout: float | None = None,
) -> int:
interrupted = False
- per_recv_timeout = timeout if timeout and timeout > 0 else 300.0
+ # `timeout` is the TOTAL response timeout (matches --help/docs). We track
+ # the deadline and compute the remaining budget for each recv() call so
+ # long-running streams still respect the overall cap. When unset, a
+ # generous per-recv idle timeout keeps the connection alive.
+ total_timeout = timeout if timeout and timeout > 0 else None
+ recv_idle_timeout = 300.0
+ deadline = None
+ if total_timeout is not None:
+ deadline = time.monotonic() + total_timeout
# In team mode the session is persistent: leader replies arrive as
# chat.final but the team keeps working (creating workflows, delegating
# to members, etc.). Only chat.processing_status(is_processing=False)
@@ -203,10 +212,30 @@ async def _run_interactive_loop(
def _on_second_sigint() -> None:
os.kill(os.getpid(), signal.SIGTERM)
+ # Windows does not support loop.add_signal_handler; fall back to
+ # signal.signal so Ctrl+C sets the interrupted flag instead of raising
+ # KeyboardInterrupt and skipping the graceful cancel path.
+ _win_prev_handler = None
+ _force_exit = False
+
try:
loop.add_signal_handler(signal.SIGINT, _on_first_sigint)
except NotImplementedError:
- pass
+ import threading
+
+ def _win_sigint_handler(signum, frame) -> None:
+ nonlocal interrupted, _force_exit
+ if interrupted:
+ # Second Ctrl+C — force exit
+ _force_exit = True
+ logger.warning("Force exiting...")
+ return
+ interrupted = True
+ logger.warning("Interrupted. Sending cancel (press Ctrl+C again to force exit)...")
+
+ # signal.signal must be called from the main thread.
+ if threading.current_thread() is threading.main_thread():
+ _win_prev_handler = signal.signal(signal.SIGINT, _win_sigint_handler)
await client.send_request(request)
@@ -215,13 +244,41 @@ async def _run_interactive_loop(
try:
while True:
+ # Compute the recv timeout: when a total deadline is set, use
+ # the remaining budget (clamped to a small floor so we still
+ # yield to the event loop); otherwise fall back to the idle
+ # timeout.
+ if deadline is not None:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ logger.warning("response timed out")
+ return 1
+ cur_timeout = max(remaining, 0.1)
+ else:
+ cur_timeout = recv_idle_timeout
try:
- data = await asyncio.wait_for(client.recv(), timeout=per_recv_timeout)
+ data = await asyncio.wait_for(client.recv(), timeout=cur_timeout)
except asyncio.TimeoutError:
- logger.warning("response timed out")
- return 1
+ if deadline is not None:
+ # Total budget exhausted
+ logger.warning("response timed out")
+ return 1
+ # Idle timeout between events — keep waiting
+ continue
except ConnectionError:
return 0
+ except KeyboardInterrupt:
+ # Windows: Ctrl+C interrupts the blocking recv() with
+ # KeyboardInterrupt even when a signal handler is set.
+ # The handler has already set the `interrupted` flag, so
+ # fall through to the graceful-cancel path below.
+ if _force_exit:
+ return 130
+ if not interrupted:
+ interrupted = True
+
+ if _force_exit:
+ return 130
if interrupted:
await client.send_request({
@@ -315,6 +372,13 @@ async def _run_interactive_loop(
await spinner
except asyncio.CancelledError:
pass
+ # Restore the previous SIGINT handler (Windows fallback or Unix
+ # loop handler removal) so the REPL loop regains control.
+ if _win_prev_handler is not None:
+ try:
+ signal.signal(signal.SIGINT, _win_prev_handler)
+ except (ValueError, OSError):
+ pass
try:
loop.remove_signal_handler(signal.SIGINT)
except (NotImplementedError, ValueError):
@@ -473,7 +537,16 @@ def _run_repl(args: argparse.Namespace) -> int:
args.session = session_id
logger.info("Session: %s", session_id)
- logger.info("Type your prompt and press Enter. Ctrl+C to interrupt, Ctrl+D to exit.")
+ if os.name == "nt":
+ logger.info(
+ "Type your prompt and press Enter. Ctrl+C to interrupt, "
+ "Ctrl+Z+Enter or /exit to exit."
+ )
+ else:
+ logger.info(
+ "Type your prompt and press Enter. Ctrl+C to interrupt, "
+ "Ctrl+D or /exit to exit."
+ )
exit_code = 0
try:
@@ -485,9 +558,15 @@ def _run_repl(args: argparse.Namespace) -> int:
break
if not line.strip():
continue
+ # Cross-platform exit commands (Ctrl+D does not send EOF on Windows)
+ if line.strip() in ("/exit", "/quit", "/q"):
+ logger.info("<exit>")
+ break
exit_code = asyncio.run(_run_chat(args, line.strip()))
if exit_code == 130:
- break
+ # Task was interrupted via Ctrl+C — cancel was already sent,
+ # stay in the REPL for the next prompt instead of exiting.
+ continue
if exit_code != 0:
logger.warning("[exit code: %s]", exit_code)
except KeyboardInterrupt: