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

feat(cli): jiuwenclaw cli implementation

gallonH3128519a1ba2
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index c77e60d26b..d3ba2e384c 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -303,6 +303,27 @@ class AgentWebSocketServer:
else:
await self._handle_history_get(ws, request, send_lock)
return
+ if request.req_method == ReqMethod.COMMAND_ADD_DIR:
+ await self._handle_command_add_dir(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_CHROME:
+ await self._handle_command_chrome(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_COMPACT:
+ await self._handle_command_compact(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_DIFF:
+ await self._handle_command_diff(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_MODEL:
+ await self._handle_command_model(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_RESUME:
+ await self._handle_command_resume(ws, request, send_lock)
+ return
+ if request.req_method == ReqMethod.COMMAND_SESSION:
+ await self._handle_command_session(ws, request, send_lock)
+ return
if request.req_method == ReqMethod.BROWSER_START:
await self._handle_browser_start(ws, request, send_lock)
return
@@ -558,6 +579,179 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire_done, ensure_ascii=False))
+ async def _handle_command_add_dir(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ params = request.params or {}
+ directory_path = params.get("path")
+ remember = params.get("remember", False)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={"path": directory_path, "remember": remember},
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.add_dir failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_chrome(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={},
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.chrome failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_compact(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ params = request.params or {}
+ custom_instructions = params.get("instructions")
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={"instructions": custom_instructions},
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.compact failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_diff(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={
+ "summary": "Workspace diff preview",
+ "items": [
+ {"label": "files_changed", "value": "3"},
+ {"label": "insertions", "value": "24"},
+ {"label": "deletions", "value": "7"},
+ ],
+ },
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.diff failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_model(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ params = request.params or {}
+ requested = params.get("model")
+ current = requested if isinstance(requested, str) and requested.strip() else "default-model"
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={
+ "current": current,
+ "requested": requested if isinstance(requested, str) and requested.strip() else None,
+ "applied": bool(isinstance(requested, str) and requested.strip()),
+ "available": ["default-model", "planner-model", "coder-model"],
+ },
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.model failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_resume(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ params = request.params or {}
+ query = params.get("query")
+ session_id = query if isinstance(query, str) and query.strip() else "sess_mock_resume"
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={
+ "session_id": session_id,
+ "query": query if isinstance(query, str) else "",
+ "resumed": True,
+ "preview": "Mock resumed conversation",
+ },
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.resume failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
+ async def _handle_command_session(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ try:
+ session_id = request.session_id or "sess_mock"
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload={
+ "session_id": session_id,
+ "remote_url": f"https://example.com/session/{session_id}",
+ "qr_text": f"session:{session_id}",
+ },
+ )
+ except Exception as e: # noqa: BLE001
+ logger.exception("[AgentWebSocketServer] command.session failed: %s", e)
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": str(e)},
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
async def _handle_browser_start(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""启动浏览器并返回执行结果(returncode)。"""
try:
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index c376392c93..41e194650d 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -20,13 +20,14 @@ import os
import sys
import time
import uuid as uuid_module
-from dataclasses import dataclass
-from typing import Any
+from dataclasses import dataclass, field
+from typing import Any, Awaitable, Callable
from urllib.parse import urlparse
from dotenv import load_dotenv
from openjiuwen.core.common.logging import LogManager
+from jiuwenclaw.gateway.route_binding import GatewayRouteBinding
from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
from jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace
@@ -47,16 +48,9 @@ logger = logging.getLogger(__name__)
def _normalize_and_forward_message(msg, channel_manager) -> bool:
- from jiuwenclaw.app_web_handlers import (
- _FORWARD_NO_LOCAL_HANDLER_METHODS,
- _FORWARD_REQ_METHODS,
- )
from jiuwenclaw.schema.message import Message, ReqMethod
method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
- if method_val not in _FORWARD_REQ_METHODS:
- return False
-
is_stream = bool(
msg.is_stream
or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
@@ -81,8 +75,8 @@ def _normalize_and_forward_message(msg, channel_manager) -> bool:
metadata=msg.metadata,
)
channel_manager.deliver_to_message_handler(normalized)
- logger.info("[App] ACP/Web inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
- return method_val in _FORWARD_NO_LOCAL_HANDLER_METHODS
+ logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
+ return False
class _InboundGatewayServer:
@@ -129,6 +123,98 @@ class _InboundGatewayServer:
logger.exception("[App] Gateway inbound handling failed: id=%s", getattr(msg, "id", None))
+class AcpRouteHandler:
+ """ACP 路由的 JSON-RPC 桥接逻辑。
+
+ ACP 专属协议桥接,不属于通用 GatewayServer。
+ """
+
+ def __init__(self, on_message_cb) -> None:
+ self._on_message_cb = on_message_cb
+ self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any]] = {}
+
+ async def inbound_intercept(self, ws: Any, data: dict[str, Any]) -> bool:
+ """拦截 ACP JSON-RPC response 帧。"""
+ if not (
+ isinstance(data, dict)
+ and str(data.get("jsonrpc") or "").strip() == "2.0"
+ and str(data.get("id") or "").strip() != ""
+ and ("result" in data or "error" in data)
+ ):
+ return False
+
+ from jiuwenclaw.schema.message import Message, ReqMethod
+
+ jsonrpc_id = str(data.get("id") or "").strip()
+ pending = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)
+ session_id = ""
+ if isinstance(pending, tuple) and len(pending) == 2:
+ session_id = str(pending[0] or "").strip()
+
+ if not jsonrpc_id or not session_id:
+ await ws.send(
+ json.dumps(
+ {
+ "type": "res",
+ "id": jsonrpc_id,
+ "ok": False,
+ "error": f"unknown acp tool response id: {jsonrpc_id}",
+ },
+ ensure_ascii=False,
+ )
+ )
+ return True
+
+ msg = Message(
+ id=f"acp_tool_resp_{uuid_module.uuid4().hex[:12]}",
+ type="req",
+ channel_id="acp",
+ session_id=session_id,
+ params={
+ "jsonrpc_id": jsonrpc_id,
+ "response": dict(data),
+ "session_id": session_id,
+ },
+ timestamp=time.time(),
+ ok=True,
+ req_method=ReqMethod.ACP_TOOL_RESPONSE,
+ is_stream=False,
+ metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},
+ )
+ if self._on_message_cb is not None:
+ result = self._on_message_cb(msg)
+ if asyncio.iscoroutine(result):
+ await result
+ return True
+
+ async def outbound_intercept(self, msg, ws: Any) -> bool:
+ """拦截 ACP output_request 出站消息。"""
+ if (
+ msg.type == "event"
+ and isinstance(msg.payload, dict)
+ and str(msg.payload.get("event_type") or "").strip() == "acp.output_request"
+ ):
+ raw_jsonrpc = msg.payload.get("jsonrpc")
+ if isinstance(raw_jsonrpc, dict):
+ jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()
+ session_id = str(msg.session_id or "").strip()
+ if jsonrpc_id and session_id:
+ self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws)
+ await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))
+ return True
+ return False
+
+ def cleanup(self, ws: Any) -> None:
+ """ws 断开时清理关联的 pending RPC 条目。"""
+ stale = [
+ jsonrpc_id
+ for jsonrpc_id, (_, client) in self._pending_client_rpc_session_by_id.items()
+ if client is ws
+ ]
+ for jsonrpc_id in stale:
+ self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)
+
+
async def _connect_with_retry(
@@ -162,17 +248,34 @@ async def _connect_with_retry(
await asyncio.sleep(interval)
+@dataclass
+class RouteConfig:
+ """单条路由的配置(/acp, /cli 等)。"""
+
+ path: str
+ channel_id: str
+ forward_methods: frozenset[str] = frozenset()
+ forward_no_local_handler_methods: frozenset[str] = frozenset()
+ local_handlers: dict[str, Callable[..., Awaitable[None]]] = field(default_factory=dict)
+ inbound_interceptor: Callable[..., Awaitable[bool]] | None = None
+ outbound_interceptor: Callable[..., Awaitable[bool]] | None = None
+ cleanup_handler: Callable[..., Any] | None = None
+
+
@dataclass
class GatewayServerConfig:
enabled: bool = True
host: str = "127.0.0.1"
port: int = 19001
- path: str = "/acp"
- channel_id: str = "acp"
+ routes: dict[str, RouteConfig] = field(default_factory=dict) # path -> config
class GatewayServer:
- """ACP 专用的 GatewayServer。"""
+ """通用多路路由 WebSocket Gateway Server。
+
+ 支持多个路径(如 /acp、/cli),每条路径可以有独立的 channel_id 和本地 handler。
+ 本地 handler 优先处理请求,未处理或无匹配则 forward 到 MessageHandler。
+ """
def __init__(self, config: GatewayServerConfig, router) -> None:
self.config = config
@@ -181,17 +284,67 @@ class GatewayServer:
self._running = False
self._on_message_cb = None
self._clients: set[Any] = set()
- self._request_to_client: dict[str, Any] = {}
- self._session_to_client: dict[str, Any] = {}
- self._pending_client_rpc_session_by_id: dict[str, tuple[str, Any]] = {}
+ self._request_to_client: dict[tuple[str, str], Any] = {}
+ self._session_to_client: dict[tuple[str, str], Any] = {}
- @property
- def channel_id(self) -> str:
- return self.config.channel_id
+ @staticmethod
+ def _client_route_key(channel_id: str | None, scoped_id: str | None) -> tuple[str, str] | None:
+ channel = str(channel_id or "").strip()
+ scope = str(scoped_id or "").strip()
+ if not channel or not scope:
+ return None
+ return channel, scope
def on_message(self, callback) -> None:
self._on_message_cb = callback
+ def register_local_handler(self, path: str, method: str, handler: Callable[..., Awaitable[None]]) -> None:
+ """为指定路径注册本地方法 handler。"""
+ route = self.config.routes.get(path)
+ if route is None:
+ route = RouteConfig(path=path, channel_id=path.strip("/"))
+ self.config.routes[path] = route
+ route.local_handlers[method] = handler
+
+ async def send_response(
+ self,
+ ws: Any,
+ req_id: str,
+ *,
+ ok: bool,
+ payload: dict[str, Any] | None = None,
+ error: str | None = None,
+ code: str | None = None,
+ ) -> None:
+ """向指定客户端发送 res 帧(供本地 handler 使用)。"""
+ frame: dict[str, Any] = {
+ "type": "res",
+ "id": req_id,
+ "ok": ok,
+ "payload": payload or {},
+ }
+ if not ok:
+ frame["error"] = error or "request failed"
+ if code:
+ frame["code"] = code
+ try:
+ await ws.send(json.dumps(frame, ensure_ascii=False))
+ except Exception:
+ logger.debug("send_response failed (client disconnected?)", exc_info=True)
+
+ async def send_event(
+ self,
+ ws: Any,
+ event: str,
+ payload: dict[str, Any],
+ ) -> None:
+ """向指定客户端发送 event 帧(供本地 handler 使用)。"""
+ frame: dict[str, Any] = {"type": "event", "event": event, "payload": payload}
+ try:
+ await ws.send(json.dumps(frame, ensure_ascii=False))
+ except Exception:
+ logger.debug("send_event failed (client disconnected?)", exc_info=True)
+
async def start(self) -> None:
if self._running or not self.config.enabled:
return
@@ -208,11 +361,12 @@ class GatewayServer:
ping_timeout=20,
)
self._running = True
+ paths = ", ".join(self.config.routes.keys())
logger.info(
- "[App] ACP Gateway server started: ws://%s:%s%s",
+ "[App] Gateway server started: ws://%s:%s [%s]",
self.config.host,
self.config.port,
- self.config.path,
+ paths,
)
async def stop(self) -> None:
@@ -223,33 +377,43 @@ class GatewayServer:
self._clients.clear()
self._request_to_client.clear()
self._session_to_client.clear()
- self._pending_client_rpc_session_by_id.clear()
if self._server is not None:
self._server.close()
await self._server.wait_closed()
self._server = None
- logger.info("[App] ACP Gateway server stopped")
+ logger.info("[App] Gateway server stopped")
async def send(self, msg) -> None:
- ws = self._request_to_client.get(str(msg.id))
- if ws is None and msg.session_id:
- ws = self._session_to_client.get(str(msg.session_id))
+ ws = None
+ request_key = self._client_route_key(getattr(msg, "channel_id", None), getattr(msg, "id", None))
+ if request_key is not None:
+ ws = self._request_to_client.get(request_key)
+ if ws is None:
+ session_key = self._client_route_key(
+ getattr(msg, "channel_id", None),
+ getattr(msg, "session_id", None),
+ )
+ if session_key is not None:
+ ws = self._session_to_client.get(session_key)
if ws is None or bool(getattr(ws, "closed", False)):
return
- if (
- msg.type == "event"
- and isinstance(msg.payload, dict)
- and str(msg.payload.get("event_type") or "").strip() == "acp.output_request"
- ):
- raw_jsonrpc = msg.payload.get("jsonrpc")
- if isinstance(raw_jsonrpc, dict):
- jsonrpc_id = str(raw_jsonrpc.get("id") or "").strip()
- session_id = str(msg.session_id or "").strip()
- if jsonrpc_id and session_id:
- self._pending_client_rpc_session_by_id[jsonrpc_id] = (session_id, ws)
- await ws.send(json.dumps(raw_jsonrpc, ensure_ascii=False))
- return
+ # 让 route 的 outbound_interceptor 有机会拦截
+ for route in self.config.routes.values():
+ if route.channel_id == msg.channel_id and route.outbound_interceptor is not None:
+ try:
+ handled = route.outbound_interceptor(msg, ws)
+ if asyncio.iscoroutine(handled):
+ handled = await handled
+ if handled:
+ return
+ except Exception:
+ logger.warning(
+ "GatewayServer outbound interceptor failed: channel_id=%s",
+ msg.channel_id,
+ exc_info=True,
+ )
+ break
if msg.type == "res":
payload = dict(msg.payload or {}) if isinstance(msg.payload, dict) else {}
@@ -281,14 +445,31 @@ class GatewayServer:
raw_path = path if path is not None else getattr(ws, "path", "")
parsed = urlparse(raw_path)
request_path = parsed.path or raw_path
- if request_path != self.config.path:
+
+ route = self.config.routes.get(request_path)
+ if route is None:
await ws.close(code=1008, reason=f"unsupported path: {request_path}")
return
self._clients.add(ws)
+
+ # connection.ack
+ try:
+ await ws.send(json.dumps({
+ "type": "event",
+ "event": "connection.ack",
+ "payload": {
+ "protocol_version": "1.0",
+ "transport": route.channel_id,
+ },
+ }, ensure_ascii=False))
+ except Exception:
+ self._clients.discard(ws)
+ return
+
try:
async for raw in ws:
- await self._handle_raw_message(ws, raw)
+ await self._handle_raw_message(ws, raw, request_path, route)
finally:
self._clients.discard(ws)
stale_request_ids = [request_id for request_id, client in self._request_to_client.items() if client is ws]
@@ -297,69 +478,17 @@ class GatewayServer:
stale_session_ids = [session_id for session_id, client in self._session_to_client.items() if client is ws]
for session_id in stale_session_ids:
self._session_to_client.pop(session_id, None)
- stale_jsonrpc_ids = [
- jsonrpc_id
- for jsonrpc_id, (_, client) in self._pending_client_rpc_session_by_id.items()
- if client is ws
- ]
- for jsonrpc_id in stale_jsonrpc_ids:
- self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)
-
- @staticmethod
- def _is_jsonrpc_response(data: dict[str, Any]) -> bool:
- return (
- isinstance(data, dict)
- and str(data.get("jsonrpc") or "").strip() == "2.0"
- and str(data.get("id") or "").strip() != ""
- and ("result" in data or "error" in data)
- )
-
- async def _handle_jsonrpc_response(self, ws: Any, data: dict[str, Any]) -> None:
- from jiuwenclaw.schema.message import Message, ReqMethod
-
- jsonrpc_id = str(data.get("id") or "").strip()
- pending = self._pending_client_rpc_session_by_id.pop(jsonrpc_id, None)
- session_id = ""
- if isinstance(pending, tuple) and len(pending) == 2:
- session_id = str(pending[0] or "").strip()
-
- if not jsonrpc_id or not session_id:
- await ws.send(
- json.dumps(
- {
- "type": "res",
- "id": jsonrpc_id,
- "ok": False,
- "error": f"unknown acp tool response id: {jsonrpc_id}",
- },
- ensure_ascii=False,
- )
- )
- return
-
- msg = Message(
- id=f"acp_tool_resp_{uuid_module.uuid4().hex[:12]}",
- type="req",
- channel_id=self.channel_id,
- session_id=session_id,
- params={
- "jsonrpc_id": jsonrpc_id,
- "response": dict(data),
- "session_id": session_id,
- },
- timestamp=time.time(),
- ok=True,
- req_method=ReqMethod.ACP_TOOL_RESPONSE,
- is_stream=False,
- metadata={"acp": {"jsonrpc_id": jsonrpc_id, "kind": "tool_response"}},
- )
- if self._on_message_cb is None:
- return
- result = self._on_message_cb(msg)
- if asyncio.iscoroutine(result):
- await result
+ if route.cleanup_handler is not None:
+ try:
+ route.cleanup_handler(ws)
+ except Exception:
+ logger.warning(
+ "GatewayServer cleanup handler failed: path=%s",
+ request_path,
+ exc_info=True,
+ )
- async def _handle_raw_message(self, ws: Any, raw: str) -> None:
+ async def _handle_raw_message(self, ws: Any, raw: str, request_path: str, route: RouteConfig) -> None:
from jiuwenclaw.schema.message import Message, Mode, ReqMethod
try:
@@ -373,9 +502,20 @@ class GatewayServer:
)
return
- if self._is_jsonrpc_response(data):
- await self._handle_jsonrpc_response(ws, data)
- return
+ # route 级别的原始帧拦截(如 ACP JSON-RPC response)
+ if route.inbound_interceptor is not None:
+ try:
+ handled = route.inbound_interceptor(ws, data)
+ if asyncio.iscoroutine(handled):
+ handled = await handled
+ if handled:
+ return
+ except Exception:
+ logger.warning(
+ "GatewayServer inbound interceptor failed: path=%s",
+ request_path,
+ exc_info=True,
+ )
if not isinstance(data, dict) or data.get("type") != "req":
await ws.send(
@@ -399,49 +539,129 @@ class GatewayServer:
return
session_id = str(params.get("session_id") or "").strip() or req_id
- req_method = None
- for item in ReqMethod:
- if item.value == method:
- req_method = item
- break
- if req_method is None:
- await ws.send(
- json.dumps(
- {"type": "res", "id": req_id, "ok": False, "error": f"unknown method: {method}"},
- ensure_ascii=False,
+
+ # 1. forward 优先:方法在 forward_methods 中则转发到 MessageHandler
+ if method in route.forward_methods:
+ req_method = None
+ for item in ReqMethod:
+ if item.value == method:
+ req_method = item
+ break
+
+ if req_method is None:
+ await ws.send(
+ json.dumps(
+ {"type": "res", "id": req_id, "ok": False, "error": f"unknown method: {method}"},
+ ensure_ascii=False,
+ )
)
+ return
+
+ request_key = self._client_route_key(route.channel_id, req_id)
+ if request_key is not None:
+ self._request_to_client[request_key] = ws
+ session_key = self._client_route_key(route.channel_id, session_id)
+ if session_key is not None:
+ self._session_to_client[session_key] = ws
+
+ mode = Mode.PLAN
+ raw_mode = params.get("mode")
+ if isinstance(raw_mode, str):
+ try:
+ mode = Mode(raw_mode.strip().lower())
+ except ValueError:
+ mode = Mode.PLAN
+
+ msg = Message(
+ id=req_id,
+ type="req",
+ channel_id=route.channel_id,
+ session_id=session_id,
+ params=params,
+ timestamp=time.time(),
+ ok=True,
+ req_method=req_method,
+ mode=mode,
+ metadata={"method": method},
)
- return
- self._request_to_client[req_id] = ws
- self._session_to_client[session_id] = ws
+ if self._on_message_cb is not None:
+ result = self._on_message_cb(msg)
+ if asyncio.iscoroutine(result):
+ await result
- mode = Mode.PLAN
- raw_mode = params.get("mode")
- if isinstance(raw_mode, str):
+ # 如果在 forward_no_local_handler_methods 中,不需要本地 ack
+ if method in route.forward_no_local_handler_methods:
+ return
+
+ # 2. 本地 handler:发 ack 或纯本地处理
+ local_handler = route.local_handlers.get(method)
+ if local_handler is not None:
try:
- mode = Mode(raw_mode.strip().lower())
- except ValueError:
- mode = Mode.PLAN
+ await local_handler(ws, req_id, params, session_id)
+ except Exception as e:
+ ws_closed = bool(getattr(ws, "closed", False))
+ if ws_closed:
+ logger.warning("GatewayServer local handler aborted on closed ws (%s): %s", method, e)
+ return
+ logger.error("GatewayServer local handler error (%s): %s", method, e)
+ try:
+ await self.send_response(
+ ws, req_id, ok=False,
+ error=f"handler error: {e}", code="INTERNAL_ERROR",
+ )
+ except Exception:
+ logger.debug(
+ "GatewayServer failed to send handler error response: method=%s id=%s",
+ method,
+ req_id,
+ exc_info=True,
+ )
+ return
- msg = Message(
- id=req_id,
- type="req",
- channel_id=self.channel_id,
- session_id=session_id,
- params=params,
- timestamp=time.time(),
- ok=True,
- req_method=req_method,
- mode=mode,
- metadata={"method": method},
+ # 3. 无 forward 也无本地 handler
+ await ws.send(
+ json.dumps(
+ {"type": "res", "id": req_id, "ok": False, "error": f"unknown method: {method}"},
+ ensure_ascii=False,
+ )
)
- if self._on_message_cb is None:
- return
- result = self._on_message_cb(msg)
- if asyncio.iscoroutine(result):
- await result
+
+
+def _build_acp_route_binding(
+ *,
+ path: str,
+ channel_id: str,
+ forward_methods: frozenset[str],
+ forward_no_local_handler_methods: frozenset[str],
+ on_message_cb,
+) -> GatewayRouteBinding:
+ acp_handler = AcpRouteHandler(on_message_cb)
+ return GatewayRouteBinding(
+ path=path,
+ channel_id=channel_id,
+ forward_methods=forward_methods,
+ forward_no_local_handler_methods=forward_no_local_handler_methods,
+ inbound_interceptor=acp_handler.inbound_intercept,
+ outbound_interceptor=acp_handler.outbound_intercept,
+ cleanup_handler=acp_handler.cleanup,
+ )
+
+
+def _build_route_config_map(bindings: list[GatewayRouteBinding]) -> dict[str, RouteConfig]:
+ return {
+ binding.path: RouteConfig(
+ path=binding.path,
+ channel_id=binding.channel_id,
+ forward_methods=binding.forward_methods,
+ forward_no_local_handler_methods=binding.forward_no_local_handler_methods,
+ inbound_interceptor=binding.inbound_interceptor,
+ outbound_interceptor=binding.outbound_interceptor,
+ cleanup_handler=binding.cleanup_handler,
+ )
+ for binding in bindings
+ }
async def _run(
@@ -473,6 +693,10 @@ async def _run(
_FORWARD_REQ_METHODS,
_register_web_handlers,
)
+ from jiuwenclaw.channel.cli_channel import (
+ CliRouteBindParams,
+ build_cli_route_binding,
+ )
from jiuwenclaw.extensions.manager import ExtensionManager
from jiuwenclaw.extensions.registry import ExtensionRegistry
from jiuwenclaw.schema.message import Message, ReqMethod
@@ -665,54 +889,89 @@ async def _run(
)
)
- def _norm_and_forward(msg: Message) -> bool:
- method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
- if method_val not in _FORWARD_REQ_METHODS:
+ def _make_norm_and_forward(
+ forward_methods: set[str] | frozenset[str],
+ no_local_methods: set[str] | frozenset[str],
+ source_label: str,
+ ):
+ def _norm_and_forward(msg: Message) -> bool:
+ method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""
+ if method_val not in forward_methods:
+ return False
+ is_stream = bool(
+ msg.is_stream
+ or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
+ )
+ params = dict(msg.params or {})
+ if "query" not in params and "content" in params:
+ params["query"] = params["content"]
+ normalized = Message(
+ id=msg.id,
+ type=msg.type,
+ channel_id=msg.channel_id,
+ session_id=msg.session_id,
+ params=params,
+ timestamp=msg.timestamp,
+ ok=msg.ok,
+ req_method=getattr(msg, "req_method", None) or ReqMethod.CHAT_SEND,
+ mode=msg.mode,
+ is_stream=is_stream,
+ stream_seq=msg.stream_seq,
+ stream_id=msg.stream_id,
+ metadata=msg.metadata,
+ )
+ channel_manager.deliver_to_message_handler(normalized)
+ logger.info("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id)
+ if method_val in no_local_methods:
+ return True
return False
- is_stream = bool(
- msg.is_stream
- or method_val in (ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value)
- )
- params = dict(msg.params or {})
- if "query" not in params and "content" in params:
- params["query"] = params["content"]
- normalized = Message(
- id=msg.id,
- type=msg.type,
- channel_id=msg.channel_id,
- session_id=msg.session_id,
- params=params,
- timestamp=msg.timestamp,
- ok=msg.ok,
- req_method=getattr(msg, "req_method", None) or ReqMethod.CHAT_SEND,
- mode=msg.mode,
- is_stream=is_stream,
- stream_seq=msg.stream_seq,
- stream_id=msg.stream_id,
- metadata=msg.metadata,
- )
- channel_manager.deliver_to_message_handler(normalized)
- logger.info("[App] Web inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)
- if method_val in _FORWARD_NO_LOCAL_HANDLER_METHODS:
- return True
- return False
- if web_channel is not None:
- channel_manager.register_channel_with_inbound(web_channel, _norm_and_forward)
+ return _norm_and_forward
- gateway_server_config = GatewayServerConfig(
- enabled=True,
- host=os.getenv("ACP_GATEWAY_HOST", "127.0.0.1"),
- port=int(os.getenv("ACP_GATEWAY_PORT", "19001")),
- path=os.getenv("ACP_GATEWAY_PATH", "/acp"),
- channel_id=str(os.getenv("ACP_GATEWAY_CHANNEL_ID", "acp")).strip() or "acp",
+ web_norm_and_forward = _make_norm_and_forward(
+ _FORWARD_REQ_METHODS,
+ _FORWARD_NO_LOCAL_HANDLER_METHODS,
+ "Web",
)
+ channel_manager.register_channel_with_inbound(web_channel, web_norm_and_forward)
+
acp_inbound_server = _InboundGatewayServer(
lambda msg: _normalize_and_forward_message(msg, channel_manager)
)
await acp_inbound_server.start()
+
+ route_bindings = [
+ _build_acp_route_binding(
+ path="/acp",
+ channel_id="acp",
+ forward_methods=_FORWARD_REQ_METHODS,
+ forward_no_local_handler_methods=_FORWARD_NO_LOCAL_HANDLER_METHODS,
+ on_message_cb=acp_inbound_server.handle_message,
+ ),
+ build_cli_route_binding(
+ CliRouteBindParams(
+ agent_client=client,
+ message_handler=message_handler,
+ on_config_saved=_on_config_saved,
+ path="/cli",
+ channel_id="cli",
+ )
+ ),
+ ]
+
+ gateway_server_config = GatewayServerConfig(
+ enabled=True,
+ host=os.getenv("GATEWAY_HOST", "127.0.0.1"),
+ port=int(os.getenv("GATEWAY_PORT", "19001")),
+ routes=_build_route_config_map(route_bindings),
+ )
gateway_server = GatewayServer(gateway_server_config, _DummyBus())
- channel_manager.register_channel_with_inbound(gateway_server, acp_inbound_server.handle_message)
+ for binding in route_bindings:
+ route_config = gateway_server_config.routes[binding.path]
+ channel_manager.register_external_channel(route_config.channel_id, gateway_server)
+ if binding.install is not None:
+ binding.install(gateway_server)
+ gateway_server.on_message(acp_inbound_server.handle_message)
feishu_channel = None
feishu_task = None
@@ -1374,4 +1633,3 @@ def main() -> None:
if __name__ == "__main__":
main()
-
diff --git a/jiuwenclaw/channel/__init__.py b/jiuwenclaw/channel/__init__.py
index fe62473516..e979728386 100644
--- a/jiuwenclaw/channel/__init__.py
+++ b/jiuwenclaw/channel/__init__.py
@@ -11,6 +11,7 @@ from jiuwenclaw.channel.dingding import DingTalkChannel, DingTalkConfig
from jiuwenclaw.channel.whatsapp_channel import WhatsAppChannel, WhatsAppChannelConfig
from jiuwenclaw.channel.wecom_channel import WecomChannel, WecomConfig
from jiuwenclaw.channel.wechat_channel import WechatChannel, WechatConfig
+from jiuwenclaw.channel.acp_channel import AcpChannel, AcpChannelConfig
__all__ = [
"BaseChannel",
@@ -30,4 +31,6 @@ __all__ = [
"WecomConfig",
"WechatChannel",
"WechatConfig",
+ "AcpChannel",
+ "AcpChannelConfig",
]
diff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.py
index e0bb16ffd2..186e2a37fb 100644
--- a/jiuwenclaw/channel/acp_channel.py
+++ b/jiuwenclaw/channel/acp_channel.py
@@ -1159,15 +1159,13 @@ def main() -> None:
)
args = parser.parse_args()
- web_host = os.getenv("ACP_GATEWAY_HOST", "127.0.0.1")
- web_port = os.getenv("ACP_GATEWAY_PORT", "19001")
- web_path = os.getenv("ACP_GATEWAY_PATH", "/acp")
+ gateway_host = os.getenv("GATEWAY_HOST", "127.0.0.1")
+ gateway_port = os.getenv("GATEWAY_PORT", "19001")
gateway_url = (
getattr(args, "gateway_url", None)
or getattr(args, "agent_server_url", None)
- or os.getenv("ACP_GATEWAY_URL")
or os.getenv("GATEWAY_URL")
- or f"ws://{web_host}:{web_port}{web_path}"
+ or f"ws://{gateway_host}:{gateway_port}/acp"
)
asyncio.run(_run(gateway_url))
diff --git a/jiuwenclaw/channel/base.py b/jiuwenclaw/channel/base.py
index db731f3770..2e0b92bfa0 100644
--- a/jiuwenclaw/channel/base.py
+++ b/jiuwenclaw/channel/base.py
@@ -28,6 +28,7 @@ class ChannelType(str, Enum):
WHATSAPP = "whatsapp"
WECOM = "wecom"
WECHAT = "wechat"
+ CLI = "cli"
@dataclass
diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.py
new file mode 100644
index 0000000000..54299bdcc4
--- /dev/null
+++ b/jiuwenclaw/channel/cli_channel.py
@@ -0,0 +1,480 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+import inspect
+import logging
+import os
+import shutil
+from dataclasses import dataclass
+from typing import Any
+
+from openjiuwen.core.foundation.llm import ProviderType
+
+from jiuwenclaw.config import (
+ get_config,
+ get_config_raw,
+ update_context_engine_enabled_in_config,
+ update_permissions_enabled_in_config,
+)
+from jiuwenclaw.gateway.route_binding import GatewayRouteBinding
+from jiuwenclaw.version import __version__
+
+logger = logging.getLogger(__name__)
+
+# ── 需要转发到 Agent 的方法集合 ──────────────────────────────
+
+CLI_FORWARD_REQ_METHODS = frozenset(
+ {
+ "command.add_dir",
+ "command.chrome",
+ "command.compact",
+ "command.diff",
+ "command.model",
+ "command.resume",
+ "command.session",
+ "chat.send",
+ "chat.interrupt",
+ "chat.resume",
+ "chat.user_answer",
+ "history.get",
+ "browser.start",
+ "skills.marketplace.list",
+ "skills.list",
+ "skills.installed",
+ "skills.get",
+ "skills.install",
+ "skills.import_local",
+ "skills.marketplace.add",
+ "skills.marketplace.remove",
+ "skills.marketplace.toggle",
+ "skills.uninstall",
+ "skills.skillnet.search",
+ "skills.skillnet.install",
+ "skills.skillnet.install_status",
+ "skills.skillnet.evaluate",
+ "skills.clawhub.get_token",
+ "skills.clawhub.set_token",
+ "skills.clawhub.search",
+ "skills.clawhub.download",
+ "skills.evolution.status",
+ "skills.evolution.get",
+ "skills.evolution.save",
+ "extensions.list",
+ "extensions.import",
+ "extensions.delete",
+ "extensions.toggle",
+ }
+)
+
+CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset(
+ {
+ "command.add_dir",
+ "command.chrome",
+ "command.compact",
+ "command.diff",
+ "command.model",
+ "command.resume",
+ "command.session",
+ "browser.start",
+ "skills.marketplace.list",
+ "skills.list",
+ "skills.installed",
+ "skills.get",
+ "skills.install",
+ "skills.import_local",
+ "skills.marketplace.add",
+ "skills.marketplace.remove",
+ "skills.marketplace.toggle",
+ "skills.uninstall",
+ "skills.skillnet.search",
+ "skills.skillnet.install",
+ "skills.skillnet.install_status",
+ "skills.skillnet.evaluate",
+ "skills.clawhub.get_token",
+ "skills.clawhub.set_token",
+ "skills.clawhub.search",
+ "skills.clawhub.download",
+ "skills.evolution.status",
+ "skills.evolution.get",
+ "skills.evolution.save",
+ "extensions.list",
+ "extensions.import",
+ "extensions.delete",
+ "extensions.toggle",
+ }
+)
+
+
+@dataclass
+class CliHandlersBindParams:
+ channel: Any # GatewayServer instance
+ agent_client: Any = None
+ message_handler: Any = None
+ on_config_saved: Any = None
+ path: str = "/cli"
+
+
+@dataclass
+class CliRouteBindParams:
+ agent_client: Any = None
+ message_handler: Any = None
+ on_config_saved: Any = None
+ path: str = "/cli"
+ channel_id: str = "cli"
+
+
+_CLI_CONFIG_SET_ENV_MAP = {
+ "model_provider": "MODEL_PROVIDER",
+ "model": "MODEL_NAME",
+ "api_base": "API_BASE",
+ "api_key": "API_KEY",
+ "video_api_base": "VIDEO_API_BASE",
+ "video_api_key": "VIDEO_API_KEY",
+ "video_model": "VIDEO_MODEL_NAME",
+ "video_provider": "VIDEO_PROVIDER",
+ "audio_api_base": "AUDIO_API_BASE",
+ "audio_api_key": "AUDIO_API_KEY",
+ "audio_model": "AUDIO_MODEL_NAME",
+ "audio_provider": "AUDIO_PROVIDER",
+ "vision_api_base": "VISION_API_BASE",
+ "vision_api_key": "VISION_API_KEY",
+ "vision_model": "VISION_MODEL_NAME",
+ "vision_provider": "VISION_PROVIDER",
+ "email_address": "EMAIL_ADDRESS",
+ "email_token": "EMAIL_TOKEN",
+ "embed_api_key": "EMBED_API_KEY",
+ "embed_api_base": "EMBED_API_BASE",
+ "embed_model": "EMBED_MODEL",
+ "jina_api_key": "JINA_API_KEY",
+ "serper_api_key": "SERPER_API_KEY",
+ "perplexity_api_key": "PERPLEXITY_API_KEY",
+ "github_token": "GITHUB_TOKEN",
+ "evolution_auto_scan": "EVOLUTION_AUTO_SCAN",
+}
+
+_CLI_CONFIG_YAML_KEYS = frozenset({"context_engine_enabled", "permissions_enabled"})
+
+
+
+async def _clear_agent_config_cache(agent_client=None) -> None:
+ try:
+ if agent_client is not None:
+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
+ from jiuwenclaw.schema.message import ReqMethod
+ import uuid
+
+ env = e2a_from_agent_fields(
+ request_id=f"cfg-cache-clear-{uuid.uuid4().hex[:8]}",
+ channel_id="",
+ req_method=ReqMethod.CONFIG_CACHE_CLEAR,
+ )
+ await agent_client.send_request(env)
+ else:
+ get_config()
+ except Exception as e: # noqa: BLE001
+ logger.debug("[cli config.set] clear agent config cache skipped: %s", e)
+
+
+def _persist_env_updates(updates: dict[str, str]) -> None:
+ from jiuwenclaw.utils import get_env_file
+
+ env_path = get_env_file()
+ if not updates:
+ return
+ try:
+ lines: list[str] = []
+ if env_path.is_file():
+ with open(env_path, "r", encoding="utf-8") as f:
+ lines = f.readlines()
+ new_lines: list[str] = []
+ for line in lines:
+ stripped = line.strip()
+ found = False
+ for env_key, value in updates.items():
+ if stripped.startswith(env_key + "="):
+ new_lines.append(
+ f'{env_key}="{value}"\n' if value else f"{env_key}=\n"
+ )
+ found = True
+ break
+ if not found:
+ new_lines.append(line)
+ for env_key, value in updates.items():
+ if not any(s.strip().startswith(env_key + "=") for s in new_lines):
+ new_lines.append(f'{env_key}="{value}"\n' if value else f"{env_key}=\n")
+ env_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(env_path, "w", encoding="utf-8") as f:
+ f.writelines(new_lines)
+ except OSError as e:
+ logger.warning("[cli config.set] 写回 .env 失败: %s", e)
+
+
+def register_cli_handlers(bind: CliHandlersBindParams) -> None:
+ channel = bind.channel
+ agent_client = bind.agent_client
+ on_config_saved = bind.on_config_saved
+ path = bind.path
+
+ async def _config_get(ws, req_id, params, session_id):
+ payload = {
+ param_key: (os.getenv(env_key) or "")
+ for param_key, env_key in _CLI_CONFIG_SET_ENV_MAP.items()
+ }
+ payload["app_version"] = __version__
+ try:
+ raw = get_config_raw()
+ for key, val in payload.items():
+ from jiuwenclaw.extensions import ExtensionRegistry
+
+ crypto_provider = ExtensionRegistry.get_instance().get_crypto_provider()
+ if (
+ "api_key" in key.lower() or "token" in key.lower()
+ ) and crypto_provider:
+ payload[key] = crypto_provider.decrypt(val)
+ ctx_cfg = (raw.get("react") or {}).get("context_engine_config") or {}
+ payload["context_engine_enabled"] = (
+ "true" if ctx_cfg.get("enabled", False) else "false"
+ )
+ perm_cfg = raw.get("permissions") or {}
+ payload["permissions_enabled"] = (
+ "true" if perm_cfg.get("enabled", False) else "false"
+ )
+ except Exception:
+ payload.setdefault("context_engine_enabled", "false")
+ payload.setdefault("permissions_enabled", "false")
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _config_set(ws, req_id, params, session_id):
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"
+ )
+ return
+ for key, val in params.items():
+ from jiuwenclaw.extensions import ExtensionRegistry
+
+ crypto_provider = ExtensionRegistry.get_instance().get_crypto_provider()
+ if ("api_key" in key.lower() or "token" in key.lower()) and crypto_provider:
+ params[key] = crypto_provider.encrypt(val)
+
+ env_updates: dict[str, str] = {}
+ yaml_updated: list[str] = []
+ available_model_providers = [provider.value for provider in ProviderType]
+
+ for param_key, env_key in _CLI_CONFIG_SET_ENV_MAP.items():
+ if param_key not in params:
+ continue
+ val = params[param_key]
+ if (
+ param_key.endswith("_provider")
+ and val
+ and val not in available_model_providers
+ ):
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error=f"Model provider must in: {available_model_providers} ",
+ code="BAD_REQUEST",
+ )
+ return
+ env_updates[env_key] = "" if val is None else str(val).strip()
+
+ for param_key in _CLI_CONFIG_YAML_KEYS:
+ if param_key not in params:
+ continue
+ parsed = str(params[param_key]).strip().lower() in ("true", "1", "yes")
+ try:
+ if param_key == "context_engine_enabled":
+ update_context_engine_enabled_in_config(parsed)
+ elif param_key == "permissions_enabled":
+ update_permissions_enabled_in_config(parsed)
+ yaml_updated.append(param_key)
+ except Exception as e:
+ logger.warning(
+ "[cli config.set] 写回 config.yaml 失败 %s: %s", param_key, e
+ )
+
+ for env_key, value in env_updates.items():
+ os.environ[env_key] = value
+ applied_without_restart = True
+
+ if env_updates:
+ _persist_env_updates(env_updates)
+ if yaml_updated:
+ real_client = agent_client.get("value") if isinstance(agent_client, dict) else agent_client
+ await _clear_agent_config_cache(real_client)
+
+ if env_updates or yaml_updated:
+ if on_config_saved:
+ config_payload = get_config()
+ callback_result = on_config_saved(
+ set(env_updates.keys()) | set(yaml_updated),
+ env_updates=dict(env_updates),
+ config_payload=config_payload,
+ )
+ if inspect.isawaitable(callback_result):
+ callback_result = await callback_result
+ applied_without_restart = bool(callback_result)
+
+ updated_param_keys = [
+ k for k, e in _CLI_CONFIG_SET_ENV_MAP.items() if e in env_updates
+ ] + yaml_updated
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=True,
+ payload={
+ "updated": updated_param_keys,
+ "applied_without_restart": applied_without_restart,
+ },
+ )
+
+ async def _session_list(ws, req_id, params, session_id):
+ from jiuwenclaw.utils import get_agent_sessions_dir
+
+ limit = 20
+ if isinstance(params, dict):
+ raw_limit = params.get("limit")
+ if isinstance(raw_limit, int):
+ limit = raw_limit
+ elif isinstance(raw_limit, str) and raw_limit.strip().isdigit():
+ limit = int(raw_limit.strip())
+ limit = max(1, min(limit, 200))
+
+ workspace_session_dir = get_agent_sessions_dir()
+ if not workspace_session_dir.exists() or not workspace_session_dir.is_dir():
+ sessions = []
+ else:
+ sessions = sorted(
+ [d.name for d in workspace_session_dir.iterdir() if d.is_dir()],
+ reverse=True,
+ )[:limit]
+ await channel.send_response(ws, req_id, ok=True, payload={"sessions": sessions})
+
+ async def _session_create(ws, req_id, params, session_id):
+ from jiuwenclaw.utils import get_agent_sessions_dir
+
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"
+ )
+ return
+ target = str(params.get("session_id") or "").strip()
+ if not target:
+ await channel.send_response(
+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"
+ )
+ return
+ workspace_session_dir = get_agent_sessions_dir()
+ workspace_session_dir.mkdir(parents=True, exist_ok=True)
+ session_dir = workspace_session_dir / target
+ if session_dir.exists():
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="session already exists",
+ code="ALREADY_EXISTS",
+ )
+ return
+ session_dir.mkdir()
+ await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})
+
+ async def _session_delete(ws, req_id, params, session_id):
+ from jiuwenclaw.utils import get_agent_sessions_dir
+
+ if not isinstance(params, dict):
+ await channel.send_response(
+ ws, req_id, ok=False, error="params must be object", code="BAD_REQUEST"
+ )
+ return
+ target = str(params.get("session_id") or "").strip()
+ if not target:
+ await channel.send_response(
+ ws, req_id, ok=False, error="session_id is required", code="BAD_REQUEST"
+ )
+ return
+ session_dir = get_agent_sessions_dir() / target
+ if not session_dir.exists():
+ await channel.send_response(
+ ws, req_id, ok=False, error="session not found", code="NOT_FOUND"
+ )
+ return
+ if not session_dir.is_dir():
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error="session is not a directory",
+ code="BAD_REQUEST",
+ )
+ return
+ shutil.rmtree(session_dir)
+ await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})
+
+ async def _chat_send(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"accepted": True, "session_id": session_id}
+ )
+
+ async def _chat_resume(ws, req_id, params, session_id):
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"accepted": True, "session_id": session_id}
+ )
+
+ async def _chat_interrupt(ws, req_id, params, session_id):
+ intent = params.get("intent") if isinstance(params, dict) else None
+ payload = {"accepted": True, "session_id": session_id}
+ if isinstance(intent, str) and intent:
+ payload["intent"] = intent
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _chat_user_answer(ws, req_id, params, session_id):
+ payload = {"accepted": True, "session_id": session_id}
+ request_id = params.get("request_id") if isinstance(params, dict) else None
+ if isinstance(request_id, str) and request_id:
+ payload["request_id"] = request_id
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ async def _history_get(ws, req_id, params, session_id):
+ payload = {"accepted": True, "session_id": session_id}
+ if isinstance(params, dict):
+ if "session_id" in params:
+ payload["session_id"] = params.get("session_id")
+ if "page_idx" in params:
+ payload["page_idx"] = params.get("page_idx")
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+
+ channel.register_local_handler(path, "config.get", _config_get)
+ channel.register_local_handler(path, "config.set", _config_set)
+ channel.register_local_handler(path, "session.list", _session_list)
+ channel.register_local_handler(path, "session.create", _session_create)
+ channel.register_local_handler(path, "session.delete", _session_delete)
+ channel.register_local_handler(path, "chat.send", _chat_send)
+ channel.register_local_handler(path, "chat.resume", _chat_resume)
+ channel.register_local_handler(path, "chat.interrupt", _chat_interrupt)
+ channel.register_local_handler(path, "chat.user_answer", _chat_user_answer)
+ channel.register_local_handler(path, "history.get", _history_get)
+
+
+def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:
+ def _install(channel: Any) -> None:
+ register_cli_handlers(
+ CliHandlersBindParams(
+ channel=channel,
+ agent_client=bind.agent_client,
+ message_handler=bind.message_handler,
+ on_config_saved=bind.on_config_saved,
+ path=bind.path,
+ )
+ )
+
+ return GatewayRouteBinding(
+ path=bind.path,
+ channel_id=bind.channel_id,
+ forward_methods=CLI_FORWARD_REQ_METHODS,
+ forward_no_local_handler_methods=CLI_FORWARD_NO_LOCAL_HANDLER_METHODS,
+ install=_install,
+ )
diff --git a/jiuwenclaw/cli/.oxfmtrc.json b/jiuwenclaw/cli/.oxfmtrc.json
new file mode 100644
index 0000000000..55c15df37b
--- /dev/null
+++ b/jiuwenclaw/cli/.oxfmtrc.json
@@ -0,0 +1,4 @@
+{
+ "$schema": "./node_modules/oxfmt/configuration_schema.json",
+ "ignorePatterns": []
+}
diff --git a/jiuwenclaw/cli/.oxlintrc.json b/jiuwenclaw/cli/.oxlintrc.json
new file mode 100644
index 0000000000..75868c2de8
--- /dev/null
+++ b/jiuwenclaw/cli/.oxlintrc.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "./node_modules/oxlint/configuration_schema.json",
+ "plugins": [
+ "typescript",
+ "unicorn",
+ "oxc"
+ ],
+ "categories": {
+ "correctness": "error"
+ },
+ "rules": {},
+ "env": {
+ "builtin": true
+ }
+}
\ No newline at end of file
diff --git a/jiuwenclaw/cli/package-lock.json b/jiuwenclaw/cli/package-lock.json
new file mode 100644
index 0000000000..0f85860c3d
--- /dev/null
+++ b/jiuwenclaw/cli/package-lock.json
@@ -0,0 +1,927 @@
+{
+ "name": "jiuwenclaw-tui",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "jiuwenclaw-tui",
+ "version": "0.1.0",
+ "dependencies": {
+ "@mariozechner/pi-tui": "^0.65.2",
+ "chalk": "^5.5.0",
+ "ws": "^8.18.0"
+ },
+ "bin": {
+ "jiuwenclaw-tui-pi": "dist/index.js"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "@types/ws": "^8.18.0",
+ "oxfmt": "^0.44.0",
+ "oxlint": "^1.59.0",
+ "typescript": "^5.8.0"
+ }
+ },
+ "node_modules/@mariozechner/pi-tui": {
+ "version": "0.65.2",
+ "resolved": "https://registry.npmmirror.com/@mariozechner/pi-tui/-/pi-tui-0.65.2.tgz",
+ "integrity": "sha512-LBPbIBASjCF4QLrc/dwmPdBzVMsbkDhzmBIAFgglX5rZBnGRppB7ekSA+1kb5pdxDpDn8IbxJX+bl7ZaeqZqxw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/mime-types": "^2.1.4",
+ "chalk": "^5.5.0",
+ "get-east-asian-width": "^1.3.0",
+ "marked": "^15.0.12",
+ "mime-types": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "optionalDependencies": {
+ "koffi": "^2.9.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-android-arm-eabi": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.44.0.tgz",
+ "integrity": "sha512-5UvghMd9SA/yvKTWCAxMAPXS1d2i054UeOf4iFjZjfayTwCINcC3oaSXjtbZfCaEpxgJod7XiOjTtby5yEv/BQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-android-arm64": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.44.0.tgz",
+ "integrity": "sha512-IVudM1BWfvrYO++Khtzr8q9n5Rxu7msUvoFMqzGJVdX7HfUXUDHwaH2zHZNB58svx2J56pmCUzophyaPFkcG/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-darwin-arm64": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.44.0.tgz",
+ "integrity": "sha512-eWCLAIKAHfx88EqEP1Ga2yz7qVcqDU5lemn4xck+07bH182hDdprOHjbogyk0In1Djys3T0/pO2JepFnRJ41Mg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-darwin-x64": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.44.0.tgz",
+ "integrity": "sha512-eHTBznHLM49++dwz07MblQ2cOXyIgeedmE3Wgy4ptUESj38/qYZyRi1MPwC9olQJWssMeY6WI3UZ7YmU5ggvyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-freebsd-x64": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.44.0.tgz",
+ "integrity": "sha512-jLMmbj0u0Ft43QpkUVr/0v1ZfQCGWAvU+WznEHcN3wZC/q6ox7XeSJtk9P36CCpiDSUf3sGnzbIuG1KdEMEDJQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm-gnueabihf": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.44.0.tgz",
+ "integrity": "sha512-n+A/u/ByK1qV8FVGOwyaSpw5NPNl0qlZfgTBqHeGIqr8Qzq1tyWZ4lAaxPoe5mZqE3w88vn3+jZtMxriHPE7tg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm-musleabihf": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.44.0.tgz",
+ "integrity": "sha512-5eax+FkxyCqAi3Rw0mrZFr7+KTt/XweFsbALR+B5ljWBLBl8nHe4ADrUnb1gLEfQCJLl+Ca5FIVD4xEt95AwIw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm64-gnu": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.44.0.tgz",
+ "integrity": "sha512-58l8JaHxSGOmOMOG2CIrNsnkRJAj0YcHQCmvNACniOa/vd1iRHhlPajczegzS5jwMENlqgreyiTR9iNlke8qCw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-arm64-musl": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.44.0.tgz",
+ "integrity": "sha512-AlObQIXyVRZ96LbtVljtFq0JqH5B92NU+BQeDFrXWBUWlCKAM0wF5GLfIhCLT5kQ3Sl+U0YjRJ7Alqj5hGQaCg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-ppc64-gnu": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.44.0.tgz",
+ "integrity": "sha512-YcFE8/q/BbrCiIiM5piwbkA6GwJc5QqhMQp2yDrqQ2fuVkZ7CInb1aIijZ/k8EXc72qXMSwKpVlBv1w/MsGO/A==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-riscv64-gnu": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.44.0.tgz",
+ "integrity": "sha512-eOdzs6RqkRzuqNHUX5C8ISN5xfGh4xDww8OEd9YAmc3OWN8oAe5bmlIqQ+rrHLpv58/0BuU48bxkhnIGjA/ATQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-riscv64-musl": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.44.0.tgz",
+ "integrity": "sha512-YBgNTxntD/QvlFUfgvh8bEdwOhXiquX8gaofZJAwYa/Xp1S1DQrFVZEeck7GFktr24DztsSp8N8WtWCBwxs0Hw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-s390x-gnu": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.44.0.tgz",
+ "integrity": "sha512-GLIh1R6WHWshl/i4QQDNgj0WtT25aRO4HNUWEoitxiywyRdhTFmFEYT2rXlcl9U6/26vhmOqG5cRlMLG3ocaIA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-x64-gnu": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.44.0.tgz",
+ "integrity": "sha512-gZOpgTlOsLcLfAF9qgpTr7FIIFSKnQN3hDf/0JvQ4CIwMY7h+eilNjxq/CorqvYcEOu+LRt1W4ZS7KccEHLOdA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-linux-x64-musl": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.44.0.tgz",
+ "integrity": "sha512-1CyS9JTB+pCUFYFI6pkQGGZaT/AY5gnhHVrQQLhFba6idP9AzVYm1xbdWfywoldTYvjxQJV6x4SuduCIfP3W+A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-openharmony-arm64": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.44.0.tgz",
+ "integrity": "sha512-bmEv70Ak6jLr1xotCbF5TxIKjsmQaiX+jFRtnGtfA03tJPf6VG3cKh96S21boAt3JZc+Vjx8PYcDuLj39vM2Pw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-arm64-msvc": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.44.0.tgz",
+ "integrity": "sha512-yWzB+oCpSnP/dmw85eFLAT5o35Ve5pkGS2uF/UCISpIwDqf1xa7OpmtomiqY/Vzg8VyvMbuf6vroF2khF/+1Vg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-ia32-msvc": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.44.0.tgz",
+ "integrity": "sha512-TcWpo18xEIE3AmIG2kpr3kz5IEhQgnx0lazl2+8L+3eTopOAUevQcmlr4nhguImNWz0OMeOZrYZOhJNCf16nlQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxfmt/binding-win32-x64-msvc": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.44.0.tgz",
+ "integrity": "sha512-oj8aLkPJZppIM4CMQNsyir9ybM1Xw/CfGPTSsTnzpVGyljgfbdP0EVUlURiGM0BDrmw5psQ6ArmGCcUY/yABaQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm-eabi": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.59.0.tgz",
+ "integrity": "sha512-etYDw/UaEv936AQUd/CRMBVd+e+XuuU6wC+VzOv1STvsTyZenLChepLWqLtnyTTp4YMlM22ypzogDDwqYxv5cg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-android-arm64": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.59.0.tgz",
+ "integrity": "sha512-TgLc7XVLKH2a4h8j3vn1MDjfK33i9MY60f/bKhRGWyVzbk5LCZ4X01VZG7iHrMmi5vYbAp8//Ponigx03CLsdw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-arm64": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.59.0.tgz",
+ "integrity": "sha512-DXyFPf5ZKldMLloRHx/B9fsxsiTQomaw7cmEW3YIJko2HgCh+GUhp9gGYwHrqlLJPsEe3dYj9JebjX92D3j3AA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-darwin-x64": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.59.0.tgz",
+ "integrity": "sha512-LgvrsdgVLX1qWqIEmNsSmMXJhpAWdtUQ0M+oR0CySwi+9IHWyOGuIL8w8+u/kbZNMyZr4WUyYB5i0+D+AKgkLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-freebsd-x64": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.59.0.tgz",
+ "integrity": "sha512-bOJhqX/ny4hrFuTPlyk8foSRx/vLRpxJh0jOOKN2NWW6FScXHPAA5rQbrwdQPcgGB5V8Ua51RS03fke8ssBcug==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-gnueabihf": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.59.0.tgz",
+ "integrity": "sha512-vVUXxYMF9trXCsz4m9H6U0IjehosVHxBzVgJUxly1uz4W1PdDyicaBnpC0KRXsHYretLVe+uS9pJy8iM57Kujw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm-musleabihf": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.59.0.tgz",
+ "integrity": "sha512-TULQW8YBPGRWg5yZpFPL54HLOnJ3/HiX6VenDPi6YfxB/jlItwSMFh3/hCeSNbh+DAMaE1Py0j5MOaivHkI/9Q==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-gnu": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.59.0.tgz",
+ "integrity": "sha512-Gt54Y4eqSgYJ90xipm24xeyaPV854706o/kiT8oZvUt3VDY7qqxdqyGqchMaujd87ib+/MXvnl9WkK8Cc1BExg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-arm64-musl": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.59.0.tgz",
+ "integrity": "sha512-3CtsKp7NFB3OfqQzbuAecrY7GIZeiv7AD+xutU4tefVQzlfmTI7/ygWLrvkzsDEjTlMq41rYHxgsn6Yh8tybmA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-ppc64-gnu": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.59.0.tgz",
+ "integrity": "sha512-K0diOpT3ncDmOfl9I1HuvpEsAuTxkts0VYwIv/w6Xiy9CdwyPBVX88Ga9l8VlGgMrwBMnSY4xIvVlVY/fkQk7Q==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-gnu": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.59.0.tgz",
+ "integrity": "sha512-xAU7+QDU6kTJJ7mJLOGgo7oOjtAtkKyFZ0Yjdb5cEo3DiCCPFLvyr08rWiQh6evZ7RiUTf+o65NY/bqttzJiQQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-riscv64-musl": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.59.0.tgz",
+ "integrity": "sha512-KUmZmKlTTyauOnvUNVxK7G40sSSx0+w5l1UhaGsC6KPpOYHenx2oqJTnabmpLJicok7IC+3Y6fXAUOMyexaeJQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-s390x-gnu": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.59.0.tgz",
+ "integrity": "sha512-4usRxC8gS0PGdkHnRmwJt/4zrQNZyk6vL0trCxwZSsAKM+OxhB8nKiR+mhjdBbl8lbMh2gc3bZpNN/ik8c4c2A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-gnu": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.59.0.tgz",
+ "integrity": "sha512-s/rNE2gDmbwAOOP493xk2X7M8LZfI1LJFSSW1+yanz3vuQCFPiHkx4GY+O1HuLUDtkzGlhtMrIcxxzyYLv308w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-linux-x64-musl": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.59.0.tgz",
+ "integrity": "sha512-+yYj1udJa2UvvIUmEm0IcKgc0UlPMgz0nsSTvkPL2y6n0uU5LgIHSwVu4AHhrve6j9BpVSoRksnz8c9QcvITJA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-openharmony-arm64": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.59.0.tgz",
+ "integrity": "sha512-bUplUb48LYsB3hHlQXP2ZMOenpieWoOyppLAnnAhuPag3MGPnt+7caxE3w/Vl9wpQsTA3gzLntQi9rxWrs7Xqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-arm64-msvc": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.59.0.tgz",
+ "integrity": "sha512-/HLsLuz42rWl7h7ePdmMTpHm2HIDmPtcEMYgm5BBEHiEiuNOrzMaUpd2z7UnNni5LGN9obJy2YoAYBLXQwazrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-ia32-msvc": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.59.0.tgz",
+ "integrity": "sha512-rUPy+JnanpPwV/aJCPnxAD1fW50+XPI0VkWr7f0vEbqcdsS8NpB24Rw6RsS7SdpFv8Dw+8ugCwao5nCFbqOUSg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@oxlint/binding-win32-x64-msvc": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.59.0.tgz",
+ "integrity": "sha512-xkE7puteDS/vUyRngLXW0t8WgdWoS/tfxXjhP/P7SMqPDx+hs44SpssO3h3qmTqECYEuXBUPzcAw5257Ka+ofA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@types/mime-types": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmmirror.com/@types/mime-types/-/mime-types-2.1.4.tgz",
+ "integrity": "sha512-lfU4b34HOri+kAY5UheuFMWPDOI+OPceBSHZKp69gEyTL/mmJ4cnU6Y/rlme3UL3GyOn6Y42hyIEw0/q8sWx5w==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "22.19.17",
+ "resolved": "https://registry.npmmirror.com/@types/node/-/node-22.19.17.tgz",
+ "integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~6.21.0"
+ }
+ },
+ "node_modules/@types/ws": {
+ "version": "8.18.1",
+ "resolved": "https://registry.npmmirror.com/@types/ws/-/ws-8.18.1.tgz",
+ "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/chalk": {
+ "version": "5.6.2",
+ "resolved": "https://registry.npmmirror.com/chalk/-/chalk-5.6.2.tgz",
+ "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
+ "node_modules/get-east-asian-width": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmmirror.com/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz",
+ "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/koffi": {
+ "version": "2.15.6",
+ "resolved": "https://registry.npmmirror.com/koffi/-/koffi-2.15.6.tgz",
+ "integrity": "sha512-WQBpM5uo74UQ17UpsFN+PUOrQQg4/nYdey4SGVluQun2drYYfePziLLWdSmFb4wSdWlJC1aimXQnjhPCheRKuw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "funding": {
+ "url": "https://liberapay.com/Koromix"
+ }
+ },
+ "node_modules/marked": {
+ "version": "15.0.12",
+ "resolved": "https://registry.npmmirror.com/marked/-/marked-15.0.12.tgz",
+ "integrity": "sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==",
+ "license": "MIT",
+ "bin": {
+ "marked": "bin/marked.js"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmmirror.com/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmmirror.com/mime-types/-/mime-types-3.0.2.tgz",
+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/oxfmt": {
+ "version": "0.44.0",
+ "resolved": "https://registry.npmmirror.com/oxfmt/-/oxfmt-0.44.0.tgz",
+ "integrity": "sha512-lnncqvHewyRvaqdrnntVIrZV2tEddz8lbvPsQzG/zlkfvgZkwy0HP1p/2u1aCDToeg1jb9zBpbJdfkV73Itw+w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinypool": "2.1.0"
+ },
+ "bin": {
+ "oxfmt": "bin/oxfmt"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxfmt/binding-android-arm-eabi": "0.44.0",
+ "@oxfmt/binding-android-arm64": "0.44.0",
+ "@oxfmt/binding-darwin-arm64": "0.44.0",
+ "@oxfmt/binding-darwin-x64": "0.44.0",
+ "@oxfmt/binding-freebsd-x64": "0.44.0",
+ "@oxfmt/binding-linux-arm-gnueabihf": "0.44.0",
+ "@oxfmt/binding-linux-arm-musleabihf": "0.44.0",
+ "@oxfmt/binding-linux-arm64-gnu": "0.44.0",
+ "@oxfmt/binding-linux-arm64-musl": "0.44.0",
+ "@oxfmt/binding-linux-ppc64-gnu": "0.44.0",
+ "@oxfmt/binding-linux-riscv64-gnu": "0.44.0",
+ "@oxfmt/binding-linux-riscv64-musl": "0.44.0",
+ "@oxfmt/binding-linux-s390x-gnu": "0.44.0",
+ "@oxfmt/binding-linux-x64-gnu": "0.44.0",
+ "@oxfmt/binding-linux-x64-musl": "0.44.0",
+ "@oxfmt/binding-openharmony-arm64": "0.44.0",
+ "@oxfmt/binding-win32-arm64-msvc": "0.44.0",
+ "@oxfmt/binding-win32-ia32-msvc": "0.44.0",
+ "@oxfmt/binding-win32-x64-msvc": "0.44.0"
+ }
+ },
+ "node_modules/oxlint": {
+ "version": "1.59.0",
+ "resolved": "https://registry.npmmirror.com/oxlint/-/oxlint-1.59.0.tgz",
+ "integrity": "sha512-0xBLeGGjP4vD9pygRo8iuOkOzEU1MqOnfiOl7KYezL/QvWL8NUg6n03zXc7ZVqltiOpUxBk2zgHI3PnRIEdAvw==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "oxlint": "bin/oxlint"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxlint/binding-android-arm-eabi": "1.59.0",
+ "@oxlint/binding-android-arm64": "1.59.0",
+ "@oxlint/binding-darwin-arm64": "1.59.0",
+ "@oxlint/binding-darwin-x64": "1.59.0",
+ "@oxlint/binding-freebsd-x64": "1.59.0",
+ "@oxlint/binding-linux-arm-gnueabihf": "1.59.0",
+ "@oxlint/binding-linux-arm-musleabihf": "1.59.0",
+ "@oxlint/binding-linux-arm64-gnu": "1.59.0",
+ "@oxlint/binding-linux-arm64-musl": "1.59.0",
+ "@oxlint/binding-linux-ppc64-gnu": "1.59.0",
+ "@oxlint/binding-linux-riscv64-gnu": "1.59.0",
+ "@oxlint/binding-linux-riscv64-musl": "1.59.0",
+ "@oxlint/binding-linux-s390x-gnu": "1.59.0",
+ "@oxlint/binding-linux-x64-gnu": "1.59.0",
+ "@oxlint/binding-linux-x64-musl": "1.59.0",
+ "@oxlint/binding-openharmony-arm64": "1.59.0",
+ "@oxlint/binding-win32-arm64-msvc": "1.59.0",
+ "@oxlint/binding-win32-ia32-msvc": "1.59.0",
+ "@oxlint/binding-win32-x64-msvc": "1.59.0"
+ },
+ "peerDependencies": {
+ "oxlint-tsgolint": ">=0.18.0"
+ },
+ "peerDependenciesMeta": {
+ "oxlint-tsgolint": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/tinypool": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmmirror.com/tinypool/-/tinypool-2.1.0.tgz",
+ "integrity": "sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/ws": {
+ "version": "8.20.0",
+ "resolved": "https://registry.npmmirror.com/ws/-/ws-8.20.0.tgz",
+ "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ }
+ }
+}
diff --git a/jiuwenclaw/cli/package.json b/jiuwenclaw/cli/package.json
new file mode 100644
index 0000000000..218d25739a
--- /dev/null
+++ b/jiuwenclaw/cli/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "jiuwenclaw-tui",
+ "version": "0.1.0",
+ "description": "Terminal UI for JiuwenClaw",
+ "bin": {
+ "jiuwenclaw-tui-pi": "dist/index.js"
+ },
+ "type": "module",
+ "scripts": {
+ "clean": "rm -rf dist",
+ "dev": "tsc && node dist/index.js",
+ "start": "node dist/index.js",
+ "build": "tsc",
+ "build:bun": "npm run clean && bun build src/index.ts --target=node --outdir dist --format=esm --sourcemap && tsc --emitDeclarationOnly",
+ "typecheck": "tsc --noEmit",
+ "lint": "oxlint --deny-warnings src",
+ "format": "oxfmt --write src package.json tsconfig.json",
+ "format:check": "oxfmt --check src package.json tsconfig.json",
+ "check": "npm run typecheck && npm run lint && npm run format:check"
+ },
+ "dependencies": {
+ "@mariozechner/pi-tui": "^0.65.2",
+ "chalk": "^5.5.0",
+ "ws": "^8.18.0"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "@types/ws": "^8.18.0",
+ "oxfmt": "^0.44.0",
+ "oxlint": "^1.59.0",
+ "typescript": "^5.8.0"
+ }
+}
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.ts
new file mode 100644
index 0000000000..b324630460
--- /dev/null
+++ b/jiuwenclaw/cli/src/app-state.ts
@@ -0,0 +1,437 @@
+import type { CommandContext } from "./core/commands/types.js";
+import { isIgnorableHistoryRestoreError } from "./core/app-state-helpers.js";
+import { generateSessionId } from "./core/session-state.js";
+import {
+ handleIncomingFrame,
+ type AppEventDelegate,
+ type PendingQuestion,
+} from "./core/event-handlers.js";
+import { isEventFrame, type EventFrame } from "./core/protocol.js";
+import {
+ StreamingState,
+ type ContextCompressionStats,
+ type HistoryItem,
+ type SubtaskState,
+ type TodoItem,
+} from "./core/types.js";
+import {
+ getCurrentAccentColor,
+ getCurrentThemeName,
+ setCurrentAccentColor,
+ setCurrentThemeName,
+ type AccentColorName,
+ type ThemeName,
+} from "./ui/theme.js";
+import { type ConnectionStatus, WsClient } from "./core/ws-client.js";
+
+export interface AppSnapshot {
+ connectionStatus: ConnectionStatus;
+ sessionId: string;
+ mode: "plan" | "agent" | "team";
+ themeName: ThemeName;
+ accentColor: AccentColorName;
+ transcriptMode: "compact" | "detailed";
+ transcriptFoldMode: "none" | "tools" | "thinking" | "all";
+ collapsedToolGroupIds: Set<string>;
+ entries: HistoryItem[];
+ streamingState: StreamingState;
+ pendingQuestion: PendingQuestion | null;
+ lastError: string | null;
+ isProcessing: boolean;
+ isPaused: boolean;
+ activeSubtasks: SubtaskState[];
+ todos: TodoItem[];
+ evolutionStatus: "idle" | "running";
+ contextCompression: ContextCompressionStats | null;
+}
+
+export class CliPiAppState {
+ private listeners = new Set<() => void>();
+ private entries: HistoryItem[] = [];
+ private connectionStatus: ConnectionStatus = "idle";
+ private sessionId: string;
+ private mode: "plan" | "agent" | "team" = "plan";
+ private themeName: ThemeName = getCurrentThemeName();
+ private accentColor: AccentColorName = getCurrentAccentColor();
+ private transcriptMode: "compact" | "detailed" = "detailed";
+ private transcriptFoldMode: "none" | "tools" | "thinking" | "all" = "none";
+ private collapsedToolGroupIds = new Set<string>();
+ private streamingState: StreamingState = StreamingState.Idle;
+ private pendingQuestion: PendingQuestion | null = null;
+ private lastError: string | null = null;
+ private activeSubtasks = new Map<string, SubtaskState>();
+ private todos: TodoItem[] = [];
+ private evolutionStatus: "idle" | "running" = "idle";
+ private contextCompression: ContextCompressionStats | null = null;
+ private historyEntries: HistoryItem[] = [];
+ private historyFlushTimer: ReturnType<typeof setTimeout> | null = null;
+ private historyRequestToken = 0;
+ private unlistenStatus: (() => void) | null = null;
+ private unlistenFrames: (() => void) | null = null;
+ private readonly eventDelegate: AppEventDelegate = {
+ getConnectionStatus: () => this.connectionStatus,
+ getSessionId: () => this.sessionId,
+ setSessionId: (sessionId) => {
+ this.sessionId = sessionId;
+ },
+ setMode: (mode) => {
+ this.mode = mode;
+ },
+ getEntries: () => this.entries,
+ setEntries: (entries) => {
+ this.entries = entries;
+ },
+ setStreamingState: (state) => {
+ this.streamingState = state;
+ },
+ setPendingQuestion: (question) => {
+ this.pendingQuestion = question;
+ },
+ setLastError: (error) => {
+ this.lastError = error;
+ },
+ getActiveSubtasks: () => this.activeSubtasks,
+ setTodos: (todos) => {
+ this.todos = todos;
+ },
+ setEvolutionStatus: (status) => {
+ this.evolutionStatus = status;
+ },
+ setContextCompression: (stats) => {
+ this.contextCompression = stats;
+ },
+ pushHistoryEntry: (entry) => {
+ this.historyEntries.push(entry);
+ },
+ scheduleHistoryFlush: () => {
+ this.scheduleHistoryFlush();
+ },
+ safeRestoreHistory: (sessionId) => {
+ this.safeRestoreHistory(sessionId);
+ },
+ };
+
+ constructor(
+ private readonly wsClient: WsClient,
+ cliSession?: string,
+ ) {
+ this.sessionId = cliSession || generateSessionId();
+ }
+
+ start(): void {
+ this.unlistenStatus = this.wsClient.onStatusChange((status) => {
+ this.connectionStatus = status;
+ this.emitChange();
+ });
+
+ this.unlistenFrames = this.wsClient.onFrame((frame) => {
+ this.handleFrame(frame);
+ });
+
+ this.wsClient.connect();
+ }
+
+ stop(): void {
+ if (this.historyFlushTimer) {
+ clearTimeout(this.historyFlushTimer);
+ this.historyFlushTimer = null;
+ }
+ this.unlistenStatus?.();
+ this.unlistenStatus = null;
+ this.unlistenFrames?.();
+ this.unlistenFrames = null;
+ this.wsClient.disconnect();
+ }
+
+ onChange(listener: () => void): () => void {
+ this.listeners.add(listener);
+ return () => {
+ this.listeners.delete(listener);
+ };
+ }
+
+ getSnapshot(): AppSnapshot {
+ const isProcessing =
+ this.streamingState === StreamingState.Responding ||
+ this.streamingState === StreamingState.WaitingForConfirmation;
+ return {
+ connectionStatus: this.connectionStatus,
+ sessionId: this.sessionId,
+ mode: this.mode,
+ themeName: this.themeName,
+ accentColor: this.accentColor,
+ transcriptMode: this.transcriptMode,
+ transcriptFoldMode: this.transcriptFoldMode,
+ collapsedToolGroupIds: new Set(this.collapsedToolGroupIds),
+ entries: [...this.entries],
+ streamingState: this.streamingState,
+ pendingQuestion: this.pendingQuestion ? { ...this.pendingQuestion } : null,
+ lastError: this.lastError,
+ isProcessing,
+ isPaused: this.streamingState === StreamingState.Paused,
+ activeSubtasks: [...this.activeSubtasks.values()].sort((a, b) => a.index - b.index),
+ todos: [...this.todos],
+ evolutionStatus: this.evolutionStatus,
+ contextCompression: this.contextCompression ? { ...this.contextCompression } : null,
+ };
+ }
+
+ getCommandContext(): CommandContext {
+ const snapshot = this.getSnapshot();
+ return {
+ sendEventOnly: this.sendEventOnly,
+ request: this.request,
+ sendMessage: this.sendMessage,
+ sessionId: snapshot.sessionId,
+ entries: snapshot.entries,
+ themeName: snapshot.themeName,
+ accentColor: snapshot.accentColor,
+ updateSession: this.updateSession,
+ addItem: this.addItem,
+ clearEntries: this.clearEntries,
+ restoreHistory: this.restoreHistory,
+ exitApp: () => {
+ // AppScreen injects the real exit handler when executing slash commands.
+ },
+ isProcessing: snapshot.isProcessing,
+ connectionStatus: snapshot.connectionStatus,
+ mode: snapshot.mode,
+ setMode: this.setMode,
+ setThemeName: this.setThemeName,
+ setAccentColor: this.setAccentColor,
+ transcriptMode: snapshot.transcriptMode,
+ setTranscriptMode: this.setTranscriptMode,
+ transcriptFoldMode: snapshot.transcriptFoldMode,
+ setTranscriptFoldMode: this.setTranscriptFoldMode,
+ collapsedToolGroupCount: snapshot.collapsedToolGroupIds.size,
+ collapseToolGroups: this.collapseToolGroups,
+ expandToolGroups: this.expandToolGroups,
+ };
+ }
+
+ readonly sendEventOnly = (method: string, params: Record<string, unknown>): string => {
+ const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;
+ this.wsClient.send({
+ type: "req",
+ id,
+ method,
+ params: { ...params, session_id: params.session_id ?? this.sessionId },
+ });
+ return id;
+ };
+
+ readonly request = async <T = Record<string, unknown>>(
+ method: string,
+ params: Record<string, unknown>,
+ ): Promise<T> => {
+ const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;
+ const response = await this.wsClient.request(id, method, {
+ ...params,
+ session_id: params.session_id ?? this.sessionId,
+ });
+ return response.payload as T;
+ };
+
+ readonly updateSession = (newId: string): void => {
+ this.sessionId = newId;
+ this.emitChange();
+ };
+
+ readonly addItem = (item: HistoryItem): void => {
+ this.entries = [...this.entries, item];
+ this.lastError = item.kind === "error" ? item.content : this.lastError;
+ this.emitChange();
+ };
+
+ readonly clearEntries = (): void => {
+ this.entries = [];
+ this.pendingQuestion = null;
+ this.lastError = null;
+ this.streamingState = StreamingState.Idle;
+ this.collapsedToolGroupIds.clear();
+ this.activeSubtasks.clear();
+ this.todos = [];
+ this.evolutionStatus = "idle";
+ this.contextCompression = null;
+ this.historyEntries = [];
+ this.emitChange();
+ };
+
+ readonly setMode = (mode: "plan" | "agent" | "team"): void => {
+ if (this.mode !== mode) {
+ this.mode = mode;
+ this.emitChange();
+ }
+ };
+
+ readonly setThemeName = (theme: ThemeName): void => {
+ if (this.themeName !== theme) {
+ this.themeName = theme;
+ setCurrentThemeName(theme);
+ this.emitChange();
+ }
+ };
+
+ readonly setAccentColor = (color: AccentColorName): void => {
+ if (this.accentColor !== color) {
+ this.accentColor = color;
+ setCurrentAccentColor(color);
+ this.emitChange();
+ }
+ };
+
+ readonly setTranscriptMode = (mode: "compact" | "detailed"): void => {
+ if (this.transcriptMode !== mode) {
+ this.transcriptMode = mode;
+ this.emitChange();
+ }
+ };
+
+ readonly setTranscriptFoldMode = (mode: "none" | "tools" | "thinking" | "all"): void => {
+ if (this.transcriptFoldMode !== mode) {
+ this.transcriptFoldMode = mode;
+ this.emitChange();
+ }
+ };
+
+ readonly collapseToolGroups = (scope: "last" | "all"): void => {
+ const ids = this.entries
+ .filter(
+ (entry): entry is Extract<HistoryItem, { kind: "tool_group" }> =>
+ entry.kind === "tool_group",
+ )
+ .map((entry) => entry.id);
+ if (scope === "all") {
+ this.collapsedToolGroupIds = new Set(ids);
+ } else {
+ const last = ids[ids.length - 1];
+ if (last) {
+ this.collapsedToolGroupIds = new Set(this.collapsedToolGroupIds);
+ this.collapsedToolGroupIds.add(last);
+ }
+ }
+ this.emitChange();
+ };
+
+ readonly expandToolGroups = (scope: "last" | "all"): void => {
+ if (scope === "all") {
+ this.collapsedToolGroupIds.clear();
+ } else {
+ const ids = this.entries
+ .filter(
+ (entry): entry is Extract<HistoryItem, { kind: "tool_group" }> =>
+ entry.kind === "tool_group",
+ )
+ .map((entry) => entry.id);
+ const last = ids[ids.length - 1];
+ if (last) {
+ this.collapsedToolGroupIds = new Set(this.collapsedToolGroupIds);
+ this.collapsedToolGroupIds.delete(last);
+ }
+ }
+ this.emitChange();
+ };
+
+ sendMessage(content: string, modeOverride?: "plan" | "agent" | "team"): string | null {
+ if (this.connectionStatus !== "connected") return null;
+ const mode = modeOverride ?? this.mode;
+ const requestId = this.sendEventOnly("chat.send", { content, query: content, mode });
+ this.lastError = null;
+ this.entries = [
+ ...this.entries,
+ {
+ kind: "user",
+ id: `user-${requestId}`,
+ sessionId: this.sessionId,
+ content,
+ at: new Date().toISOString(),
+ },
+ {
+ kind: "assistant",
+ id: `assistant-${requestId}`,
+ sessionId: this.sessionId,
+ content: "",
+ streaming: true,
+ requestId,
+ at: new Date().toISOString(),
+ },
+ ];
+ this.streamingState = StreamingState.Responding;
+ this.emitChange();
+ return requestId;
+ }
+
+ cancel(): void {
+ this.sendEventOnly("chat.interrupt", { intent: "cancel" });
+ }
+
+ resume(): void {
+ this.sendEventOnly("chat.resume", {});
+ }
+
+ answerQuestion(answer: string): void {
+ if (!this.pendingQuestion) return;
+ this.sendEventOnly("chat.user_answer", {
+ request_id: this.pendingQuestion.requestId,
+ content: answer,
+ });
+ this.pendingQuestion = null;
+ this.streamingState = StreamingState.Idle;
+ this.emitChange();
+ }
+
+ async restoreHistory(targetSessionId: string): Promise<void> {
+ this.historyRequestToken += 1;
+ const requestToken = this.historyRequestToken;
+ this.historyEntries = [];
+ if (this.historyFlushTimer) {
+ clearTimeout(this.historyFlushTimer);
+ this.historyFlushTimer = null;
+ }
+ await this.request("history.get", { session_id: targetSessionId });
+ setTimeout(() => {
+ if (requestToken !== this.historyRequestToken) return;
+ this.entries = [...this.historyEntries];
+ this.emitChange();
+ }, 80);
+ }
+
+ private emitChange(): void {
+ for (const listener of this.listeners) {
+ listener();
+ }
+ }
+
+ private handleFrame(frame: unknown): void {
+ if (!isEventFrame(frame as EventFrame | any)) return;
+ const typedFrame = frame as EventFrame;
+ if (handleIncomingFrame(this.eventDelegate, typedFrame)) {
+ this.emitChange();
+ }
+ }
+
+ private scheduleHistoryFlush(): void {
+ if (this.historyFlushTimer) {
+ clearTimeout(this.historyFlushTimer);
+ }
+ this.historyFlushTimer = setTimeout(() => {
+ this.historyFlushTimer = null;
+ this.entries = [...this.historyEntries];
+ this.emitChange();
+ }, 50);
+ }
+
+ private safeRestoreHistory(sessionId: string): void {
+ void (async () => {
+ try {
+ await this.restoreHistory(sessionId);
+ } catch (error) {
+ if (isIgnorableHistoryRestoreError(error)) {
+ return;
+ }
+ this.lastError = error instanceof Error ? error.message : String(error);
+ this.emitChange();
+ }
+ })();
+ }
+}
diff --git a/jiuwenclaw/cli/src/core/app-state-helpers.ts b/jiuwenclaw/cli/src/core/app-state-helpers.ts
new file mode 100644
index 0000000000..e509bd9011
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/app-state-helpers.ts
@@ -0,0 +1,83 @@
+import { applyToolResult, createToolCallDisplay } from "./history-parser.js";
+import type { HistoryItem } from "./types.js";
+
+export function createId(prefix: string): string {
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+}
+
+export function findLastIndex<T>(
+ items: T[],
+ predicate: (item: T, index: number) => boolean,
+): number {
+ for (let index = items.length - 1; index >= 0; index -= 1) {
+ const item = items[index];
+ if (item !== undefined && predicate(item, index)) return index;
+ }
+ return -1;
+}
+
+export function isIgnorableHistoryRestoreError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return message.includes("invalid page_idx or session history not found");
+}
+
+export function upsertToolGroup(
+ entries: HistoryItem[],
+ sessionId: string,
+ requestId: string | undefined,
+ toolPayload: Record<string, unknown>,
+ isResult: boolean,
+): HistoryItem[] {
+ const nested =
+ toolPayload[isResult ? "tool_result" : "tool_call"] &&
+ typeof toolPayload[isResult ? "tool_result" : "tool_call"] === "object"
+ ? (toolPayload[isResult ? "tool_result" : "tool_call"] as Record<string, unknown>)
+ : toolPayload;
+ const callId =
+ typeof nested.id === "string"
+ ? nested.id
+ : typeof nested.tool_call_id === "string"
+ ? nested.tool_call_id
+ : typeof nested.toolCallId === "string"
+ ? nested.toolCallId
+ : typeof toolPayload.tool_call_id === "string"
+ ? toolPayload.tool_call_id
+ : undefined;
+ const groupIndex = findLastIndex(
+ entries,
+ (item) =>
+ item.kind === "tool_group" &&
+ item.sessionId === sessionId &&
+ ((Boolean(callId) && item.tools.some((tool) => tool.callId === callId)) ||
+ (Boolean(requestId) && item.requestId === requestId)),
+ );
+
+ if (groupIndex === -1) {
+ const baseTool = createToolCallDisplay(toolPayload);
+ const nextTool = isResult ? applyToolResult(baseTool, toolPayload) : baseTool;
+ return [
+ ...entries,
+ {
+ kind: "tool_group",
+ id: createId("tool-group"),
+ sessionId,
+ requestId,
+ tools: [nextTool],
+ at: new Date().toISOString(),
+ },
+ ];
+ }
+
+ return entries.map((item, index) => {
+ if (index !== groupIndex || item.kind !== "tool_group") return item;
+ const nextTools = [...item.tools];
+ const toolIndex = callId ? nextTools.findIndex((tool) => tool.callId === callId) : -1;
+ if (toolIndex === -1) {
+ const baseTool = createToolCallDisplay(toolPayload);
+ nextTools.push(isResult ? applyToolResult(baseTool, toolPayload) : baseTool);
+ } else if (isResult) {
+ nextTools[toolIndex] = applyToolResult(nextTools[toolIndex]!, toolPayload);
+ }
+ return { ...item, tools: nextTools };
+ });
+}
diff --git a/jiuwenclaw/cli/src/core/commands/CommandService.ts b/jiuwenclaw/cli/src/core/commands/CommandService.ts
new file mode 100644
index 0000000000..ce188202a4
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/CommandService.ts
@@ -0,0 +1,127 @@
+import type { CommandContext, CommandSuggestion, SlashCommand } from "./types.js";
+import { makeItem, parseArgs } from "./helpers.js";
+
+export function parseSlashCommand(raw: string, commands: readonly SlashCommand[]) {
+ const trimmed = raw.trim();
+ const parts = trimmed.substring(1).trim().split(/\s+/).filter(Boolean);
+ let currentCommands = commands;
+ let command: SlashCommand | undefined;
+ let parentCommand: SlashCommand | undefined;
+ let pathIndex = 0;
+ const canonicalPath: string[] = [];
+
+ for (const part of parts) {
+ let found = currentCommands.find((candidate) => candidate.name === part);
+ if (!found) {
+ found = currentCommands.find((candidate) => candidate.altNames?.includes(part));
+ }
+ if (!found) break;
+ parentCommand = command;
+ command = found;
+ canonicalPath.push(found.name);
+ pathIndex += 1;
+ if (found.subCommands) {
+ currentCommands = found.subCommands;
+ } else {
+ break;
+ }
+ }
+
+ const args = parts.slice(pathIndex).join(" ");
+ if (command && command.takesArgs === false && args.length > 0 && parentCommand) {
+ return {
+ name: parentCommand.name,
+ args: parts.slice(pathIndex - 1).join(" "),
+ canonicalPath: canonicalPath.slice(0, -1),
+ command: parentCommand,
+ };
+ }
+
+ return {
+ name: command?.name ?? parts[0] ?? "",
+ args,
+ canonicalPath,
+ command,
+ };
+}
+
+export class CommandService {
+ private commands = new Map<string, SlashCommand>();
+ private aliases = new Map<string, string>();
+
+ register(commands: readonly SlashCommand[]): void {
+ for (const command of commands) {
+ this.registerCommand(command);
+ }
+ }
+
+ private registerCommand(command: SlashCommand): void {
+ this.commands.set(command.name, command);
+ for (const alias of command.altNames ?? []) {
+ this.aliases.set(alias, command.name);
+ }
+ for (const subCommand of command.subCommands ?? []) {
+ this.registerCommand(subCommand);
+ }
+ }
+
+ resolve(name: string): SlashCommand | undefined {
+ const target = this.aliases.get(name) ?? name;
+ return this.commands.get(target);
+ }
+
+ getAll(): SlashCommand[] {
+ return [...this.commands.values()]
+ .filter((command) => !command.hidden)
+ .sort((a, b) => a.name.localeCompare(b.name));
+ }
+
+ async execute(raw: string, ctx: CommandContext): Promise<void> {
+ const parsed = parseSlashCommand(raw.trim(), this.getAll());
+ const command = parsed.command;
+ if (!command) {
+ ctx.addItem(makeItem(ctx.sessionId, "error", `Unknown command: /${parsed.name || ""}`));
+ return;
+ }
+ try {
+ await command.action(ctx, parsed.args);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(makeItem(ctx.sessionId, "error", message));
+ }
+ }
+
+ async getSuggestions(partial: string, ctx?: CommandContext): Promise<CommandSuggestion[]> {
+ const normalized = partial.replace(/^\//, "").toLowerCase();
+ const parts = parseArgs(normalized);
+
+ if (parts.length > 1) {
+ const command = this.resolve(parts[0] ?? "");
+ if (command?.completion && ctx) {
+ const values = await command.completion(ctx, parts.slice(1).join(" "));
+ return values.map((value) => ({
+ value: `/${command.name} ${value}`,
+ description: command.description,
+ usage: command.usage,
+ example: command.example,
+ }));
+ }
+ }
+
+ return this.getAll()
+ .flatMap((command) =>
+ [command.name, ...(command.altNames ?? [])].map((alias) => ({ command, alias })),
+ )
+ .filter(({ alias }) => alias.startsWith(normalized))
+ .map(({ command }) => ({
+ value: `/${command.name}`,
+ description: command.description,
+ usage: command.usage,
+ example: command.example,
+ }))
+ .filter(
+ (item, index, self) =>
+ self.findIndex((candidate) => candidate.value === item.value) === index,
+ );
+ }
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/_placeholder.ts b/jiuwenclaw/cli/src/core/commands/builtins/_placeholder.ts
new file mode 100644
index 0000000000..d0fcaf8a6e
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/_placeholder.ts
@@ -0,0 +1,29 @@
+import { addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createPlaceholderCommand(options: {
+ name: string;
+ description: string;
+ usage: string;
+ example: string;
+ altNames?: string[];
+ takesArgs?: boolean;
+ completion?: SlashCommand["completion"];
+ message: string | ((args: string) => string);
+}): SlashCommand {
+ return {
+ name: options.name,
+ altNames: options.altNames,
+ description: options.description,
+ usage: options.usage,
+ example: options.example,
+ kind: CommandKind.BUILT_IN,
+ takesArgs: options.takesArgs,
+ completion: options.completion,
+ action: (ctx, args) => {
+ const message =
+ typeof options.message === "function" ? options.message(args) : options.message;
+ ctx.addItem(addInfo(ctx.sessionId, message, "i"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/add-dir.ts b/jiuwenclaw/cli/src/core/commands/builtins/add-dir.ts
new file mode 100644
index 0000000000..ed792e57a7
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/add-dir.ts
@@ -0,0 +1,48 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createAddDirCommand(): SlashCommand {
+ return {
+ name: "add-dir",
+ description: "Add a new working directory",
+ usage: "/add-dir <path>",
+ example: "/add-dir ../another-repo",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const directoryPath = args.trim();
+ try {
+ const payload = await ctx.request<{ path?: string; remember?: boolean }>(
+ "command.add_dir",
+ {
+ ...(directoryPath ? { path: directoryPath } : {}),
+ remember: false,
+ },
+ );
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ payload?.path
+ ? `Requested working directory: ${payload.path}`
+ : "Requested add-dir flow without explicit path",
+ "i",
+ {
+ view: "kv",
+ title: "Add Directory",
+ items: [
+ {
+ label: "path",
+ value: typeof payload?.path === "string" ? payload.path : "(interactive)",
+ },
+ { label: "remember", value: String(Boolean(payload?.remember)) },
+ ],
+ },
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `add-dir failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts b/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts
new file mode 100644
index 0000000000..816f4d355b
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts
@@ -0,0 +1,15 @@
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createCancelCommand(): SlashCommand {
+ return {
+ name: "cancel",
+ description: "Cancel the active request",
+ usage: "/cancel",
+ example: "/cancel",
+ isSafeConcurrent: true,
+ kind: CommandKind.BUILT_IN,
+ action: (ctx) => {
+ ctx.sendEventOnly("chat.interrupt", { intent: "cancel" });
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/chrome.ts b/jiuwenclaw/cli/src/core/commands/builtins/chrome.ts
new file mode 100644
index 0000000000..03766ff5d3
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/chrome.ts
@@ -0,0 +1,27 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createChromeCommand(): SlashCommand {
+ return {
+ name: "chrome",
+ description: "Browser integration settings",
+ usage: "/chrome",
+ example: "/chrome",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ try {
+ await ctx.request("command.chrome", {});
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ "Chrome integration command was dispatched to the agent backend",
+ "i",
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `chrome failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/clear.ts b/jiuwenclaw/cli/src/core/commands/builtins/clear.ts
new file mode 100644
index 0000000000..ef938276ac
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/clear.ts
@@ -0,0 +1,34 @@
+import { generateSessionId } from "../../session-state.js";
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createClearCommand(): SlashCommand {
+ return {
+ name: "clear",
+ altNames: ["reset", "new"],
+ description: "Clear conversation history and free up context",
+ usage: "/clear",
+ example: "/new",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ if (ctx.isProcessing) {
+ ctx.addItem(
+ addError(ctx.sessionId, "session is busy; stop the current run before clearing"),
+ );
+ return;
+ }
+
+ const nextId = generateSessionId();
+ try {
+ await ctx.request("session.create", { session_id: nextId });
+ } catch {
+ // Some backends may create the session lazily on first message.
+ }
+
+ ctx.updateSession(nextId);
+ ctx.clearEntries();
+ ctx.addItem(addInfo(nextId, `Started a fresh conversation in ${nextId}`, "i"));
+ await ctx.restoreHistory(nextId);
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/collapse.ts b/jiuwenclaw/cli/src/core/commands/builtins/collapse.ts
new file mode 100644
index 0000000000..df6a1da776
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/collapse.ts
@@ -0,0 +1,32 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+const COLLAPSE_SCOPES = ["last", "all"] as const;
+
+export function createCollapseCommand(): SlashCommand {
+ return {
+ name: "collapse",
+ description: "Collapse tool groups",
+ usage: "/collapse <last|all>",
+ example: "/collapse last",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => [...COLLAPSE_SCOPES],
+ action: async (ctx, args) => {
+ const scope = args.trim();
+ if (!COLLAPSE_SCOPES.includes(scope as (typeof COLLAPSE_SCOPES)[number])) {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "usage: /collapse <last|all>"));
+ return;
+ }
+ ctx.collapseToolGroups(scope as (typeof COLLAPSE_SCOPES)[number]);
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "info",
+ `Collapsed ${scope === "all" ? "all tool groups" : "latest tool group"}`,
+ "-",
+ ),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/color.ts b/jiuwenclaw/cli/src/core/commands/builtins/color.ts
new file mode 100644
index 0000000000..899ad10bb4
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/color.ts
@@ -0,0 +1,44 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+import { getAccentColorOptions } from "../../../ui/theme.js";
+
+const COLOR_OPTIONS = getAccentColorOptions();
+
+export function createColorCommand(): SlashCommand {
+ return {
+ name: "color",
+ description: "Set the prompt bar color for this session",
+ usage: "/color <color|default>",
+ example: "/color blue",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => [...COLOR_OPTIONS],
+ action: (ctx, args) => {
+ const value = args.trim().toLowerCase();
+ if (!value) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Current color: ${ctx.accentColor}`, "c", {
+ view: "list",
+ title: "Accent Color",
+ items: COLOR_OPTIONS.map((option) => ({
+ label: option,
+ description: option === ctx.accentColor ? "current" : undefined,
+ })),
+ }),
+ );
+ return;
+ }
+ if (!COLOR_OPTIONS.includes(value as (typeof COLOR_OPTIONS)[number])) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `invalid color "${value}". available: ${COLOR_OPTIONS.join(", ")}`,
+ ),
+ );
+ return;
+ }
+ ctx.setAccentColor(value as (typeof COLOR_OPTIONS)[number]);
+ ctx.addItem(addInfo(ctx.sessionId, `Session accent color set to ${value}`, "c"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/compact.ts b/jiuwenclaw/cli/src/core/commands/builtins/compact.ts
new file mode 100644
index 0000000000..66c12b518d
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/compact.ts
@@ -0,0 +1,34 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createCompactCommand(): SlashCommand {
+ return {
+ name: "compact",
+ description: "Clear conversation history but keep a summary in context",
+ usage: "/compact [instructions]",
+ example: "/compact focus the summary on architectural decisions",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const instructions = args.trim();
+ try {
+ const payload = await ctx.request<{ instructions?: string }>(
+ "command.compact",
+ instructions ? { instructions } : {},
+ );
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ payload?.instructions
+ ? `Compact requested with custom instructions: ${payload.instructions}`
+ : "Compact requested with default instructions",
+ "i",
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `compact failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/config.ts b/jiuwenclaw/cli/src/core/commands/builtins/config.ts
new file mode 100644
index 0000000000..5e8ef6b06e
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/config.ts
@@ -0,0 +1,83 @@
+import { addError, addInfo, extractObject, formatValue } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+function flattenConfigEntries(
+ value: unknown,
+ prefix = "",
+): Array<{ label: string; value: string }> {
+ if (value === null || value === undefined) {
+ return prefix ? [{ label: prefix, value: String(value) }] : [];
+ }
+
+ if (Array.isArray(value)) {
+ if (!prefix) {
+ return value.map((item, index) => ({ label: `[${index}]`, value: formatValue(item) }));
+ }
+ return [{ label: prefix, value: formatValue(value) }];
+ }
+
+ if (typeof value !== "object") {
+ return prefix
+ ? [{ label: prefix, value: formatValue(value) }]
+ : [{ label: "value", value: formatValue(value) }];
+ }
+
+ const obj = value as Record<string, unknown>;
+ const entries = Object.entries(obj).sort(([left], [right]) => left.localeCompare(right));
+ const flattened = entries.flatMap(([key, nested]) => {
+ const nextPrefix = prefix ? `${prefix}.${key}` : key;
+ if (nested && typeof nested === "object" && !Array.isArray(nested)) {
+ return flattenConfigEntries(nested, nextPrefix);
+ }
+ return [{ label: nextPrefix, value: formatValue(nested) }];
+ });
+
+ return flattened.length > 0 ? flattened : prefix ? [{ label: prefix, value: "{}" }] : [];
+}
+
+export function createConfigCommand(): SlashCommand {
+ return {
+ name: "config",
+ altNames: ["settings", "setting"],
+ description: "View backend config",
+ usage: "/config [key]",
+ example: "/config model_name",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const key = args.trim();
+ let payload: unknown;
+ try {
+ payload = await ctx.request("config.get", key ? { key } : {});
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
+ return;
+ }
+
+ const objectPayload = extractObject(payload);
+ const items = objectPayload
+ ? flattenConfigEntries(objectPayload)
+ : [{ label: key || "value", value: formatValue(payload) }];
+
+ if (items.length === 0) {
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ key ? `No config value found for ${key}` : "No config values returned",
+ "c",
+ ),
+ );
+ return;
+ }
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, key ? `Config: ${key}` : "Config values", "c", {
+ view: "kv",
+ title: key ? `Config · ${key}` : "Config",
+ items,
+ }),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/copy.ts b/jiuwenclaw/cli/src/core/commands/builtins/copy.ts
new file mode 100644
index 0000000000..9d209beb52
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/copy.ts
@@ -0,0 +1,50 @@
+import { copyToClipboard } from "../clipboard.js";
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+function getRecentAssistantMessages(ctx: Parameters<SlashCommand["action"]>[0]): string[] {
+ const texts: string[] = [];
+ for (let index = ctx.entries.length - 1; index >= 0; index -= 1) {
+ const entry = ctx.entries[index];
+ if (!entry || entry.kind !== "assistant") continue;
+ const text = entry.content.trim();
+ if (!text) continue;
+ texts.push(text);
+ }
+ return texts;
+}
+
+export function createCopyCommand(): SlashCommand {
+ return {
+ name: "copy",
+ description: "Copy the latest assistant response to clipboard (or /copy N for the Nth-latest)",
+ usage: "/copy [N]",
+ example: "/copy 2",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: (ctx, args) => {
+ const arg = args.trim();
+ const index = arg ? Number.parseInt(arg, 10) : 1;
+ if (!Number.isInteger(index) || index < 1) {
+ ctx.addItem(
+ addError(ctx.sessionId, `Usage: /copy [N] where N is 1, 2, 3, ... Got: ${arg}`),
+ );
+ return;
+ }
+
+ const texts = getRecentAssistantMessages(ctx);
+ const text = texts[index - 1];
+ if (!text) {
+ ctx.addItem(addError(ctx.sessionId, `No assistant response found for /copy ${index}`));
+ return;
+ }
+
+ if (!copyToClipboard(text)) {
+ ctx.addItem(addError(ctx.sessionId, "Clipboard integration is unavailable on this system"));
+ return;
+ }
+
+ ctx.addItem(addInfo(ctx.sessionId, `Copied assistant response #${index} to clipboard`, "c"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/diff.ts b/jiuwenclaw/cli/src/core/commands/builtins/diff.ts
new file mode 100644
index 0000000000..fde0ba7401
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/diff.ts
@@ -0,0 +1,30 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createDiffCommand(): SlashCommand {
+ return {
+ name: "diff",
+ description: "View uncommitted changes and per-turn diffs",
+ usage: "/diff",
+ example: "/diff",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ try {
+ const payload = await ctx.request<{
+ summary?: string;
+ items?: Array<{ label: string; value?: string }>;
+ }>("command.diff", {});
+ ctx.addItem(
+ addInfo(ctx.sessionId, payload.summary || "Workspace diff summary", "d", {
+ view: "kv",
+ title: "Diff",
+ items: payload.items ?? [],
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `diff failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/exit.ts b/jiuwenclaw/cli/src/core/commands/builtins/exit.ts
new file mode 100644
index 0000000000..76dc153b8c
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/exit.ts
@@ -0,0 +1,15 @@
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createExitCommand(): SlashCommand {
+ return {
+ name: "exit",
+ altNames: ["quit"],
+ description: "Exit the REPL",
+ usage: "/exit",
+ example: "/quit",
+ kind: CommandKind.BUILT_IN,
+ action: (ctx) => {
+ ctx.exitApp();
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/expand.ts b/jiuwenclaw/cli/src/core/commands/builtins/expand.ts
new file mode 100644
index 0000000000..b71156f4d6
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/expand.ts
@@ -0,0 +1,32 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+const EXPAND_SCOPES = ["last", "all"] as const;
+
+export function createExpandCommand(): SlashCommand {
+ return {
+ name: "expand",
+ description: "Expand tool groups",
+ usage: "/expand <last|all>",
+ example: "/expand all",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => [...EXPAND_SCOPES],
+ action: async (ctx, args) => {
+ const scope = args.trim();
+ if (!EXPAND_SCOPES.includes(scope as (typeof EXPAND_SCOPES)[number])) {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "usage: /expand <last|all>"));
+ return;
+ }
+ ctx.expandToolGroups(scope as (typeof EXPAND_SCOPES)[number]);
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "info",
+ `Expanded ${scope === "all" ? "all tool groups" : "latest tool group"}`,
+ "+",
+ ),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/fold.ts b/jiuwenclaw/cli/src/core/commands/builtins/fold.ts
new file mode 100644
index 0000000000..abe851ef9d
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/fold.ts
@@ -0,0 +1,25 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+const FOLD_MODES = ["none", "tools", "thinking", "all"] as const;
+
+export function createFoldCommand(): SlashCommand {
+ return {
+ name: "fold",
+ description: "Fold transcript sections",
+ usage: "/fold <none|tools|thinking|all>",
+ example: "/fold tools",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => [...FOLD_MODES],
+ action: async (ctx, args) => {
+ const mode = args.trim();
+ if (!FOLD_MODES.includes(mode as (typeof FOLD_MODES)[number])) {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "usage: /fold <none|tools|thinking|all>"));
+ return;
+ }
+ ctx.setTranscriptFoldMode(mode as (typeof FOLD_MODES)[number]);
+ ctx.addItem(makeItem(ctx.sessionId, "info", `Transcript fold set to ${mode}`, "f"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/help.ts b/jiuwenclaw/cli/src/core/commands/builtins/help.ts
new file mode 100644
index 0000000000..97d12187a9
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/help.ts
@@ -0,0 +1,28 @@
+import { CommandKind, type SlashCommand, type SlashCommandListProvider } from "../types.js";
+import { makeItem } from "../helpers.js";
+
+export function createHelpCommand(getCommands: SlashCommandListProvider): SlashCommand {
+ return {
+ name: "help",
+ description: "Show available commands",
+ usage: "/help",
+ example: "/help",
+ kind: CommandKind.BUILT_IN,
+ action: (ctx) => {
+ const lines = getCommands()
+ .filter((command) => !command.hidden)
+ .map((command) => ({
+ label: `/${command.name}`,
+ value: command.usage?.replace(/^\/[^\s]+/, "").trim() || undefined,
+ description: command.description,
+ }));
+ ctx.addItem(
+ makeItem(ctx.sessionId, "info", "Available commands", "?", {
+ view: "help",
+ title: "Slash Commands",
+ items: lines,
+ }),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/history.ts b/jiuwenclaw/cli/src/core/commands/builtins/history.ts
new file mode 100644
index 0000000000..0625884e83
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/history.ts
@@ -0,0 +1,15 @@
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createHistoryCommand(): SlashCommand {
+ return {
+ name: "history",
+ description: "Reload current session history",
+ usage: "/history",
+ example: "/history",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ ctx.clearEntries();
+ await ctx.restoreHistory(ctx.sessionId);
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/hotkey.ts b/jiuwenclaw/cli/src/core/commands/builtins/hotkey.ts
new file mode 100644
index 0000000000..f545ef5cd0
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/hotkey.ts
@@ -0,0 +1,28 @@
+import { APP_SCREEN_KEY_BINDINGS } from "../../../ui/keymap.js";
+import { addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createHotkeyCommand(): SlashCommand {
+ return {
+ name: "hotkey",
+ description: "Show available keyboard shortcuts",
+ usage: "/hotkey",
+ example: "/hotkey",
+ kind: CommandKind.BUILT_IN,
+ action: (ctx) => {
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Keyboard shortcuts", "k", {
+ view: "list",
+ title: "Hotkeys",
+ items: [
+ ...APP_SCREEN_KEY_BINDINGS.map((binding) => ({
+ label: binding.label,
+ description: binding.description,
+ })),
+ { label: "/help", description: "show slash commands" },
+ ],
+ }),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/mode.ts b/jiuwenclaw/cli/src/core/commands/builtins/mode.ts
new file mode 100644
index 0000000000..ad4a5aa40f
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/mode.ts
@@ -0,0 +1,28 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createModeCommand(): SlashCommand {
+ return {
+ name: "mode",
+ description: "Switch chat mode",
+ usage: "/mode <plan|agent>",
+ example: "/mode agent",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => ["plan", "agent"],
+ action: async (ctx, args) => {
+ const nextMode = args.trim();
+ if (nextMode !== "plan" && nextMode !== "agent") {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "usage: /mode <plan|agent>"));
+ return;
+ }
+ try {
+ await ctx.request("mode.set", { mode: nextMode });
+ } catch {
+ // Some backends still accept mode only on chat.send.
+ }
+ ctx.setMode(nextMode);
+ ctx.addItem(makeItem(ctx.sessionId, "info", `Mode set to ${nextMode}`, "m"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/model.ts b/jiuwenclaw/cli/src/core/commands/builtins/model.ts
new file mode 100644
index 0000000000..b7fb8770aa
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/model.ts
@@ -0,0 +1,50 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createModelCommand(): SlashCommand {
+ return {
+ name: "model",
+ description: "Set the active AI model",
+ usage: "/model [model]",
+ example: "/model sonnet",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const value = args.trim();
+ try {
+ const payload = await ctx.request<{
+ current?: string;
+ requested?: string;
+ applied?: boolean;
+ available?: string[];
+ }>("command.model", value ? { model: value } : {});
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ payload.requested
+ ? `Requested model: ${payload.requested}`
+ : `Current model: ${payload.current ?? "unknown"}`,
+ "m",
+ {
+ view: "kv",
+ title: "Model",
+ items: [
+ { label: "current", value: payload.current ?? "unknown" },
+ ...(payload.requested ? [{ label: "requested", value: payload.requested }] : []),
+ ...(typeof payload.applied === "boolean"
+ ? [{ label: "applied", value: String(payload.applied) }]
+ : []),
+ ...(payload.available?.length
+ ? [{ label: "available", value: payload.available.join(", ") }]
+ : []),
+ ],
+ },
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `model failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/new.ts b/jiuwenclaw/cli/src/core/commands/builtins/new.ts
new file mode 100644
index 0000000000..445a3477fc
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/new.ts
@@ -0,0 +1,26 @@
+import { generateSessionId } from "../../session-state.js";
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createNewCommand(): SlashCommand {
+ return {
+ name: "new",
+ description: "Create and switch to a session",
+ usage: "/new [id]",
+ example: "/new trip-plan",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ if (ctx.isProcessing) {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "session is busy, run /cancel first"));
+ return;
+ }
+ const nextId = args.trim() || generateSessionId();
+ await ctx.request("session.create", { session_id: nextId });
+ ctx.updateSession(nextId);
+ ctx.clearEntries();
+ ctx.addItem(makeItem(nextId, "info", `Switched to session ${nextId}`, "i"));
+ await ctx.restoreHistory(nextId);
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/plan.ts b/jiuwenclaw/cli/src/core/commands/builtins/plan.ts
new file mode 100644
index 0000000000..a8cc9aab4f
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/plan.ts
@@ -0,0 +1,42 @@
+import { addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createPlanCommand(): SlashCommand {
+ return {
+ name: "plan",
+ description: "Enable plan mode or view the current session plan",
+ usage: "/plan [open|<description>]",
+ example: "/plan outline the migration steps",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: (ctx, args) => {
+ const value = args.trim();
+ if (ctx.mode !== "plan") {
+ ctx.setMode("plan");
+ }
+
+ if (!value) {
+ ctx.addItem(addInfo(ctx.sessionId, "Plan mode enabled", "p"));
+ return;
+ }
+
+ if (value === "open") {
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ "Plan mode is active. Type your planning request directly or run /plan <description>.",
+ "p",
+ ),
+ );
+ return;
+ }
+
+ const requestId = ctx.sendMessage(value, "plan");
+ if (!requestId) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, "offline: waiting for reconnect before sending plan request", "p"),
+ );
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
new file mode 100644
index 0000000000..b1a951cb65
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
@@ -0,0 +1,56 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createResumeCommand(): SlashCommand {
+ return {
+ name: "resume",
+ altNames: ["continue"],
+ description: "Resume a previous conversation",
+ usage: "/resume [conversation id or search term]",
+ example: "/resume sess_1234",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const value = args.trim();
+ try {
+ const payload = await ctx.request<{
+ session_id?: string;
+ query?: string;
+ resumed?: boolean;
+ preview?: string;
+ }>("command.resume", value ? { query: value } : {});
+ const nextSessionId = payload.session_id?.trim();
+ if (payload.resumed && nextSessionId) {
+ ctx.updateSession(nextSessionId);
+ ctx.clearEntries();
+ ctx.addItem(addInfo(nextSessionId, `Resumed session ${nextSessionId}`, "r"));
+ void ctx.restoreHistory(nextSessionId);
+ return;
+ }
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ nextSessionId
+ ? `Resume candidate: ${nextSessionId}`
+ : value
+ ? `No resume match for ${value}`
+ : "No resumable session returned",
+ "r",
+ {
+ view: "kv",
+ title: "Resume",
+ items: [
+ ...(nextSessionId ? [{ label: "session", value: nextSessionId }] : []),
+ ...(payload.query ? [{ label: "query", value: payload.query }] : []),
+ ...(payload.preview ? [{ label: "preview", value: payload.preview }] : []),
+ ],
+ },
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `resume failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/session.ts b/jiuwenclaw/cli/src/core/commands/builtins/session.ts
new file mode 100644
index 0000000000..b3e4a2972f
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/session.ts
@@ -0,0 +1,36 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createSessionCommand(): SlashCommand {
+ return {
+ name: "session",
+ altNames: ["remote", "sessions"],
+ description: "Show remote session URL and QR code",
+ usage: "/session",
+ example: "/remote",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ try {
+ const payload = await ctx.request<{
+ session_id?: string;
+ remote_url?: string;
+ qr_text?: string;
+ }>("command.session", {});
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Session details", "s", {
+ view: "kv",
+ title: "Session",
+ items: [
+ { label: "current", value: payload.session_id ?? ctx.sessionId },
+ { label: "remote", value: payload.remote_url ?? "not available" },
+ ...(payload.qr_text ? [{ label: "qr", value: payload.qr_text }] : []),
+ ],
+ }),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `session failed: ${message}`));
+ }
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/sessions.ts b/jiuwenclaw/cli/src/core/commands/builtins/sessions.ts
new file mode 100644
index 0000000000..cf0dab2a0e
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/sessions.ts
@@ -0,0 +1,32 @@
+import { flattenArrayPayload, formatValue, makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createSessionsCommand(): SlashCommand {
+ return {
+ name: "sessions",
+ description: "List sessions",
+ usage: "/sessions",
+ example: "/sessions",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ const payload = await ctx.request("session.list", {});
+ const items = flattenArrayPayload(payload).map((item, index) => ({
+ label: String(index + 1),
+ value: typeof item === "string" ? item : formatValue(item),
+ }));
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "info",
+ items.length > 0 ? "Available sessions" : "No sessions returned",
+ "s",
+ {
+ view: "list",
+ title: "Sessions",
+ items,
+ },
+ ),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/skills.ts b/jiuwenclaw/cli/src/core/commands/builtins/skills.ts
new file mode 100644
index 0000000000..3eac105b16
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/skills.ts
@@ -0,0 +1,39 @@
+import { flattenArrayPayload, formatValue, makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createSkillsCommand(): SlashCommand {
+ return {
+ name: "skills",
+ description: "List skills",
+ usage: "/skills",
+ example: "/skills",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ const payload = await ctx.request("skills.list", {});
+ const items = flattenArrayPayload(payload).map((item, index) => {
+ if (item && typeof item === "object") {
+ const obj = item as Record<string, unknown>;
+ return {
+ label: typeof obj.name === "string" ? obj.name : String(index + 1),
+ value: typeof obj.path === "string" ? obj.path : undefined,
+ description: typeof obj.description === "string" ? obj.description : undefined,
+ };
+ }
+ return { label: String(index + 1), value: formatValue(item) };
+ });
+ ctx.addItem(
+ makeItem(
+ ctx.sessionId,
+ "info",
+ items.length > 0 ? "Installed skills" : "No skills returned",
+ "*",
+ {
+ view: "list",
+ title: "Skills",
+ items,
+ },
+ ),
+ );
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/team.ts b/jiuwenclaw/cli/src/core/commands/builtins/team.ts
new file mode 100644
index 0000000000..4026590c9a
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/team.ts
@@ -0,0 +1,41 @@
+import { generateSessionId } from "../../session-state.js";
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createTeamCommand(): SlashCommand {
+ return {
+ name: "team",
+ description: "Toggle team mode",
+ usage: "/team",
+ example: "/team",
+ kind: CommandKind.BUILT_IN,
+ action: async (ctx) => {
+ if (ctx.isProcessing) {
+ ctx.addItem(addError(ctx.sessionId, "session is busy; stop the current run before switching team mode"));
+ return;
+ }
+
+ const nextMode = ctx.mode === "team" ? "plan" : "team";
+ const nextId = generateSessionId();
+ try {
+ await ctx.request("session.create", { session_id: nextId });
+ } catch {
+ // Some backends may create the session lazily on first message.
+ }
+
+ ctx.setMode(nextMode);
+ ctx.updateSession(nextId);
+ ctx.clearEntries();
+ ctx.addItem(
+ addInfo(
+ nextId,
+ nextMode === "team"
+ ? `Team mode enabled. Started a fresh conversation in ${nextId}`
+ : `Team mode disabled. Back to plan mode in ${nextId}`,
+ "t",
+ ),
+ );
+ await ctx.restoreHistory(nextId);
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/theme.ts b/jiuwenclaw/cli/src/core/commands/builtins/theme.ts
new file mode 100644
index 0000000000..082957fb85
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/theme.ts
@@ -0,0 +1,46 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+import { getThemeOptions } from "../../../ui/theme.js";
+
+const THEME_OPTIONS = getThemeOptions();
+
+export function createThemeCommand(): SlashCommand {
+ return {
+ name: "theme",
+ description: "Change the theme",
+ usage: "/theme [system|dark|light]",
+ example: "/theme dark",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => [...THEME_OPTIONS],
+ action: (ctx, args) => {
+ const value = args.trim().toLowerCase();
+ if (!value) {
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Current theme: ${ctx.themeName}`, "t", {
+ view: "list",
+ title: "Theme",
+ items: THEME_OPTIONS.map((option) => ({
+ label: option,
+ description: option === ctx.themeName ? "current" : undefined,
+ })),
+ }),
+ );
+ return;
+ }
+
+ if (!THEME_OPTIONS.includes(value as (typeof THEME_OPTIONS)[number])) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `invalid theme "${value}". available: ${THEME_OPTIONS.join(", ")}`,
+ ),
+ );
+ return;
+ }
+
+ ctx.setThemeName(value as (typeof THEME_OPTIONS)[number]);
+ ctx.addItem(addInfo(ctx.sessionId, `Theme set to ${value}`, "t"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/view.ts b/jiuwenclaw/cli/src/core/commands/builtins/view.ts
new file mode 100644
index 0000000000..f7c14634e6
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/view.ts
@@ -0,0 +1,23 @@
+import { makeItem } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+export function createViewCommand(): SlashCommand {
+ return {
+ name: "view",
+ description: "Switch transcript density",
+ usage: "/view <compact|detailed>",
+ example: "/view compact",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: async () => ["compact", "detailed"],
+ action: async (ctx, args) => {
+ const nextMode = args.trim();
+ if (nextMode !== "compact" && nextMode !== "detailed") {
+ ctx.addItem(makeItem(ctx.sessionId, "error", "usage: /view <compact|detailed>"));
+ return;
+ }
+ ctx.setTranscriptMode(nextMode);
+ ctx.addItem(makeItem(ctx.sessionId, "info", `Transcript view set to ${nextMode}`, "v"));
+ },
+ };
+}
diff --git a/jiuwenclaw/cli/src/core/commands/clipboard.ts b/jiuwenclaw/cli/src/core/commands/clipboard.ts
new file mode 100644
index 0000000000..9f3c7b55e2
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/clipboard.ts
@@ -0,0 +1,36 @@
+import { execFileSync } from "node:child_process";
+
+function tryClipboard(command: string, args: string[], text: string): boolean {
+ try {
+ execFileSync(command, args, { input: text, stdio: ["pipe", "ignore", "ignore"] });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export function copyToClipboard(text: string): boolean {
+ if (!text) return false;
+
+ if (process.platform === "darwin") {
+ return tryClipboard("pbcopy", [], text);
+ }
+
+ if (process.platform === "win32") {
+ return tryClipboard("clip", [], text);
+ }
+
+ if (process.env.WAYLAND_DISPLAY && tryClipboard("wl-copy", [], text)) {
+ return true;
+ }
+
+ if (process.env.DISPLAY && tryClipboard("xclip", ["-selection", "clipboard"], text)) {
+ return true;
+ }
+
+ if (process.env.DISPLAY && tryClipboard("xsel", ["--clipboard", "--input"], text)) {
+ return true;
+ }
+
+ return false;
+}
diff --git a/jiuwenclaw/cli/src/core/commands/helpers.ts b/jiuwenclaw/cli/src/core/commands/helpers.ts
new file mode 100644
index 0000000000..939be4bec8
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/helpers.ts
@@ -0,0 +1,61 @@
+import type { HistoryItem } from "../types.js";
+
+function now(): string {
+ return new Date().toISOString();
+}
+
+export function makeItem(
+ sessionId: string,
+ kind: HistoryItem["kind"],
+ content: string,
+ icon?: string,
+ meta?: Extract<HistoryItem, { kind: "info" }>["meta"],
+): HistoryItem {
+ const id = `${kind}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ if (kind === "info") return { kind, id, sessionId, content, icon, meta, at: now() };
+ if (kind === "error") return { kind, id, sessionId, content, at: now() };
+ return { kind: "system", id, sessionId, content, at: now() };
+}
+
+export function addInfo(
+ sessionId: string,
+ content: string,
+ icon?: string,
+ meta?: Extract<HistoryItem, { kind: "info" }>["meta"],
+): HistoryItem {
+ return makeItem(sessionId, "info", content, icon, meta);
+}
+
+export function addError(sessionId: string, content: string): HistoryItem {
+ return makeItem(sessionId, "error", content);
+}
+
+export function parseArgs(raw: string): string[] {
+ return raw.trim().split(/\s+/).filter(Boolean);
+}
+
+export function formatValue(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
+
+export function flattenArrayPayload(payload: unknown): unknown[] {
+ if (Array.isArray(payload)) return payload;
+ if (payload && typeof payload === "object") {
+ const obj = payload as Record<string, unknown>;
+ for (const key of ["items", "sessions", "skills", "data"]) {
+ if (Array.isArray(obj[key])) return obj[key] as unknown[];
+ }
+ }
+ return [];
+}
+
+export function extractObject(payload: unknown): Record<string, unknown> | null {
+ return payload && typeof payload === "object" && !Array.isArray(payload)
+ ? (payload as Record<string, unknown>)
+ : null;
+}
diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.ts
new file mode 100644
index 0000000000..06baae4067
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/registry.ts
@@ -0,0 +1,46 @@
+import type { SlashCommand } from "./types.js";
+import { createAddDirCommand } from "./builtins/add-dir.js";
+import { createCancelCommand } from "./builtins/cancel.js";
+import { createChromeCommand } from "./builtins/chrome.js";
+import { createClearCommand } from "./builtins/clear.js";
+import { createColorCommand } from "./builtins/color.js";
+import { createCompactCommand } from "./builtins/compact.js";
+import { createConfigCommand } from "./builtins/config.js";
+import { createCopyCommand } from "./builtins/copy.js";
+import { createDiffCommand } from "./builtins/diff.js";
+import { createExitCommand } from "./builtins/exit.js";
+import { createHelpCommand } from "./builtins/help.js";
+import { createHotkeyCommand } from "./builtins/hotkey.js";
+import { createModelCommand } from "./builtins/model.js";
+import { createPlanCommand } from "./builtins/plan.js";
+import { createResumeCommand } from "./builtins/resume.js";
+import { createSessionCommand } from "./builtins/session.js";
+import { createSkillsCommand } from "./builtins/skills.js";
+import { createTeamCommand } from "./builtins/team.js";
+import { createThemeCommand } from "./builtins/theme.js";
+
+export function createBuiltinCommands(): SlashCommand[] {
+ const commands: SlashCommand[] = [
+ createHelpCommand(() => commands),
+ createAddDirCommand(),
+ createCancelCommand(),
+ createChromeCommand(),
+ createClearCommand(),
+ createColorCommand(),
+ createCompactCommand(),
+ createConfigCommand(),
+ createCopyCommand(),
+ createDiffCommand(),
+ createExitCommand(),
+ createModelCommand(),
+ createPlanCommand(),
+ createResumeCommand(),
+ createSessionCommand(),
+ createSkillsCommand(),
+ createTeamCommand(),
+ createThemeCommand(),
+ createHotkeyCommand(),
+ ];
+
+ return commands;
+}
diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.ts
new file mode 100644
index 0000000000..7b47d790f6
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/types.ts
@@ -0,0 +1,63 @@
+import type { HistoryItem } from "../types.js";
+import type { AccentColorName, ThemeName } from "../../ui/theme.js";
+
+export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";
+
+export enum CommandKind {
+ BUILT_IN = "built-in",
+}
+
+export interface CommandSuggestion {
+ value: string;
+ description?: string;
+ usage?: string;
+ example?: string;
+}
+
+export interface CommandContext {
+ sendEventOnly: (method: string, params: Record<string, unknown>) => string;
+ request: <T = Record<string, unknown>>(
+ method: string,
+ params: Record<string, unknown>,
+ ) => Promise<T>;
+ sendMessage: (content: string, mode?: "plan" | "agent" | "team") => string | null;
+ sessionId: string;
+ entries: HistoryItem[];
+ themeName: ThemeName;
+ accentColor: AccentColorName;
+ updateSession: (id: string) => void;
+ addItem: (item: HistoryItem) => void;
+ clearEntries: () => void;
+ restoreHistory: (sessionId: string) => Promise<void>;
+ exitApp: () => void;
+ isProcessing: boolean;
+ connectionStatus: ConnectionStatus;
+ mode: "plan" | "agent" | "team";
+ setMode: (mode: "plan" | "agent" | "team") => void;
+ setThemeName: (theme: ThemeName) => void;
+ setAccentColor: (color: AccentColorName) => void;
+ transcriptMode: "compact" | "detailed";
+ setTranscriptMode: (mode: "compact" | "detailed") => void;
+ transcriptFoldMode: "none" | "tools" | "thinking" | "all";
+ setTranscriptFoldMode: (mode: "none" | "tools" | "thinking" | "all") => void;
+ collapsedToolGroupCount: number;
+ collapseToolGroups: (scope: "last" | "all") => void;
+ expandToolGroups: (scope: "last" | "all") => void;
+}
+
+export interface SlashCommand {
+ name: string;
+ altNames?: string[];
+ description: string;
+ usage?: string;
+ example?: string;
+ hidden?: boolean;
+ isSafeConcurrent?: boolean;
+ kind: CommandKind;
+ action: (ctx: CommandContext, args: string) => void | Promise<void>;
+ completion?: (ctx: CommandContext, partial: string) => string[] | Promise<string[]>;
+ takesArgs?: boolean;
+ subCommands?: SlashCommand[];
+}
+
+export type SlashCommandListProvider = () => readonly SlashCommand[];
diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.ts
new file mode 100644
index 0000000000..922415af26
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/event-handlers.ts
@@ -0,0 +1,431 @@
+import { parseHistoryFrame, createSessionResultToolDisplay } from "./history-parser.js";
+import type { EventFrame } from "./protocol.js";
+import {
+ StreamingState,
+ type ContextCompressionStats,
+ type HistoryItem,
+ type JsonObject,
+ type SubtaskState,
+ type TodoItem,
+} from "./types.js";
+import type { ConnectionStatus } from "./ws-client.js";
+import {
+ createId,
+ findLastIndex,
+ isIgnorableHistoryRestoreError,
+ upsertToolGroup,
+} from "./app-state-helpers.js";
+
+export interface PendingQuestion {
+ requestId: string;
+ text: string;
+}
+
+export interface AppEventDelegate {
+ getConnectionStatus(): ConnectionStatus;
+ getSessionId(): string;
+ setSessionId(sessionId: string): void;
+ setMode(mode: "plan" | "agent" | "team"): void;
+ getEntries(): HistoryItem[];
+ setEntries(entries: HistoryItem[]): void;
+ setStreamingState(state: StreamingState): void;
+ setPendingQuestion(question: PendingQuestion | null): void;
+ setLastError(error: string | null): void;
+ getActiveSubtasks(): Map<string, SubtaskState>;
+ setTodos(todos: TodoItem[]): void;
+ setEvolutionStatus(status: "idle" | "running"): void;
+ setContextCompression(stats: ContextCompressionStats | null): void;
+ pushHistoryEntry(entry: HistoryItem): void;
+ scheduleHistoryFlush(): void;
+ safeRestoreHistory(sessionId: string): void;
+}
+
+function appendEntry(delegate: AppEventDelegate, entry: HistoryItem): void {
+ delegate.setEntries([...delegate.getEntries(), entry]);
+}
+
+function addSessionResultEntry(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+ effectiveEvent: string,
+): void {
+ const tool = createSessionResultToolDisplay(payload, effectiveEvent);
+ appendEntry(delegate, {
+ kind: "tool_group",
+ id: createId("session-result"),
+ sessionId: activeSessionId,
+ requestId: typeof payload.request_id === "string" ? payload.request_id : undefined,
+ tools: [tool],
+ at: new Date().toISOString(),
+ });
+}
+
+function handleConnectionAck(delegate: AppEventDelegate, frame: EventFrame): boolean {
+ if (frame.event !== "connection.ack") {
+ return false;
+ }
+ // session_id is determined at construction time; connection.ack is only
+ // used as a signal to restore history once connected.
+ const sessionId = delegate.getSessionId();
+ if (sessionId && delegate.getConnectionStatus() === "connected") {
+ delegate.safeRestoreHistory(sessionId);
+ }
+ return true;
+}
+
+function handleDelta(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+): boolean {
+ const content = typeof payload.content === "string" ? payload.content : "";
+ if (!content) return false;
+
+ const entries = delegate.getEntries();
+ if (payload.source_chunk_type === "llm_reasoning") {
+ const existingIndex = findLastIndex(entries, (entry) => entry.kind === "thinking");
+ if (existingIndex === -1) {
+ delegate.setEntries([
+ ...entries,
+ {
+ kind: "thinking",
+ id: createId("reasoning"),
+ sessionId: activeSessionId,
+ content,
+ at: new Date().toISOString(),
+ },
+ ]);
+ return true;
+ }
+ delegate.setEntries(
+ entries.map((entry, index) =>
+ index === existingIndex && entry.kind === "thinking"
+ ? { ...entry, content: `${entry.content}${content}` }
+ : entry,
+ ),
+ );
+ return true;
+ }
+
+ const requestId = typeof payload.request_id === "string" ? payload.request_id : undefined;
+ const existingIndex = findLastIndex(
+ entries,
+ (entry) => entry.kind === "assistant" && entry.streaming === true,
+ );
+ if (existingIndex === -1) {
+ delegate.setEntries([
+ ...entries,
+ {
+ kind: "assistant",
+ id: createId("stream"),
+ sessionId: activeSessionId,
+ content,
+ requestId,
+ streaming: true,
+ at: new Date().toISOString(),
+ },
+ ]);
+ } else {
+ delegate.setEntries(
+ entries.map((entry, index) =>
+ index === existingIndex && entry.kind === "assistant"
+ ? { ...entry, content: entry.content + content, requestId: entry.requestId ?? requestId }
+ : entry,
+ ),
+ );
+ }
+ delegate.setStreamingState(StreamingState.Responding);
+ return true;
+}
+
+function handleFinal(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+): boolean {
+ const content = typeof payload.content === "string" ? payload.content : "";
+ const entries = delegate.getEntries();
+ const hasStreaming = entries.some((entry) => entry.kind === "assistant" && entry.streaming);
+ delegate.setEntries(
+ hasStreaming
+ ? entries.map((entry) =>
+ entry.kind === "assistant" && entry.streaming
+ ? { ...entry, content: content || entry.content, streaming: false }
+ : entry,
+ )
+ : [
+ ...entries,
+ {
+ kind: "assistant",
+ id: createId("assistant-final"),
+ sessionId: activeSessionId,
+ content,
+ requestId: typeof payload.request_id === "string" ? payload.request_id : undefined,
+ streaming: false,
+ at: new Date().toISOString(),
+ },
+ ],
+ );
+ delegate.setStreamingState(StreamingState.Idle);
+ return true;
+}
+
+function handleReasoning(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+): boolean {
+ const content = typeof payload.content === "string" ? payload.content : "";
+ if (!content) return false;
+ appendEntry(delegate, {
+ kind: "thinking",
+ id: createId("reasoning"),
+ sessionId: activeSessionId,
+ content,
+ at: new Date().toISOString(),
+ });
+ return true;
+}
+
+function handleError(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+): boolean {
+ const message =
+ typeof payload.error === "string"
+ ? payload.error
+ : typeof payload.content === "string"
+ ? payload.content
+ : "Unknown error";
+ if (isIgnorableHistoryRestoreError(message)) {
+ return false;
+ }
+ appendEntry(delegate, {
+ kind: "error",
+ id: createId("error"),
+ sessionId: activeSessionId,
+ content: message,
+ at: new Date().toISOString(),
+ });
+ delegate.setLastError(message);
+ delegate.setStreamingState(StreamingState.Idle);
+ return true;
+}
+
+function handleMediaEvent(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+ activeSessionId: string,
+ effectiveEvent: "chat.media" | "chat.file",
+): boolean {
+ const name =
+ typeof payload.file_name === "string"
+ ? payload.file_name
+ : typeof payload.name === "string"
+ ? payload.name
+ : "";
+ const content = name ? `[${effectiveEvent}: ${name}]` : `[${effectiveEvent}]`;
+ appendEntry(delegate, {
+ kind: "system",
+ id: createId("system"),
+ sessionId: activeSessionId,
+ content,
+ at: new Date().toISOString(),
+ meta: {
+ eventType: effectiveEvent,
+ rawPayload: payload as JsonObject,
+ fileName: name || undefined,
+ filePath: typeof payload.path === "string" ? payload.path : undefined,
+ },
+ });
+ return true;
+}
+
+function handleContextCompressed(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+): boolean {
+ const rate = typeof payload.rate === "number" ? payload.rate : 0;
+ const before = typeof payload.before_compressed === "number" ? payload.before_compressed : null;
+ const after = typeof payload.after_compressed === "number" ? payload.after_compressed : null;
+ delegate.setContextCompression({
+ rate,
+ beforeCompressed: before,
+ afterCompressed: after,
+ });
+ return true;
+}
+
+function handleSubtaskUpdate(
+ delegate: AppEventDelegate,
+ payload: Record<string, unknown>,
+): boolean {
+ const taskId = typeof payload.task_id === "string" ? payload.task_id : "";
+ if (!taskId) return false;
+ const subtasks = delegate.getActiveSubtasks();
+ if (payload.status === "completed" || payload.status === "error") {
+ subtasks.delete(taskId);
+ return true;
+ }
+ subtasks.set(taskId, {
+ task_id: taskId,
+ description: typeof payload.description === "string" ? payload.description : "",
+ status: (typeof payload.status === "string"
+ ? payload.status
+ : "starting") as SubtaskState["status"],
+ index: typeof payload.index === "number" ? payload.index : 0,
+ total: typeof payload.total === "number" ? payload.total : 0,
+ tool_name: typeof payload.tool_name === "string" ? payload.tool_name : undefined,
+ tool_count: typeof payload.tool_count === "number" ? payload.tool_count : 0,
+ message: typeof payload.message === "string" ? payload.message : undefined,
+ is_parallel: payload.is_parallel === true,
+ });
+ return true;
+}
+
+function handleTodoUpdated(delegate: AppEventDelegate, payload: Record<string, unknown>): boolean {
+ const todos = Array.isArray(payload.todos) ? payload.todos : [];
+ delegate.setTodos(
+ todos
+ .filter((item): item is TodoItem => Boolean(item && typeof item === "object"))
+ .map((item) => ({
+ id: typeof item.id === "string" ? item.id : "",
+ content: typeof item.content === "string" ? item.content : "",
+ activeForm: typeof item.activeForm === "string" ? item.activeForm : "",
+ status: (item.status === "in_progress" || item.status === "completed"
+ ? item.status
+ : "pending") as TodoItem["status"],
+ createdAt: typeof item.createdAt === "string" ? item.createdAt : new Date().toISOString(),
+ updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : new Date().toISOString(),
+ }))
+ .filter((item) => item.id.length > 0),
+ );
+ return true;
+}
+
+export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFrame): boolean {
+ const connectionChanged = handleConnectionAck(delegate, frame);
+
+ const payload = frame.payload;
+ const effectiveEvent = typeof payload.event_type === "string" ? payload.event_type : frame.event;
+ const activeSessionId = delegate.getSessionId();
+ const eventSessionId = typeof payload.session_id === "string" ? payload.session_id : "";
+ if (eventSessionId && eventSessionId !== activeSessionId) {
+ return connectionChanged;
+ }
+
+ switch (effectiveEvent) {
+ case "chat.delta":
+ return handleDelta(delegate, payload, activeSessionId) || connectionChanged;
+
+ case "chat.final":
+ return handleFinal(delegate, payload, activeSessionId) || connectionChanged;
+
+ case "chat.reasoning":
+ return handleReasoning(delegate, payload, activeSessionId) || connectionChanged;
+
+ case "chat.error":
+ return handleError(delegate, payload, activeSessionId) || connectionChanged;
+
+ case "chat.tool_call":
+ delegate.setEntries(
+ upsertToolGroup(
+ delegate.getEntries(),
+ activeSessionId,
+ typeof payload.request_id === "string" ? payload.request_id : undefined,
+ payload,
+ false,
+ ),
+ );
+ return true;
+
+ case "chat.tool_result":
+ delegate.setEntries(
+ upsertToolGroup(
+ delegate.getEntries(),
+ activeSessionId,
+ typeof payload.request_id === "string" ? payload.request_id : undefined,
+ payload,
+ true,
+ ),
+ );
+ return true;
+
+ case "chat.processing_status":
+ delegate.setStreamingState(
+ payload.is_processing === true ? StreamingState.Responding : StreamingState.Idle,
+ );
+ if (payload.is_processing !== true) {
+ delegate.getActiveSubtasks().clear();
+ delegate.setEvolutionStatus("idle");
+ }
+ return true;
+
+ case "chat.interrupt_result": {
+ const intent = typeof payload.intent === "string" ? payload.intent : "cancel";
+ delegate.setStreamingState(intent === "cancel" ? StreamingState.Idle : StreamingState.Paused);
+ return true;
+ }
+
+ case "chat.ask_user_question": {
+ const text =
+ typeof payload.text === "string"
+ ? payload.text
+ : typeof payload.content === "string"
+ ? payload.content
+ : "";
+ const requestId = typeof payload.request_id === "string" ? payload.request_id : "";
+ if (!text || !requestId) {
+ return connectionChanged;
+ }
+ delegate.setPendingQuestion({ requestId, text });
+ delegate.setStreamingState(StreamingState.WaitingForConfirmation);
+ return true;
+ }
+
+ case "history.message": {
+ const entry = parseHistoryFrame(frame);
+ if (!entry) {
+ return connectionChanged;
+ }
+ delegate.pushHistoryEntry(entry);
+ delegate.scheduleHistoryFlush();
+ return connectionChanged;
+ }
+
+ case "chat.media":
+ case "chat.file":
+ return handleMediaEvent(delegate, payload, activeSessionId, effectiveEvent);
+
+ case "context.compressed":
+ return handleContextCompressed(delegate, payload);
+
+ case "chat.subtask_update":
+ return handleSubtaskUpdate(delegate, payload);
+
+ case "chat.session_result":
+ case "session_result":
+ addSessionResultEntry(delegate, payload, activeSessionId, effectiveEvent);
+ return true;
+
+ case "chat.evolution_status":
+ delegate.setEvolutionStatus(payload.status === "start" ? "running" : "idle");
+ return true;
+
+ case "todo.updated":
+ return handleTodoUpdated(delegate, payload);
+
+ case "session.updated": {
+ const mode = typeof payload.mode === "string" ? payload.mode : "";
+ if (mode === "plan" || mode === "agent" || mode === "team") {
+ delegate.setMode(mode as "plan" | "agent" | "team");
+ }
+ return true;
+ }
+
+ default:
+ return connectionChanged;
+ }
+}
diff --git a/jiuwenclaw/cli/src/core/history-parser.ts b/jiuwenclaw/cli/src/core/history-parser.ts
new file mode 100644
index 0000000000..c782c1be9e
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/history-parser.ts
@@ -0,0 +1,255 @@
+import type { EventFrame } from "./protocol.js";
+import type { HistoryItem, JsonObject, JsonValue, ToolCallDisplay } from "./types.js";
+
+function asString(value: unknown): string | undefined {
+ return typeof value === "string" && value.length > 0 ? value : undefined;
+}
+
+function asBoolean(value: unknown): boolean | undefined {
+ return typeof value === "boolean" ? value : undefined;
+}
+
+function toJsonObject(value: Record<string, unknown>): JsonObject {
+ return value as unknown as JsonObject;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | undefined {
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
+}
+
+function parseArguments(raw: unknown): Record<string, unknown> | undefined {
+ if (raw && typeof raw === "object") return raw as Record<string, unknown>;
+ if (typeof raw === "string") {
+ try {
+ const parsed = JSON.parse(raw);
+ if (parsed && typeof parsed === "object") {
+ return parsed as Record<string, unknown>;
+ }
+ } catch {
+ // Ignore parse failures.
+ }
+ }
+ return undefined;
+}
+
+function resolveToolPayload(
+ payload: Record<string, unknown>,
+ key: "tool_call" | "tool_result",
+): Record<string, unknown> {
+ return asRecord(payload[key]) ?? payload;
+}
+
+function resolveToolCallId(
+ payload: Record<string, unknown>,
+ fallback?: Record<string, unknown>,
+): string | undefined {
+ return (
+ asString(payload.id) ??
+ asString(payload.tool_call_id) ??
+ asString(payload.toolCallId) ??
+ asString(fallback?.tool_call_id) ??
+ asString(fallback?.toolCallId)
+ );
+}
+
+function resolveToolName(
+ payload: Record<string, unknown>,
+ fallback?: Record<string, unknown>,
+): string {
+ return (
+ asString(payload.name) ??
+ asString(payload.tool_name) ??
+ asString(fallback?.tool_name) ??
+ "unknown"
+ );
+}
+
+export function createToolCallDisplay(payload: Record<string, unknown>): ToolCallDisplay {
+ const toolPayload = resolveToolPayload(payload, "tool_call");
+ return {
+ callId: resolveToolCallId(toolPayload, payload) ?? `tool-${Date.now()}`,
+ name: resolveToolName(toolPayload, payload),
+ arguments: parseArguments(toolPayload.arguments),
+ description: asString(toolPayload.description),
+ formattedArgs: asString(toolPayload.formatted_args),
+ status: "running",
+ };
+}
+
+export function applyToolResult(
+ tool: ToolCallDisplay,
+ payload: Record<string, unknown>,
+): ToolCallDisplay {
+ const toolPayload = resolveToolPayload(payload, "tool_result");
+ const result =
+ typeof toolPayload.result === "string"
+ ? toolPayload.result
+ : toolPayload.data !== undefined
+ ? stringifyJson(toolPayload.data as JsonValue)
+ : typeof toolPayload.error === "string"
+ ? toolPayload.error
+ : payload.content !== undefined
+ ? stringifyJson(payload.content as JsonValue)
+ : undefined;
+ const status = asString(toolPayload.status);
+ const success = typeof toolPayload.success === "boolean" ? toolPayload.success : undefined;
+ const isError =
+ (success !== undefined ? !success : undefined) ??
+ (status ? status === "error" : undefined) ??
+ asBoolean(payload.is_error) ??
+ false;
+ return {
+ ...tool,
+ status: isError ? "error" : "completed",
+ result,
+ summary: asString(toolPayload.summary),
+ isError,
+ };
+}
+
+export function createSessionResultToolDisplay(
+ payload: Record<string, unknown>,
+ effectiveEvent = "chat.session_result",
+): ToolCallDisplay {
+ const sessionId = asString(payload.session_id) ?? "";
+ const description = asString(payload.description) ?? "";
+ const result = asString(payload.result) ?? "";
+ const status = payload.status === "error" ? "error" : "completed";
+ const callId = `session-${sessionId || "unknown"}-${typeof payload.index === "number" ? payload.index : Date.now()}`;
+ const fullResult = description ? `描述: ${description}\n\n结果: ${result}` : result;
+
+ return {
+ callId,
+ name: "session",
+ arguments: {
+ session_id: sessionId,
+ description,
+ event_type: effectiveEvent,
+ status: typeof payload.status === "string" ? payload.status : undefined,
+ index: typeof payload.index === "number" ? payload.index : undefined,
+ total: typeof payload.total === "number" ? payload.total : undefined,
+ is_parallel: payload.is_parallel === true,
+ },
+ description: description || "会话完成",
+ formattedArgs: `会话任务:【${description || "未知任务"}】`,
+ status,
+ result: fullResult,
+ summary: status === "error" ? "失败" : "完成",
+ isError: status === "error",
+ };
+}
+
+export function parseHistoryFrame(frame: EventFrame): HistoryItem | null {
+ if (frame.event !== "history.message") return null;
+
+ const payload = frame.payload;
+ const sessionId = asString(payload.session_id) ?? "";
+ const role = asString(payload.role) ?? "";
+ const eventType = asString(payload.event_type) ?? asString(payload.type) ?? "";
+ const sourceChunkType = asString(payload.source_chunk_type) ?? "";
+ const at = asString(payload.at) ?? new Date().toISOString();
+ const id = asString(payload.id) ?? `hist-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+
+ if (role === "user") {
+ const content = asString(payload.content) ?? "";
+ if (!content) return null;
+ return { kind: "user", id, sessionId, content, at };
+ }
+
+ if (eventType === "chat.tool_call") {
+ return {
+ kind: "tool_group",
+ id,
+ sessionId,
+ requestId: asString(payload.request_id),
+ tools: [createToolCallDisplay(payload)],
+ at,
+ };
+ }
+
+ if (eventType === "chat.tool_result") {
+ return {
+ kind: "tool_group",
+ id,
+ sessionId,
+ requestId: asString(payload.request_id),
+ tools: [applyToolResult(createToolCallDisplay(payload), payload)],
+ at,
+ };
+ }
+
+ if (eventType === "chat.media" || eventType === "chat.file") {
+ const name = asString(payload.file_name) ?? asString(payload.name);
+ const label = name ? `[${eventType}: ${name}]` : `[${eventType}]`;
+ return {
+ kind: "system",
+ id,
+ sessionId,
+ content: label,
+ at,
+ meta: {
+ eventType,
+ rawPayload: toJsonObject(payload),
+ fileName: name,
+ filePath: asString(payload.path),
+ },
+ };
+ }
+
+ if (
+ eventType === "chat.reasoning" ||
+ (eventType === "chat.delta" && sourceChunkType === "llm_reasoning")
+ ) {
+ const content = asString(payload.content) ?? "";
+ if (!content) return null;
+ return {
+ kind: "thinking",
+ id,
+ sessionId,
+ content,
+ at,
+ };
+ }
+
+ if (eventType === "chat.session_result" || eventType === "session_result") {
+ return {
+ kind: "tool_group",
+ id,
+ sessionId,
+ requestId: asString(payload.request_id),
+ tools: [createSessionResultToolDisplay(payload, eventType)],
+ at,
+ };
+ }
+
+ if (
+ eventType === "context.compressed" ||
+ eventType === "chat.subtask_update" ||
+ eventType === "chat.evolution_status" ||
+ eventType === "chat.processing_status" ||
+ eventType === "chat.interrupt_result" ||
+ eventType === "chat.ask_user_question"
+ ) {
+ return null;
+ }
+
+ const content = asString(payload.content) ?? "";
+ if (!content) return null;
+ return {
+ kind: "assistant",
+ id,
+ sessionId,
+ content,
+ requestId: asString(payload.request_id),
+ at,
+ };
+}
+
+export function stringifyJson(value: JsonValue): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+}
diff --git a/jiuwenclaw/cli/src/core/protocol.ts b/jiuwenclaw/cli/src/core/protocol.ts
new file mode 100644
index 0000000000..6f0f3587c9
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/protocol.ts
@@ -0,0 +1,33 @@
+export interface ReqFrame {
+ readonly type: "req";
+ readonly id: string;
+ readonly method: string;
+ readonly params: Record<string, unknown>;
+}
+
+export interface ResFrame {
+ readonly type: "res";
+ readonly id: string;
+ readonly ok: boolean;
+ readonly payload: Record<string, unknown>;
+ readonly error?: string;
+ readonly code?: string;
+}
+
+export interface EventFrame {
+ readonly type: "event";
+ readonly event: string;
+ readonly payload: Record<string, unknown>;
+ readonly seq?: number;
+ readonly stream_id?: string;
+}
+
+export type Frame = ReqFrame | ResFrame | EventFrame;
+
+export function isResFrame(frame: Frame): frame is ResFrame {
+ return frame.type === "res";
+}
+
+export function isEventFrame(frame: Frame): frame is EventFrame {
+ return frame.type === "event";
+}
diff --git a/jiuwenclaw/cli/src/core/session-state.ts b/jiuwenclaw/cli/src/core/session-state.ts
new file mode 100644
index 0000000000..a42d16546b
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/session-state.ts
@@ -0,0 +1,7 @@
+import crypto from "node:crypto";
+
+export function generateSessionId(): string {
+ const ts = Math.floor(Date.now() / 1000).toString(16);
+ const suffix = crypto.randomBytes(3).toString("hex");
+ return `sess_${ts}_${suffix}`;
+}
diff --git a/jiuwenclaw/cli/src/core/types.ts b/jiuwenclaw/cli/src/core/types.ts
new file mode 100644
index 0000000000..56ff44eb2b
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/types.ts
@@ -0,0 +1,107 @@
+export enum StreamingState {
+ Idle = "idle",
+ Responding = "responding",
+ Paused = "paused",
+ WaitingForConfirmation = "waiting_for_confirmation",
+}
+
+export type JsonPrimitive = string | number | boolean | null;
+export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
+export interface JsonObject {
+ [key: string]: JsonValue;
+}
+
+export interface SystemMeta {
+ eventType?: "chat.media" | "chat.file" | "notice";
+ rawPayload?: JsonObject;
+ fileName?: string;
+ filePath?: string;
+}
+
+export interface InfoMeta {
+ view?: "help" | "list" | "kv";
+ title?: string;
+ items?: Array<{ label: string; value?: string; description?: string }>;
+}
+
+export interface ToolCallDisplay {
+ callId: string;
+ name: string;
+ arguments?: unknown;
+ description?: string;
+ formattedArgs?: string;
+ status: "running" | "completed" | "error";
+ result?: string;
+ summary?: string;
+ isError?: boolean;
+}
+
+export type SubtaskStatus = "starting" | "tool_call" | "tool_result" | "completed" | "error";
+
+export interface SubtaskState {
+ task_id: string;
+ description: string;
+ status: SubtaskStatus;
+ index: number;
+ total: number;
+ tool_name?: string;
+ tool_count: number;
+ message?: string;
+ is_parallel: boolean;
+}
+
+export interface ContextCompressionStats {
+ rate: number;
+ beforeCompressed: number | null;
+ afterCompressed: number | null;
+}
+
+export type TodoStatus = "pending" | "in_progress" | "completed";
+
+export interface TodoItem {
+ id: string;
+ content: string;
+ activeForm: string;
+ status: TodoStatus;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export type HistoryItem =
+ | { kind: "user"; id: string; sessionId: string; content: string; at: string }
+ | {
+ kind: "assistant";
+ id: string;
+ sessionId: string;
+ content: string;
+ streaming?: boolean;
+ requestId?: string;
+ at: string;
+ }
+ | { kind: "thinking"; id: string; sessionId: string; content: string; at: string }
+ | {
+ kind: "tool_group";
+ id: string;
+ sessionId: string;
+ requestId?: string;
+ tools: ToolCallDisplay[];
+ at: string;
+ }
+ | {
+ kind: "system";
+ id: string;
+ sessionId: string;
+ content: string;
+ meta?: SystemMeta;
+ at: string;
+ }
+ | { kind: "error"; id: string; sessionId: string; content: string; at: string }
+ | {
+ kind: "info";
+ id: string;
+ sessionId: string;
+ content: string;
+ icon?: string;
+ meta?: InfoMeta;
+ at: string;
+ };
diff --git a/jiuwenclaw/cli/src/core/ws-client.ts b/jiuwenclaw/cli/src/core/ws-client.ts
new file mode 100644
index 0000000000..27f851a762
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/ws-client.ts
@@ -0,0 +1,210 @@
+import WebSocket from "ws";
+import type { Frame, ResFrame } from "./protocol.js";
+import { isResFrame } from "./protocol.js";
+
+export type FrameHandler = (frame: Frame) => void;
+export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";
+
+interface PendingRequest {
+ resolve: (frame: ResFrame) => void;
+ reject: (err: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+export class WsClient {
+ private ws: WebSocket | null = null;
+ private readonly url: string;
+ private readonly token: string;
+ private handlers: FrameHandler[] = [];
+ private pending = new Map<string, PendingRequest>();
+ private retryCount = 0;
+ private readonly maxRetries = 5;
+ private readonly baseDelay = 1000;
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ private _status: ConnectionStatus = "idle";
+ private statusListeners: Array<(status: ConnectionStatus) => void> = [];
+ private closeCode = 0;
+ private closeReason = "";
+
+ constructor(url: string, token = "") {
+ this.url = url;
+ this.token = token;
+ }
+
+ get status(): ConnectionStatus {
+ return this._status;
+ }
+
+ get lastCloseCode(): number {
+ return this.closeCode;
+ }
+
+ get lastCloseReason(): string {
+ return this.closeReason;
+ }
+
+ onStatusChange(fn: (status: ConnectionStatus) => void): () => void {
+ this.statusListeners.push(fn);
+ return () => {
+ this.statusListeners = this.statusListeners.filter((item) => item !== fn);
+ };
+ }
+
+ onFrame(handler: FrameHandler): () => void {
+ this.handlers.push(handler);
+ return () => {
+ this.handlers = this.handlers.filter((item) => item !== handler);
+ };
+ }
+
+ connect(): void {
+ this.setStatus("connecting");
+ this.doConnect();
+ }
+
+ disconnect(): void {
+ this.clearReconnectTimer();
+ if (this.ws) {
+ const ws = this.ws;
+ this.ws = null;
+ ws.removeAllListeners();
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
+ ws.close();
+ }
+ }
+ this.rejectAllPending(new Error("disconnected"));
+ this.setStatus("idle");
+ }
+
+ send(frame: Frame): void {
+ if (this.ws?.readyState === WebSocket.OPEN) {
+ this.ws.send(JSON.stringify(frame));
+ }
+ }
+
+ request(
+ id: string,
+ method: string,
+ params: Record<string, unknown>,
+ timeoutMs = 30000,
+ ): Promise<ResFrame> {
+ return new Promise((resolve, reject) => {
+ if (this.ws?.readyState !== WebSocket.OPEN) {
+ reject(new Error(`socket not connected: ${method}`));
+ return;
+ }
+ const frame = { type: "req" as const, id, method, params };
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`request timeout: ${method}`));
+ }, timeoutMs);
+ this.pending.set(id, { resolve, reject, timer });
+ this.send(frame);
+ });
+ }
+
+ private setStatus(status: ConnectionStatus): void {
+ this._status = status;
+ for (const listener of this.statusListeners) {
+ listener(status);
+ }
+ }
+
+ private doConnect(): void {
+ const headers: Record<string, string> = {};
+ if (this.token) {
+ headers.Authorization = `Bearer ${this.token}`;
+ }
+
+ this.ws = new WebSocket(this.url, { headers });
+
+ this.ws.on("open", () => {
+ this.retryCount = 0;
+ this.setStatus("connected");
+ });
+
+ this.ws.on("message", (data: WebSocket.Data) => {
+ try {
+ const frame = JSON.parse(data.toString()) as Frame;
+ this.dispatchFrame(frame);
+ } catch {
+ // Ignore malformed frames.
+ }
+ });
+
+ this.ws.on("close", (code: number, reason: Buffer) => {
+ this.closeCode = code;
+ this.closeReason = reason.toString();
+ this.ws = null;
+
+ if (code === 1008) {
+ this.setStatus("auth_failed");
+ this.rejectAllPending(new Error(`auth failed: ${this.closeReason}`));
+ return;
+ }
+
+ if (code === 1013) {
+ this.setStatus("idle");
+ this.rejectAllPending(new Error("cli channel busy"));
+ return;
+ }
+
+ this.handleReconnect();
+ });
+
+ this.ws.on("error", () => {
+ // The close handler runs afterwards.
+ });
+ }
+
+ private dispatchFrame(frame: Frame): void {
+ if (isResFrame(frame)) {
+ const pending = this.pending.get(frame.id);
+ if (pending) {
+ clearTimeout(pending.timer);
+ this.pending.delete(frame.id);
+ if (frame.ok) {
+ pending.resolve(frame);
+ } else {
+ pending.reject(new Error(frame.error ?? `request failed: ${frame.code ?? "unknown"}`));
+ }
+ return;
+ }
+ }
+
+ for (const handler of this.handlers) {
+ try {
+ handler(frame);
+ } catch {
+ // Ignore handler errors.
+ }
+ }
+ }
+
+ private handleReconnect(): void {
+ if (this.retryCount >= this.maxRetries) {
+ this.setStatus("idle");
+ return;
+ }
+
+ this.setStatus("reconnecting");
+ const delay = Math.min(this.baseDelay * 2 ** this.retryCount, 30000);
+ this.retryCount += 1;
+ this.reconnectTimer = setTimeout(() => this.doConnect(), delay);
+ }
+
+ private clearReconnectTimer(): void {
+ if (this.reconnectTimer) {
+ clearTimeout(this.reconnectTimer);
+ this.reconnectTimer = null;
+ }
+ }
+
+ private rejectAllPending(error: Error): void {
+ for (const pending of this.pending.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(error);
+ }
+ this.pending.clear();
+ }
+}
diff --git a/jiuwenclaw/cli/src/index.ts b/jiuwenclaw/cli/src/index.ts
new file mode 100644
index 0000000000..3f2dd46309
--- /dev/null
+++ b/jiuwenclaw/cli/src/index.ts
@@ -0,0 +1,88 @@
+#!/usr/bin/env node
+
+import { ProcessTerminal, TUI } from "@mariozechner/pi-tui";
+import { parseArgs } from "node:util";
+import { CliPiAppState } from "./app-state.js";
+import { CommandService } from "./core/commands/CommandService.js";
+import { createBuiltinCommands } from "./core/commands/registry.js";
+import { WsClient } from "./core/ws-client.js";
+import { AppScreen } from "./ui/app-screen.js";
+
+const { values } = parseArgs({
+ options: {
+ url: { type: "string", default: "ws://127.0.0.1:19001/cli" },
+ session: { type: "string" },
+ token: { type: "string", default: "" },
+ help: { type: "boolean", short: "h" },
+ },
+ strict: true,
+});
+
+if (values.help) {
+ console.log(`jiuwenclaw-tui-pi - Terminal UI for JiuwenClaw using pi-tui
+
+Options:
+ --url <url> Gateway CLI WebSocket URL (default: ws://127.0.0.1:19001/cli)
+ --session <id> Resume a specific session
+ --token <token> Authentication token
+ -h, --help Show this help
+`);
+ process.exit(0);
+}
+
+if (!process.stdin.isTTY || !process.stdout.isTTY) {
+ console.error("jiuwenclaw-tui-pi requires an interactive TTY");
+ process.exit(1);
+}
+
+const wsClient = new WsClient(values.url ?? "ws://127.0.0.1:19001/cli", values.token ?? "");
+const appState = new CliPiAppState(wsClient, values.session);
+const commandService = new CommandService();
+commandService.register(createBuiltinCommands());
+
+const terminal = new ProcessTerminal();
+const tui = new TUI(terminal);
+tui.setClearOnShrink(true);
+
+let closed = false;
+let screen: AppScreen | null = null;
+
+function closeUi(exitCode = 0): void {
+ if (closed) return;
+ closed = true;
+ screen?.dispose();
+ appState.stop();
+ try {
+ tui.stop();
+ } catch {
+ // Ignore repeated stop failures.
+ }
+ process.exit(exitCode);
+}
+
+function crash(error: unknown): void {
+ const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
+ if (!closed) {
+ screen?.dispose();
+ appState.stop();
+ try {
+ tui.stop();
+ } catch {
+ // Ignore repeated stop failures.
+ }
+ closed = true;
+ }
+ console.error(message);
+ process.exit(1);
+}
+
+screen = new AppScreen(tui, appState, commandService, () => closeUi(0));
+tui.addChild(screen);
+tui.setFocus(screen);
+
+process.on("SIGTERM", () => closeUi(0));
+process.on("uncaughtException", crash);
+process.on("unhandledRejection", crash);
+
+appState.start();
+tui.start();
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
new file mode 100644
index 0000000000..cf361fdcc8
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -0,0 +1,265 @@
+import {
+ CombinedAutocompleteProvider,
+ Editor,
+ type AutocompleteItem,
+ type Component,
+ type Focusable,
+ type SlashCommand as TuiSlashCommand,
+ TUI,
+} from "@mariozechner/pi-tui";
+import type { CliPiAppState } from "../app-state.js";
+import { CommandService, parseSlashCommand } from "../core/commands/CommandService.js";
+import { handleAppScreenKeyInput } from "./keymap.js";
+import { buildAppScreenLines } from "./screen-layout.js";
+import { padToWidth } from "./rendering/text.js";
+import { editorTheme, palette } from "./theme.js";
+
+const END_CURSOR = "\x1b[7m \x1b[0m";
+
+export class AppScreen implements Component, Focusable {
+ private readonly editor: Editor;
+ private readonly unsubscribe: () => void;
+ private _focused = false;
+ private activeQuestionId: string | null = null;
+ private draftBeforeQuestion = "";
+ private showFullThinking = false;
+ private showToolDetails = false;
+ private showShortcutHelp = false;
+ private exitArmedUntil = 0;
+ private transientNotice: string | null = null;
+ private transientNoticeTimer: ReturnType<typeof setTimeout> | null = null;
+
+ constructor(
+ private readonly tui: TUI,
+ private readonly state: CliPiAppState,
+ private readonly commands: CommandService,
+ private readonly exit: () => void,
+ ) {
+ this.editor = new Editor(tui, editorTheme, { paddingX: 1, autocompleteMaxVisible: 6 });
+ this.editor.setAutocompleteProvider(
+ new CombinedAutocompleteProvider(this.buildSlashCommands(), process.cwd()),
+ );
+ this.editor.onChange = () => {
+ this.tui.requestRender();
+ };
+ this.editor.onSubmit = (value) => {
+ void this.handleSubmit(value);
+ };
+ this.unsubscribe = this.state.onChange(() => {
+ this.handleStateChange();
+ });
+ }
+
+ get focused(): boolean {
+ return this._focused;
+ }
+
+ set focused(value: boolean) {
+ this._focused = value;
+ this.editor.focused = value;
+ }
+
+ dispose(): void {
+ if (this.transientNoticeTimer) {
+ clearTimeout(this.transientNoticeTimer);
+ this.transientNoticeTimer = null;
+ }
+ this.unsubscribe();
+ }
+
+ invalidate(): void {
+ this.editor.invalidate();
+ }
+
+ handleInput(data: string): void {
+ const handled = handleAppScreenKeyInput(data, {
+ getSnapshot: () => this.state.getSnapshot(),
+ cancel: () => this.state.cancel(),
+ requestExit: () => {
+ const now = Date.now();
+ if (now <= this.exitArmedUntil) {
+ this.exit();
+ return;
+ }
+ this.exitArmedUntil = now + 1500;
+ this.transientNotice = "Press Ctrl+C again to exit";
+ if (this.transientNoticeTimer) {
+ clearTimeout(this.transientNoticeTimer);
+ }
+ this.transientNoticeTimer = setTimeout(() => {
+ this.transientNotice = null;
+ this.transientNoticeTimer = null;
+ this.tui.requestRender();
+ }, 1500);
+ this.tui.requestRender();
+ },
+ toggleThinking: () => {
+ this.showFullThinking = !this.showFullThinking;
+ this.tui.requestRender();
+ },
+ toggleToolDetails: () => {
+ this.showToolDetails = !this.showToolDetails;
+ this.tui.requestRender();
+ },
+ toggleShortcutHelp: () => {
+ this.showShortcutHelp = !this.showShortcutHelp;
+ this.tui.requestRender();
+ },
+ });
+ if (handled) {
+ return;
+ }
+
+ this.editor.handleInput(data);
+ }
+
+ render(width: number): string[] {
+ const snapshot = this.state.getSnapshot();
+ this.editor.borderColor = snapshot.pendingQuestion
+ ? palette.border.question
+ : palette.border.active;
+ const editorLines = this.applySlashCommandHint(this.editor.render(width), width);
+ return buildAppScreenLines(snapshot, {
+ width,
+ terminalRows: this.tui.terminal.rows,
+ editorLines,
+ showFullThinking: this.showFullThinking,
+ showToolDetails: this.showToolDetails,
+ showShortcutHelp: this.showShortcutHelp,
+ transientNotice: this.transientNotice,
+ });
+ }
+
+ private async handleSubmit(raw: string): Promise<void> {
+ const text = raw.trim();
+ if (!text) return;
+
+ const snapshot = this.state.getSnapshot();
+ if (snapshot.pendingQuestion) {
+ this.state.answerQuestion(text);
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ return;
+ }
+
+ if (text.startsWith("/")) {
+ await this.commands.execute(text, {
+ ...this.state.getCommandContext(),
+ exitApp: this.exit,
+ });
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ return;
+ }
+
+ if (snapshot.isProcessing) {
+ this.state.addItem({
+ kind: "error",
+ id: `busy-${Date.now()}`,
+ sessionId: snapshot.sessionId,
+ content: "session is busy, run /cancel first",
+ at: new Date().toISOString(),
+ });
+ return;
+ }
+
+ const requestId = this.state.sendMessage(text);
+ if (!requestId) {
+ this.state.addItem({
+ kind: "error",
+ id: `offline-${Date.now()}`,
+ sessionId: snapshot.sessionId,
+ content: "offline: waiting for reconnect",
+ at: new Date().toISOString(),
+ });
+ return;
+ }
+
+ this.editor.addToHistory(text);
+ this.editor.setText("");
+ }
+
+ private handleStateChange(): void {
+ const snapshot = this.state.getSnapshot();
+ const questionId = snapshot.pendingQuestion?.requestId ?? null;
+ if (questionId && questionId !== this.activeQuestionId) {
+ this.activeQuestionId = questionId;
+ this.draftBeforeQuestion = this.editor.getText();
+ this.editor.setText("");
+ } else if (!questionId && this.activeQuestionId) {
+ this.activeQuestionId = null;
+ if (!this.editor.getText() && this.draftBeforeQuestion) {
+ this.editor.setText(this.draftBeforeQuestion);
+ }
+ this.draftBeforeQuestion = "";
+ }
+ this.tui.requestRender();
+ }
+
+ private applySlashCommandHint(editorLines: string[], width: number): string[] {
+ const hint = this.getInlineSlashCommandHint();
+ if (!hint || editorLines.length < 3) {
+ return editorLines;
+ }
+
+ const contentIndex = 1;
+ const line = editorLines[contentIndex] ?? "";
+ const cursorIndex = line.indexOf(END_CURSOR);
+ if (cursorIndex === -1) {
+ return editorLines;
+ }
+
+ const hintedLine = padToWidth(
+ line.replace(END_CURSOR, `${END_CURSOR}${palette.text.dim(` ${hint}`)}`),
+ width,
+ );
+
+ const nextLines = [...editorLines];
+ nextLines[contentIndex] = hintedLine;
+ return nextLines;
+ }
+
+ private getInlineSlashCommandHint(): string | null {
+ const text = this.editor.getText();
+ if (!text.startsWith("/") || text.includes("\n")) {
+ return null;
+ }
+
+ const cursor = this.editor.getCursor();
+ const lines = this.editor.getLines();
+ const currentLine = lines[cursor.line] ?? "";
+ if (cursor.line !== 0 || cursor.col !== currentLine.length) {
+ return null;
+ }
+
+ const parsed = parseSlashCommand(text, this.commands.getAll());
+ if (!parsed.command || parsed.args.trim()) {
+ return null;
+ }
+
+ const usage = parsed.command.usage?.trim() ?? "";
+ if (!usage.startsWith("/")) {
+ return null;
+ }
+
+ const suffix = usage.replace(/^\/[^\s]+/, "").trim();
+ return suffix || null;
+ }
+
+ private buildSlashCommands(): TuiSlashCommand[] {
+ return this.commands.getAll().map((command) => ({
+ name: command.name,
+ description: command.description,
+ getArgumentCompletions: command.completion
+ ? async (argumentPrefix: string): Promise<AutocompleteItem[] | null> => {
+ const items = await command.completion!(this.state.getCommandContext(), argumentPrefix);
+ return items.map((value) => ({
+ value,
+ label: value,
+ description: command.description,
+ }));
+ }
+ : undefined,
+ }));
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/message-components.ts b/jiuwenclaw/cli/src/ui/components/message-components.ts
new file mode 100644
index 0000000000..e297266289
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/message-components.ts
@@ -0,0 +1,2 @@
+export { renderHistoryEntry } from "./messages/index.js";
+export type { MessageRenderOptions } from "./messages/index.js";
diff --git a/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts b/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts
new file mode 100644
index 0000000000..fbc802d4fb
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/basic-message-components.ts
@@ -0,0 +1,177 @@
+import { truncateToWidth, type Component } from "@mariozechner/pi-tui";
+import type { HistoryItem } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import {
+ prefixedLines,
+ renderMarkdownLines,
+ renderStyledMarkdownLines,
+ renderWrappedText,
+ summarize,
+} from "../../rendering/text.js";
+import { summarizeToolResultByKind } from "../tools/index.js";
+
+export class UserMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "user" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const lines = renderStyledMarkdownLines(
+ Math.max(1, width - 2),
+ this.entry.content,
+ {
+ bgColor: palette.surface.user,
+ color: (value: string) => value,
+ },
+ 1,
+ 1,
+ );
+ return prefixedLines(lines, width, "> ", palette.text.accent);
+ }
+}
+
+export class AssistantMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "assistant" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const body = this.entry.content.trim();
+ if (!body) {
+ return [];
+ }
+ const lines = renderMarkdownLines(Math.max(1, width - 2), body, 1, 0);
+ if (this.entry.streaming && lines.length > 0) {
+ const lastIndex = lines.length - 1;
+ lines[lastIndex] = truncateToWidth(
+ lines[lastIndex] + palette.status.warning(" [streaming]"),
+ Math.max(1, width - 2),
+ );
+ }
+ return prefixedLines(lines, width, "• ", palette.text.dim);
+ }
+}
+
+export class ThinkingMessageComponent implements Component {
+ constructor(
+ private readonly entry: Extract<HistoryItem, { kind: "thinking" }>,
+ private readonly expanded: boolean,
+ ) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ if (!this.expanded) {
+ const lines = renderStyledMarkdownLines(
+ Math.max(1, width - 2),
+ "Thinking...",
+ {
+ color: palette.text.dim,
+ italic: true,
+ },
+ 1,
+ 0,
+ );
+ return prefixedLines(lines, width, "• ", palette.status.success);
+ }
+ const wrapped = renderStyledMarkdownLines(
+ Math.max(1, width - 2),
+ this.entry.content,
+ {
+ color: palette.text.dim,
+ italic: true,
+ },
+ 1,
+ 0,
+ );
+ return prefixedLines(wrapped, width, "• ", palette.status.success);
+ }
+}
+
+export class SystemMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "system" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), this.entry.content, palette.text.dim),
+ width,
+ "· ",
+ palette.text.dim,
+ );
+ }
+}
+
+export class ErrorMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "error" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ return prefixedLines(
+ renderWrappedText(Math.max(1, width - 2), this.entry.content, palette.status.error),
+ width,
+ "! ",
+ palette.status.error,
+ );
+ }
+}
+
+export class InfoMessageComponent implements Component {
+ constructor(private readonly entry: Extract<HistoryItem, { kind: "info" }>) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ const meta = this.entry.meta;
+ const lines: string[] = [];
+ const innerWidth = Math.max(1, width - 2);
+ const title = meta?.title ?? this.entry.content;
+ lines.push(...renderWrappedText(innerWidth, title, palette.status.info));
+ for (const item of meta?.items ?? []) {
+ const value = item.value ? `: ${item.value}` : "";
+ lines.push(...renderWrappedText(innerWidth, ` ${item.label}${value}`, palette.text.primary));
+ if (item.description) {
+ lines.push(...renderWrappedText(innerWidth, ` ${item.description}`, palette.text.dim));
+ }
+ }
+ return prefixedLines(lines, width, "· ", palette.text.dim);
+ }
+}
+
+export class CompactMessageComponent implements Component {
+ constructor(private readonly entry: HistoryItem) {}
+
+ invalidate(): void {}
+
+ render(width: number): string[] {
+ if (this.entry.kind === "tool_group") {
+ const lastTool = this.entry.tools[this.entry.tools.length - 1];
+ const summary = lastTool
+ ? `${lastTool.name}${lastTool.result ? ` - ${lastTool.summary ?? summarizeToolResultByKind(lastTool.name, lastTool.result) ?? summarize(lastTool.result, 72)}` : ""}`
+ : "tool activity";
+ return renderWrappedText(width, `[tool] ${summary}`, palette.text.dim);
+ }
+
+ const content =
+ this.entry.kind === "assistant" || this.entry.kind === "thinking"
+ ? summarize(this.entry.content, 120)
+ : this.entry.content;
+ const prefix =
+ this.entry.kind === "assistant" || this.entry.kind === "thinking"
+ ? "[a] "
+ : this.entry.kind === "user"
+ ? "> "
+ : this.entry.kind === "error"
+ ? "! "
+ : "- ";
+ const color =
+ this.entry.kind === "error"
+ ? palette.status.error
+ : this.entry.kind === "assistant"
+ ? palette.text.primary
+ : palette.text.dim;
+ return renderWrappedText(width, `${prefix}${content}`, color);
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts b/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts
new file mode 100644
index 0000000000..d0a609e74d
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/history-entry.ts
@@ -0,0 +1,49 @@
+import type { HistoryItem } from "../../../core/types.js";
+import {
+ AssistantMessageComponent,
+ CompactMessageComponent,
+ ErrorMessageComponent,
+ InfoMessageComponent,
+ SystemMessageComponent,
+ ThinkingMessageComponent,
+ UserMessageComponent,
+} from "./basic-message-components.js";
+import { ToolGroupMessageComponent } from "../tools/index.js";
+
+export interface MessageRenderOptions {
+ compact: boolean;
+ collapsed: boolean;
+ thinkingExpanded: boolean;
+ toolDetailsExpanded: boolean;
+}
+
+export function renderHistoryEntry(
+ entry: HistoryItem,
+ width: number,
+ options: MessageRenderOptions,
+): string[] {
+ if (options.compact) {
+ return new CompactMessageComponent(entry).render(width);
+ }
+
+ switch (entry.kind) {
+ case "user":
+ return new UserMessageComponent(entry).render(width);
+ case "assistant":
+ return new AssistantMessageComponent(entry).render(width);
+ case "thinking":
+ return new ThinkingMessageComponent(entry, options.thinkingExpanded).render(width);
+ case "tool_group":
+ return new ToolGroupMessageComponent(
+ entry,
+ options.collapsed,
+ options.toolDetailsExpanded,
+ ).render(width);
+ case "system":
+ return new SystemMessageComponent(entry).render(width);
+ case "error":
+ return new ErrorMessageComponent(entry).render(width);
+ case "info":
+ return new InfoMessageComponent(entry).render(width);
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/components/messages/index.ts b/jiuwenclaw/cli/src/ui/components/messages/index.ts
new file mode 100644
index 0000000000..b14eeb73bb
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/messages/index.ts
@@ -0,0 +1,11 @@
+export {
+ AssistantMessageComponent,
+ CompactMessageComponent,
+ ErrorMessageComponent,
+ InfoMessageComponent,
+ SystemMessageComponent,
+ ThinkingMessageComponent,
+ UserMessageComponent,
+} from "./basic-message-components.js";
+export { renderHistoryEntry } from "./history-entry.js";
+export type { MessageRenderOptions } from "./history-entry.js";
diff --git a/jiuwenclaw/cli/src/ui/components/todo-list.ts b/jiuwenclaw/cli/src/ui/components/todo-list.ts
new file mode 100644
index 0000000000..1dfe9a1994
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/todo-list.ts
@@ -0,0 +1,47 @@
+import { SelectList } from "@mariozechner/pi-tui";
+import type { TodoItem } from "../../core/types.js";
+import { padToWidth } from "../rendering/text.js";
+import { palette, selectListTheme } from "../theme.js";
+
+function todoLabel(todo: TodoItem): string {
+ const prefix = todo.status === "in_progress" ? "●" : todo.status === "completed" ? "✓" : "○";
+ return `${prefix} ${todo.activeForm || todo.content}`;
+}
+
+function todoDescription(todo: TodoItem): string {
+ if (todo.status === "in_progress") {
+ return "in progress";
+ }
+ if (todo.status === "completed") {
+ return "completed";
+ }
+ return "pending";
+}
+
+export function renderTodoList(todos: TodoItem[], width: number): string[] {
+ if (todos.length === 0) {
+ return [];
+ }
+
+ const ordered = [
+ ...todos.filter((todo) => todo.status === "in_progress"),
+ ...todos.filter((todo) => todo.status === "pending"),
+ ...todos.filter((todo) => todo.status === "completed"),
+ ];
+
+ const list = new SelectList(
+ ordered.map((todo) => ({
+ value: todo.id,
+ label: todoLabel(todo),
+ description: todoDescription(todo),
+ })),
+ Math.min(Math.max(ordered.length, 1), 8),
+ selectListTheme,
+ );
+
+ return [
+ padToWidth(palette.text.secondary("Todo"), width),
+ ...list.render(width),
+ " ".repeat(width),
+ ];
+}
diff --git a/jiuwenclaw/cli/src/ui/components/tool-group-message.ts b/jiuwenclaw/cli/src/ui/components/tool-group-message.ts
new file mode 100644
index 0000000000..0020579d46
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tool-group-message.ts
@@ -0,0 +1 @@
+export { ToolGroupMessageComponent, summarizeToolResultByKind } from "./tools/index.js";
diff --git a/jiuwenclaw/cli/src/ui/components/tools/index.ts b/jiuwenclaw/cli/src/ui/components/tools/index.ts
new file mode 100644
index 0000000000..1f8fd3f19f
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/index.ts
@@ -0,0 +1 @@
+export { ToolGroupMessageComponent, summarizeToolResultByKind } from "./tool-group-message.js";
diff --git a/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts b/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts
new file mode 100644
index 0000000000..92219089a1
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/components/tools/tool-group-message.ts
@@ -0,0 +1,554 @@
+import type { Component } from "@mariozechner/pi-tui";
+import type { HistoryItem, ToolCallDisplay } from "../../../core/types.js";
+import { palette } from "../../theme.js";
+import {
+ prefixedLines,
+ renderIndentedBlock,
+ renderWrappedText,
+ summarize,
+} from "../../rendering/text.js";
+
+function summarizePath(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const parts = value.split(/[\\/]/).filter(Boolean);
+ return parts.slice(-3).join("/");
+}
+
+function summarizeToolArguments(name: string, args: unknown): string | undefined {
+ if (!args || typeof args !== "object") {
+ return typeof args === "string" ? summarize(args, 72) : undefined;
+ }
+ const obj = args as Record<string, unknown>;
+ const normalized = name.toLowerCase();
+ if (normalized.includes("read") || normalized.includes("view")) {
+ return summarizePath(obj.path ?? obj.file_path ?? obj.file);
+ }
+ if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
+ return summarizePath(obj.path ?? obj.file_path ?? obj.file) ?? "content change";
+ }
+ if (normalized.includes("search") || normalized.includes("grep") || normalized.includes("glob")) {
+ const pattern =
+ typeof obj.pattern === "string"
+ ? obj.pattern
+ : typeof obj.query === "string"
+ ? obj.query
+ : undefined;
+ const root = summarizePath(obj.path ?? obj.cwd ?? obj.root);
+ return [pattern, root].filter(Boolean).join(" in ") || undefined;
+ }
+ if (
+ normalized.includes("exec") ||
+ normalized.includes("bash") ||
+ normalized.includes("shell") ||
+ normalized.includes("command")
+ ) {
+ return typeof obj.cmd === "string"
+ ? summarize(obj.cmd, 72)
+ : typeof obj.command === "string"
+ ? summarize(obj.command, 72)
+ : undefined;
+ }
+ return summarize(JSON.stringify(args), 72);
+}
+
+export function summarizeToolResultByKind(name: string, result: string): string | undefined {
+ const normalized = name.toLowerCase();
+ const lines = result.split("\n").filter(Boolean).length;
+ if (normalized.includes("read") || normalized.includes("view")) return `${lines} lines loaded`;
+ if (normalized.includes("search") || normalized.includes("grep")) return `${lines} matches`;
+ if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch"))
+ return "edit applied";
+ if (
+ normalized.includes("exec") ||
+ normalized.includes("bash") ||
+ normalized.includes("shell") ||
+ normalized.includes("command")
+ ) {
+ return summarize(result.split("\n")[0] ?? "", 88);
+ }
+ return undefined;
+}
+
+function countLogicalLines(text: string): number {
+ if (!text) return 0;
+ return text.split("\n").length;
+}
+
+function isCodeLikePath(path: string | undefined): boolean {
+ if (!path) return false;
+ return /\.(ts|tsx|js|jsx|py|rs|go|java|c|cc|cpp|h|hpp|json|yaml|yml|toml|md|sh|sql|css|scss|html)$/i.test(
+ path,
+ );
+}
+
+function getToolFilePath(args: Record<string, unknown>): string | undefined {
+ const value = args.path ?? args.file_path ?? args.file ?? args.dir_path;
+ return typeof value === "string" && value ? (summarizePath(value) ?? value) : undefined;
+}
+
+function isReadTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "read" || normalized === "read_file";
+}
+
+function isListTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "ls" || normalized === "list_files";
+}
+
+function isWriteTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "write" || normalized === "write_file";
+}
+
+function isEditTool(name: string): boolean {
+ const normalized = name.toLowerCase();
+ return normalized === "edit" || normalized === "edit_file";
+}
+
+function renderDiffRow(
+ width: number,
+ sign: " " | "+" | "-",
+ text: string,
+ colorFn: (value: string) => string,
+): string[] {
+ return renderWrappedText(width, `${sign} ${text}`, colorFn);
+}
+
+function renderSimpleDiff(width: number, beforeText: string, afterText: string): string[] {
+ const beforeLines = beforeText.split("\n");
+ const afterLines = afterText.split("\n");
+ const total = Math.max(beforeLines.length, afterLines.length);
+ const lines: string[] = [];
+ for (let i = 0; i < total; i++) {
+ const before = beforeLines[i];
+ const after = afterLines[i];
+ if (before === after && before !== undefined) {
+ lines.push(...renderDiffRow(width, " ", before, palette.diff.context));
+ continue;
+ }
+ if (before !== undefined) {
+ lines.push(...renderDiffRow(width, "-", before, palette.diff.remove));
+ }
+ if (after !== undefined) {
+ lines.push(...renderDiffRow(width, "+", after, palette.diff.add));
+ }
+ }
+ return lines;
+}
+
+function renderAddedLines(width: number, text: string): string[] {
+ return text
+ .split("\n")
+ .filter((line) => line.length > 0)
+ .flatMap((line) => renderDiffRow(width, "+", line, palette.diff.add));
+}
+
+function extractTrailingBracketNotices(text: string): { mainLines: string[]; notices: string[] } {
+ const lines = text.split("\n");
+ const notices: string[] = [];
+ let end = lines.length;
+ while (end > 0) {
+ const current = lines[end - 1]?.trim() ?? "";
+ if (current.startsWith("[") && current.endsWith("]")) {
+ notices.unshift(current);
+ end -= 1;
+ continue;
+ }
+ break;
+ }
+ return {
+ mainLines: lines.slice(0, end).filter((line) => line.length > 0),
+ notices,
+ };
+}
+
+export class ToolGroupMessageComponent implements Component {
+ constructor(
+ private readonly entry: Extract<HistoryItem, { kind: "tool_group" }>,
+ private readonly collapsed: boolean,
+ private readonly showDetails: boolean,
+ ) {}
+
+ invalidate(): void {}
+
+ private renderSessionTool(tool: ToolCallDisplay, width: number): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const description =
+ typeof args.description === "string" && args.description
+ ? args.description
+ : (tool.description ?? "会话任务");
+ const index = typeof args.index === "number" ? args.index : undefined;
+ const total = typeof args.total === "number" ? args.total : undefined;
+ const status = tool.isError ? "error" : tool.status === "running" ? "running" : "completed";
+
+ const lines: string[] = [];
+ const headerParts = ["[session]"];
+ if (index !== undefined && total !== undefined) {
+ headerParts.push(`${index}/${total}`);
+ }
+ headerParts.push(status);
+ headerParts.push(description);
+ lines.push(
+ ...renderWrappedText(
+ width,
+ headerParts.join(" | "),
+ tool.isError ? palette.status.error : palette.status.info,
+ ),
+ );
+
+ if (tool.result) {
+ if (!this.showDetails) {
+ lines.push(
+ ...renderWrappedText(
+ width,
+ ` ${tool.summary ?? summarize(tool.result, 120)}`,
+ tool.isError ? palette.status.error : palette.text.dim,
+ ),
+ );
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ return lines;
+ }
+ const previewLines = tool.result.split("\n").filter(Boolean);
+ const shown = previewLines.slice(0, 6);
+ for (const line of shown) {
+ lines.push(
+ ...renderWrappedText(
+ width,
+ ` ${line}`,
+ tool.isError ? palette.status.error : palette.text.primary,
+ ),
+ );
+ }
+ if (previewLines.length > shown.length) {
+ lines.push(
+ ...renderWrappedText(
+ width,
+ ` ... ${previewLines.length - shown.length} more lines`,
+ palette.text.dim,
+ ),
+ );
+ }
+ }
+
+ return lines;
+ }
+
+ private renderReadTool(tool: ToolCallDisplay, width: number): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const offset = typeof args.offset === "number" ? args.offset : undefined;
+ const limit = typeof args.limit === "number" ? args.limit : undefined;
+ const lines: string[] = [];
+ const header = `[read] ${path ?? tool.description ?? tool.name}${offset !== undefined || limit !== undefined ? `:${offset ?? 1}${limit !== undefined ? `-${(offset ?? 1) + limit - 1}` : ""}` : ""}`;
+ lines.push(...renderWrappedText(width, header, palette.text.secondary));
+ if (tool.result) {
+ const { mainLines, notices } = extractTrailingBracketNotices(tool.result);
+ const shown = mainLines.slice(0, this.showDetails ? 10 : 4);
+ if (path) {
+ const meta = `${countLogicalLines(tool.result)} lines${isCodeLikePath(path) ? " | code" : ""}`;
+ lines.push(...renderIndentedBlock(width, meta, palette.text.dim));
+ }
+ if (this.showDetails) {
+ for (const line of shown) {
+ lines.push(...renderIndentedBlock(width, line, palette.text.primary));
+ }
+ if (mainLines.length > shown.length) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `... ${mainLines.length - shown.length} more lines`,
+ palette.text.dim,
+ ),
+ );
+ }
+ } else {
+ lines.push(...renderIndentedBlock(width, "content hidden", palette.text.dim));
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ }
+ for (const notice of notices) {
+ lines.push(...renderIndentedBlock(width, notice, palette.status.warning));
+ }
+ }
+ return lines;
+ }
+
+ private renderListTool(tool: ToolCallDisplay, width: number): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args) ?? ".";
+ const limit = typeof args.limit === "number" ? args.limit : undefined;
+ const lines: string[] = [];
+ lines.push(
+ ...renderWrappedText(
+ width,
+ `[list] ${path}${limit !== undefined ? ` (limit ${limit})` : ""}`,
+ palette.text.secondary,
+ ),
+ );
+ if (tool.result) {
+ const { mainLines, notices } = extractTrailingBracketNotices(tool.result);
+ const shown = mainLines.slice(0, this.showDetails ? 12 : 6);
+ lines.push(...renderIndentedBlock(width, `${mainLines.length} entries`, palette.text.dim));
+ for (const entry of shown) {
+ lines.push(...renderIndentedBlock(width, entry, palette.text.primary));
+ }
+ if (mainLines.length > shown.length) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `... ${mainLines.length - shown.length} more entries`,
+ palette.text.dim,
+ ),
+ );
+ }
+ if (!this.showDetails && mainLines.length > 0) {
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ }
+ for (const notice of notices) {
+ lines.push(...renderIndentedBlock(width, notice, palette.status.warning));
+ }
+ }
+ return lines;
+ }
+
+ private renderWriteTool(tool: ToolCallDisplay, width: number): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const content = typeof args.content === "string" ? args.content : "";
+ const lines: string[] = [];
+ lines.push(
+ ...renderWrappedText(
+ width,
+ `[write] ${path ?? tool.description ?? tool.name}`,
+ tool.isError ? palette.status.error : palette.text.secondary,
+ ),
+ );
+ if (content) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `${countLogicalLines(content)} lines | ${content.length} chars`,
+ palette.text.dim,
+ ),
+ );
+ const diffLines = renderAddedLines(width, content);
+ const shown = this.showDetails ? diffLines : diffLines.slice(0, 6);
+ lines.push(...shown);
+ if (!this.showDetails && diffLines.length > shown.length) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `... ${diffLines.length - shown.length} more diff lines`,
+ palette.text.dim,
+ ),
+ );
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ }
+ }
+ if (tool.result) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ tool.summary ?? summarize(tool.result, 120),
+ tool.isError ? palette.status.error : palette.status.success,
+ ),
+ );
+ }
+ return lines;
+ }
+
+ private renderEditTool(tool: ToolCallDisplay, width: number): string[] {
+ const args =
+ tool.arguments && typeof tool.arguments === "object"
+ ? (tool.arguments as Record<string, unknown>)
+ : {};
+ const path = getToolFilePath(args);
+ const lines: string[] = [];
+ lines.push(
+ ...renderWrappedText(
+ width,
+ `[edit] ${path ?? tool.description ?? tool.name}`,
+ tool.isError ? palette.status.error : palette.text.secondary,
+ ),
+ );
+
+ const oldString =
+ typeof args.old_string === "string"
+ ? args.old_string
+ : typeof args.oldText === "string"
+ ? args.oldText
+ : undefined;
+ const newString =
+ typeof args.new_string === "string"
+ ? args.new_string
+ : typeof args.newText === "string"
+ ? args.newText
+ : undefined;
+
+ if (oldString !== undefined && newString !== undefined) {
+ const diffLines = renderSimpleDiff(width, oldString, newString);
+ const shown = this.showDetails ? diffLines : diffLines.slice(0, 6);
+ lines.push(...shown);
+ if (!this.showDetails && diffLines.length > shown.length) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `... ${diffLines.length - shown.length} more diff lines`,
+ palette.text.dim,
+ ),
+ );
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ }
+ } else if (Array.isArray(args.edits)) {
+ lines.push(
+ ...renderIndentedBlock(width, `${args.edits.length} edit block(s)`, palette.text.dim),
+ );
+ const shownEdits = args.edits.slice(0, this.showDetails ? 3 : 1);
+ for (const edit of shownEdits) {
+ if (!edit || typeof edit !== "object") continue;
+ const item = edit as Record<string, unknown>;
+ const before =
+ typeof item.oldText === "string"
+ ? item.oldText
+ : typeof item.old_string === "string"
+ ? item.old_string
+ : "";
+ const after =
+ typeof item.newText === "string"
+ ? item.newText
+ : typeof item.new_string === "string"
+ ? item.new_string
+ : "";
+ if (!before && !after) continue;
+ const diffLines = renderSimpleDiff(width, before, after);
+ lines.push(...diffLines.slice(0, this.showDetails ? 6 : 2));
+ }
+ if (args.edits.length > shownEdits.length) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ `... ${args.edits.length - shownEdits.length} more edit blocks`,
+ palette.text.dim,
+ ),
+ );
+ }
+ if (!this.showDetails && args.edits.length > 0) {
+ lines.push(...renderIndentedBlock(width, "ctrl+g to expand", palette.text.dim));
+ }
+ }
+
+ if (tool.result) {
+ lines.push(
+ ...renderIndentedBlock(
+ width,
+ tool.summary ?? summarize(tool.result, 120),
+ tool.isError ? palette.status.error : palette.status.success,
+ ),
+ );
+ }
+ return lines;
+ }
+
+ render(width: number): string[] {
+ const lines: string[] = [];
+ const innerWidth = Math.max(1, width - 2);
+ const tools = this.collapsed ? this.entry.tools.slice(-1) : this.entry.tools;
+ for (const tool of tools) {
+ if (tool.name === "session") {
+ lines.push(
+ ...prefixedLines(this.renderSessionTool(tool, innerWidth), width, "· ", palette.text.dim),
+ );
+ continue;
+ }
+ if (isReadTool(tool.name)) {
+ lines.push(
+ ...prefixedLines(this.renderReadTool(tool, innerWidth), width, "· ", palette.text.dim),
+ );
+ continue;
+ }
+ if (isListTool(tool.name)) {
+ lines.push(
+ ...prefixedLines(this.renderListTool(tool, innerWidth), width, "· ", palette.text.dim),
+ );
+ continue;
+ }
+ if (isWriteTool(tool.name)) {
+ lines.push(
+ ...prefixedLines(this.renderWriteTool(tool, innerWidth), width, "· ", palette.text.dim),
+ );
+ continue;
+ }
+ if (isEditTool(tool.name)) {
+ lines.push(
+ ...prefixedLines(this.renderEditTool(tool, innerWidth), width, "· ", palette.text.dim),
+ );
+ continue;
+ }
+ const status = tool.status === "running" ? "[run]" : tool.isError ? "[err]" : "[ok]";
+ const detail = tool.description ?? summarizeToolArguments(tool.name, tool.arguments);
+ lines.push(
+ ...prefixedLines(
+ renderWrappedText(
+ innerWidth,
+ `${status} ${tool.name}${detail ? ` - ${detail}` : ""}`,
+ tool.isError ? palette.status.error : palette.text.secondary,
+ ),
+ width,
+ "· ",
+ palette.text.dim,
+ ),
+ );
+ if (!this.collapsed && tool.result) {
+ const summary =
+ tool.summary ??
+ summarizeToolResultByKind(tool.name, tool.result) ??
+ summarize(tool.result, 120);
+ lines.push(
+ ...prefixedLines(
+ renderWrappedText(
+ innerWidth,
+ ` ${summary}`,
+ tool.isError ? palette.status.error : palette.text.dim,
+ ),
+ width,
+ " ",
+ (value) => value,
+ ),
+ );
+ if (this.showDetails) {
+ const preview = tool.result
+ .split("\n")
+ .slice(0, tool.isError ? 2 : 4)
+ .join("\n");
+ for (const line of preview.split("\n").filter(Boolean)) {
+ lines.push(
+ ...prefixedLines(
+ renderWrappedText(
+ innerWidth,
+ ` ${line}`,
+ tool.isError ? palette.status.error : palette.text.primary,
+ ),
+ width,
+ " ",
+ (value) => value,
+ ),
+ );
+ }
+ }
+ }
+ }
+ return lines;
+ }
+}
diff --git a/jiuwenclaw/cli/src/ui/keymap.ts b/jiuwenclaw/cli/src/ui/keymap.ts
new file mode 100644
index 0000000000..1720f20bbc
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/keymap.ts
@@ -0,0 +1,68 @@
+import { matchesKey } from "@mariozechner/pi-tui";
+import type { AppSnapshot } from "../app-state.js";
+
+export interface AppScreenKeymapDelegate {
+ getSnapshot(): AppSnapshot;
+ cancel(): void;
+ requestExit(): void;
+ toggleThinking(): void;
+ toggleToolDetails(): void;
+ toggleShortcutHelp(): void;
+}
+
+interface KeyBinding {
+ key: Parameters<typeof matchesKey>[1];
+ label: string;
+ description: string;
+ run: (delegate: AppScreenKeymapDelegate) => void;
+}
+
+export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [
+ {
+ key: "ctrl+c",
+ label: "ctrl+c",
+ description: "cancel active run or arm exit",
+ run: (delegate) => {
+ const snapshot = delegate.getSnapshot();
+ if (snapshot.isProcessing) {
+ delegate.cancel();
+ } else {
+ delegate.requestExit();
+ }
+ },
+ },
+ {
+ key: "ctrl+t",
+ label: "ctrl+t",
+ description: "toggle thinking detail",
+ run: (delegate) => {
+ delegate.toggleThinking();
+ },
+ },
+ {
+ key: "ctrl+o",
+ label: "ctrl+o",
+ description: "toggle tool detail",
+ run: (delegate) => {
+ delegate.toggleToolDetails();
+ },
+ },
+ {
+ key: "ctrl+k",
+ label: "ctrl+k",
+ description: "toggle shortcut help",
+ run: (delegate) => {
+ delegate.toggleShortcutHelp();
+ },
+ },
+] as const;
+
+export function handleAppScreenKeyInput(data: string, delegate: AppScreenKeymapDelegate): boolean {
+ for (const binding of APP_SCREEN_KEY_BINDINGS) {
+ if (!matchesKey(data, binding.key)) continue;
+ binding.run(delegate);
+ return true;
+ }
+
+ return false;
+}
diff --git a/jiuwenclaw/cli/src/ui/rendering/text.ts b/jiuwenclaw/cli/src/ui/rendering/text.ts
new file mode 100644
index 0000000000..0e07a6b6e3
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/rendering/text.ts
@@ -0,0 +1,80 @@
+import {
+ Markdown,
+ truncateToWidth,
+ visibleWidth,
+ wrapTextWithAnsi,
+ type DefaultTextStyle,
+} from "@mariozechner/pi-tui";
+import { markdownTheme } from "../theme.js";
+
+export function emptyLine(width: number): string {
+ return " ".repeat(Math.max(0, width));
+}
+
+export function padToWidth(value: string, width: number): string {
+ const clipped = truncateToWidth(value, width);
+ const padding = Math.max(0, width - visibleWidth(clipped));
+ return clipped + " ".repeat(padding);
+}
+
+export function summarize(value: unknown, max = 88): string {
+ const raw = typeof value === "string" ? value : JSON.stringify(value);
+ if (!raw) return "";
+ return raw.length > max ? `${raw.slice(0, max - 3)}...` : raw;
+}
+
+export function prefixedLines(
+ lines: string[],
+ width: number,
+ prefix: string,
+ prefixFn: (value: string) => string,
+): string[] {
+ const bodyWidth = Math.max(1, width - prefix.length);
+ const prefixPad = " ".repeat(prefix.length);
+ return lines.map(
+ (line, index) => prefixFn(index === 0 ? prefix : prefixPad) + padToWidth(line, bodyWidth),
+ );
+}
+
+export function renderWrappedText(
+ width: number,
+ text: string,
+ colorFn?: (value: string) => string,
+): string[] {
+ const lines = wrapTextWithAnsi(text || "", Math.max(1, width));
+ return (lines.length > 0 ? lines : [""]).map((line) =>
+ colorFn ? colorFn(padToWidth(line, width)) : padToWidth(line, width),
+ );
+}
+
+export function renderMarkdownLines(
+ width: number,
+ text: string,
+ paddingX = 0,
+ paddingY = 0,
+): string[] {
+ const markdown = new Markdown(text || "", paddingX, paddingY, markdownTheme);
+ const lines = markdown.render(width);
+ return lines.length > 0 ? lines : [emptyLine(width)];
+}
+
+export function renderStyledMarkdownLines(
+ width: number,
+ text: string,
+ style: DefaultTextStyle,
+ paddingX = 0,
+ paddingY = 0,
+): string[] {
+ const markdown = new Markdown(text || "", paddingX, paddingY, markdownTheme, style);
+ const lines = markdown.render(width);
+ return lines.length > 0 ? lines : [emptyLine(width)];
+}
+
+export function renderIndentedBlock(
+ width: number,
+ text: string,
+ colorFn?: (value: string) => string,
+ prefix = " ",
+): string[] {
+ return renderWrappedText(width, `${prefix}${text}`, colorFn);
+}
diff --git a/jiuwenclaw/cli/src/ui/screen-layout.ts b/jiuwenclaw/cli/src/ui/screen-layout.ts
new file mode 100644
index 0000000000..a0590447bf
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/screen-layout.ts
@@ -0,0 +1,179 @@
+import type { AppSnapshot } from "../app-state.js";
+import { renderHistoryEntry } from "./components/messages/index.js";
+import { renderTodoList } from "./components/todo-list.js";
+import { APP_SCREEN_KEY_BINDINGS } from "./keymap.js";
+import { padToWidth } from "./rendering/text.js";
+import { palette } from "./theme.js";
+import { buildWelcomeLines } from "./welcome.js";
+
+export interface ScreenLayoutOptions {
+ width: number;
+ terminalRows: number;
+ editorLines: string[];
+ showFullThinking: boolean;
+ showToolDetails: boolean;
+ showShortcutHelp: boolean;
+ transientNotice: string | null;
+}
+
+function formatSubtaskStatus(status: string): string {
+ switch (status) {
+ case "starting":
+ return "starting";
+ case "tool_call":
+ return "tool";
+ case "tool_result":
+ return "result";
+ case "completed":
+ return "done";
+ case "error":
+ return "error";
+ default:
+ return status;
+ }
+}
+
+function buildQuestionLines(text: string, width: number): string[] {
+ const question = `[question] ${text}`;
+ const clipped = question.length > width ? question.slice(0, width) : question;
+ return [padToWidth(palette.status.warning(clipped), width), " ".repeat(width)];
+}
+
+function buildStatusLines(
+ snapshot: AppSnapshot,
+ width: number,
+ transientNotice: string | null,
+): string[] {
+ const left = [
+ `status:${snapshot.connectionStatus}`,
+ `mode:${snapshot.mode}`,
+ `view:${snapshot.transcriptMode}`,
+ ];
+ if (snapshot.transcriptFoldMode !== "none") left.push(`fold:${snapshot.transcriptFoldMode}`);
+
+ const right = snapshot.lastError
+ ? `error:${snapshot.lastError}`
+ : snapshot.isPaused
+ ? "paused"
+ : snapshot.isProcessing
+ ? "running"
+ : "ready";
+
+ const lines = transientNotice ? [padToWidth(palette.status.warning(transientNotice), width)] : [];
+ const content = `${left.join(" | ")} | ${right}`;
+ lines.push(padToWidth(palette.text.dim(content), width));
+ const leadSubtask = snapshot.activeSubtasks[0];
+ if (leadSubtask) {
+ const parts = [
+ `subtask ${leadSubtask.index}/${leadSubtask.total || "?"}`,
+ formatSubtaskStatus(leadSubtask.status),
+ leadSubtask.description || leadSubtask.task_id,
+ ];
+ if (leadSubtask.tool_name) parts.push(leadSubtask.tool_name);
+ if (leadSubtask.message) parts.push(leadSubtask.message);
+ if (snapshot.activeSubtasks.length > 1)
+ parts.push(`+${snapshot.activeSubtasks.length - 1} more`);
+ lines.push(padToWidth(palette.text.dim(parts.join(" | ")), width));
+ } else if (snapshot.evolutionStatus === "running") {
+ lines.push(padToWidth(palette.text.dim("evolution | running"), width));
+ }
+ if (snapshot.contextCompression) {
+ const { beforeCompressed, afterCompressed, rate } = snapshot.contextCompression;
+ const parts = ["context"];
+ if (beforeCompressed !== null && afterCompressed !== null) {
+ parts.push(`${beforeCompressed} -> ${afterCompressed}`);
+ }
+ if (rate) {
+ parts.push(`${rate.toFixed(1)}%`);
+ }
+ lines.push(padToWidth(palette.text.dim(parts.join(" | ")), width));
+ }
+ return lines;
+}
+
+function buildShortcutLines(width: number): string[] {
+ const lines = [
+ padToWidth(palette.text.secondary("Shortcuts"), width),
+ ...APP_SCREEN_KEY_BINDINGS.map((binding) =>
+ padToWidth(palette.text.dim(`${binding.label} | ${binding.description}`), width),
+ ),
+ padToWidth(palette.text.dim("/help | show slash commands"), width),
+ " ".repeat(width),
+ ];
+ return lines;
+}
+
+function buildTranscriptLines(
+ snapshot: AppSnapshot,
+ width: number,
+ showFullThinking: boolean,
+ showToolDetails: boolean,
+): string[] {
+ let displayEntries =
+ snapshot.transcriptMode === "compact"
+ ? snapshot.entries
+ .filter((entry) => entry.kind !== "system")
+ .map((entry) =>
+ entry.kind === "tool_group" ? { ...entry, tools: entry.tools.slice(-1) } : entry,
+ )
+ : snapshot.entries;
+
+ if (snapshot.transcriptFoldMode === "all") {
+ displayEntries = displayEntries.filter(
+ (entry) =>
+ entry.kind === "user" ||
+ entry.kind === "assistant" ||
+ entry.kind === "thinking" ||
+ entry.kind === "error",
+ );
+ } else if (snapshot.transcriptFoldMode === "thinking") {
+ displayEntries = displayEntries.filter((entry) => entry.kind !== "thinking");
+ } else if (snapshot.transcriptFoldMode === "tools") {
+ displayEntries = displayEntries.filter(
+ (entry) => entry.kind !== "system" && entry.kind !== "info",
+ );
+ }
+
+ const allLines: string[] = [];
+ if (displayEntries.length === 0) {
+ allLines.push(...buildWelcomeLines(width));
+ }
+ for (const entry of displayEntries) {
+ const collapsed = entry.kind === "tool_group" && snapshot.collapsedToolGroupIds.has(entry.id);
+ allLines.push(
+ ...renderHistoryEntry(entry, width, {
+ compact: snapshot.transcriptMode === "compact",
+ collapsed,
+ thinkingExpanded: showFullThinking,
+ toolDetailsExpanded: showToolDetails,
+ }),
+ );
+ allLines.push(" ".repeat(width));
+ }
+ return allLines;
+}
+
+export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutOptions): string[] {
+ const questionLines = snapshot.pendingQuestion
+ ? buildQuestionLines(snapshot.pendingQuestion.text, options.width)
+ : [];
+ const statusLines = buildStatusLines(snapshot, options.width, options.transientNotice);
+ const shortcutLines = options.showShortcutHelp ? buildShortcutLines(options.width) : [];
+
+ const transcriptLines = buildTranscriptLines(
+ snapshot,
+ options.width,
+ options.showFullThinking,
+ options.showToolDetails,
+ );
+ const todoLines = renderTodoList(snapshot.todos, options.width);
+
+ return [
+ ...transcriptLines,
+ ...todoLines,
+ ...questionLines,
+ ...options.editorLines,
+ ...statusLines,
+ ...shortcutLines,
+ ];
+}
diff --git a/jiuwenclaw/cli/src/ui/theme.ts b/jiuwenclaw/cli/src/ui/theme.ts
new file mode 100644
index 0000000000..c6b8bd9cd2
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/theme.ts
@@ -0,0 +1,222 @@
+import { Chalk } from "chalk";
+import type { EditorTheme, MarkdownTheme, SelectListTheme } from "@mariozechner/pi-tui";
+
+export const chalk = new Chalk({ level: 3 });
+
+export type ThemeName = "system" | "dark" | "light";
+export type AccentColorName = "default" | "blue" | "green" | "pink" | "purple" | "red" | "yellow";
+
+const THEME_OPTIONS: readonly ThemeName[] = ["system", "dark", "light"] as const;
+const ACCENT_OPTIONS: readonly AccentColorName[] = [
+ "default",
+ "blue",
+ "green",
+ "pink",
+ "purple",
+ "red",
+ "yellow",
+] as const;
+
+type ThemeDefinition = {
+ textPrimary: string;
+ textSecondary: string;
+ textDim: string;
+ textAccent: string;
+ statusSuccess: string;
+ statusError: string;
+ statusWarning: string;
+ statusInfo: string;
+ borderPanel: string;
+ borderQuestion: string;
+ surfaceUserBg: string;
+ surfaceUserFg: string;
+ markdownHeading: string;
+ markdownCode: string;
+ markdownCodeBlock: string;
+ diffAddBg: string;
+ diffAddFg: string;
+ diffRemoveBg: string;
+ diffRemoveFg: string;
+ diffContextBg: string;
+ diffContextFg: string;
+};
+
+const THEME_DEFINITIONS: Record<"light" | "dark", ThemeDefinition> = {
+ light: {
+ textPrimary: "#1f2937",
+ textSecondary: "#0f766e",
+ textDim: "#6b7280",
+ textAccent: "#2563eb",
+ statusSuccess: "#15803d",
+ statusError: "#dc2626",
+ statusWarning: "#ca8a04",
+ statusInfo: "#0891b2",
+ borderPanel: "#94a3b8",
+ borderQuestion: "#d97706",
+ surfaceUserBg: "#e8e8e8",
+ surfaceUserFg: "#111827",
+ markdownHeading: "#0f766e",
+ markdownCode: "#a16207",
+ markdownCodeBlock: "#111827",
+ diffAddBg: "#dcfce7",
+ diffAddFg: "#14532d",
+ diffRemoveBg: "#fee2e2",
+ diffRemoveFg: "#7f1d1d",
+ diffContextBg: "#f3f4f6",
+ diffContextFg: "#6b7280",
+ },
+ dark: {
+ textPrimary: "#e5e7eb",
+ textSecondary: "#67e8f9",
+ textDim: "#94a3b8",
+ textAccent: "#60a5fa",
+ statusSuccess: "#4ade80",
+ statusError: "#f87171",
+ statusWarning: "#fbbf24",
+ statusInfo: "#22d3ee",
+ borderPanel: "#475569",
+ borderQuestion: "#f59e0b",
+ surfaceUserBg: "#1f2937",
+ surfaceUserFg: "#f9fafb",
+ markdownHeading: "#67e8f9",
+ markdownCode: "#fbbf24",
+ markdownCodeBlock: "#f3f4f6",
+ diffAddBg: "#14532d",
+ diffAddFg: "#dcfce7",
+ diffRemoveBg: "#7f1d1d",
+ diffRemoveFg: "#fee2e2",
+ diffContextBg: "#1f2937",
+ diffContextFg: "#94a3b8",
+ },
+};
+
+const ACCENT_COLORS: Record<Exclude<AccentColorName, "default">, string> = {
+ blue: "#2563eb",
+ green: "#16a34a",
+ pink: "#db2777",
+ purple: "#7c3aed",
+ red: "#dc2626",
+ yellow: "#ca8a04",
+};
+
+let currentThemeName: ThemeName = "light";
+let currentAccentColor: AccentColorName = "default";
+
+// TODO: Persist theme/accent across CLI restarts after the broader config/settings story is finalized.
+
+function detectSystemTheme(): "light" | "dark" {
+ const colorfgbg = process.env.COLORFGBG;
+ if (colorfgbg) {
+ const parts = colorfgbg.split(";");
+ const bg = Number.parseInt(parts[parts.length - 1] ?? "", 10);
+ if (Number.isFinite(bg)) {
+ return bg >= 0 && bg <= 6 ? "dark" : "light";
+ }
+ }
+ return process.env.TERM_PROGRAM === "Apple_Terminal" ? "light" : "dark";
+}
+
+function getResolvedThemeName(): "light" | "dark" {
+ return currentThemeName === "system" ? detectSystemTheme() : currentThemeName;
+}
+
+function getThemeDefinition(): ThemeDefinition {
+ return THEME_DEFINITIONS[getResolvedThemeName()];
+}
+
+function getAccentHex(): string {
+ if (currentAccentColor === "default") {
+ return getThemeDefinition().textAccent;
+ }
+ return ACCENT_COLORS[currentAccentColor];
+}
+
+export function getThemeOptions(): readonly ThemeName[] {
+ return THEME_OPTIONS;
+}
+
+export function getAccentColorOptions(): readonly AccentColorName[] {
+ return ACCENT_OPTIONS;
+}
+
+export function getCurrentThemeName(): ThemeName {
+ return currentThemeName;
+}
+
+export function getCurrentAccentColor(): AccentColorName {
+ return currentAccentColor;
+}
+
+export function setCurrentThemeName(theme: ThemeName): void {
+ currentThemeName = theme;
+}
+
+export function setCurrentAccentColor(color: AccentColorName): void {
+ currentAccentColor = color;
+}
+
+export const palette = {
+ text: {
+ primary: (value: string) => chalk.hex(getThemeDefinition().textPrimary)(value),
+ secondary: (value: string) => chalk.hex(getThemeDefinition().textSecondary)(value),
+ accent: (value: string) => chalk.hex(getAccentHex())(value),
+ dim: (value: string) => chalk.hex(getThemeDefinition().textDim)(value),
+ },
+ surface: {
+ user: (value: string) =>
+ chalk.bgHex(getThemeDefinition().surfaceUserBg).hex(getThemeDefinition().surfaceUserFg)(
+ value,
+ ),
+ },
+ status: {
+ success: (value: string) => chalk.hex(getThemeDefinition().statusSuccess)(value),
+ error: (value: string) => chalk.hex(getThemeDefinition().statusError)(value),
+ warning: (value: string) => chalk.hex(getThemeDefinition().statusWarning)(value),
+ info: (value: string) => chalk.hex(getThemeDefinition().statusInfo)(value),
+ },
+ diff: {
+ add: (value: string) =>
+ chalk.bgHex(getThemeDefinition().diffAddBg).hex(getThemeDefinition().diffAddFg)(value),
+ remove: (value: string) =>
+ chalk.bgHex(getThemeDefinition().diffRemoveBg).hex(getThemeDefinition().diffRemoveFg)(value),
+ context: (value: string) =>
+ chalk.bgHex(getThemeDefinition().diffContextBg).hex(getThemeDefinition().diffContextFg)(
+ value,
+ ),
+ },
+ border: {
+ panel: (value: string) => chalk.hex(getThemeDefinition().borderPanel)(value),
+ active: (value: string) => chalk.hex(getAccentHex())(value),
+ question: (value: string) => chalk.hex(getThemeDefinition().borderQuestion)(value),
+ },
+};
+
+export const selectListTheme: SelectListTheme = {
+ selectedPrefix: (value: string) => chalk.hex(getAccentHex())(value),
+ selectedText: (value: string) => chalk.bold.hex(getThemeDefinition().textPrimary)(value),
+ description: (value: string) => chalk.hex(getThemeDefinition().textDim)(value),
+ scrollInfo: (value: string) => chalk.hex(getThemeDefinition().textDim)(value),
+ noMatch: (value: string) => chalk.hex(getThemeDefinition().textDim)(value),
+};
+
+export const editorTheme: EditorTheme = {
+ borderColor: (value: string) => chalk.hex(getThemeDefinition().borderPanel)(value),
+ selectList: selectListTheme,
+};
+
+export const markdownTheme: MarkdownTheme = {
+ heading: (value: string) => chalk.bold.hex(getThemeDefinition().markdownHeading)(value),
+ link: (value: string) => chalk.hex(getAccentHex())(value),
+ linkUrl: (value: string) => chalk.hex(getThemeDefinition().textDim)(value),
+ code: (value: string) => chalk.hex(getThemeDefinition().markdownCode)(value),
+ codeBlock: (value: string) => chalk.hex(getThemeDefinition().markdownCodeBlock)(value),
+ codeBlockBorder: (value: string) => chalk.hex(getThemeDefinition().borderPanel)(value),
+ quote: (value: string) => chalk.italic.hex(getThemeDefinition().textDim)(value),
+ quoteBorder: (value: string) => chalk.hex(getThemeDefinition().borderPanel)(value),
+ hr: (value: string) => chalk.hex(getThemeDefinition().borderPanel)(value),
+ listBullet: (value: string) => chalk.hex(getAccentHex())(value),
+ bold: (value: string) => chalk.bold(value),
+ italic: (value: string) => chalk.italic(value),
+ strikethrough: (value: string) => chalk.strikethrough(value),
+ underline: (value: string) => chalk.underline(value),
+};
diff --git a/jiuwenclaw/cli/src/ui/welcome.ts b/jiuwenclaw/cli/src/ui/welcome.ts
new file mode 100644
index 0000000000..69d75208b3
--- /dev/null
+++ b/jiuwenclaw/cli/src/ui/welcome.ts
@@ -0,0 +1,19 @@
+import { padToWidth } from "./rendering/text.js";
+import { palette } from "./theme.js";
+
+export function buildWelcomeLines(width: number): string[] {
+ return [
+ padToWidth(palette.text.secondary("JiuwenClaw CLI"), width),
+ padToWidth(
+ palette.text.dim(
+ "Ask questions, inspect tool output, and drive the session from the terminal.",
+ ),
+ width,
+ ),
+ padToWidth(
+ palette.text.dim("Use /help for commands or /hotkey for keyboard shortcuts."),
+ width,
+ ),
+ " ".repeat(width),
+ ];
+}
diff --git a/jiuwenclaw/cli/tsconfig.json b/jiuwenclaw/cli/tsconfig.json
new file mode 100644
index 0000000000..23b6bbc88e
--- /dev/null
+++ b/jiuwenclaw/cli/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "strict": true,
+ "esModuleInterop": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "declaration": true,
+ "sourceMap": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "lib": ["ES2022"]
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
diff --git a/jiuwenclaw/gateway/channel_manager.py b/jiuwenclaw/gateway/channel_manager.py
index 36bfc704a4..5ccb8caca4 100644
--- a/jiuwenclaw/gateway/channel_manager.py
+++ b/jiuwenclaw/gateway/channel_manager.py
@@ -82,6 +82,10 @@ class ChannelManager(ABC):
self._channels[channel.channel_id] = channel
channel.on_message(on_message)
+ def register_external_channel(self, channel_id: str, channel: Any) -> None:
+ """登记一个已由外部完成入站装配的 channel 实例。"""
+ self._channels[channel_id] = channel
+
def deliver_to_message_handler(self, msg: "Message") -> None:
"""将消息交给 MessageHandler(供自定义入站路径使用)。"""
self._message_handler.handle_message(msg)
diff --git a/jiuwenclaw/gateway/route_binding.py b/jiuwenclaw/gateway/route_binding.py
new file mode 100644
index 0000000000..ccb8cc825c
--- /dev/null
+++ b/jiuwenclaw/gateway/route_binding.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Awaitable, Callable
+
+
+@dataclass
+class GatewayRouteBinding:
+ """统一描述 Gateway 路由及其附加安装动作。"""
+
+ path: str
+ channel_id: str
+ forward_methods: frozenset[str] = frozenset()
+ forward_no_local_handler_methods: frozenset[str] = frozenset()
+ inbound_interceptor: Callable[..., Awaitable[bool]] | None = None
+ outbound_interceptor: Callable[..., Awaitable[bool]] | None = None
+ cleanup_handler: Callable[..., Any] | None = None
+ install: Callable[[Any], None] | None = None
diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.py
index 8a6ed50fbf..0a0bc0dbac 100644
--- a/jiuwenclaw/schema/message.py
+++ b/jiuwenclaw/schema/message.py
@@ -16,6 +16,13 @@ class ReqMethod(Enum):
CHAT_CANCEL = "chat.interrupt"
CHAT_ANSWER = "chat.user_answer"
HISTORY_GET = "history.get"
+ COMMAND_ADD_DIR = "command.add_dir"
+ COMMAND_CHROME = "command.chrome"
+ COMMAND_COMPACT = "command.compact"
+ COMMAND_DIFF = "command.diff"
+ COMMAND_MODEL = "command.model"
+ COMMAND_RESUME = "command.resume"
+ COMMAND_SESSION = "command.session"
CONFIG_GET = "config.get"
CONFIG_SET = "config.set"
diff --git a/tests/system_tests/test_cli_channel_ws.py b/tests/system_tests/test_cli_channel_ws.py
new file mode 100644
index 0000000000..a86637a0b0
--- /dev/null
+++ b/tests/system_tests/test_cli_channel_ws.py
@@ -0,0 +1,167 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""System test for CLI route on GatewayServer."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import websockets
+
+pytestmark = [pytest.mark.integration, pytest.mark.system]
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+def _pick_free_port() -> int:
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ sock.close()
+ return port
+
+
+def _start_process(cmd: list[str], *, env: dict[str, str], log_path: Path) -> subprocess.Popen:
+ log_file = log_path.open("w", encoding="utf-8")
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(REPO_ROOT),
+ env=env,
+ stdout=log_file,
+ stderr=subprocess.STDOUT,
+ text=True,
+ )
+ log_file.close()
+ return proc
+
+
+def _stop_process(proc: subprocess.Popen | None) -> None:
+ if proc is None:
+ return
+ if proc.poll() is not None:
+ try:
+ proc.wait(timeout=1)
+ except subprocess.TimeoutExpired:
+ pass
+ return
+
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ return
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ pass
+
+
+async def _wait_for_log(log_path: Path, needle: str, timeout: float = 30.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ if log_path.exists():
+ text = log_path.read_text(encoding="utf-8", errors="ignore")
+ if needle in text:
+ return
+ await asyncio.sleep(0.2)
+ log_text = (
+ log_path.read_text(encoding="utf-8", errors="ignore")
+ if log_path.exists()
+ else ""
+ )
+ raise AssertionError(
+ f"Timed out waiting for log line: {needle}\nlog={log_text}"
+ )
+
+
+async def _wait_for_websocket_ready(url: str, timeout: float = 30.0) -> None:
+ deadline = asyncio.get_running_loop().time() + timeout
+ last_error: Exception | None = None
+ while asyncio.get_running_loop().time() < deadline:
+ try:
+ async with websockets.connect(url):
+ return
+ except Exception as exc: # noqa: BLE001
+ last_error = exc
+ await asyncio.sleep(0.2)
+ raise AssertionError(
+ f"Timed out waiting for websocket: {url} last_error={last_error}"
+ )
+
+
+async def _recv_until_response(ws, req_id: str, timeout: float = 10.0) -> dict:
+ deadline = asyncio.get_running_loop().time() + timeout
+ while asyncio.get_running_loop().time() < deadline:
+ remaining = max(0.1, deadline - asyncio.get_running_loop().time())
+ frame = json.loads(await asyncio.wait_for(ws.recv(), timeout=remaining))
+ if frame.get("type") == "res" and frame.get("id") == req_id:
+ return frame
+ raise AssertionError(f"Timed out waiting for response id={req_id}")
+
+
+async def test_cli_route_system_roundtrip(temp_home: Path, monkeypatch: pytest.MonkeyPatch):
+ agent_port = _pick_free_port()
+ web_port = _pick_free_port()
+ gateway_port = _pick_free_port()
+
+ env = os.environ.copy()
+ env["HOME"] = str(temp_home)
+ env["AGENT_SERVER_HOST"] = "127.0.0.1"
+ env["AGENT_SERVER_PORT"] = str(agent_port)
+ env["WEB_HOST"] = "127.0.0.1"
+ env["WEB_PORT"] = str(web_port)
+ env["GATEWAY_HOST"] = "127.0.0.1"
+ env["GATEWAY_PORT"] = str(gateway_port)
+
+ agent_log = temp_home / "agentserver.log"
+ gateway_log = temp_home / "gateway.log"
+
+ agent_proc = _start_process(
+ [sys.executable, "-m", "jiuwenclaw.app_agentserver", "--port", str(agent_port)],
+ env=env,
+ log_path=agent_log,
+ )
+ gateway_proc = None
+ try:
+ await _wait_for_log(agent_log, "ready:", timeout=60)
+
+ gateway_proc = _start_process(
+ [sys.executable, "-m", "jiuwenclaw.app_gateway", "--port", str(web_port)],
+ env=env,
+ log_path=gateway_log,
+ )
+ await _wait_for_websocket_ready(
+ f"ws://127.0.0.1:{gateway_port}/cli",
+ timeout=60,
+ )
+
+ async with websockets.connect(f"ws://127.0.0.1:{gateway_port}/cli") as ws:
+ req_chat = {
+ "type": "req",
+ "id": "req-chat",
+ "method": "chat.send",
+ "params": {
+ "session_id": "sess_test",
+ "content": "hello cli",
+ "mode": "plan",
+ },
+ }
+ await ws.send(json.dumps(req_chat, ensure_ascii=False))
+ chat_res = await _recv_until_response(ws, "req-chat", timeout=10)
+ assert chat_res["type"] == "res"
+ assert chat_res["id"] == "req-chat"
+ assert chat_res["ok"] is True
+ assert chat_res["payload"]["accepted"] is True
+ assert chat_res["payload"]["session_id"] == "sess_test"
+ finally:
+ _stop_process(gateway_proc)
+ _stop_process(agent_proc)
diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py
new file mode 100644
index 0000000000..bc21d53454
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py
@@ -0,0 +1,205 @@
+import asyncio
+import json
+
+import pytest
+
+from jiuwenclaw.agentserver import agent_ws_server as agent_ws_server_module
+from jiuwenclaw.schema.agent import AgentRequest
+from jiuwenclaw.schema.message import ReqMethod
+
+
+class FakeWebSocket:
+ def __init__(self):
+ self.sent = []
+
+ async def send(self, payload):
+ self.sent.append(json.loads(payload))
+
+
+class AgentWebSocketServerHarness(agent_ws_server_module.AgentWebSocketServer):
+ async def handle_command_add_dir_for_test(self, ws, request, send_lock):
+ await self._handle_command_add_dir(ws, request, send_lock)
+
+ async def handle_command_compact_for_test(self, ws, request, send_lock):
+ await self._handle_command_compact(ws, request, send_lock)
+
+ async def handle_command_diff_for_test(self, ws, request, send_lock):
+ await self._handle_command_diff(ws, request, send_lock)
+
+ async def handle_command_model_for_test(self, ws, request, send_lock):
+ await self._handle_command_model(ws, request, send_lock)
+
+ async def handle_command_resume_for_test(self, ws, request, send_lock):
+ await self._handle_command_resume(ws, request, send_lock)
+
+ async def handle_command_session_for_test(self, ws, request, send_lock):
+ await self._handle_command_session(ws, request, send_lock)
+
+
+def fake_encode_agent_response_for_wire(resp, response_id):
+ return {
+ "response_id": response_id,
+ "payload": resp.payload,
+ "ok": resp.ok,
+ }
+
+
+def server():
+ return AgentWebSocketServerHarness()
+
+
+def fake_ws():
+ return FakeWebSocket()
+
+
[email protected](autouse=True)
+def patch_wire_encoder(monkeypatch):
+ monkeypatch.setattr(
+ agent_ws_server_module,
+ "encode_agent_response_for_wire",
+ fake_encode_agent_response_for_wire,
+ )
+
+
+async def test_handle_command_add_dir_returns_path_and_remember(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-add-dir",
+ channel_id="cli",
+ req_method=ReqMethod.COMMAND_ADD_DIR,
+ params={"path": "/tmp/demo", "remember": True},
+ )
+
+ await server.handle_command_add_dir_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-add-dir",
+ "payload": {"path": "/tmp/demo", "remember": True},
+ "ok": True,
+ }
+ ]
+
+
+async def test_handle_command_compact_returns_custom_instructions(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-compact",
+ channel_id="cli",
+ req_method=ReqMethod.COMMAND_COMPACT,
+ params={"instructions": "focus on architecture"},
+ )
+
+ await server.handle_command_compact_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-compact",
+ "payload": {"instructions": "focus on architecture"},
+ "ok": True,
+ }
+ ]
+
+
+async def test_handle_command_diff_returns_summary_payload(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-diff",
+ channel_id="cli",
+ req_method=ReqMethod.COMMAND_DIFF,
+ params={},
+ )
+
+ await server.handle_command_diff_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-diff",
+ "payload": {
+ "summary": "Workspace diff preview",
+ "items": [
+ {"label": "files_changed", "value": "3"},
+ {"label": "insertions", "value": "24"},
+ {"label": "deletions", "value": "7"},
+ ],
+ },
+ "ok": True,
+ }
+ ]
+
+
+async def test_handle_command_model_returns_current_and_requested_model(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-model",
+ channel_id="cli",
+ req_method=ReqMethod.COMMAND_MODEL,
+ params={"model": "planner-model"},
+ )
+
+ await server.handle_command_model_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-model",
+ "payload": {
+ "current": "planner-model",
+ "requested": "planner-model",
+ "applied": True,
+ "available": ["default-model", "planner-model", "coder-model"],
+ },
+ "ok": True,
+ }
+ ]
+
+
+async def test_handle_command_resume_returns_mock_session(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-resume",
+ channel_id="cli",
+ req_method=ReqMethod.COMMAND_RESUME,
+ params={"query": "sess_123"},
+ )
+
+ await server.handle_command_resume_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-resume",
+ "payload": {
+ "session_id": "sess_123",
+ "query": "sess_123",
+ "resumed": True,
+ "preview": "Mock resumed conversation",
+ },
+ "ok": True,
+ }
+ ]
+
+
+async def test_handle_command_session_returns_remote_handoff(server, fake_ws):
+ request = AgentRequest(
+ request_id="req-session",
+ channel_id="cli",
+ session_id="sess_demo",
+ req_method=ReqMethod.COMMAND_SESSION,
+ params={},
+ )
+
+ await server.handle_command_session_for_test(fake_ws, request, asyncio.Lock())
+
+ assert fake_ws.sent == [
+ {
+ "response_id": "req-session",
+ "payload": {
+ "session_id": "sess_demo",
+ "remote_url": "https://example.com/session/sess_demo",
+ "qr_text": "session:sess_demo",
+ },
+ "ok": True,
+ }
+ ]
diff --git a/tests/unit_tests/gateway/test_app_gateway_acp.py b/tests/unit_tests/gateway/test_app_gateway_acp.py
index 03c4677824..3370e4eb2b 100644
--- a/tests/unit_tests/gateway/test_app_gateway_acp.py
+++ b/tests/unit_tests/gateway/test_app_gateway_acp.py
@@ -1,9 +1,10 @@
import json
import time
+from typing import Any
import pytest
-from jiuwenclaw.app_gateway import GatewayServer, GatewayServerConfig
+from jiuwenclaw.app_gateway import AcpRouteHandler, GatewayServer, GatewayServerConfig, RouteConfig
from jiuwenclaw.schema.message import EventType, Message, ReqMethod
@@ -27,14 +28,30 @@ class FakeWebSocket:
class GatewayServerProbe(GatewayServer):
- def bind_request_client(self, request_id: str, ws) -> None:
- self._request_to_client[request_id] = ws
+ def __init__(self, config: GatewayServerConfig, router) -> None:
+ super().__init__(config, router)
+ self._probe_on_message = None
- def bind_session_client(self, session_id: str, ws) -> None:
- self._session_to_client[session_id] = ws
+ def on_message(self, callback) -> None:
+ self._probe_on_message = callback
+ super().on_message(callback)
- async def handle_raw_message_public(self, ws, raw: str) -> None:
- await self._handle_raw_message(ws, raw)
+ def bind_request_client(self, request_id: str, ws, *, channel_id: str = "acp") -> None:
+ self._request_to_client[(channel_id, request_id)] = ws
+
+ def bind_session_client(self, session_id: str, ws, *, channel_id: str = "acp") -> None:
+ self._session_to_client[(channel_id, session_id)] = ws
+
+ async def handle_raw_message_public(self, ws, raw: str, *, path: str = "/acp") -> None:
+ await self._handle_raw_message(ws, raw, path, self.config.routes[path])
+
+ async def dispatch_public_message(self, msg: Any) -> bool:
+ if self._probe_on_message is None:
+ return False
+ result = self._probe_on_message(msg)
+ if hasattr(result, "__await__"):
+ result = await result
+ return bool(result)
def build_server() -> GatewayServerProbe:
@@ -42,10 +59,25 @@ def build_server() -> GatewayServerProbe:
enabled=True,
host="127.0.0.1",
port=19001,
- path="/acp",
- channel_id="acp",
+ routes={},
)
- return GatewayServerProbe(config, DummyBus())
+ server = GatewayServerProbe(config, DummyBus())
+ acp_handler = AcpRouteHandler(server.dispatch_public_message)
+ config.routes.update({
+ "/acp": RouteConfig(
+ path="/acp",
+ channel_id="acp",
+ forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),
+ outbound_interceptor=acp_handler.outbound_intercept,
+ inbound_interceptor=acp_handler.inbound_intercept,
+ ),
+ "/cli": RouteConfig(
+ path="/cli",
+ channel_id="cli",
+ forward_methods=frozenset({ReqMethod.CHAT_SEND.value, ReqMethod.HISTORY_GET.value}),
+ ),
+ })
+ return server
@pytest.mark.asyncio
@@ -269,3 +301,38 @@ async def test_gateway_server_handle_raw_message_rejects_unknown_method():
assert frame["id"] == "req-4"
assert frame["ok"] is False
assert frame["error"] == "unknown method: unknown.method"
+
+
+async def test_gateway_server_send_event_routes_same_session_id_by_channel():
+ server = build_server()
+ acp_ws = FakeWebSocket()
+ cli_ws = FakeWebSocket()
+ server.bind_session_client("shared-session", acp_ws, channel_id="acp")
+ server.bind_session_client("shared-session", cli_ws, channel_id="cli")
+
+ await server.send(
+ Message(
+ id="req-cli",
+ type="event",
+ channel_id="cli",
+ session_id="shared-session",
+ params={},
+ timestamp=time.time(),
+ ok=True,
+ payload={"content": "hello cli"},
+ event_type=EventType.CHAT_DELTA,
+ )
+ )
+
+ assert acp_ws.sent_frames == []
+ assert cli_ws.sent_frames == [
+ {
+ "type": "event",
+ "event": "chat.delta",
+ "payload": {
+ "content": "hello cli",
+ "session_id": "shared-session",
+ },
+ }
+ ]
diff --git a/tests/unit_tests/gateway/test_cli_channel_handlers.py b/tests/unit_tests/gateway/test_cli_channel_handlers.py
new file mode 100644
index 0000000000..6cc9308470
--- /dev/null
+++ b/tests/unit_tests/gateway/test_cli_channel_handlers.py
@@ -0,0 +1,82 @@
+import pytest
+
+from jiuwenclaw.channel.cli_channel import (
+ CliHandlersBindParams,
+ CliRouteBindParams,
+ build_cli_route_binding,
+ register_cli_handlers,
+)
+
+
+class FakeGatewayServer:
+ """Fake GatewayServer for testing CLI handler registration."""
+
+ def __init__(self):
+ self.local_handlers: dict[str, dict] = {} # path -> {method: handler}
+ self.responses = []
+
+ def register_local_handler(self, path, method, handler):
+ if path not in self.local_handlers:
+ self.local_handlers[path] = {}
+ self.local_handlers[path][method] = handler
+
+ async def send_response(self, ws, req_id, *, ok, payload=None, error=None, code=None):
+ self.responses.append(
+ {
+ "id": req_id,
+ "ok": ok,
+ "payload": payload or {},
+ "error": error,
+ "code": code,
+ }
+ )
+
+
+async def test_register_cli_handlers_registers_local_methods():
+ server = FakeGatewayServer()
+
+ register_cli_handlers(
+ CliHandlersBindParams(
+ channel=server,
+ agent_client=None,
+ message_handler=None,
+ on_config_saved=None,
+ path="/cli",
+ )
+ )
+
+ cli_handlers = server.local_handlers["/cli"]
+ assert "config.get" in cli_handlers
+ assert "session.list" in cli_handlers
+ assert "chat.send" in cli_handlers
+ assert "history.get" in cli_handlers
+
+ await cli_handlers["chat.send"](object(), "req-1", {}, "sess-1")
+
+ assert server.responses == [
+ {
+ "id": "req-1",
+ "ok": True,
+ "payload": {"accepted": True, "session_id": "sess-1"},
+ "error": None,
+ "code": None,
+ }
+ ]
+
+
+def test_build_cli_route_binding_creates_route_and_install_hook():
+ binding = build_cli_route_binding(CliRouteBindParams(path="/cli"))
+ server = FakeGatewayServer()
+
+ assert binding.path == "/cli"
+ assert binding.channel_id == "cli"
+ assert "chat.send" in binding.forward_methods
+ assert "history.get" in binding.forward_methods
+ assert binding.install is not None
+
+ binding.install(server)
+
+ cli_handlers = server.local_handlers["/cli"]
+ assert "config.get" in cli_handlers
+ assert "chat.send" in cli_handlers