Skip to content
This repository was archived by the owner on Sep 23, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/kimi_cli/ui/print/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
ChatProviderError,
)
from kosong.message import Message
from rich import print

from kimi_cli.background.models import is_terminal_status
from kimi_cli.cli import ExitCode, InputFormat, OutputFormat
Expand All @@ -28,6 +27,7 @@
run_soul,
)
from kimi_cli.soul.kimisoul import KimiSoul
from kimi_cli.ui.print.output import safe_rich_print
from kimi_cli.ui.print.visualize import visualize
from kimi_cli.utils.logging import logger, open_original_stderr
from kimi_cli.utils.signals import install_sigint_handler
Expand Down Expand Up @@ -88,7 +88,7 @@ def _handler():
if command:
logger.info("Running agent with command: {command}", command=command)
if self.output_format == "text" and not self.final_only:
print(command)
safe_rich_print(command)
runtime = self.soul.runtime if isinstance(self.soul, KimiSoul) else None
await run_soul(
self.soul,
Expand Down Expand Up @@ -409,27 +409,27 @@ def _handler():
command = None
except LLMNotSet as e:
logger.exception("LLM not set:")
print(str(e))
safe_rich_print(str(e))
return ExitCode.FAILURE
except LLMNotSupported as e:
logger.exception("LLM not supported:")
print(str(e))
safe_rich_print(str(e))
return ExitCode.FAILURE
except ChatProviderError as e:
logger.exception("LLM provider error:")
print(str(e))
safe_rich_print(str(e))
return self._classify_provider_error(e)
except MaxStepsReached as e:
logger.warning("Max steps reached: {n_steps}", n_steps=e.n_steps)
print(str(e))
safe_rich_print(str(e))
return ExitCode.FAILURE
except RunCancelled:
logger.error("Interrupted by user")
print("Interrupted by user")
safe_rich_print("Interrupted by user")
return ExitCode.FAILURE
except BaseException as e:
logger.exception("Unknown error:")
print(f"Unknown error: {e}")
safe_rich_print(f"Unknown error: {e}")
raise
finally:
remove_sigint()
Expand Down
44 changes: 44 additions & 0 deletions src/kimi_cli/ui/print/output.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import builtins
import sys
from typing import Any, TextIO, cast

from rich.console import Console


def _encode_for_stream(text: str, stream: TextIO) -> str:
encoding = getattr(stream, "encoding", None)
if encoding is None:
return text

try:
return text.encode(encoding, errors="replace").decode(encoding, errors="replace")
except (LookupError, UnicodeError):
return text.encode("ascii", errors="replace").decode("ascii")


class EncodingSafeStream:
def __init__(self, stream: TextIO) -> None:
self._stream = stream

@property
def encoding(self) -> str | None:
return getattr(self._stream, "encoding", None)

def write(self, text: str) -> int:
return self._stream.write(_encode_for_stream(text, self._stream))

def flush(self) -> None:
self._stream.flush()

def __getattr__(self, name: str) -> Any:
return getattr(self._stream, name)


def safe_print(text: str) -> None:
"""Print text while replacing characters unsupported by stdout's encoding."""
builtins.print(_encode_for_stream(text, sys.stdout), flush=True)


def safe_rich_print(text: str) -> None:
"""Render Rich text through the same encoding-safe stdout as visualizers."""
Console(file=cast(TextIO, EncodingSafeStream(sys.stdout))).print(text)
21 changes: 12 additions & 9 deletions src/kimi_cli/ui/print/visualize.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from typing import Protocol
import sys
from typing import Protocol, TextIO, cast

import rich
from kosong.message import Message
from rich.console import Console

from kimi_cli.cli import OutputFormat
from kimi_cli.soul.message import tool_result_to_message
from kimi_cli.ui.print.output import EncodingSafeStream, safe_print
from kimi_cli.utils.aioqueue import QueueShutDown
from kimi_cli.wire import Wire
from kimi_cli.wire.types import (
Expand Down Expand Up @@ -33,7 +35,8 @@ def _merge_content(buffer: list[ContentPart], part: ContentPart) -> None:

class TextPrinter(Printer):
def feed(self, msg: WireMessage) -> None:
rich.print(msg)
safe_stream = cast(TextIO, EncodingSafeStream(sys.stdout))
Console(file=safe_stream).print(msg)

def flush(self) -> None:
pass
Expand Down Expand Up @@ -77,11 +80,11 @@ def feed(self, msg: WireMessage) -> None:
self._flush_assistant_message()
self._flush_notifications()
message = tool_result_to_message(result)
print(message.model_dump_json(exclude_none=True), flush=True)
safe_print(message.model_dump_json(exclude_none=True))
case PlanDisplay() as plan:
self._flush_assistant_message()
self._flush_notifications()
print(plan.model_dump_json(exclude_none=True), flush=True)
safe_print(plan.model_dump_json(exclude_none=True))
case _:
# ignore other messages
pass
Expand All @@ -100,14 +103,14 @@ def _flush_assistant_message(self) -> None:
content=self._content_buffer,
tool_calls=self._tool_call_buffer or None,
)
print(message.model_dump_json(exclude_none=True), flush=True)
safe_print(message.model_dump_json(exclude_none=True))

self._content_buffer.clear()
self._tool_call_buffer.clear()
self._last_tool_call = None

def _emit_notification(self, notification: Notification) -> None:
print(notification.model_dump_json(exclude_none=True), flush=True)
safe_print(notification.model_dump_json(exclude_none=True))

def _flush_notifications(self) -> None:
for notification in self._pending_notifications:
Expand Down Expand Up @@ -138,7 +141,7 @@ def flush(self) -> None:
message = Message(role="assistant", content=self._content_buffer)
text = message.extract_text()
if text:
print(text, flush=True)
safe_print(text)
self._content_buffer.clear()


Expand All @@ -162,7 +165,7 @@ def flush(self) -> None:
text = message.extract_text()
if text:
final_message = Message(role="assistant", content=text)
print(final_message.model_dump_json(exclude_none=True), flush=True)
safe_print(final_message.model_dump_json(exclude_none=True))
self._content_buffer.clear()


Expand Down
100 changes: 100 additions & 0 deletions tests/ui_and_conv/test_print_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Regression tests for print-mode output on legacy stdout encodings."""

from __future__ import annotations

import io
import json
import sys
from pathlib import Path
from unittest.mock import AsyncMock

import pytest
from kosong.chat_provider import APIConnectionError, ChatProviderError

from kimi_cli.cli import ExitCode
from kimi_cli.ui.print import Print
from kimi_cli.ui.print.visualize import JsonPrinter, TextPrinter
from kimi_cli.wire.types import TextPart


class _StrictEncodingStream(io.StringIO):
encoding = "gbk"

def write(self, text: str) -> int:
text.encode(self.encoding)
return super().write(text)


def test_json_printer_replaces_characters_unsupported_by_stdout(monkeypatch) -> None:
stream = _StrictEncodingStream()
monkeypatch.setattr(sys, "stdout", stream)

printer = JsonPrinter()
printer.feed(TextPart(text="model output \u0133"))
printer.flush()

output = stream.getvalue()
output.encode(stream.encoding)
payload = json.loads(output)
assert payload["content"] == "model output ?"


def test_text_printer_replaces_characters_unsupported_by_stdout(monkeypatch) -> None:
stream = _StrictEncodingStream()
monkeypatch.setattr(sys, "stdout", stream)

TextPrinter().feed(TextPart(text="model output \u0133"))

output = stream.getvalue()
output.encode(stream.encoding)
assert "model output ?" in output


@pytest.mark.asyncio
async def test_print_run_echo_replaces_unsupported_characters(monkeypatch, tmp_path: Path) -> None:
stream = _StrictEncodingStream()
monkeypatch.setattr(sys, "stdout", stream)
run_soul = AsyncMock()
monkeypatch.setattr("kimi_cli.ui.print.run_soul", run_soul)
app = Print(AsyncMock(), "text", "text", tmp_path / "context.json")

assert await app.run("explain \U0001f9ea 中文") == ExitCode.SUCCESS

run_soul.assert_awaited_once()
assert "explain ? 中文" in stream.getvalue()


@pytest.mark.asyncio
@pytest.mark.parametrize(
("error", "exit_code"),
[
(ChatProviderError("provider \U0001f9ea 中文"), ExitCode.FAILURE),
(APIConnectionError("connection \U0001f9ea 中文"), ExitCode.RETRYABLE),
],
)
async def test_print_run_error_replaces_unsupported_characters(
monkeypatch, tmp_path: Path, error: ChatProviderError, exit_code: int
) -> None:
stream = _StrictEncodingStream()
monkeypatch.setattr(sys, "stdout", stream)
monkeypatch.setattr("kimi_cli.ui.print.run_soul", AsyncMock(side_effect=error))
app = Print(AsyncMock(), "text", "text", tmp_path / "context.json")

assert await app.run("hello") == exit_code
assert "? 中文" in stream.getvalue()


@pytest.mark.asyncio
async def test_print_run_unknown_error_preserves_original_exception(
monkeypatch, tmp_path: Path
) -> None:
stream = _StrictEncodingStream()
monkeypatch.setattr(sys, "stdout", stream)
error = RuntimeError("unexpected \U0001f9ea 中文")
monkeypatch.setattr("kimi_cli.ui.print.run_soul", AsyncMock(side_effect=error))
app = Print(AsyncMock(), "text", "text", tmp_path / "context.json")

with pytest.raises(RuntimeError) as caught:
await app.run("hello")
assert caught.value is error
assert "Unknown error: unexpected ? 中文" in stream.getvalue()