kimi-cli 0.44__py3-none-any.whl → 0.46__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of kimi-cli might be problematic. Click here for more details.
- kimi_cli/CHANGELOG.md +23 -0
- kimi_cli/app.py +9 -2
- kimi_cli/cli.py +17 -3
- kimi_cli/config.py +1 -1
- kimi_cli/llm.py +35 -4
- kimi_cli/soul/toolset.py +2 -1
- kimi_cli/tools/__init__.py +13 -10
- kimi_cli/tools/bash/__init__.py +13 -4
- kimi_cli/tools/dmail/__init__.py +3 -3
- kimi_cli/tools/file/glob.py +2 -2
- kimi_cli/tools/file/grep.py +1 -1
- kimi_cli/tools/file/patch.py +38 -8
- kimi_cli/tools/file/read.py +5 -4
- kimi_cli/tools/file/replace.py +2 -2
- kimi_cli/tools/file/write.py +2 -2
- kimi_cli/tools/mcp.py +6 -3
- kimi_cli/tools/task/__init__.py +2 -2
- kimi_cli/tools/web/search.py +2 -2
- kimi_cli/ui/shell/__init__.py +11 -2
- kimi_cli/ui/shell/liveview.py +36 -5
- kimi_cli/ui/shell/visualize.py +7 -3
- kimi_cli/ui/wire/README.md +109 -0
- kimi_cli/ui/wire/__init__.py +340 -0
- kimi_cli/ui/wire/jsonrpc.py +48 -0
- kimi_cli/wire/message.py +89 -2
- {kimi_cli-0.44.dist-info → kimi_cli-0.46.dist-info}/METADATA +3 -2
- {kimi_cli-0.44.dist-info → kimi_cli-0.46.dist-info}/RECORD +29 -26
- {kimi_cli-0.44.dist-info → kimi_cli-0.46.dist-info}/WHEEL +0 -0
- {kimi_cli-0.44.dist-info → kimi_cli-0.46.dist-info}/entry_points.txt +0 -0
kimi_cli/ui/shell/visualize.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
from contextlib import asynccontextmanager, suppress
|
|
3
3
|
|
|
4
|
-
from kosong.base.message import ContentPart, TextPart, ToolCall, ToolCallPart
|
|
4
|
+
from kosong.base.message import ContentPart, TextPart, ThinkPart, ToolCall, ToolCallPart
|
|
5
5
|
from kosong.tooling import ToolResult
|
|
6
6
|
|
|
7
7
|
from kimi_cli.soul import StatusSnapshot
|
|
@@ -42,6 +42,7 @@ async def visualize(
|
|
|
42
42
|
*,
|
|
43
43
|
initial_status: StatusSnapshot,
|
|
44
44
|
cancel_event: asyncio.Event | None = None,
|
|
45
|
+
markdown: bool = True,
|
|
45
46
|
):
|
|
46
47
|
"""
|
|
47
48
|
A loop to consume agent events and visualize the agent behavior.
|
|
@@ -60,7 +61,8 @@ async def visualize(
|
|
|
60
61
|
while True:
|
|
61
62
|
# TODO: Maybe we can always have a StepLiveView here.
|
|
62
63
|
# No need to recreate for each step.
|
|
63
|
-
|
|
64
|
+
LiveView = StepLiveViewWithMarkdown if markdown else StepLiveView
|
|
65
|
+
with LiveView(latest_status, cancel_event) as step:
|
|
64
66
|
async with _keyboard_listener(step):
|
|
65
67
|
# spin the moon at the beginning of each step
|
|
66
68
|
with console.status("", spinner="moon"):
|
|
@@ -78,7 +80,9 @@ async def visualize(
|
|
|
78
80
|
while True:
|
|
79
81
|
match msg:
|
|
80
82
|
case TextPart(text=text):
|
|
81
|
-
step.append_text(text)
|
|
83
|
+
step.append_text(text, mode="text")
|
|
84
|
+
case ThinkPart(think=think):
|
|
85
|
+
step.append_text(think, mode="think")
|
|
82
86
|
case ContentPart():
|
|
83
87
|
# TODO: support more content parts
|
|
84
88
|
step.append_text(f"[{msg.__class__.__name__}]")
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Wire over STDIO
|
|
2
|
+
|
|
3
|
+
Learn how `WireServer` (src/kimi_cli/ui/wire/__init__.py) exposes the Soul runtime over stdio.
|
|
4
|
+
Use this reference when building clients or SDKs.
|
|
5
|
+
|
|
6
|
+
## Transport
|
|
7
|
+
- The server acquires stdio streams via `acp.stdio_streams()` and stays alive until stdin closes.
|
|
8
|
+
- Messages use newline-delimited JSON. Each object must include `"jsonrpc": "2.0"`.
|
|
9
|
+
- Outbound JSON is UTF-8 encoded with compact separators `(",", ":")`.
|
|
10
|
+
|
|
11
|
+
## Lifecycle
|
|
12
|
+
1. A client launches `kimi` (or another entry point) with the wire UI enabled.
|
|
13
|
+
2. `WireServer.run()` spawns a reader loop on stdin and a writer loop draining an internal queue.
|
|
14
|
+
3. Incoming payloads are validated by `JSONRPC_MESSAGE_ADAPTER`; invalid objects only log warnings.
|
|
15
|
+
4. The Soul uses `Wire` (src/kimi_cli/wire/__init__.py); the UI forwards every message as JSON-RPC.
|
|
16
|
+
5. EOF on stdin or a fatal error cancels the Soul, rejects approvals, and closes stdout.
|
|
17
|
+
|
|
18
|
+
## Client → Server calls
|
|
19
|
+
|
|
20
|
+
### `run`
|
|
21
|
+
- Request:
|
|
22
|
+
```json
|
|
23
|
+
{"jsonrpc": "2.0", "id": "<request-id>", "method": "run", "params": {"input": "<prompt>"}}
|
|
24
|
+
```
|
|
25
|
+
`params.prompt` is accepted as an alias for `params.input`.
|
|
26
|
+
- Success results:
|
|
27
|
+
- `{"status": "finished"}` when the run completes.
|
|
28
|
+
- `{"status": "cancelled"}` when either side interrupts.
|
|
29
|
+
- `{"status": "max_steps_reached", "steps": <int>}` when the step limit triggers.
|
|
30
|
+
- Error codes:
|
|
31
|
+
- `-32000`: A run is already in progress.
|
|
32
|
+
- `-32602`: The `input` or `prompt` parameter is missing or not a string.
|
|
33
|
+
- `-32001`: LLM is not configured.
|
|
34
|
+
- `-32002`: The chat provider reported an error.
|
|
35
|
+
- `-32003`: The requested LLM is unsupported.
|
|
36
|
+
- `-32099`: An unhandled exception occurred during the run.
|
|
37
|
+
|
|
38
|
+
### `interrupt`
|
|
39
|
+
- Request:
|
|
40
|
+
```json
|
|
41
|
+
{"jsonrpc": "2.0", "id": "<request-id>", "method": "interrupt", "params": {}}
|
|
42
|
+
```
|
|
43
|
+
The `id` field is optional; omitting it turns the request into a notification.
|
|
44
|
+
- Success results:
|
|
45
|
+
- `{"status": "ok"}` when a running Soul acknowledges the interrupt.
|
|
46
|
+
- `{"status": "idle"}` when no run is active.
|
|
47
|
+
- Interrupt requests never raise protocol errors.
|
|
48
|
+
|
|
49
|
+
## Server → Client traffic
|
|
50
|
+
|
|
51
|
+
### Event notifications
|
|
52
|
+
Events are JSON-RPC notifications with method `event` and no `id`.
|
|
53
|
+
Payloads come from `serialize_event` (src/kimi_cli/wire/message.py):
|
|
54
|
+
- `step_begin`: payload `{"n": <int>}` with the 1-based step counter.
|
|
55
|
+
- `step_interrupted`: no payload; the Soul paused mid-step.
|
|
56
|
+
- `compaction_begin`: no payload; a compaction pass started.
|
|
57
|
+
- `compaction_end`: no payload; always follows `compaction_begin`.
|
|
58
|
+
- `status_update`: payload `{"context_usage": <int>}` from `StatusSnapshot`.
|
|
59
|
+
- `content_part`: JSON object produced by `ContentPart.model_dump(mode="json", exclude_none=True)`.
|
|
60
|
+
- `tool_call`: JSON object produced by `ToolCall.model_dump(mode="json", exclude_none=True)`.
|
|
61
|
+
- `tool_call_part`: JSON object from `ToolCallPart.model_dump(mode="json", exclude_none=True)`.
|
|
62
|
+
- `tool_result`: object with `tool_call_id`, `ok`, and `result` (`output`, `message`, `brief`).
|
|
63
|
+
When `ok` is true the `output` may be text, a JSON object, or an array of JSON objects for
|
|
64
|
+
multi-part content.
|
|
65
|
+
|
|
66
|
+
Event order mirrors Soul execution because the server uses an `asyncio.Queue` for FIFO delivery.
|
|
67
|
+
|
|
68
|
+
### Approval requests
|
|
69
|
+
- Approval prompts use method `request`; their `id` equals the UUID in `ApprovalRequest.id`:
|
|
70
|
+
```json
|
|
71
|
+
{
|
|
72
|
+
"jsonrpc": "2.0",
|
|
73
|
+
"id": "<approval-id>",
|
|
74
|
+
"method": "request",
|
|
75
|
+
"params": {
|
|
76
|
+
"type": "approval",
|
|
77
|
+
"payload": {
|
|
78
|
+
"id": "<approval-id>",
|
|
79
|
+
"tool_call_id": "<tool-call-id>",
|
|
80
|
+
"sender": "<agent>",
|
|
81
|
+
"action": "<action>",
|
|
82
|
+
"description": "<human readable context>"
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
- Clients reply with JSON-RPC success.
|
|
88
|
+
`result.response` must be `approve`, `approve_for_session`, or `reject`:
|
|
89
|
+
```json
|
|
90
|
+
{"jsonrpc": "2.0", "id": "<approval-id>", "result": {"response": "approve"}}
|
|
91
|
+
```
|
|
92
|
+
- Error responses or unknown values are interpreted as rejection.
|
|
93
|
+
- Unanswered approvals are auto-rejected during server shutdown.
|
|
94
|
+
|
|
95
|
+
## Error responses from the server
|
|
96
|
+
Errors follow JSON-RPC semantics.
|
|
97
|
+
The error object includes `code` and `message`.
|
|
98
|
+
Custom codes live in the `-320xx` range.
|
|
99
|
+
Clients should allow an optional `data` field even though the server omits it today.
|
|
100
|
+
|
|
101
|
+
## Shutdown semantics
|
|
102
|
+
- Shutdown cancels runs, stops the writer queue, rejects pending approvals, and closes stdout.
|
|
103
|
+
- EOF on stdout signals process exit; clients can treat it as terminal.
|
|
104
|
+
|
|
105
|
+
## Implementation notes for SDK authors
|
|
106
|
+
- Only one `run` call may execute at a time; queue additional runs client side.
|
|
107
|
+
- The payloads for `content_part`, `tool_call`, and `tool_call_part` already contain JSON objects.
|
|
108
|
+
- Approval handling is synchronous; always send a response even if the user cancels.
|
|
109
|
+
- Logging is verbose for non-stream messages; unknown methods are ignored for forward compatibility.
|
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import contextlib
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Awaitable, Callable
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
import acp # pyright: ignore[reportMissingTypeStubs]
|
|
8
|
+
from kosong.chat_provider import ChatProviderError
|
|
9
|
+
from pydantic import ValidationError
|
|
10
|
+
|
|
11
|
+
from kimi_cli.soul import LLMNotSet, LLMNotSupported, MaxStepsReached, RunCancelled, Soul, run_soul
|
|
12
|
+
from kimi_cli.utils.logging import logger
|
|
13
|
+
from kimi_cli.wire import WireUISide
|
|
14
|
+
from kimi_cli.wire.message import (
|
|
15
|
+
ApprovalRequest,
|
|
16
|
+
ApprovalResponse,
|
|
17
|
+
Event,
|
|
18
|
+
serialize_approval_request,
|
|
19
|
+
serialize_event,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from .jsonrpc import (
|
|
23
|
+
JSONRPC_MESSAGE_ADAPTER,
|
|
24
|
+
JSONRPC_VERSION,
|
|
25
|
+
JSONRPCErrorResponse,
|
|
26
|
+
JSONRPCRequest,
|
|
27
|
+
JSONRPCSuccessResponse,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
_ResultKind = Literal["ok", "error"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _SoulRunner:
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
soul: Soul,
|
|
37
|
+
send_event: Callable[[Event], Awaitable[None]],
|
|
38
|
+
request_approval: Callable[[ApprovalRequest], Awaitable[ApprovalResponse]],
|
|
39
|
+
):
|
|
40
|
+
self._soul = soul
|
|
41
|
+
self._send_event = send_event
|
|
42
|
+
self._request_approval = request_approval
|
|
43
|
+
self._cancel_event: asyncio.Event | None = None
|
|
44
|
+
self._task: asyncio.Task[tuple[_ResultKind, Any]] | None = None
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def is_running(self) -> bool:
|
|
48
|
+
return self._task is not None and not self._task.done()
|
|
49
|
+
|
|
50
|
+
async def run(self, user_input: str) -> tuple[_ResultKind, Any]:
|
|
51
|
+
if self.is_running:
|
|
52
|
+
raise RuntimeError("Soul is already running")
|
|
53
|
+
|
|
54
|
+
self._cancel_event = asyncio.Event()
|
|
55
|
+
self._task = asyncio.create_task(self._run(user_input))
|
|
56
|
+
try:
|
|
57
|
+
return await self._task
|
|
58
|
+
finally:
|
|
59
|
+
self._task = None
|
|
60
|
+
self._cancel_event = None
|
|
61
|
+
|
|
62
|
+
async def interrupt(self) -> None:
|
|
63
|
+
if self._cancel_event is not None:
|
|
64
|
+
self._cancel_event.set()
|
|
65
|
+
|
|
66
|
+
async def shutdown(self) -> None:
|
|
67
|
+
await self.interrupt()
|
|
68
|
+
if self._task is not None:
|
|
69
|
+
self._task.cancel()
|
|
70
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
71
|
+
await self._task
|
|
72
|
+
self._task = None
|
|
73
|
+
self._cancel_event = None
|
|
74
|
+
|
|
75
|
+
async def _run(self, user_input: str) -> tuple[_ResultKind, Any]:
|
|
76
|
+
assert self._cancel_event is not None
|
|
77
|
+
try:
|
|
78
|
+
await run_soul(
|
|
79
|
+
self._soul,
|
|
80
|
+
user_input,
|
|
81
|
+
self._ui_loop,
|
|
82
|
+
self._cancel_event,
|
|
83
|
+
)
|
|
84
|
+
except LLMNotSet:
|
|
85
|
+
return ("error", (-32001, "LLM is not configured"))
|
|
86
|
+
except LLMNotSupported as e:
|
|
87
|
+
return ("error", (-32003, f"LLM not supported: {e}"))
|
|
88
|
+
except ChatProviderError as e:
|
|
89
|
+
return ("error", (-32002, f"LLM provider error: {e}"))
|
|
90
|
+
except MaxStepsReached as e:
|
|
91
|
+
return ("ok", {"status": "max_steps_reached", "steps": e.n_steps})
|
|
92
|
+
except RunCancelled:
|
|
93
|
+
return ("ok", {"status": "cancelled"})
|
|
94
|
+
except asyncio.CancelledError:
|
|
95
|
+
raise
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.exception("Soul run failed:")
|
|
98
|
+
return ("error", (-32099, f"Run failed: {e}"))
|
|
99
|
+
return ("ok", {"status": "finished"})
|
|
100
|
+
|
|
101
|
+
async def _ui_loop(self, wire: WireUISide) -> None:
|
|
102
|
+
while True:
|
|
103
|
+
message = await wire.receive()
|
|
104
|
+
if isinstance(message, ApprovalRequest):
|
|
105
|
+
response = await self._request_approval(message)
|
|
106
|
+
message.resolve(response)
|
|
107
|
+
else:
|
|
108
|
+
# must be Event
|
|
109
|
+
await self._send_event(message)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class WireServer:
|
|
113
|
+
def __init__(self, soul: Soul):
|
|
114
|
+
self._reader: asyncio.StreamReader | None = None
|
|
115
|
+
self._writer: asyncio.StreamWriter | None = None
|
|
116
|
+
self._write_task: asyncio.Task[None] | None = None
|
|
117
|
+
self._send_queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
|
118
|
+
self._pending_requests: dict[str, ApprovalRequest] = {}
|
|
119
|
+
self._runner = _SoulRunner(
|
|
120
|
+
soul,
|
|
121
|
+
send_event=self._send_event,
|
|
122
|
+
request_approval=self._request_approval,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
async def run(self) -> bool:
|
|
126
|
+
logger.info("Starting Wire server on stdio")
|
|
127
|
+
|
|
128
|
+
self._reader, self._writer = await acp.stdio_streams()
|
|
129
|
+
self._write_task = asyncio.create_task(self._write_loop())
|
|
130
|
+
try:
|
|
131
|
+
await self._read_loop()
|
|
132
|
+
finally:
|
|
133
|
+
await self._shutdown()
|
|
134
|
+
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
async def _read_loop(self) -> None:
|
|
138
|
+
assert self._reader is not None
|
|
139
|
+
|
|
140
|
+
while True:
|
|
141
|
+
line = await self._reader.readline()
|
|
142
|
+
if not line:
|
|
143
|
+
logger.info("stdin closed, Wire server exiting")
|
|
144
|
+
break
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
payload = json.loads(line.decode("utf-8"))
|
|
148
|
+
except json.JSONDecodeError:
|
|
149
|
+
logger.warning("Invalid JSON line: {line}", line=line)
|
|
150
|
+
continue
|
|
151
|
+
|
|
152
|
+
await self._dispatch(payload)
|
|
153
|
+
|
|
154
|
+
async def _dispatch(self, payload: dict[str, Any]) -> None:
|
|
155
|
+
version = payload.get("jsonrpc")
|
|
156
|
+
if version != JSONRPC_VERSION:
|
|
157
|
+
logger.warning("Unexpected jsonrpc version: {version}", version=version)
|
|
158
|
+
return
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
message = JSONRPC_MESSAGE_ADAPTER.validate_python(payload)
|
|
162
|
+
except ValidationError as e:
|
|
163
|
+
logger.warning(
|
|
164
|
+
"Ignoring malformed JSON-RPC payload: {message}; error={error}",
|
|
165
|
+
message=payload,
|
|
166
|
+
error=str(e),
|
|
167
|
+
)
|
|
168
|
+
return
|
|
169
|
+
|
|
170
|
+
match message:
|
|
171
|
+
case JSONRPCRequest():
|
|
172
|
+
await self._handle_request(message)
|
|
173
|
+
case JSONRPCSuccessResponse() | JSONRPCErrorResponse():
|
|
174
|
+
await self._handle_response(message)
|
|
175
|
+
|
|
176
|
+
async def _handle_request(self, message: JSONRPCRequest) -> None:
|
|
177
|
+
method = message.method
|
|
178
|
+
msg_id = message.id
|
|
179
|
+
params = message.params
|
|
180
|
+
|
|
181
|
+
if method == "run":
|
|
182
|
+
await self._handle_run(msg_id, params)
|
|
183
|
+
elif method == "interrupt":
|
|
184
|
+
await self._handle_interrupt(msg_id)
|
|
185
|
+
else:
|
|
186
|
+
logger.warning("Unknown method: {method}", method=method)
|
|
187
|
+
if msg_id is not None:
|
|
188
|
+
await self._send_error(msg_id, -32601, f"Unknown method: {method}")
|
|
189
|
+
|
|
190
|
+
async def _handle_response(
|
|
191
|
+
self,
|
|
192
|
+
message: JSONRPCSuccessResponse | JSONRPCErrorResponse,
|
|
193
|
+
) -> None:
|
|
194
|
+
msg_id = message.id
|
|
195
|
+
if msg_id is None:
|
|
196
|
+
logger.warning("Response without id: {message}", message=message.model_dump())
|
|
197
|
+
return
|
|
198
|
+
|
|
199
|
+
pending = self._pending_requests.get(msg_id)
|
|
200
|
+
if pending is None:
|
|
201
|
+
logger.warning("No pending request for response id={id}", id=msg_id)
|
|
202
|
+
return
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
if isinstance(message, JSONRPCErrorResponse):
|
|
206
|
+
pending.resolve(ApprovalResponse.REJECT)
|
|
207
|
+
else:
|
|
208
|
+
response = self._parse_approval_response(message.result)
|
|
209
|
+
pending.resolve(response)
|
|
210
|
+
finally:
|
|
211
|
+
self._pending_requests.pop(msg_id, None)
|
|
212
|
+
|
|
213
|
+
async def _handle_run(self, msg_id: Any, params: dict[str, Any]) -> None:
|
|
214
|
+
if msg_id is None:
|
|
215
|
+
logger.warning("Run notification ignored")
|
|
216
|
+
return
|
|
217
|
+
|
|
218
|
+
if self._runner.is_running:
|
|
219
|
+
await self._send_error(msg_id, -32000, "Run already in progress")
|
|
220
|
+
return
|
|
221
|
+
|
|
222
|
+
user_input = params.get("input")
|
|
223
|
+
if not isinstance(user_input, str):
|
|
224
|
+
user_input = params.get("prompt")
|
|
225
|
+
if not isinstance(user_input, str):
|
|
226
|
+
await self._send_error(msg_id, -32602, "`input` (or `prompt`) must be a string")
|
|
227
|
+
return
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
kind, payload = await self._runner.run(user_input)
|
|
231
|
+
except RuntimeError:
|
|
232
|
+
await self._send_error(msg_id, -32000, "Run already in progress")
|
|
233
|
+
return
|
|
234
|
+
|
|
235
|
+
if kind == "error":
|
|
236
|
+
code, message = payload
|
|
237
|
+
await self._send_error(msg_id, code, message)
|
|
238
|
+
else:
|
|
239
|
+
await self._send_response(msg_id, payload)
|
|
240
|
+
|
|
241
|
+
async def _handle_interrupt(self, msg_id: Any) -> None:
|
|
242
|
+
if not self._runner.is_running:
|
|
243
|
+
if msg_id is not None:
|
|
244
|
+
await self._send_response(msg_id, {"status": "idle"})
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
await self._runner.interrupt()
|
|
248
|
+
if msg_id is not None:
|
|
249
|
+
await self._send_response(msg_id, {"status": "ok"})
|
|
250
|
+
|
|
251
|
+
async def _send_event(self, event: Event) -> None:
|
|
252
|
+
await self._send_notification("event", serialize_event(event))
|
|
253
|
+
|
|
254
|
+
async def _request_approval(self, request: ApprovalRequest) -> ApprovalResponse:
|
|
255
|
+
self._pending_requests[request.id] = request
|
|
256
|
+
|
|
257
|
+
await self._send_request(
|
|
258
|
+
request.id,
|
|
259
|
+
"request",
|
|
260
|
+
{"type": "approval", "payload": serialize_approval_request(request)},
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
try:
|
|
264
|
+
return await request.wait()
|
|
265
|
+
finally:
|
|
266
|
+
self._pending_requests.pop(request.id, None)
|
|
267
|
+
|
|
268
|
+
def _parse_approval_response(self, result: dict[str, Any]) -> ApprovalResponse:
|
|
269
|
+
value = result.get("response")
|
|
270
|
+
try:
|
|
271
|
+
if isinstance(value, ApprovalResponse):
|
|
272
|
+
return value
|
|
273
|
+
return ApprovalResponse(str(value))
|
|
274
|
+
except ValueError:
|
|
275
|
+
logger.warning("Unknown approval response: {value}", value=value)
|
|
276
|
+
return ApprovalResponse.REJECT
|
|
277
|
+
|
|
278
|
+
async def _write_loop(self) -> None:
|
|
279
|
+
assert self._writer is not None
|
|
280
|
+
|
|
281
|
+
try:
|
|
282
|
+
while True:
|
|
283
|
+
try:
|
|
284
|
+
payload = await self._send_queue.get()
|
|
285
|
+
except asyncio.QueueShutDown:
|
|
286
|
+
logger.debug("Send queue shut down, stopping Wire server write loop")
|
|
287
|
+
break
|
|
288
|
+
data = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
|
289
|
+
self._writer.write(data.encode("utf-8") + b"\n")
|
|
290
|
+
await self._writer.drain()
|
|
291
|
+
except asyncio.CancelledError:
|
|
292
|
+
raise
|
|
293
|
+
except Exception:
|
|
294
|
+
logger.exception("Wire server write loop error:")
|
|
295
|
+
raise
|
|
296
|
+
|
|
297
|
+
async def _send_notification(self, method: str, params: Any) -> None:
|
|
298
|
+
await self._enqueue_payload(
|
|
299
|
+
{"jsonrpc": JSONRPC_VERSION, "method": method, "params": params}
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
async def _send_request(self, msg_id: Any, method: str, params: Any) -> None:
|
|
303
|
+
await self._enqueue_payload(
|
|
304
|
+
{"jsonrpc": JSONRPC_VERSION, "id": msg_id, "method": method, "params": params}
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
async def _send_response(self, msg_id: Any, result: Any) -> None:
|
|
308
|
+
await self._enqueue_payload({"jsonrpc": JSONRPC_VERSION, "id": msg_id, "result": result})
|
|
309
|
+
|
|
310
|
+
async def _send_error(self, msg_id: Any, code: int, message: str) -> None:
|
|
311
|
+
await self._enqueue_payload(
|
|
312
|
+
{"jsonrpc": JSONRPC_VERSION, "id": msg_id, "error": {"code": code, "message": message}}
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
async def _enqueue_payload(self, payload: dict[str, Any]) -> None:
|
|
316
|
+
try:
|
|
317
|
+
await self._send_queue.put(payload)
|
|
318
|
+
except asyncio.QueueShutDown:
|
|
319
|
+
logger.debug("Send queue shut down; dropping payload: {payload}", payload=payload)
|
|
320
|
+
|
|
321
|
+
async def _shutdown(self) -> None:
|
|
322
|
+
await self._runner.shutdown()
|
|
323
|
+
self._send_queue.shutdown()
|
|
324
|
+
|
|
325
|
+
if self._write_task is not None:
|
|
326
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
327
|
+
await self._write_task
|
|
328
|
+
|
|
329
|
+
for request in self._pending_requests.values():
|
|
330
|
+
if not request.resolved:
|
|
331
|
+
request.resolve(ApprovalResponse.REJECT)
|
|
332
|
+
self._pending_requests.clear()
|
|
333
|
+
|
|
334
|
+
if self._writer is not None:
|
|
335
|
+
self._writer.close()
|
|
336
|
+
with contextlib.suppress(Exception):
|
|
337
|
+
await self._writer.wait_closed()
|
|
338
|
+
self._writer = None
|
|
339
|
+
|
|
340
|
+
self._reader = None
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from typing import Any, Literal
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter
|
|
4
|
+
|
|
5
|
+
JSONRPC_VERSION = "2.0"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class _MessageBase(BaseModel):
|
|
9
|
+
jsonrpc: Literal["2.0"]
|
|
10
|
+
|
|
11
|
+
model_config = ConfigDict(extra="forbid")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class JSONRPCRequest(_MessageBase):
|
|
15
|
+
method: str
|
|
16
|
+
id: str | None = None
|
|
17
|
+
params: dict[str, Any] = Field(default_factory=dict)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _ResponseBase(_MessageBase):
|
|
21
|
+
id: str | None
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class JSONRPCSuccessResponse(_ResponseBase):
|
|
25
|
+
result: dict[str, Any]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class JSONRPCErrorObject(BaseModel):
|
|
29
|
+
code: int
|
|
30
|
+
message: str
|
|
31
|
+
data: Any | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class JSONRPCErrorResponse(_ResponseBase):
|
|
35
|
+
error: JSONRPCErrorObject
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
JSONRPCMessage = JSONRPCRequest | JSONRPCSuccessResponse | JSONRPCErrorResponse
|
|
39
|
+
JSONRPC_MESSAGE_ADAPTER = TypeAdapter[JSONRPCMessage](JSONRPCMessage)
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"JSONRPCRequest",
|
|
43
|
+
"JSONRPCSuccessResponse",
|
|
44
|
+
"JSONRPCErrorObject",
|
|
45
|
+
"JSONRPCErrorResponse",
|
|
46
|
+
"JSONRPCMessage",
|
|
47
|
+
"JSONRPC_MESSAGE_ADAPTER",
|
|
48
|
+
]
|
kimi_cli/wire/message.py
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import uuid
|
|
3
|
+
from collections.abc import Sequence
|
|
3
4
|
from enum import Enum
|
|
4
|
-
from typing import TYPE_CHECKING, NamedTuple
|
|
5
|
+
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
5
6
|
|
|
6
7
|
from kosong.base.message import ContentPart, ToolCall, ToolCallPart
|
|
7
|
-
from kosong.tooling import ToolResult
|
|
8
|
+
from kosong.tooling import ToolOk, ToolResult
|
|
8
9
|
|
|
9
10
|
if TYPE_CHECKING:
|
|
10
11
|
from kimi_cli.soul import StatusSnapshot
|
|
@@ -89,3 +90,89 @@ class ApprovalRequest:
|
|
|
89
90
|
|
|
90
91
|
|
|
91
92
|
type WireMessage = Event | ApprovalRequest
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def serialize_event(event: Event) -> dict[str, Any]:
|
|
96
|
+
"""
|
|
97
|
+
Convert an event message into a JSON-serializable dictionary.
|
|
98
|
+
"""
|
|
99
|
+
match event:
|
|
100
|
+
case StepBegin():
|
|
101
|
+
return {"type": "step_begin", "payload": {"n": event.n}}
|
|
102
|
+
case StepInterrupted():
|
|
103
|
+
return {"type": "step_interrupted"}
|
|
104
|
+
case CompactionBegin():
|
|
105
|
+
return {"type": "compaction_begin"}
|
|
106
|
+
case CompactionEnd():
|
|
107
|
+
return {"type": "compaction_end"}
|
|
108
|
+
case StatusUpdate():
|
|
109
|
+
return {
|
|
110
|
+
"type": "status_update",
|
|
111
|
+
"payload": {"context_usage": event.status.context_usage},
|
|
112
|
+
}
|
|
113
|
+
case ContentPart():
|
|
114
|
+
return {
|
|
115
|
+
"type": "content_part",
|
|
116
|
+
"payload": event.model_dump(mode="json", exclude_none=True),
|
|
117
|
+
}
|
|
118
|
+
case ToolCall():
|
|
119
|
+
return {
|
|
120
|
+
"type": "tool_call",
|
|
121
|
+
"payload": event.model_dump(mode="json", exclude_none=True),
|
|
122
|
+
}
|
|
123
|
+
case ToolCallPart():
|
|
124
|
+
return {
|
|
125
|
+
"type": "tool_call_part",
|
|
126
|
+
"payload": event.model_dump(mode="json", exclude_none=True),
|
|
127
|
+
}
|
|
128
|
+
case ToolResult():
|
|
129
|
+
return {
|
|
130
|
+
"type": "tool_result",
|
|
131
|
+
"payload": serialize_tool_result(event),
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def serialize_approval_request(request: ApprovalRequest) -> dict[str, Any]:
|
|
136
|
+
"""
|
|
137
|
+
Convert an ApprovalRequest into a JSON-serializable dictionary.
|
|
138
|
+
"""
|
|
139
|
+
return {
|
|
140
|
+
"id": request.id,
|
|
141
|
+
"tool_call_id": request.tool_call_id,
|
|
142
|
+
"sender": request.sender,
|
|
143
|
+
"action": request.action,
|
|
144
|
+
"description": request.description,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def serialize_tool_result(result: ToolResult) -> dict[str, Any]:
|
|
149
|
+
if isinstance(result.result, ToolOk):
|
|
150
|
+
ok = True
|
|
151
|
+
result_data = {
|
|
152
|
+
"output": _serialize_tool_output(result.result.output),
|
|
153
|
+
"message": result.result.message,
|
|
154
|
+
"brief": result.result.brief,
|
|
155
|
+
}
|
|
156
|
+
else:
|
|
157
|
+
ok = False
|
|
158
|
+
result_data = {
|
|
159
|
+
"output": result.result.output,
|
|
160
|
+
"message": result.result.message,
|
|
161
|
+
"brief": result.result.brief,
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
"tool_call_id": result.tool_call_id,
|
|
165
|
+
"ok": ok,
|
|
166
|
+
"result": result_data,
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _serialize_tool_output(
|
|
171
|
+
output: str | ContentPart | Sequence[ContentPart],
|
|
172
|
+
) -> str | list[Any] | dict[str, Any]:
|
|
173
|
+
if isinstance(output, str):
|
|
174
|
+
return output
|
|
175
|
+
elif isinstance(output, ContentPart):
|
|
176
|
+
return output.model_dump(mode="json", exclude_none=True)
|
|
177
|
+
else: # Sequence[ContentPart]
|
|
178
|
+
return [part.model_dump(mode="json", exclude_none=True) for part in output]
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.3
|
|
2
2
|
Name: kimi-cli
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.46
|
|
4
4
|
Summary: Kimi CLI is your next CLI agent.
|
|
5
5
|
Requires-Dist: agent-client-protocol==0.6.2
|
|
6
6
|
Requires-Dist: aiofiles==25.1.0
|
|
7
7
|
Requires-Dist: aiohttp==3.13.2
|
|
8
8
|
Requires-Dist: click==8.3.0
|
|
9
|
-
Requires-Dist: kosong==0.
|
|
9
|
+
Requires-Dist: kosong==0.17.0
|
|
10
10
|
Requires-Dist: loguru==0.7.3
|
|
11
11
|
Requires-Dist: patch-ng==1.19.0
|
|
12
12
|
Requires-Dist: prompt-toolkit==3.0.52
|
|
@@ -29,6 +29,7 @@ Description-Content-Type: text/markdown
|
|
|
29
29
|
[](https://github.com/MoonshotAI/kimi-cli/actions)
|
|
30
30
|
[](https://pypi.org/project/kimi-cli/)
|
|
31
31
|
[](https://pypistats.org/packages/kimi-cli)
|
|
32
|
+
[](https://deepwiki.com/MoonshotAI/kimi-cli)
|
|
32
33
|
|
|
33
34
|
[中文](https://www.kimi.com/coding/docs/kimi-cli.html)
|
|
34
35
|
|