源码: conversation.rs:170-283
(
self,
user_input: str,
prompter: Optional[PermissionPrompter] = None,
)
| 326 | # -------------------------------------------------------- |
| 327 | |
| 328 | def run_turn( |
| 329 | self, |
| 330 | user_input: str, |
| 331 | prompter: Optional[PermissionPrompter] = None, |
| 332 | ) -> TurnSummary: |
| 333 | """源码: conversation.rs:170-283""" |
| 334 | # 推入用户消息 — conversation.rs:175-176 |
| 335 | self._session.messages.append(Message.user_text(user_input)) |
| 336 | |
| 337 | assistant_messages: list[Message] = [] |
| 338 | tool_results: list[Message] = [] |
| 339 | iterations = 0 |
| 340 | |
| 341 | # ===== 主循环 ===== |
| 342 | while True: |
| 343 | iterations += 1 |
| 344 | if iterations > self._max_iterations: |
| 345 | raise RuntimeError( |
| 346 | "conversation loop exceeded the maximum number of iterations" |
| 347 | ) |
| 348 | |
| 349 | # 调 API — conversation.rs:191-195 |
| 350 | events = self._api_client.stream( |
| 351 | self._system_prompt, |
| 352 | self._session.messages, |
| 353 | ) |
| 354 | |
| 355 | # 事件流 → 结构化消息 — conversation.rs:196 |
| 356 | assistant_message, usage = build_assistant_message(events) |
| 357 | |
| 358 | if usage is not None: |
| 359 | self._usage_tracker.record(usage) |
| 360 | |
| 361 | # 提取 tool_use blocks — conversation.rs:200-209 |
| 362 | pending_tool_uses: list[tuple[str, str, str]] = [] |
| 363 | for block in assistant_message.content: |
| 364 | if isinstance(block, ToolContentBlock): |
| 365 | pending_tool_uses.append( |
| 366 | (block.id, block.name, block.input) |
| 367 | ) |
| 368 | |
| 369 | # 推入 session — conversation.rs:211 |
| 370 | self._session.messages.append(assistant_message) |
| 371 | assistant_messages.append(assistant_message) |
| 372 | |
| 373 | # 没有 tool_use → 结束 — conversation.rs:214-216 |
| 374 | if not pending_tool_uses: |
| 375 | break |
| 376 | |
| 377 | # 对每个 tool_use 执行 — conversation.rs:218-271 |
| 378 | for tool_use_id, tool_name, tool_input in pending_tool_uses: |
| 379 | result_message = self._process_tool_use( |
| 380 | tool_use_id, tool_name, tool_input, prompter, |
| 381 | ) |
| 382 | self._session.messages.append(result_message) |
| 383 | tool_results.append(result_message) |
| 384 | |
| 385 | # 自动压缩 — conversation.rs:274 |
no test coverage detected