yimo-kit 0.1.0__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.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,643 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-11-10
21
+ """Agent 工具循环、生命周期与档案锁定。
22
+
23
+ 本模块刻意不 import fastmcp:MCP 连接在 ``__aenter__`` 内延迟导入,
24
+ 因此未安装 ``agent`` extra 的环境仍可对循环做纯单测。
25
+ """
26
+
27
+ import asyncio
28
+ import json
29
+ import time
30
+ from collections.abc import Callable, Sequence
31
+ from typing import Any, Literal, Protocol, cast
32
+
33
+ from yimo.kit.ai.agent.approval import (
34
+ ApprovalHook,
35
+ ApprovalRequest,
36
+ DefaultApproval,
37
+ )
38
+ from yimo.kit.ai.agent.errors import (
39
+ AgentEmptyReplyError,
40
+ AgentError,
41
+ AgentModelError,
42
+ AgentTimeoutError,
43
+ AgentTruncatedError,
44
+ ApprovalDeniedError,
45
+ MaxTurnsExceeded,
46
+ ToolExecutionError,
47
+ ToolNotFoundError,
48
+ )
49
+ from yimo.kit.ai.agent.registry import ToolRegistry
50
+ from yimo.kit.ai.agent.session import Session
51
+ from yimo.kit.ai.agent.skill import SkillRegistry
52
+ from yimo.kit.ai.agent.types import (
53
+ AgentResult,
54
+ McpServerConfig,
55
+ ToolCallRecord,
56
+ ToolResult,
57
+ ToolSpec,
58
+ )
59
+ from yimo.kit.ai.exceptions import AIError
60
+ from yimo.kit.ai.messages import ChatReply, Message, ToolCall
61
+ from yimo.kit.config.log_config import get_default_logger
62
+
63
+ __all__ = ["Agent", "ChatLike"]
64
+
65
+ logger = get_default_logger(__name__)
66
+
67
+ # 截断判定:OpenAI 系给 length,部分兼容端点给 max_tokens
68
+ _TRUNCATED_REASONS = frozenset({"length", "max_tokens"})
69
+
70
+ _VALID_ROLES = frozenset({"system", "user", "assistant", "tool"})
71
+
72
+
73
+ class ChatLike(Protocol):
74
+ """Agent 依赖的对话服务最小契约(测试可注入 fake)。"""
75
+
76
+ async def create_with_tools(
77
+ self,
78
+ messages: list[dict[str, Any]],
79
+ tools: Sequence[ToolSpec],
80
+ *,
81
+ deadline: float | None = None,
82
+ ) -> ChatReply:
83
+ """带工具定义的对话。"""
84
+ ...
85
+
86
+
87
+ class Agent:
88
+ """模型驱动的工具循环。
89
+
90
+ 生命周期::
91
+
92
+ async with Agent(skills=..., servers=[...]) as agent:
93
+ result = await agent.run("问题")
94
+ result2 = await agent.run("继续")
95
+
96
+ 同一实例非线程安全,不可并发 ``run()``;并发场景每协程一个实例。
97
+ """
98
+
99
+ def __init__(
100
+ self,
101
+ *,
102
+ tools: ToolRegistry | None = None,
103
+ skills: SkillRegistry | None = None,
104
+ servers: Sequence[McpServerConfig] = (),
105
+ session: Session | None = None,
106
+ system_prompt: str | None = None,
107
+ approval: ApprovalHook | None = None,
108
+ approval_timeout: float = 30.0,
109
+ max_turns: int = 8,
110
+ timeout: float = 120.0,
111
+ tool_timeout: float = 30.0,
112
+ max_tool_result_chars: int = 8000,
113
+ chat: ChatLike | None = None,
114
+ chat_factory: Callable[[str], ChatLike] | None = None,
115
+ model: str | None = None,
116
+ ) -> None:
117
+ if max_turns < 1:
118
+ raise ValueError("max_turns 必须 >= 1")
119
+ if timeout <= 0:
120
+ raise ValueError("timeout 必须 > 0")
121
+ if tool_timeout <= 0:
122
+ raise ValueError("tool_timeout 必须 > 0")
123
+ if approval_timeout <= 0:
124
+ raise ValueError("approval_timeout 必须 > 0")
125
+ if max_tool_result_chars < 1:
126
+ raise ValueError("max_tool_result_chars 必须 >= 1")
127
+ self._tools: ToolRegistry = tools if tools is not None else ToolRegistry()
128
+ self._skills: SkillRegistry | None = skills
129
+ self._servers: tuple[McpServerConfig, ...] = tuple(servers)
130
+ self._system_prompt: str | None = system_prompt or None
131
+ self._approval: ApprovalHook = (
132
+ approval if approval is not None else DefaultApproval()
133
+ )
134
+ self._approval_timeout: float = approval_timeout
135
+ self._max_turns: int = max_turns
136
+ self._timeout: float = timeout
137
+ self._tool_timeout: float = tool_timeout
138
+ self._max_tool_result_chars: int = max_tool_result_chars
139
+ self._chat: ChatLike | None = chat
140
+ self._chat_factory: Callable[[str], ChatLike] | None = chat_factory
141
+ self._model: str | None = model
142
+ self._session: Session = (
143
+ session
144
+ if session is not None
145
+ else Session(self._compose_system_prompt())
146
+ )
147
+
148
+ self._merged: ToolRegistry | None = None
149
+ self._mcp: list[Any] = []
150
+ self._pool: Any = None
151
+ self._failover: Any = None
152
+ self._locked_chat: ChatLike | None = None
153
+ self._owns_chat: bool = False
154
+ self._entered: bool = False
155
+
156
+ # ------------------------------------------------------------------
157
+ # 生命周期
158
+ # ------------------------------------------------------------------
159
+
160
+ async def __aenter__(self) -> "Agent":
161
+ if self._entered:
162
+ raise RuntimeError("Agent 已在上下文中,不可重复进入")
163
+ merged = ToolRegistry()
164
+ for entry in self._tools.entries():
165
+ merged.register(
166
+ entry.spec,
167
+ entry.handler,
168
+ kind=entry.kind,
169
+ approval_target=entry.approval_target,
170
+ replace=True,
171
+ )
172
+ if self._skills is not None:
173
+ for spec, handler in self._skills.tools():
174
+ merged.register(spec, handler, kind="skill_read")
175
+
176
+ mcp_connections: list[Any] = []
177
+ try:
178
+ for config in self._servers:
179
+ connection = await self._open_mcp(config)
180
+ if connection is None:
181
+ continue
182
+ mcp_connections.append(connection)
183
+ for adapter in connection.adapters():
184
+ merged.register(
185
+ adapter.spec,
186
+ adapter,
187
+ kind="mcp_tool",
188
+ approval_target=adapter.spec.name,
189
+ )
190
+ except Exception:
191
+ for connection in reversed(mcp_connections):
192
+ await connection.close()
193
+ raise
194
+
195
+ self._mcp = mcp_connections
196
+ self._merged = merged
197
+ try:
198
+ self._ensure_model_service()
199
+ except Exception:
200
+ for connection in reversed(mcp_connections):
201
+ await connection.close()
202
+ self._mcp = []
203
+ self._merged = None
204
+ raise
205
+ self._entered = True
206
+ return self
207
+
208
+ async def __aexit__(self, *exc_info: object) -> None:
209
+ for connection in reversed(self._mcp):
210
+ await connection.close()
211
+ self._mcp = []
212
+ if self._locked_chat is not None:
213
+ await _close_quietly(self._locked_chat)
214
+ self._locked_chat = None
215
+ if self._pool is not None:
216
+ try:
217
+ await self._pool.close_all()
218
+ except Exception as exc: # noqa: BLE001 - 退出阶段失败不影响主流程
219
+ logger.warning(f"关闭候选池失败: {exc}")
220
+ self._pool = None
221
+ if self._owns_chat and self._chat is not None:
222
+ await _close_quietly(self._chat)
223
+ self._chat = None
224
+ self._owns_chat = False
225
+ self._failover = None
226
+ self._merged = None
227
+ self._entered = False
228
+
229
+ async def _open_mcp(self, config: McpServerConfig) -> Any:
230
+ """打开单个 MCP server;optional 失败时告警并返回 None。"""
231
+ from yimo.kit.ai.agent.mcp import McpConnection
232
+
233
+ connection = McpConnection(config)
234
+ try:
235
+ await connection.open()
236
+ except AgentError as exc:
237
+ await connection.close()
238
+ if config.optional:
239
+ logger.warning(f"MCP server {config.name!r} 连接失败(已跳过): {exc}")
240
+ return None
241
+ raise
242
+ return connection
243
+
244
+ def _ensure_model_service(self) -> None:
245
+ """按需构建模型服务:注入 > 指定档案 > 候选链。"""
246
+ if self._chat is not None or self._failover is not None:
247
+ return
248
+ if self._model is not None:
249
+ from yimo.kit.ai.model_builder import ModelBuilder
250
+
251
+ self._chat = cast(ChatLike, ModelBuilder.build_chat(self._model))
252
+ self._owns_chat = True
253
+ return
254
+ from yimo.kit.ai._internal.failover import FailoverChatService
255
+ from yimo.kit.ai._internal.pool import AIServicePool
256
+
257
+ self._pool = AIServicePool()
258
+ self._failover = FailoverChatService(self._pool)
259
+
260
+ def _compose_system_prompt(self) -> str:
261
+ parts = [self._system_prompt or ""]
262
+ if self._skills is not None:
263
+ parts.append(self._skills.index_block())
264
+ return "\n\n".join(part for part in parts if part)
265
+
266
+ # ------------------------------------------------------------------
267
+ # 入口
268
+ # ------------------------------------------------------------------
269
+
270
+ async def run(
271
+ self,
272
+ question: str,
273
+ *,
274
+ messages: list[Message] | None = None,
275
+ session: Session | None = None,
276
+ ) -> AgentResult:
277
+ """执行一次完整工具循环。
278
+
279
+ Args:
280
+ question: 本轮用户问题;为空串时不追加用户消息
281
+ messages: 外部历史消息(优先级最高,不写入任何 Session)
282
+ session: 外部会话(优先级次之,运行后会写入该 Session)
283
+ """
284
+ self._require_ready()
285
+ prepared, sink = self._prepare_messages(question, messages, session)
286
+ deadline = time.monotonic() + self._timeout
287
+ records: list[ToolCallRecord] = []
288
+ turns = 0
289
+
290
+ for turn in range(1, self._max_turns + 1):
291
+ turns = turn
292
+ started = time.perf_counter()
293
+ reply = await self._call_model(prepared, deadline, turn)
294
+ logger.info(
295
+ f"turn={turn} tool_calls={len(reply.tool_calls)} "
296
+ f"elapsed={time.perf_counter() - started:.2f}s"
297
+ )
298
+ if reply.finish_reason in _TRUNCATED_REASONS:
299
+ raise AgentTruncatedError(
300
+ f"第 {turn} 轮输出被长度截断(finish_reason={reply.finish_reason})"
301
+ )
302
+ if not reply.tool_calls:
303
+ text = reply.content or ""
304
+ if not text.strip():
305
+ raise AgentEmptyReplyError(f"第 {turn} 轮模型既无正文也无工具调用")
306
+ self._append_assistant(prepared, sink, reply)
307
+ return AgentResult(
308
+ text=text,
309
+ messages=[dict(message) for message in prepared],
310
+ turns=turn,
311
+ tool_calls=records,
312
+ stop_reason="completed",
313
+ )
314
+
315
+ if turn >= self._max_turns:
316
+ # 最后一轮不再执行工具:没有余量回灌结果,避免无意义副作用
317
+ raise MaxTurnsExceeded(self._max_turns, turn, records)
318
+ self._append_assistant(prepared, sink, reply)
319
+ for call in reply.tool_calls:
320
+ try:
321
+ record = await self._dispatch_tool_call(call, deadline, turn)
322
+ except ApprovalDeniedError:
323
+ # 会话里补一条拒绝结果,避免留下悬空的 tool_call
324
+ if sink is not None:
325
+ sink.add_tool(call["id"], "[审批拒绝]")
326
+ raise
327
+ records.append(record)
328
+ prepared.append(
329
+ {
330
+ "role": "tool",
331
+ "content": record.result.content,
332
+ "tool_call_id": call["id"],
333
+ }
334
+ )
335
+ if sink is not None:
336
+ sink.add_tool(call["id"], record.result.content)
337
+
338
+ raise MaxTurnsExceeded(self._max_turns, turns, records)
339
+
340
+ async def run_once(
341
+ self,
342
+ question: str,
343
+ *,
344
+ messages: list[Message] | None = None,
345
+ session: Session | None = None,
346
+ ) -> AgentResult:
347
+ """便捷入口:开 → run → 关,仅适合单次任务。"""
348
+ if self._entered:
349
+ raise RuntimeError(
350
+ "Agent 已进入 async with,不能调用 run_once;"
351
+ "请直接 await agent.run(...)"
352
+ )
353
+ async with self:
354
+ return await self.run(question, messages=messages, session=session)
355
+
356
+ def run_sync(
357
+ self,
358
+ question: str,
359
+ *,
360
+ messages: list[Message] | None = None,
361
+ session: Session | None = None,
362
+ timeout: float | None = None,
363
+ ) -> AgentResult:
364
+ """同步上下文执行整轮(含连接建立)。
365
+
366
+ 连接在后台事件循环内创建并销毁;不可与同一实例的 ``async with`` 混用。
367
+ """
368
+ if self._entered:
369
+ raise RuntimeError(
370
+ "Agent 已进入 async with,不能调用 run_sync;"
371
+ "同步上下文请直接用 run_sync,异步上下文请用 async with"
372
+ )
373
+ from yimo.kit.ai.runner import run_sync as _run_sync
374
+
375
+ clone = self._clone()
376
+ budget = timeout if timeout is not None else max(self._timeout + 10.0, 60.0)
377
+ return _run_sync(
378
+ lambda: clone.run_once(question, messages=messages, session=session),
379
+ timeout=budget,
380
+ )
381
+
382
+ def _clone(self) -> "Agent":
383
+ """复制配置(不复制已建立的连接与合并注册表)。"""
384
+ return Agent(
385
+ tools=self._tools,
386
+ skills=self._skills,
387
+ servers=self._servers,
388
+ session=self._session,
389
+ system_prompt=self._system_prompt,
390
+ approval=self._approval,
391
+ approval_timeout=self._approval_timeout,
392
+ max_turns=self._max_turns,
393
+ timeout=self._timeout,
394
+ tool_timeout=self._tool_timeout,
395
+ max_tool_result_chars=self._max_tool_result_chars,
396
+ chat=self._chat,
397
+ chat_factory=self._chat_factory,
398
+ model=self._model,
399
+ )
400
+
401
+ # ------------------------------------------------------------------
402
+ # 消息准备
403
+ # ------------------------------------------------------------------
404
+
405
+ def _require_ready(self) -> ToolRegistry:
406
+ if not self._entered or self._merged is None:
407
+ raise RuntimeError(
408
+ "Agent 未进入上下文:请使用 `async with Agent(...)` "
409
+ "或 `await agent.run_once(...)` / `agent.run_sync(...)`"
410
+ )
411
+ return self._merged
412
+
413
+ def _prepare_messages(
414
+ self,
415
+ question: str,
416
+ messages: list[Message] | None,
417
+ session: Session | None,
418
+ ) -> tuple[list[Message], Session | None]:
419
+ if messages is not None:
420
+ prepared = self._validate_messages(messages)
421
+ sink: Session | None = None
422
+ else:
423
+ target = session if session is not None else self._session
424
+ prepared = self._validate_messages(target.messages())
425
+ sink = target
426
+ index = self._skills.index_block() if self._skills is not None else ""
427
+ prepared = self._inject_system(prepared, index)
428
+ if question:
429
+ prepared.append({"role": "user", "content": question})
430
+ if sink is not None:
431
+ sink.add_user(question)
432
+ return prepared, sink
433
+
434
+ def _validate_messages(self, messages: Sequence[Any]) -> list[Message]:
435
+ if not isinstance(messages, list):
436
+ raise ValueError("messages 必须是 list")
437
+ validated: list[Message] = []
438
+ for index, message in enumerate(messages):
439
+ if not isinstance(message, dict):
440
+ raise ValueError(f"messages[{index}] 必须是 dict")
441
+ role = message.get("role")
442
+ if role not in _VALID_ROLES:
443
+ raise ValueError(f"messages[{index}] 的 role 非法: {role!r}")
444
+ if role in ("system", "user") and not isinstance(
445
+ message.get("content"), str
446
+ ):
447
+ raise ValueError(f"messages[{index}] 缺少字符串 content")
448
+ if role == "tool":
449
+ if not isinstance(message.get("content"), str):
450
+ raise ValueError(f"messages[{index}] 缺少字符串 content")
451
+ if not isinstance(message.get("tool_call_id"), str):
452
+ raise ValueError(f"messages[{index}] 缺少 tool_call_id")
453
+ validated.append(cast(Message, dict(message)))
454
+ return validated
455
+
456
+ def _inject_system(self, messages: list[Message], index: str) -> list[Message]:
457
+ """把技能索引加入 system 消息(已有 system 则追加,否则前插)。"""
458
+ if not index:
459
+ return messages
460
+ if messages and messages[0]["role"] == "system":
461
+ current = messages[0].get("content") or ""
462
+ if index in current:
463
+ return messages
464
+ merged = f"{current}\n\n{index}".strip()
465
+ return cast(
466
+ list[Message],
467
+ [{"role": "system", "content": merged}, *messages[1:]],
468
+ )
469
+ prefix = "\n\n".join(
470
+ part for part in (self._system_prompt or "", index) if part
471
+ )
472
+ return cast(list[Message], [{"role": "system", "content": prefix}, *messages])
473
+
474
+ def _append_assistant(
475
+ self,
476
+ messages: list[Message],
477
+ sink: Session | None,
478
+ reply: ChatReply,
479
+ ) -> None:
480
+ message: dict[str, Any] = {
481
+ "role": "assistant",
482
+ "content": reply.content,
483
+ }
484
+ if reply.tool_calls:
485
+ message["tool_calls"] = reply.tool_calls
486
+ messages.append(cast(Message, message))
487
+ if sink is not None:
488
+ sink.add_assistant(reply.content, reply.tool_calls)
489
+
490
+ # ------------------------------------------------------------------
491
+ # 模型调用与档案锁定
492
+ # ------------------------------------------------------------------
493
+
494
+ async def _call_model(
495
+ self, messages: list[Message], deadline: float, turn: int
496
+ ) -> ChatReply:
497
+ remaining = deadline - time.monotonic()
498
+ if remaining <= 0:
499
+ raise AgentTimeoutError(
500
+ f"第 {turn} 轮开始前整轮预算已耗尽", turn=turn, phase="model"
501
+ )
502
+ service = self._model_service()
503
+ try:
504
+ async with asyncio.timeout(remaining):
505
+ reply = await service.create_with_tools(
506
+ cast(list[dict[str, Any]], messages),
507
+ self._require_ready().specs(),
508
+ deadline=deadline,
509
+ )
510
+ except TimeoutError as exc:
511
+ raise AgentTimeoutError(
512
+ f"第 {turn} 轮模型调用超过整轮预算", turn=turn, phase="model"
513
+ ) from exc
514
+ except AIError as exc:
515
+ raise AgentModelError(f"第 {turn} 轮模型调用失败: {exc}") from exc
516
+ self._lock_profile_after()
517
+ return reply
518
+
519
+ def _model_service(self) -> ChatLike:
520
+ if self._locked_chat is not None:
521
+ return self._locked_chat
522
+ if self._chat is not None:
523
+ return self._chat
524
+ if self._failover is None:
525
+ raise AgentModelError("模型服务未初始化")
526
+ return cast(ChatLike, self._failover)
527
+
528
+ def _lock_profile_after(self) -> None:
529
+ """首轮成功后锁定实际档案;后续轮次不再切候选。"""
530
+ if self._locked_chat is not None:
531
+ return
532
+ if self._failover is None and self._chat_factory is None:
533
+ return
534
+ source = self._failover if self._failover is not None else self._chat
535
+ profile = getattr(source, "last_profile", None)
536
+ if not isinstance(profile, str) or not profile:
537
+ return
538
+ try:
539
+ self._locked_chat = self._build_locked_chat(profile)
540
+ except AIError as exc:
541
+ raise AgentModelError(f"锁定档案 {profile!r} 失败: {exc}") from exc
542
+ logger.info(f"工具循环已锁定档案: {profile}")
543
+
544
+ def _build_locked_chat(self, profile: str) -> ChatLike:
545
+ if self._chat_factory is not None:
546
+ return self._chat_factory(profile)
547
+ from yimo.kit.ai.model_builder import ModelBuilder
548
+
549
+ return cast(ChatLike, ModelBuilder.build_chat(profile))
550
+
551
+ # ------------------------------------------------------------------
552
+ # 工具分发
553
+ # ------------------------------------------------------------------
554
+
555
+ async def _dispatch_tool_call(
556
+ self, call: ToolCall, deadline: float, turn: int
557
+ ) -> ToolCallRecord:
558
+ name = call["function"]["name"]
559
+ raw_arguments = call["function"]["arguments"]
560
+ started = time.perf_counter()
561
+ arguments: dict[str, Any] = {}
562
+ try:
563
+ parsed = json.loads(raw_arguments or "{}")
564
+ except json.JSONDecodeError as exc:
565
+ result = ToolResult(
566
+ content=f"工具参数不是合法 JSON: {exc}", is_error=True
567
+ )
568
+ else:
569
+ if not isinstance(parsed, dict):
570
+ result = ToolResult(content="工具参数必须是 JSON 对象", is_error=True)
571
+ else:
572
+ arguments = parsed
573
+ result = await self._invoke_tool(name, arguments, deadline, turn)
574
+
575
+ result = self._truncate_result(result)
576
+ elapsed = time.perf_counter() - started
577
+ logger.debug(
578
+ f"tool={name} ok={not result.is_error} elapsed={elapsed:.2f}s "
579
+ f"args_keys={len(arguments)} args_chars={len(raw_arguments or '')}"
580
+ )
581
+ return ToolCallRecord(
582
+ name=name, arguments=arguments, result=result, elapsed=elapsed
583
+ )
584
+
585
+ async def _invoke_tool(
586
+ self, name: str, arguments: dict[str, Any], deadline: float, turn: int
587
+ ) -> ToolResult:
588
+ merged = self._require_ready()
589
+ try:
590
+ entry = merged.get(name)
591
+ except ToolNotFoundError:
592
+ return ToolResult(content=f"未知工具: {name}", is_error=True)
593
+
594
+ if entry.kind in ("mcp_tool", "skill_script"):
595
+ request = ApprovalRequest(
596
+ kind=cast(Literal["mcp_tool", "skill_script"], entry.kind),
597
+ target=entry.approval_target or name,
598
+ arguments=arguments,
599
+ )
600
+ try:
601
+ async with asyncio.timeout(self._approval_timeout):
602
+ approved = await self._approval(request)
603
+ except TimeoutError as exc:
604
+ raise ApprovalDeniedError(
605
+ f"审批超时({self._approval_timeout:g}s): {request.target}"
606
+ ) from exc
607
+ if not approved:
608
+ raise ApprovalDeniedError(f"审批拒绝: {request.target}")
609
+
610
+ remaining = deadline - time.monotonic()
611
+ if remaining <= 0:
612
+ raise AgentTimeoutError(
613
+ "工具调用前整轮预算已耗尽", turn=turn, phase="tool"
614
+ )
615
+ budget = min(self._tool_timeout, remaining)
616
+ try:
617
+ async with asyncio.timeout(budget):
618
+ return await merged.call(name, arguments)
619
+ except TimeoutError:
620
+ return ToolResult(
621
+ content=f"[timeout after {budget:g}s]", is_error=True
622
+ )
623
+ except ToolExecutionError as exc:
624
+ return ToolResult(content=str(exc), is_error=True)
625
+
626
+ def _truncate_result(self, result: ToolResult) -> ToolResult:
627
+ if len(result.content) <= self._max_tool_result_chars:
628
+ return result
629
+ return ToolResult(
630
+ content=result.content[: self._max_tool_result_chars] + "\n[truncated]",
631
+ is_error=result.is_error,
632
+ )
633
+
634
+
635
+ async def _close_quietly(service: ChatLike) -> None:
636
+ """关闭服务(若有 close),失败只告警。"""
637
+ close = getattr(service, "close", None)
638
+ if close is None:
639
+ return
640
+ try:
641
+ await close()
642
+ except Exception as exc: # noqa: BLE001 - 关闭阶段失败不影响退出
643
+ logger.warning(f"关闭锁定档案服务失败: {exc}")