@hfyjq/crannia 1.1.1 → 1.2.0

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 (306) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +48 -45
  3. package/README.md +1 -1
  4. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  5. package/THIRD-PARTY-PYTHON-linux.md +174 -0
  6. package/THIRD-PARTY-PYTHON.md +176 -162
  7. package/THIRD-PARTY.md +323 -316
  8. package/apps/desktop/quotes.txt +56 -56
  9. package/bus/core.py +677 -671
  10. package/bus/loaders/channel_loader.py +64 -64
  11. package/bus/loaders/provider_loader.py +4 -7
  12. package/bus/loaders/skill_loader.py +46 -27
  13. package/bus/loaders/skill_md.py +9 -9
  14. package/bus/mcp_disabled.py +4 -6
  15. package/bus/quarantine.py +10 -13
  16. package/bus/registry.py +2315 -2284
  17. package/bus/skill_state.py +124 -124
  18. package/channels/cli_channel/handler.py +3 -3
  19. package/channels/cli_channel/manifest.yaml +5 -5
  20. package/channels/dingtalk_channel/handler.py +32 -32
  21. package/channels/dingtalk_channel/manifest.yaml +12 -12
  22. package/channels/feishu_channel/handler.py +33 -33
  23. package/channels/feishu_channel/manifest.yaml +12 -12
  24. package/channels/qq_bot_channel/__init__.py +1 -1
  25. package/channels/qq_bot_channel/handler.py +24 -24
  26. package/channels/qq_bot_channel/manifest.yaml +4 -4
  27. package/channels/telegram_channel/__init__.py +1 -1
  28. package/channels/telegram_channel/handler.py +21 -21
  29. package/channels/telegram_channel/manifest.yaml +4 -4
  30. package/channels/telegram_channel/media.py +231 -231
  31. package/channels/textfmt.py +58 -58
  32. package/channels/wechat_channel/__init__.py +1 -1
  33. package/channels/wechat_channel/converter.py +1 -1
  34. package/channels/wechat_channel/handler.py +8 -8
  35. package/channels/wechat_channel/manifest.yaml +5 -5
  36. package/channels/wechat_channel/media.py +178 -178
  37. package/core/activity.py +753 -709
  38. package/core/agent_loop.py +7673 -7523
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +36 -26
  41. package/core/approval_timeout.py +256 -228
  42. package/core/artifacts.py +3 -3
  43. package/core/attachment_gc.py +21 -0
  44. package/core/auto_review.py +2 -2
  45. package/core/browser/cdp.py +5 -2
  46. package/core/browser/discover.py +55 -19
  47. package/core/browser/session.py +4 -4
  48. package/core/cache_break_detector.py +97 -0
  49. package/core/cache_breakpoints.py +103 -0
  50. package/core/cache_policies.py +255 -0
  51. package/core/cancellation.py +3 -3
  52. package/core/channel_configs.py +3 -3
  53. package/core/channel_turns.py +13 -13
  54. package/core/child_approval.py +2 -3
  55. package/core/code_intel.py +11 -11
  56. package/core/command_policy.py +13 -7
  57. package/core/computer/annotate.py +231 -11
  58. package/core/computer/capture.py +140 -1
  59. package/core/computer/guard.py +7 -4
  60. package/core/computer/input.py +452 -26
  61. package/core/computer/session.py +563 -381
  62. package/core/computer/tools.py +2170 -928
  63. package/core/computer/uia.py +100 -1
  64. package/core/computer/watch.py +1 -1
  65. package/core/computer/win32.py +302 -7
  66. package/core/config_requirements.py +205 -205
  67. package/core/cron/runner.py +4 -4
  68. package/core/daily_log.py +2 -2
  69. package/core/dedup.py +2 -2
  70. package/core/egress_channels.py +326 -0
  71. package/core/egress_gate.py +96 -8
  72. package/core/egress_preapproved.py +59 -3
  73. package/core/endpoint.py +141 -141
  74. package/core/events.py +17 -8
  75. package/core/extension.py +2 -2
  76. package/core/file_history.py +15 -15
  77. package/core/file_tools.py +3 -3
  78. package/core/github_config.py +1 -1
  79. package/core/group_digest.py +3 -4
  80. package/core/group_minutes.py +5 -5
  81. package/core/group_reply.py +24 -0
  82. package/core/groups.py +5 -9
  83. package/core/hooks.py +15 -15
  84. package/core/i18n.py +2 -2
  85. package/core/ice/canary.py +3 -3
  86. package/core/ice/net_heuristics.py +2 -2
  87. package/core/im_routing.py +3 -3
  88. package/core/image_input.py +183 -43
  89. package/core/inbound.py +3 -3
  90. package/core/jobs.py +6 -6
  91. package/core/last_good.py +150 -150
  92. package/core/leaf_md.py +3 -3
  93. package/core/llm_errors.py +37 -28
  94. package/core/mail_config.py +2 -2
  95. package/core/memory/compressor.py +8 -8
  96. package/core/memory/manager.py +30 -45
  97. package/core/memory/session_memory.py +1 -2
  98. package/core/memory/short_term.py +4 -4
  99. package/core/memory_extract.py +1 -1
  100. package/core/memory_organize.py +8 -8
  101. package/core/memory_store.py +7 -9
  102. package/core/memory_transfer.py +2 -2
  103. package/core/model_capabilities.py +2 -2
  104. package/core/model_configs.py +219 -68
  105. package/core/model_profiles.py +333 -0
  106. package/core/modes.py +12 -11
  107. package/core/net_proxy.py +3 -3
  108. package/core/pipeline/scheduler.py +48 -43
  109. package/core/pipeline/stage.py +3 -0
  110. package/core/pipeline/stages/agent_loop.py +36 -15
  111. package/core/pipeline/stages/group_reply.py +22 -20
  112. package/core/pipeline/stages/post_process.py +7 -7
  113. package/core/pipeline/stages/pre_process.py +369 -77
  114. package/core/prompt_assembler.py +13 -4
  115. package/core/recycle.py +227 -16
  116. package/core/response_language.py +1 -1
  117. package/core/retention.py +2 -2
  118. package/core/rg.py +4 -3
  119. package/core/security.py +26 -8
  120. package/core/services.py +8 -8
  121. package/core/session_model.py +3 -5
  122. package/core/session_pool.py +35 -5
  123. package/core/session_recap.py +40 -3
  124. package/core/session_workspace.py +2 -3
  125. package/core/settings_baseline.py +2 -2
  126. package/core/settings_transfer.py +25 -1
  127. package/core/shell.py +52 -20
  128. package/core/side_call.py +3 -3
  129. package/core/skill_config.py +164 -0
  130. package/core/skill_factory.py +2 -2
  131. package/core/skill_guidance.py +2 -4
  132. package/core/skill_index.py +3 -4
  133. package/core/skill_settings.py +1 -1
  134. package/core/skill_sources.py +7 -7
  135. package/core/ssh_config.py +129 -0
  136. package/core/state_registry.py +67 -5
  137. package/core/subagent.py +28 -5
  138. package/core/subagent_defs.py +3 -3
  139. package/core/summarizer.py +4 -5
  140. package/core/tasks_notify.py +6 -6
  141. package/core/tiers.py +2 -2
  142. package/core/todos.py +1 -1
  143. package/core/token_calibrator.py +1 -4
  144. package/core/tool_outcome.py +108 -108
  145. package/core/touched_files.py +1 -1
  146. package/core/trace.py +12 -3
  147. package/core/unlock.py +4 -4
  148. package/core/update_tui.py +184 -158
  149. package/core/updater.py +5 -3
  150. package/core/version.py +14 -14
  151. package/core/vision_budget.py +235 -0
  152. package/core/web_cache.py +152 -152
  153. package/core/web_request.py +474 -0
  154. package/core/window_estimate.py +1 -1
  155. package/core/workspace.py +56 -26
  156. package/crannia_tray.py +278 -278
  157. package/licenses/GPL-3.0.txt +619 -619
  158. package/licenses/LGPL-2.1.txt +502 -502
  159. package/licenses/LGPL-3.0.txt +165 -165
  160. package/licenses/MIT-chat-on-wechat.txt +18 -18
  161. package/licenses/MIT-deepseek-harness.txt +21 -21
  162. package/licenses/Molio-LICENSE.txt +44 -44
  163. package/locales/en.json +1876 -1762
  164. package/main.py +154 -154
  165. package/mcpx/client.py +12 -1
  166. package/mcpx/manager.py +530 -522
  167. package/mcpx/servers/web_search.py +5 -13
  168. package/package.json +15 -23
  169. package/providers/anthropic/client.py +35 -33
  170. package/providers/base.py +13 -13
  171. package/providers/cache_policies.json +294 -0
  172. package/providers/cost_table.json +3779 -3779
  173. package/providers/lmstudio/client.py +2 -2
  174. package/providers/model_capabilities.json +6665 -6665
  175. package/providers/model_profiles.json +629 -0
  176. package/providers/ollama/client.py +2 -2
  177. package/providers/openai_compat.py +37 -16
  178. package/providers/openrouter/client.py +2 -2
  179. package/providers/qwen/__init__.py +1 -1
  180. package/providers/qwen/client.py +2 -2
  181. package/providers/qwen/manifest.yaml +16 -16
  182. package/providers/rate_limiter.py +2 -2
  183. package/providers/siliconflow/client.py +2 -2
  184. package/providers/validation.py +171 -171
  185. package/providers/vision_profiles.json +89 -0
  186. package/providers/window_table.json +8909 -8909
  187. package/requirements.txt +59 -51
  188. package/sbom-linux-x64.json +4580 -0
  189. package/sbom.json +4600 -4413
  190. package/skills/diagram/SKILL.md +47 -0
  191. package/skills/diagram/__init__.py +1 -0
  192. package/skills/diagram/handler.py +294 -0
  193. package/skills/diagram/layout.py +174 -0
  194. package/skills/diagram/manifest.yaml +106 -0
  195. package/skills/diagram/mermaid.py +170 -0
  196. package/skills/diagram/svg.py +223 -0
  197. package/skills/entertainment/SKILL.md +35 -35
  198. package/skills/entertainment/__init__.py +1 -1
  199. package/skills/entertainment/handler.py +91 -91
  200. package/skills/entertainment/manifest.yaml +26 -26
  201. package/skills/file_parser/GUIDANCE.md +10 -10
  202. package/skills/file_parser/handler.py +33 -11
  203. package/skills/github/SKILL.md +32 -32
  204. package/skills/github/__init__.py +1 -1
  205. package/skills/mail_parser/SKILL.md +68 -68
  206. package/skills/mail_parser/__init__.py +1 -1
  207. package/skills/mail_parser/handler.py +1 -1
  208. package/skills/media_gen/GUIDANCE.md +19 -19
  209. package/skills/media_gen/SKILL.md +43 -43
  210. package/skills/media_gen/__init__.py +1 -1
  211. package/skills/media_gen/handler.py +1 -1
  212. package/skills/media_gen/manifest.yaml +93 -93
  213. package/skills/netops/SKILL.md +45 -0
  214. package/skills/netops/__init__.py +1 -0
  215. package/skills/netops/handler.py +418 -0
  216. package/skills/netops/manifest.yaml +118 -0
  217. package/skills/office_parser/_excel_io.py +3 -3
  218. package/skills/office_parser/handler.py +2 -2
  219. package/skills/office_parser/ppt_tools.py +1 -1
  220. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  221. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  222. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  223. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  224. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  225. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  226. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  227. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  228. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  229. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  230. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  231. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  232. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  233. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
  234. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  235. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  236. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  237. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  238. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  239. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  240. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  241. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  242. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  243. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  244. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  245. package/skills/office_parser/references/layout_library.md +816 -816
  246. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  247. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  248. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  249. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  250. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  251. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  252. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  253. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  254. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  255. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  256. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  257. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  258. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  259. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  260. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  261. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  262. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  263. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  264. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  265. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  266. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  267. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  268. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  269. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  270. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  271. package/skills/office_parser/references/spec_lock.md +235 -235
  272. package/skills/office_parser/soffice.py +68 -68
  273. package/skills/office_parser/word_tools.py +3 -3
  274. package/skills/ssh/SKILL.md +81 -0
  275. package/skills/ssh/__init__.py +1 -0
  276. package/skills/ssh/handler.py +609 -0
  277. package/skills/ssh/manifest.yaml +182 -0
  278. package/tui/crannia.cmd +134 -134
  279. package/tui/crannia.sh +82 -0
  280. package/tui/crannia_tui/__init__.py +1 -1
  281. package/tui/crannia_tui/app.py +240 -17
  282. package/tui/crannia_tui/app.tcss +21 -0
  283. package/tui/crannia_tui/clipboard.py +78 -10
  284. package/tui/crannia_tui/commands.py +37 -0
  285. package/tui/crannia_tui/events.py +6 -0
  286. package/tui/crannia_tui/i18n.py +164 -164
  287. package/tui/crannia_tui/locales/en.json +32 -7
  288. package/tui/crannia_tui/paths.py +4 -1
  289. package/tui/crannia_tui/profile.py +178 -169
  290. package/tui/crannia_tui/settings.py +134 -134
  291. package/tui/crannia_tui/setup.py +44 -5
  292. package/tui/crannia_tui/ui.py +156 -16
  293. package/tui/crannia_tui/update.py +393 -389
  294. package/vendor/ripgrep/COPYING.txt +3 -3
  295. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  296. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  297. package/vendor/ripgrep/README.md +30 -14
  298. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  299. package/vendor/ripgrep/linux-x64/rg +0 -0
  300. package/vendor/ripgrep/package-source.json +15 -16
  301. package/web/__main__.py +12 -15
  302. package/web/server.py +8481 -8594
  303. package/web/static/img/channel-telegram.svg +1 -1
  304. package/web/static/img/channel-wechat.svg +1 -1
  305. package/web/templates/logs.html +49 -49
  306. package/web/templates/models.html +46 -46
package/core/groups.py CHANGED
@@ -99,7 +99,7 @@ def _read() -> dict[str, dict]:
99
99
  # 账本坏了,当没有群。判据同 `bus/mcp_disabled._read`:
100
100
  # 宁可让用户重建一个群,不可凭一个读不动的文件把界面上那 8 个头像
101
101
  # 渲染成半截(那看起来像"群还在,只是坏了")。
102
- print(f"[groups] 账本读不动({type(exc).__name__}: {exc})—— 按空账本走")
102
+ print(f"[groups] ledger unreadable ({type(exc).__name__}: {exc}) - treating as empty")
103
103
  return {}
104
104
  return raw if isinstance(raw, dict) else {}
105
105
 
@@ -384,8 +384,7 @@ def create(*, name: str = "", members=None, brief="",
384
384
  except Exception as exc: # noqa: BLE001
385
385
  # 写不进去也照样算建成了(本次运行内是真的)—— 同
386
386
  # `mcp_disabled.disable` 那条;但要说出来。
387
- print(f"[groups] 账本写不进去({type(exc).__name__}: {exc})"
388
- f" —— 本次运行**仍然有**这个群 '{gid}'")
387
+ print(f"[groups] ledger write failed ({type(exc).__name__}: {exc}) - group '{gid}' still present for this run")
389
388
  return dict(entry)
390
389
 
391
390
 
@@ -420,8 +419,7 @@ def update(gid: str, *, name=None, members=None, brief=None,
420
419
  try:
421
420
  _write(data)
422
421
  except Exception as exc: # noqa: BLE001
423
- print(f"[groups] 账本写不进去({type(exc).__name__}: {exc})"
424
- f" —— 本次运行**改动仍然生效** '{gid}'")
422
+ print(f"[groups] ledger write failed ({type(exc).__name__}: {exc}) - changes remain active for this run '{gid}'")
425
423
  return dict(next_entry)
426
424
 
427
425
 
@@ -479,8 +477,7 @@ def update_member(gid: str, index: int, *, name: str = "",
479
477
  try:
480
478
  _write(data)
481
479
  except Exception as exc: # noqa: BLE001
482
- print(f"[groups] 账本写不进去({type(exc).__name__}: {exc})"
483
- f" —— 本次运行**改动仍然生效** '{gid}'")
480
+ print(f"[groups] ledger write failed ({type(exc).__name__}: {exc}) - changes remain active for this run '{gid}'")
484
481
  return dict(next_entry)
485
482
 
486
483
 
@@ -501,8 +498,7 @@ def delete(gid: str) -> bool:
501
498
  try:
502
499
  _write(data)
503
500
  except Exception as exc: # noqa: BLE001
504
- print(f"[groups] 账本写不进去({type(exc).__name__}: {exc})"
505
- f" —— 本次运行**仍然删掉了** '{gid}'")
501
+ print(f"[groups] ledger write failed ({type(exc).__name__}: {exc}) - still deleted for this run '{gid}'")
506
502
  return True
507
503
 
508
504
 
package/core/hooks.py CHANGED
@@ -189,7 +189,7 @@ def parse_config(raw, *, workspace: Path, source: str,
189
189
  if event not in EVENTS:
190
190
  if event in ("SubagentStart", "SubagentStop"):
191
191
  _warn_once("unsupported:" + event,
192
- "配置里的 %s 暂不支持,已跳过(支持的是 %s)"
192
+ "unsupported event %s in config, skipped (supported: %s)"
193
193
  % (event, " / ".join(EVENTS)))
194
194
  continue
195
195
  if not isinstance(groups, list):
@@ -205,7 +205,7 @@ def parse_config(raw, *, workspace: Path, source: str,
205
205
  rx = re.compile(matcher_raw)
206
206
  except re.error as exc:
207
207
  _warn_once("badmatcher:%s:%s" % (source, matcher_raw),
208
- "%s 里的 matcher 不是合法正则(%s):%r"
208
+ "invalid matcher regex in %s (%s): %r"
209
209
  % (source, exc, matcher_raw))
210
210
  continue
211
211
  hooks = group.get("hooks")
@@ -216,7 +216,7 @@ def parse_config(raw, *, workspace: Path, source: str,
216
216
  continue
217
217
  if str(h.get("type") or "") != "command":
218
218
  _warn_once("type:%s:%s" % (source, h.get("type")),
219
- "%s 里有非命令钩子(type=%r),已跳过"
219
+ "non-command hook in %s (type=%r), skipped"
220
220
  % (source, h.get("type")))
221
221
  continue
222
222
  cmd = h.get("command")
@@ -268,7 +268,7 @@ def _package_hook_files() -> list:
268
268
  out.append((p, root, bool(pkg.from_workspace)))
269
269
  break
270
270
  except Exception as exc: # noqa: BLE001
271
- _warn_once("packages", "读取插件包钩子失败(%s: %s)"
271
+ _warn_once("packages", "failed to read plugin package hooks (%s: %s)"
272
272
  % (type(exc).__name__, exc))
273
273
  return out
274
274
 
@@ -292,14 +292,14 @@ def _load(workspace: Path) -> list:
292
292
  if project and not allowed:
293
293
  if path.exists():
294
294
  _warn_once("trust:" + str(path),
295
- "工作区里的钩子配置没有执行:项目级钩子要先在"
296
- "「设置 → 安全设置 → 工作区钩子」里打开")
295
+ "workspace hook config not executed: enable it in "
296
+ "Settings > Security > Workspace hooks first")
297
297
  continue
298
298
  if from_ws and not plugin_allowed:
299
299
  if path.exists():
300
300
  _warn_once("plugin-trust:" + str(path),
301
- "工作区插件包里的钩子没有执行:要先在"
302
- "「设置 → 安全设置 → 工作区插件」里打开")
301
+ "workspace plugin hooks not executed: enable them in "
302
+ "Settings > Security > Workspace plugins first")
303
303
  continue
304
304
  try:
305
305
  st = path.stat()
@@ -316,10 +316,10 @@ def _load(workspace: Path) -> list:
316
316
  raw = json.loads(path.read_text(encoding="utf-8"))
317
317
  except (OSError, ValueError) as exc:
318
318
  _warn_once("read:" + str(path),
319
- "%s 读不出来(%s)—— 这一份跳过" % (path, exc))
319
+ "cannot read %s (%s) - skipping this one" % (path, exc))
320
320
  continue
321
321
  if plugin_root is not None:
322
- print("[hooks] 插件包钩子已加载:%s" % path)
322
+ print("[hooks] plugin-pack hooks loaded: %s" % path)
323
323
  hooks.extend(parse_config(raw, workspace=workspace, source=str(path),
324
324
  plugin_root=plugin_root))
325
325
  _cache_key, _cache_hooks = key, hooks
@@ -384,15 +384,15 @@ def _spawn_async(hook: _Hook, payload: dict, workspace: Path) -> None:
384
384
  try:
385
385
  out = _run_now(hook, payload, workspace)
386
386
  except Exception as exc: # noqa: BLE001
387
- print("[hooks] 后台钩子异常(%s:%s)" % (type(exc).__name__, exc))
387
+ print("[hooks] background hook error (%s: %s)" % (type(exc).__name__, exc))
388
388
  return
389
389
  finally:
390
390
  _async_threads.discard(threading.current_thread())
391
391
  if out.get("blocked") or out.get("ask"):
392
- print("[hooks] 后台钩子想拦下/询问这一步,但它标了 async ⇒ 弃权:%s"
392
+ print("[hooks] background hook tried to block/ask but is async => abstained: %s"
393
393
  % hook.command)
394
394
  elif out.get("context") or out.get("args") is not None:
395
- print("[hooks] 后台钩子回了上下文/参数,但它标了 async ⇒ 送不回去:%s"
395
+ print("[hooks] background hook returned context/args but is async => cannot deliver: %s"
396
396
  % hook.command)
397
397
  t = threading.Thread(target=_worker, daemon=True)
398
398
  _async_threads.add(t)
@@ -416,10 +416,10 @@ def _run_now(hook: _Hook, payload: dict, workspace: Path) -> dict:
416
416
  )
417
417
  except subprocess.TimeoutExpired:
418
418
  _warn_once("timeout:" + hook.command,
419
- "钩子超时(%d ms):%s" % (hook.timeout_ms, hook.command))
419
+ "hook timed out (%d ms): %s" % (hook.timeout_ms, hook.command))
420
420
  return {}
421
421
  except OSError as exc:
422
- _warn_once("spawn:" + hook.command, "钩子起不来(%s):%s" % (exc, hook.command))
422
+ _warn_once("spawn:" + hook.command, "hook failed to start (%s): %s" % (exc, hook.command))
423
423
  return {}
424
424
 
425
425
  if proc.returncode == 2:
package/core/i18n.py CHANGED
@@ -131,7 +131,7 @@ def _pack(lang: str) -> dict:
131
131
  raise ValueError("top level is %s, not an object" % type(data).__name__)
132
132
  data = {str(k): str(v) for k, v in data.items() if isinstance(v, str)}
133
133
  except Exception as exc: # noqa: BLE001
134
- print("[i18n] %s 读不出来,回落中文:%s: %s"
134
+ print("[i18n] %s unreadable, falling back to zh: %s: %s"
135
135
  % (p, type(exc).__name__, exc))
136
136
  data = {}
137
137
  with _lock:
@@ -255,7 +255,7 @@ def current() -> str:
255
255
  lang = DEFAULT_LANG
256
256
  if not _cache["bad_noted"]:
257
257
  _cache["bad_noted"] = True
258
- print("[i18n] 设置里的 %s=%r 认不出 —— 按中文处理"
258
+ print("[i18n] setting %s=%r not recognized - treating as zh"
259
259
  % (SETTING_KEY, code))
260
260
  with _lock:
261
261
  _cache["cur"].update(mtime=mtime, lang=lang)
@@ -75,7 +75,7 @@ def is_enabled() -> bool:
75
75
  # 读不到,关。这一条的失败方向与"信息层读不到,关"同源:
76
76
  # ICE 整体是增强(`ICE_DEFAULT_ON = False`),读不出设置时
77
77
  # 不启用它,而不是凭空启用一套会拦人的东西。
78
- print(f"[ice] 网络层开关读不到(按关处理):{type(exc).__name__}: {exc}")
78
+ print(f"[ice] network layer switch unreadable (treating as off): {type(exc).__name__}: {exc}")
79
79
  return False
80
80
 
81
81
 
@@ -106,7 +106,7 @@ def note_trip(where: str, hits, session_key: str = "") -> None:
106
106
  会话号取不到(有人在循环外直接调工具),只打控制台,绝不因此弄挂一次调用。
107
107
  """
108
108
  shown = "、".join(hits) if hits else ""
109
- print(f"[ice] 金丝雀触发({where}):{shown} —— 已阻断并报警")
109
+ print(f"[ice] canary triggered ({where}): {shown} - blocked and reported")
110
110
 
111
111
  key = str(session_key or "")
112
112
  if not key:
@@ -124,7 +124,7 @@ def note_trip(where: str, hits, session_key: str = "") -> None:
124
124
  where=str(where), hits=list(hits or ()))
125
125
  except Exception as exc: # noqa: BLE001
126
126
  # 报警失败不许吞掉整次调用 —— 但也不许静默(判据 4)。
127
- print(f"[ice] 报警事件发送失败:{type(exc).__name__}: {exc}")
127
+ print(f"[ice] alert event send failed: {type(exc).__name__}: {exc}")
128
128
 
129
129
 
130
130
  def check_outbound(text: str, *, where: str, session_key: str = "") -> Dict | None:
@@ -175,7 +175,7 @@ def note_signals(url: str, *, where: str, session_key: str = "") -> List[Signal]
175
175
  if not sigs:
176
176
  return []
177
177
  shown = ";".join(s.why for s in sigs)
178
- print("[ice] 网络侧弱信号(%s):%s" % (where, shown))
178
+ print("[ice] network weak signals (%s): %s" % (where, shown))
179
179
 
180
180
  key = str(session_key or "")
181
181
  if not key:
@@ -194,5 +194,5 @@ def note_signals(url: str, *, where: str, session_key: str = "") -> List[Signal]
194
194
  keys=[s.key for s in sigs],
195
195
  reasons=[s.why for s in sigs])
196
196
  except Exception as exc: # noqa: BLE001
197
- print("[ice] 弱信号事件发失败(%s: %s)" % (type(exc).__name__, exc))
197
+ print("[ice] weak-signal event send failed (%s: %s)" % (type(exc).__name__, exc))
198
198
  return sigs
@@ -91,7 +91,7 @@ def _load() -> None:
91
91
  _bindings.update(
92
92
  {str(k): str(v) for k, v in bindings.items() if v})
93
93
  except Exception as exc: # noqa: BLE001
94
- print("[routing] routing.json 读不出来,按空表算:%s: %s"
94
+ print("[routing] routing.json unreadable, using empty table: %s: %s"
95
95
  % (type(exc).__name__, exc))
96
96
 
97
97
 
@@ -103,7 +103,7 @@ def _save_locked() -> None:
103
103
  json.dumps({"bindings": _bindings}, ensure_ascii=False, indent=2),
104
104
  encoding="utf-8")
105
105
  except Exception as exc: # noqa: BLE001
106
- print("[routing] routing.json 写不进去:%s: %s" % (type(exc).__name__, exc))
106
+ print("[routing] routing.json write failed: %s: %s" % (type(exc).__name__, exc))
107
107
 
108
108
 
109
109
  # 决策
@@ -201,7 +201,7 @@ def _render_question(numbering: Dict[int, str],
201
201
  def _tips() -> str:
202
202
  #: 这是给用户看的一句话:不用 Markdown(`**`)、不用内部词
203
203
  #: ("接入"/"换默认"),说清两个动作各自会发生什么。
204
- return ("提示:临时切到其他会话,发 `/c<编号> 你的话`;设为默认,发 `/change <编号>`。")
204
+ return ("提示:临时切到其他会话,发 `/c<编号> 您的话`;设为默认,发 `/change <编号>`。")
205
205
 
206
206
 
207
207
  def route(event, activity: Dict[str, float],
@@ -139,7 +139,25 @@ AUDIO_TOKEN_FALLBACK = 1000
139
139
  #: 那一格管"一轮能贴几张",这一格管"历史里能留几张"。
140
140
  #: 保留最近 N 张而不是"最近 N 轮":一轮四张图是常态,
141
141
  #: 按轮算会让一个四图轮把预算吃光是同一条行为,但按张算更好解释。
142
- KEEP_IMAGES_IN_REQUEST = 2
142
+ #: 3 张是接管那一档的要求:最近几次观察的截图必须在上下文里,
143
+ #: 模型翻旧图时不能把它们挤掉(详见 offload_old_images)。
144
+ KEEP_IMAGES_IN_REQUEST = 3
145
+
146
+ #: 接管轨迹里每隔多少张截图才批量卸载一次。其余轮次只追加、不改写历史 ——
147
+ #: 每轮都改一处前缀,付出的是整段缓存重算的代价,而省下的只是几张图的钱。
148
+ BATCH_EVERY_OBSERVATIONS = 25
149
+
150
+ #: 批量边界之前允许堆多少张图。纯按次数等 25 轮的话,中途账单会一直涨;
151
+ #: 到了这个数就提前卸一次,属于"再不裁就要付更多"的兜底。
152
+ MAX_INLINE_IMAGES = 12
153
+
154
+ #: 卸载时按来源分优先级:接管截图是受保护的,read_file 翻出来的旧图先清。
155
+ #: 来源不靠新字段,靠历史里本来就有的 tool_call_id 反查工具名 ——
156
+ #: 消息级的私有字段没有统一的 wire 剥除处(兼容层只剥 artifacts 与块级下划线键),
157
+ #: 而 tool_call_id / tool_calls 会随 extra_json 落库、装载时还原。
158
+ _PIN_TOOL = "computer"
159
+ _TRANSIENT_TOOL = "read_file"
160
+ _PIN_RECENT = 3
143
161
 
144
162
  #: 认这四种。判据来自附件校验(列的就是这四个),
145
163
  #: 也正好是 OpenAI 兼容端点普遍接受的集合。
@@ -356,6 +374,15 @@ class PreparedImage:
356
374
  # 可认的标记"。两者是同一条:别让类型成为语义。
357
375
 
358
376
 
377
+ class TrustedText(str):
378
+ """框架自己写的一段回执文本 —— 不进 `<user_document>` 隔离。
379
+
380
+ 只给"整段都是框架的话"的回执用(按键/点击/滚动/按住这类动作回执)。
381
+ 判据:不含任何应用/第三人写的内容 —— 窗口标题、元素树、搜索框名字
382
+ 都不能进;那些仍然走隔离。误标的后果是把不可信内容当成了框架的话。
383
+ """
384
+
385
+
359
386
  @dataclass
360
387
  class ImageToolResult:
361
388
  """工具回执里带图时的形状:一段文本 + N 张已经归一化好的图。
@@ -374,14 +401,30 @@ class ImageToolResult:
374
401
  text: str = ""
375
402
  #: 已经归一化 + 落盘的图。0 张 = 这就是一条普通的文本回执。
376
403
  prepared: list[PreparedImage] = field(default_factory=list)
404
+ #: 这段文本是不是框架自己的话(见 `TrustedText`)。
405
+ trusted_text: bool = False
406
+ #: 框架自己的前置段(读数 / 建议 / 下一步)—— 在 `<user_document>` 之外。
407
+ #: `text` 那一半仍按不可信内容处理(窗口标题 / 元素树 / 搜索框名字)。
408
+ trusted_prefix: str = ""
377
409
 
378
410
  @property
379
411
  def blocks(self) -> list[dict]:
380
412
  """发到 wire 上的那串块(OpenAI 形状,见模块 docstring 判据 1)。"""
381
413
  return [p.block for p in self.prepared]
382
414
 
415
+ def render_untrusted(self) -> str:
416
+ """不可信那一半:正文 + 每张图一行说明 + 图自己的 notes。"""
417
+ lines: list[str] = []
418
+ if self.text:
419
+ lines.append(self.text)
420
+ for idx, p in enumerate(self.prepared, 1):
421
+ lines.append("%d. %s(已存在 %s)" % (idx, p.label, p.path.as_posix()))
422
+ for note in p.notes:
423
+ lines.append(" - %s" % note)
424
+ return "\n".join(lines)
425
+
383
426
  def render(self) -> str:
384
- """文本部分 = 调用方给的话 + 每张图一行说明 + 它自己的 notes。
427
+ """文本视图 = 可信前置段 + 不可信正文(落库 / 压缩 / 回放都用它)。
385
428
 
386
429
  判据 3(超了要说):`PreparedImage.notes`(已降采样 / EXIF 已剥离 /
387
430
  动图只取首帧 / 已降质量)非空就必须进上下文 —— 空列表 = 一个
@@ -390,22 +433,26 @@ class ImageToolResult:
390
433
  `content_text` 再产一遍,同一张图两个指针,下一轮装回两张图
391
434
  (`paths_in_text` 按出现次数还原)。落库那句指针由 `content_text` 一处产。
392
435
  """
393
- lines: list[str] = []
394
- if self.text:
395
- lines.append(self.text)
396
- for idx, p in enumerate(self.prepared, 1):
397
- lines.append("%d. %s(已存在 %s)" % (idx, p.label, p.path.as_posix()))
398
- for note in p.notes:
399
- lines.append(" - %s" % note)
400
- return "\n".join(lines)
436
+ body = self.render_untrusted()
437
+ if self.trusted_prefix:
438
+ return self.trusted_prefix + ("\n\n" + body if body else "")
439
+ return body
401
440
 
402
441
 
403
442
  # 三、规范化
404
443
 
405
444
 
406
- def _normalize(data: bytes, media_type: str, source: str) -> PreparedImage:
445
+ def _normalize(data: bytes, media_type: str, source: str,
446
+ max_edge: int | None = None,
447
+ max_pixels: int | None = None) -> PreparedImage:
407
448
  """校验 -> 转正 -> 剥元数据 -> 限尺寸 -> 编码,产出 `PreparedImage`。
408
449
 
450
+ `max_edge` / `max_pixels` 是这一轮的目标预算(接管截图按当前模型给),
451
+ 不给就沿用 `MAX_EDGE_PX` —— 用户贴图、文档抽图这些路径的默认行为不变。
452
+
453
+ 为什么不许直接把 `MAX_EDGE_PX` 改小:那是所有图片路径共用的天花板,
454
+ 接管需要按模型缩,别的路径不需要。目标预算必须从调用方进来。
455
+
409
456
  无条件重编码(判据 2):不做"字节没变就原样透传"的短路。
410
457
  那条短路看着省事,实际把两个洞一起放进来 ——
411
458
  ① 元数据里能塞任意文本(`tEXt` / EXIF `ImageDescription` / ICC 描述),
@@ -495,15 +542,33 @@ def _normalize(data: bytes, media_type: str, source: str) -> PreparedImage:
495
542
  img = img.convert("RGBA")
496
543
 
497
544
  # 限尺寸(判据 3:超了要说出来)
545
+ #
546
+ # 两条上限同时生效:长边(模型的分块档)与总像素(那一档的像素预算)。
547
+ # 一次算出最小比例、只缩一次 —— 缩两遍会让字更糊,而方向是"只缩一次"。
548
+ limit_edge = int(max_edge) if max_edge else MAX_EDGE_PX
549
+ if limit_edge <= 0:
550
+ limit_edge = MAX_EDGE_PX
551
+ limit_pixels = int(max_pixels) if max_pixels else 0
498
552
  w, h = img.size
499
553
  longest = max(w, h)
500
- if longest > MAX_EDGE_PX:
501
- scale = MAX_EDGE_PX / float(longest)
502
- new_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))
554
+ scale = 1.0
555
+ why = ""
556
+ if longest > limit_edge:
557
+ scale = limit_edge / float(longest)
558
+ why = "长边上限 %d" % limit_edge
559
+ if limit_pixels > 0 and w * h * scale * scale > limit_pixels:
560
+ by_pixels = (limit_pixels / float(w * h)) ** 0.5
561
+ if by_pixels < scale:
562
+ scale = by_pixels
563
+ why = "总像素上限 %d 万" % (limit_pixels // 10000)
564
+ if scale < 1.0:
565
+ # 向下取整而不是四舍五入:round 会让两边各多半个像素,
566
+ # 加起来刚好越过像素预算(1,150,188 > 1,150,000 那种)。
567
+ new_size = (max(1, int(w * scale)), max(1, int(h * scale)))
503
568
  img = img.resize(new_size, _resample())
504
- notes.append("已降采样 %d×%d -> %d×%d(超过长边上限 %d,那个尺寸对模型"
505
- "没有额外信息,只是更多 token)"
506
- % (w, h, new_size[0], new_size[1], MAX_EDGE_PX))
569
+ notes.append("已降采样 %d×%d -> %d×%d(%s,那个尺寸对模型没有额外信息,"
570
+ "只是更多 token)"
571
+ % (w, h, new_size[0], new_size[1], why))
507
572
  w, h = new_size
508
573
 
509
574
  # 编码(不带 exif / icc / pnginfo —— 元数据在这里掉光)
@@ -639,11 +704,16 @@ def _guard_b64_size(b64: str, what: str) -> None:
639
704
 
640
705
 
641
706
  def prepare_bytes(data: bytes, *, media_type: str = "",
642
- source: str = "") -> PreparedImage:
707
+ source: str = "",
708
+ max_edge: int | None = None,
709
+ max_pixels: int | None = None) -> PreparedImage:
643
710
  """从内存里的字节做一张图。`media_type` 只是提示 —— 真正判的是魔数。
644
711
 
645
712
  魔数优先:`media_type` 传了也只在魔数认不出时当兜底,
646
713
  因为"用户说它是 PNG"与"它真的是 PNG"是两件事。
714
+
715
+ `max_edge` / `max_pixels` 是这一轮的目标预算(接管截图按当前模型给);
716
+ 不给就走 `MAX_EDGE_PX`,所有既有路径的行为不变。
647
717
  """
648
718
  if not data:
649
719
  raise ImageInputError("这张图是空的(0 字节)")
@@ -656,7 +726,8 @@ def prepare_bytes(data: bytes, *, media_type: str = "",
656
726
  claimed = ("(说是 %s,但文件头对不上)" % media_type) if media_type else ""
657
727
  raise ImageInputError(
658
728
  "认不出这是什么图片格式%s —— 支持 PNG / JPEG / WebP / GIF。" % claimed)
659
- return _normalize(data, sniffed, source)
729
+ return _normalize(data, sniffed, source,
730
+ max_edge=max_edge, max_pixels=max_pixels)
660
731
 
661
732
 
662
733
  def prepare_path(path: str | Path, *, source: str = "") -> PreparedImage:
@@ -758,7 +829,7 @@ def prepare_chain(components: Iterable[Any]) -> tuple[list[PreparedImage],
758
829
  "它们没有被处理,分开几轮发。"
759
830
  % (rest, _human_bytes(total_bytes),
760
831
  _human_bytes(MAX_TURN_TOTAL_BYTES)))
761
- print("[image] 合计字节到顶:%s >= %s,余下 %d 张没收下"
832
+ print("[image] total bytes at cap: %s >= %s, %d images not taken"
762
833
  % (_human_bytes(total_bytes),
763
834
  _human_bytes(MAX_TURN_TOTAL_BYTES), rest))
764
835
  break
@@ -769,10 +840,10 @@ def prepare_chain(components: Iterable[Any]) -> tuple[list[PreparedImage],
769
840
  except ImageInputError as exc:
770
841
  # 两个出口,两个读者:
771
842
  # 给模型的 = 短句(进这一轮正文);给控制台的 = 完整判据(只 print)。
772
- print("[image] 第 %d 张没收下 —— %s" % (idx, exc.detail))
843
+ print("[image] image %d not taken - %s" % (idx, exc.detail))
773
844
  notes.append("%s(第 %d 张)" % (_NO_ACTION_BRIEF % exc.brief, idx))
774
845
  except Exception as exc: # noqa: BLE001 —— 一张坏图不该毁掉整轮
775
- print("[image] 第 %d 张没收下(%s):%s"
846
+ print("[image] image %d not taken (%s): %s"
776
847
  % (idx, type(exc).__name__, exc))
777
848
  notes.append("%s(第 %d 张,%s)"
778
849
  % (_NO_ACTION_BRIEF % "这张图没能读出来",
@@ -1159,7 +1230,7 @@ def prepare_turn(components, *, sees_images: bool = True,
1159
1230
  " 图片(视觉)能力」为「强制开启」;或者把 `config.yaml` 的"
1160
1231
  " `model` 段那一行改成 `true` 或删掉它(默认就是开)。"
1161
1232
  "**这一步由用户决定、用户来做 —— 你不要去改配置。**" % n)
1162
- print("[image] 能力闸拦下 %d 张(supports_vision 被显式关掉了)" % n)
1233
+ print("[image] capability gate dropped %d images (supports_vision explicitly off)" % n)
1163
1234
  notes.append(note)
1164
1235
  dropped = n
1165
1236
  else:
@@ -1354,7 +1425,7 @@ def content_text(content: Any) -> str:
1354
1425
  parts.append("[音频 %d]" % n_audio)
1355
1426
  return "\n".join(p for p in parts if p)
1356
1427
  # 认不出来的形状:不抛(一条坏消息不该毁掉整轮),但要说出来
1357
- print("[image] content 是认不出的类型 %s —— 按空文本处理"
1428
+ print("[image] content has unrecognized type %s - treated as empty text"
1358
1429
  % type(content).__name__)
1359
1430
  return ""
1360
1431
 
@@ -1500,7 +1571,10 @@ def rebuild_audio_blocks(paths: Sequence[str]) -> tuple[list[dict], list[str]]:
1500
1571
 
1501
1572
 
1502
1573
  def expand_attachments(messages: Sequence[dict],
1503
- keep: int = KEEP_IMAGES_IN_REQUEST) -> int:
1574
+ keep: int = KEEP_IMAGES_IN_REQUEST, *,
1575
+ batch_every: int = BATCH_EVERY_OBSERVATIONS,
1576
+ max_inline: int = MAX_INLINE_IMAGES,
1577
+ eviction: str = "batch") -> int:
1504
1578
  """把历史里那些指针装回成图片块,然后卸载掉太老的。返回装回去几张。
1505
1579
 
1506
1580
  ## 它为什么存在
@@ -1553,7 +1627,9 @@ def expand_attachments(messages: Sequence[dict],
1553
1627
  # (b)这一轮刚append 上去的新图,两者合起来一样会超 `keep`。
1554
1628
  # 挂在上面的 `if n:` 里,第 3 张图进来那一轮卸载不发生,
1555
1629
  # 而症状是"账单比预期高"(没有任何地方会红)。
1556
- offload_old_images(messages, keep=keep)
1630
+ if eviction != "none":
1631
+ offload_old_images(messages, keep=keep,
1632
+ batch_every=batch_every, max_inline=max_inline)
1557
1633
  return n
1558
1634
 
1559
1635
 
@@ -1619,9 +1695,35 @@ def audio_token_allowance(content: Any) -> int:
1619
1695
  return total
1620
1696
 
1621
1697
 
1698
+ def _tool_names_by_call(messages: Sequence[dict]) -> dict[str, str]:
1699
+ """每条工具结果对应的工具名,从 assistant 的 `tool_calls` 反查。
1700
+
1701
+ 为什么不给图片块加内部键:块级下划线键在兼容层会被剥掉,消息级的却没有
1702
+ 统一的剥除处(那里只剥 `artifacts`),加了就可能漏上 wire 被严格网关拒。
1703
+ 工具名是历史本来就有的字段,随 `extra_json` 落库、装载时还原,跨轮次不丢。
1704
+ """
1705
+ out: dict[str, str] = {}
1706
+ for msg in messages:
1707
+ if not isinstance(msg, dict):
1708
+ continue
1709
+ calls = msg.get("tool_calls")
1710
+ if not isinstance(calls, (list, tuple)):
1711
+ continue
1712
+ for tc in calls:
1713
+ if not isinstance(tc, dict) or not tc.get("id"):
1714
+ continue
1715
+ fn = tc.get("function")
1716
+ name = fn.get("name") if isinstance(fn, dict) else ""
1717
+ if name:
1718
+ out[str(tc["id"])] = str(name)
1719
+ return out
1720
+
1721
+
1622
1722
  def offload_old_images(messages: Sequence[dict],
1623
- keep: int = KEEP_IMAGES_IN_REQUEST) -> int:
1624
- """把最近 `keep` 张之外的图片块换成一句带路径的话。返回换了几张。
1723
+ keep: int = KEEP_IMAGES_IN_REQUEST, *,
1724
+ batch_every: int = 0,
1725
+ max_inline: int = 0) -> int:
1726
+ """把该卸的图片块换成一句带路径的话。返回换了几张。
1625
1727
 
1626
1728
  ## 为什么要卸载
1627
1729
 
@@ -1629,15 +1731,25 @@ def offload_old_images(messages: Sequence[dict],
1629
1731
  账单随轮数线性涨,而模型早就不看它们了。四类裁剪里第四类(图片卸载)
1630
1732
  干的就是这件事。
1631
1733
 
1632
- ## 两条判据
1734
+ ## 三条判据
1735
+
1736
+ 卸载不等于丢掉:换上去的那句话里带着路径,而 `data/attachments/`
1737
+ 是可读的(`_framework_readable`),模型取得回来。不写路径的卸载
1738
+ 就是把丢失伪装成清理。
1739
+
1740
+ 就地改,不改结构:只替换块里面那一项,`content` 仍是同一个列表、
1741
+ 同样的块数,前后两条消息的 JSON 形状一致,压缩与持久化都不用知道。
1742
+
1743
+ 受保护的图不能因为翻旧图被顶掉:接管截图里最近三张永远留着。
1744
+ 模型用 `read_file` 翻出来的旧图排在它们后面,单看位置会误把新截图
1745
+ 当成"更早的图"卸掉,所以要看来源,不能只看下标。
1746
+
1747
+ ## 批量边界
1633
1748
 
1634
- * 卸载 ≠ 丢掉:换上去的那句话里带着路径,而 `data/attachments/`
1635
- 是可读的(`_framework_readable`),模型取得回来。
1636
- 这是「指针必须真能取到」的直接套用 —— 不写路径的卸载就是"把丢失
1637
- 伪装成清理"。
1638
- * 就地改,不改结构:只替换块里面那一项,
1639
- `content` 仍然是同一个列表、同样的块数,前后两条消息的 JSON 形状一致,
1640
- 压缩/分类器/持久化都不需要知道这里发生过什么。
1749
+ `batch_every > 0` 且历史里有接管截图时,只有截图数到边界、或总图数
1750
+ 超过 `max_inline` 才卸载一次。其余轮次一个字节都不改,前缀纯追加。
1751
+ 没有接管截图(普通用户贴图)时不启用批量,仍按每轮保留最后 `keep` 张 ——
1752
+ 那种轨迹里图很少,批量带来的前缀收益抵不上多留几张的成本。
1641
1753
 
1642
1754
  它是有副作用的(改 `messages` 里的对象)—— 所以调用点必须在
1643
1755
  发请求之前、且在 `messages` 的副本语义明确之后。返回计数是为了让
@@ -1646,22 +1758,50 @@ def offload_old_images(messages: Sequence[dict],
1646
1758
  if keep < 0:
1647
1759
  keep = 0
1648
1760
 
1649
- # 先从后往前数出所有图片块的位置(`(msg_idx, part_idx)`),再决定换哪些。
1650
- found: list[tuple[int, int, str]] = []
1761
+ names = _tool_names_by_call(messages)
1762
+ # 位置三元组再加一格来源(工具名),路径来自块自身的内容摘要。
1763
+ found: list[tuple[int, int, str, str]] = []
1651
1764
  for mi, msg in enumerate(messages):
1652
- content = msg.get("content") if isinstance(msg, dict) else None
1765
+ if not isinstance(msg, dict):
1766
+ continue
1767
+ content = msg.get("content")
1653
1768
  if not isinstance(content, list):
1654
1769
  continue
1770
+ source = names.get(str(msg.get("tool_call_id") or ""), "")
1655
1771
  for pi, part in enumerate(content):
1656
1772
  if isinstance(part, dict) and part.get("type") == "image_url":
1657
- path = _path_of(part)
1658
- found.append((mi, pi, path))
1773
+ found.append((mi, pi, _path_of(part), source))
1659
1774
 
1660
1775
  if len(found) <= keep:
1661
1776
  return 0
1662
1777
 
1778
+ pins = [x for x in found if x[3] == _PIN_TOOL]
1779
+ batching = bool(pins) and batch_every > 0
1780
+ if batching:
1781
+ # 观察次数按累计的 tool_calls 数,不按当前图块数 —— 卸载会把老图块换成
1782
+ # 文本,按图块数数的话每卸一次序号就倒退,25 次边界永远到不了。
1783
+ obs_seq = sum(1 for name in names.values() if name == _PIN_TOOL)
1784
+ boundary = obs_seq > 0 and obs_seq % batch_every == 0
1785
+ overflow = max_inline > 0 and len(found) > max_inline
1786
+ if not (boundary or overflow):
1787
+ return 0
1788
+
1789
+ if not pins:
1790
+ # 没有接管截图:保留最后的 keep 张,这是批量机制加入之前的行为。
1791
+ victims = found[:-keep] if keep else list(found)
1792
+ else:
1793
+ # 最近三张截图受保护。翻出来的旧图先清,再清其它来源的旧图;
1794
+ # 每个来源内部仍从最老的开始,序号是模型唯一的指代方式,不能重排。
1795
+ protected = {(x[0], x[1]) for x in pins[-_PIN_RECENT:]}
1796
+ others = [x for x in found if (x[0], x[1]) not in protected]
1797
+ transient = [x for x in others if x[3] == _TRANSIENT_TOOL]
1798
+ normal = [x for x in others if x[3] != _TRANSIENT_TOOL]
1799
+ order = transient + normal
1800
+ slots = max(0, keep - len(protected))
1801
+ victims = order[:max(0, len(order) - slots)]
1802
+
1663
1803
  replaced = 0
1664
- for mi, pi, path in found[:-keep] if keep else found:
1804
+ for mi, pi, path, _source in victims:
1665
1805
  messages[mi]["content"][pi] = {
1666
1806
  "type": "text",
1667
1807
  "text": _OFFLOAD_TEMPLATE.format(
@@ -1801,7 +1941,7 @@ __all__ = [
1801
1941
  "MAX_EDGE_PX", "MAX_BASE64_BYTES", "MAX_IMAGE_BYTES",
1802
1942
  "MAX_IMAGES_PER_TURN", "MAX_TURN_TOTAL_BYTES",
1803
1943
  "MAX_SOURCE_BYTES", "SUPPORTED_MEDIA", "ATTACHMENT_DIR",
1804
- "KEEP_IMAGES_IN_REQUEST",
1944
+ "KEEP_IMAGES_IN_REQUEST", "BATCH_EVERY_OBSERVATIONS", "MAX_INLINE_IMAGES",
1805
1945
  "ImageInputError", "PreparedImage", "ImageToolResult",
1806
1946
  "sniff_media_type", "looks_like_image", "image_kind_name",
1807
1947
  "prepare_bytes", "prepare_path", "prepare_data_url",
package/core/inbound.py CHANGED
@@ -174,7 +174,7 @@ def submit(*, platform: str, kind: str, session_id: str, source: str,
174
174
  try:
175
175
  _reply(text_out)
176
176
  except Exception as exc: # noqa: BLE001
177
- print("[inbound] 回复回调失败(%s: %s)"
177
+ print("[inbound] reply callback failed (%s: %s)"
178
178
  % (type(exc).__name__, exc))
179
179
  event.reply_callback = _cb
180
180
 
@@ -187,7 +187,7 @@ def submit(*, platform: str, kind: str, session_id: str, source: str,
187
187
  if not queue(key, _job):
188
188
  #: 队列满了:这条没排上。回 `accepted: True` 就是撒谎 ——
189
189
  #: 调用方会以为投递成功,而用户什么都没等到。
190
- print("[inbound] 来源 %s 的队列满了,这条没有投递" % src)
190
+ print("[inbound] queue for source %s is full, not delivered" % src)
191
191
  return {"accepted": False, "error": "会话队列已满,请稍后重试"}
192
- print("[inbound] 来源 %s 投递了一条(%s:%s:%s)" % (src, plat, kd, sid))
192
+ print("[inbound] source %s delivered one (%s:%s:%s)" % (src, plat, kd, sid))
193
193
  return {"accepted": True, "session_key": key}