@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
@@ -23,7 +23,8 @@ from core.session_key import session_key_for, session_key_of_ctx
23
23
  from core.pipeline.stage import Stage, StageContext, register_stage
24
24
  # 所有"审批没有发生"的文案头。放在模块顶是因为七个结算器每一条拒绝路径
25
25
  # 都要用它,而 `core/approval.py` 只 import `re`/`dataclasses`,不会成环。
26
- from core.approval import outcome_line
26
+ from core.approval import (GRANT_NONE, GRANT_ONCE, GRANT_PERSIST,
27
+ GRANT_SESSION, outcome_line)
27
28
  # 投入档的唯一入口与它的"拒"。放在模块顶是因为守卫每轮都要跑
28
29
  # (`/clear` 分支里的 `reset_tier_cache` 仍是就地 import —— 它只在那条路上用得到)。
29
30
  from core.tiers import TierUnsupported, current_spec
@@ -91,7 +92,7 @@ class PreProcessStage(Stage):
91
92
  "下面这条是用户的新消息。)\n\n" + ctx.user_message)
92
93
  user_input = ctx.user_message.strip()
93
94
  except Exception as exc: # noqa: BLE001
94
- print("[cancel] 读『上一轮被打断』标记失败(不影响这一轮):%s: %s"
95
+ print("[cancel] failed to read the 'previous turn interrupted' marker (does not affect this turn): %s: %s"
95
96
  % (type(exc).__name__, exc))
96
97
 
97
98
  # ---- 轮首清掉上一轮的 ICE 放行 ----
@@ -107,7 +108,7 @@ class PreProcessStage(Stage):
107
108
  from core.ice import reveal as _ice_reveal
108
109
  _ice_reveal.clear_exempt(session_key)
109
110
  except Exception as exc: # noqa: BLE001
110
- print("[ice] 放行表清理失败(%s: %s)" % (type(exc).__name__, exc))
111
+ print("[ice] failed to clean allow table (%s: %s)" % (type(exc).__name__, exc))
111
112
 
112
113
  # 审批回答的唯一入口
113
114
  # 跨区 / 删除 / 计划三块几乎一样的代码,各自判 `active`、各自用精确
@@ -141,7 +142,7 @@ class PreProcessStage(Stage):
141
142
  ctx.metadata["dedup_skipped"] = True
142
143
  # 不许静默:这条消息被丢掉了,用户那边看见的是"没有回复"。
143
144
  # 一行日志是"重复投递"与"它没收到"唯一的区别。
144
- print("[dedup] 重复投递,跳过这一条(platform=%s scope=%s id=%s)"
145
+ print("[dedup] duplicate delivery, skipping this one (platform=%s scope=%s id=%s)"
145
146
  % (platform, _dedup_args["scope"], message_id))
146
147
  return ctx
147
148
  #: 轮末要用同一组参数落账 / 放位(`post_process` 与调度器读这一格)。
@@ -177,7 +178,7 @@ class PreProcessStage(Stage):
177
178
  if _exp.get("context"):
178
179
  _block = _block + "\n\n" + _exp["context"]
179
180
  except Exception as _exc: # noqa: BLE001
180
- print("[hooks] UserPromptExpansion 失败(忽略):%s: %s"
181
+ print("[hooks] UserPromptExpansion failed (ignored): %s: %s"
181
182
  % (type(_exc).__name__, _exc))
182
183
  user_input = _block
183
184
  ctx.user_message = _block
@@ -278,7 +279,7 @@ class PreProcessStage(Stage):
278
279
  _recap = recap_for(session_key)
279
280
  except Exception as exc: # noqa: BLE001
280
281
  # 回顾是锦上添花 —— 绝不能因此弄挂这一轮。
281
- print("[recap] 生成失败(%s: %s)—— 这一轮没有回顾"
282
+ print("[recap] generation failed (%s: %s) - no recap this turn"
282
283
  % (type(exc).__name__, exc))
283
284
  _recap = None
284
285
  if _recap:
@@ -295,7 +296,7 @@ class PreProcessStage(Stage):
295
296
  ctx.events.emit(EVT_RECAP, session_key=session_key,
296
297
  recap=_recap)
297
298
  except Exception as exc: # noqa: BLE001
298
- print("[recap] 事件发失败(%s: %s)—— 回顾这次看不到"
299
+ print("[recap] failed to emit event (%s: %s) - recap not shown"
299
300
  % (type(exc).__name__, exc))
300
301
 
301
302
  # 档位读取:设置读不出来,在这一轮开始前拒
@@ -318,7 +319,7 @@ class PreProcessStage(Stage):
318
319
  f"{exc}\n\n"
319
320
  "改 `data/settings.json` 的 `effort_level`(1–5 档),或在设置页里改。"
320
321
  )
321
- print(f"[tier] 拒了这一轮:{exc}")
322
+ print(f"[tier] rejected this turn: {exc}")
322
323
  return ctx
323
324
 
324
325
  # 工作区热重载检测
@@ -379,7 +380,7 @@ class PreProcessStage(Stage):
379
380
  "content": "[hook] " + _up["context"],
380
381
  "kind": "hook_context"})
381
382
  except Exception as _he: # noqa: BLE001
382
- print("[hooks] 本轮钩子失败(不影响对话):%s: %s"
383
+ print("[hooks] hook failed this turn (does not affect the conversation): %s: %s"
383
384
  % (type(_he).__name__, _he))
384
385
  # 这一段对话的工作目录
385
386
  #
@@ -404,10 +405,10 @@ class PreProcessStage(Stage):
404
405
  if _ok:
405
406
  _sw.set_for(sid, _ws_req)
406
407
  else:
407
- print("[workspace] 这一轮带的工作目录用不了(按未选处理):%s"
408
+ print("[workspace] this turn's workspace dir unusable (treated as not selected): %s"
408
409
  % _why)
409
410
  except Exception as _wse: # noqa: BLE001
410
- print("[workspace] 写本轮工作目录失败(按未选处理):%s: %s"
411
+ print("[workspace] failed to write this turn's workspace dir (treated as not selected): %s: %s"
411
412
  % (type(_wse).__name__, _wse))
412
413
  # 把解析出的段写回事件 —— 唯一的读者是 `core/cron/runner.py`,
413
414
  # 它要记下"这一次落在哪一段"。
@@ -764,9 +765,17 @@ class PreProcessStage(Stage):
764
765
  # · `/model 默认` / `跟随`,切回"跟随默认"
765
766
  session_key = session_key_of_ctx(ctx)
766
767
  parts = user_input.split(maxsplit=1)
768
+ rest = parts[1].strip() if len(parts) == 2 else ""
767
769
  ctx.metadata["stop"] = True
768
- if len(parts) == 2:
769
- ctx.response = _switch_session_model(session_key, parts[1].strip())
770
+ sub, _, tail = rest.partition(" ")
771
+ if sub == "more" and not tail.strip():
772
+ ctx.response = _list_all_models()
773
+ elif sub == "set":
774
+ ctx.response = _edit_model_guidance(tail.strip())
775
+ elif rest:
776
+ ctx.response = _switch_session_model(
777
+ session_key, rest, pool=ctx.session_pool,
778
+ provider=getattr(ctx, "provider", None))
770
779
  else:
771
780
  ctx.response = _describe_session_model(session_key)
772
781
  return ctx
@@ -806,7 +815,7 @@ class PreProcessStage(Stage):
806
815
  threads = _visible_threads(
807
816
  pool.list_threads(session_key, limit=_RESUME_LIMIT))
808
817
  if not threads:
809
- ctx.response = tr("这条通道还没有对话可以切换。")
818
+ ctx.response = tr("此通道还没有对话可以切换。")
810
819
  else:
811
820
  ctx.response = (_render_thread_list(threads)
812
821
  + tr("\n(用 `/change <编号>` 切过去;"
@@ -860,6 +869,16 @@ class PreProcessStage(Stage):
860
869
  ctx.response = _handle_mode(parts, session_key)
861
870
  return ctx
862
871
 
872
+ def _cmd_takeover(self, ctx: StageContext, user_input: str) -> StageContext:
873
+ # ---- /takeover on|off ----
874
+ # 接管的开关只能在完全权限下用 —— 与 `/api/computer-use/enable`
875
+ # 同一道判据(`frozen_mode == "full_access"`),两处不许各写一套。
876
+ # 这条命令让 TUI / IM / CLI 也有入口:GUI 那颗按钮不是唯一的路。
877
+ ctx.metadata["stop"] = True
878
+ ctx.response = _handle_takeover(user_input.split(),
879
+ session_key_of_ctx(ctx))
880
+ return ctx
881
+
863
882
  def _cmd_btw(self, ctx: StageContext, user_input: str) -> StageContext:
864
883
  # ---- /btw ----
865
884
  # 问一句题外话,不打断主对话。
@@ -1053,7 +1072,7 @@ def _validate_input(text: str) -> str | None:
1053
1072
  )
1054
1073
  if len(text) >= 20 and emoji_count / len(text) > _MAX_EMOJI_RATIO:
1055
1074
  return (
1056
- tr("⚠️ 你的消息主要是表情符号。请用文字描述你的需求,我会尽力帮助你。")
1075
+ tr("⚠️ 您的消息主要是表情符号。请用文字描述您的需求,我会尽力帮助您。")
1057
1076
  )
1058
1077
 
1059
1078
  # --- 3. Gibberish / binary detection ---
@@ -1067,7 +1086,7 @@ def _validate_input(text: str) -> str | None:
1067
1086
  ratio = printable / max(len(text), 1)
1068
1087
  if ratio < _MIN_PRINTABLE_RATIO:
1069
1088
  return (
1070
- tr("⚠️ 你的输入似乎包含大量非文本内容。如果你想解析文件,请使用对应的解析指令。")
1089
+ tr("⚠️ 您的输入似乎包含大量非文本内容。如果您想解析文件,请使用对应的解析指令。")
1071
1090
  )
1072
1091
 
1073
1092
  return None
@@ -1112,7 +1131,7 @@ def _handle_mcp_command() -> str:
1112
1131
  # 把"你没装 Node"说成"连不上",用户会去查服务器、而不是装东西。
1113
1132
  missing = missing_runtime(cfg)
1114
1133
  if missing:
1115
- status = trf("运行环境缺失:找不到 {cmd}", missing)
1134
+ status = trf("运行环境缺失:无法找到 {cmd}", missing)
1116
1135
  else:
1117
1136
  status = tr("❌ 未连接(重启后自动连接)")
1118
1137
  lines.append(f" {status} {name} ({transport}: {cmd})")
@@ -1146,6 +1165,103 @@ def _count_external_tools(mgr) -> int:
1146
1165
  return 0
1147
1166
 
1148
1167
 
1168
+ #: 无参清单只显示前几条。超过这个数就该走 `/model more`。
1169
+ _MODEL_LIST_LIMIT = 8
1170
+
1171
+
1172
+ def _model_no_config() -> str:
1173
+ return tr("未配置模型,拉起一个终端运行 crannia setup 以配置,"
1174
+ "或前往 GUI 内的端配置页尝试添加")
1175
+
1176
+
1177
+ def _model_dup_names(rows) -> set:
1178
+ """同名的那些名字。撞名时列表里要带 id,否则切换那条会回"重名"。"""
1179
+ seen: dict = {}
1180
+ for name, _cid, _label, _model in rows:
1181
+ key = str(name or "").strip().lower()
1182
+ seen[key] = seen.get(key, 0) + 1
1183
+ return {k for k, n in seen.items() if n > 1}
1184
+
1185
+
1186
+ def _model_item(index: int, row, default_id: str, dups: set) -> str:
1187
+ """列表里的一条:`1、「名字」(模型,默认)`。"""
1188
+ name, cid, _label, model = row
1189
+ tail = str(model or "").strip() or "-"
1190
+ is_default = cid == default_id
1191
+ dup = str(name or "").strip().lower() in dups
1192
+ if is_default and dup:
1193
+ tail = tr("%s,默认,id %s") % (tail, cid)
1194
+ elif is_default:
1195
+ tail = tr("%s,默认") % tail
1196
+ elif dup:
1197
+ tail = tr("%s,id %s") % (tail, cid)
1198
+ return tr("%d、「%s」(%s)") % (index, name or cid, tail)
1199
+
1200
+
1201
+ def _model_list_block(rows, default_id: str, *, limit=None) -> list[str]:
1202
+ """配置清单:一行头 + 一行条目(用 ` · ` 分开,终端自己折行)。"""
1203
+ total = len(rows)
1204
+ if not total:
1205
+ return []
1206
+ shown = rows if limit is None else rows[:limit]
1207
+ if limit is None:
1208
+ head = tr("全部配置(%d 条):") % total
1209
+ elif total > limit:
1210
+ head = tr("已配置 %d 条(显示前 %d 条,/model more 看全部):") % (
1211
+ total, limit)
1212
+ else:
1213
+ head = tr("已配置 %d 条:") % total
1214
+ dups = _model_dup_names(rows)
1215
+ items = [_model_item(i, row, default_id, dups)
1216
+ for i, row in enumerate(shown, 1)]
1217
+ return [head, " · ".join(items)]
1218
+
1219
+
1220
+ def _model_usage_lines() -> list[str]:
1221
+ """切换与修改的用法。两条路各一句,不混在一起。"""
1222
+ return [
1223
+ tr("使用 /model 编号、/model 配置名 或 /model <id> 切换;"
1224
+ "/model 默认 切回跟随默认。"),
1225
+ tr("使用 /model more 打印完整配置单;"
1226
+ "/model set <编号|配置名|id> 修改现有配置。"),
1227
+ ]
1228
+
1229
+
1230
+ def _resolve_model_ref(ref: str):
1231
+ """名字 / id / 编号 → 一条配置。编号是完整清单里的序号(从 1 起)。
1232
+
1233
+ 先按名字与 id 精确找,找不到才当编号 —— 一条正好叫 `9` 的配置
1234
+ 不会被编号 9 抢走。
1235
+ """
1236
+ from core import model_configs as _mc
1237
+
1238
+ ref = str(ref or "").strip()
1239
+ if not ref:
1240
+ return None
1241
+ hit = _mc.find_by_ref(ref)
1242
+ if hit is not None:
1243
+ return hit
1244
+ if ref.isdigit():
1245
+ rows = _mc.list_names()
1246
+ n = int(ref)
1247
+ if 1 <= n <= len(rows):
1248
+ return _mc.get(rows[n - 1][1])
1249
+ return None
1250
+
1251
+
1252
+ def _model_ref_error(ref: str) -> str:
1253
+ """引用找不到 / 撞名时的拒绝话术 —— 切换与修改共用这一份。"""
1254
+ from core import model_configs as _mc
1255
+
1256
+ clash = _mc.name_clashes(ref)
1257
+ if clash:
1258
+ return tr("存在重名配置,%s,使用/model id 以指定") % ref
1259
+ rows = _mc.list_names()
1260
+ avail = ("、".join(f"「{n}」" for n, _i, _c, _m in rows) if rows
1261
+ else tr("(空)"))
1262
+ return trf("没有找到此配置,已配置列表:{avail}", avail)
1263
+
1264
+
1149
1265
  def _describe_session_model(session_key: str) -> str:
1150
1266
  """`/model` 不带参数 —— 这一段现在用哪条模型配置。
1151
1267
 
@@ -1153,22 +1269,63 @@ def _describe_session_model(session_key: str) -> str:
1153
1269
  默认换掉之后这一段会不会跟着变。
1154
1270
  少了第二样,用户看到"正在用 A"就分不出那是自己选的还是恰好是默认的
1155
1271
  —— 而这正是他问 `/model` 想知道的事。
1272
+
1273
+ 清单与用法也接在这里:只说"跟随默认配置中"等于让用户自己猜下一步,
1274
+ 而配置名与 id 是切换唯一能用的两种引用。
1156
1275
  """
1157
1276
  from core import model_configs as _mc
1158
1277
  from core import session_model as _sm
1159
1278
 
1160
1279
  info = _sm.describe(session_key)
1161
- if not info["config_id"]:
1162
- return tr("跟随默认配置——前往端配置页配置一个模型以开始")
1280
+ rows, default_id = _mc.list_names(), _mc.default_id()
1281
+ if not rows:
1282
+ return _model_no_config()
1163
1283
  if info["frozen"]:
1164
1284
  e = _mc.get(info["config_id"]) or {}
1165
- return (tr("当前固定:%s,使用/model 配置名 以切换模型")
1166
- % (e.get("name") or info["config_id"]))
1167
- return tr("跟随默认配置中")
1285
+ head = tr("当前固定:「%s」。") % (e.get("name")
1286
+ or info["config_id"])
1287
+ elif not info["config_id"]:
1288
+ head = tr("还没有默认模型。")
1289
+ else:
1290
+ head = tr("跟随默认配置中。")
1291
+ return "\n".join([head,
1292
+ *_model_list_block(rows, default_id,
1293
+ limit=_MODEL_LIST_LIMIT),
1294
+ *_model_usage_lines()])
1295
+
1296
+
1297
+ def _list_all_models() -> str:
1298
+ """`/model more` —— 完整配置单。"""
1299
+ from core import model_configs as _mc
1300
+
1301
+ rows, default_id = _mc.list_names(), _mc.default_id()
1302
+ if not rows:
1303
+ return _model_no_config()
1304
+ return "\n".join([*_model_list_block(rows, default_id),
1305
+ *_model_usage_lines()])
1306
+
1307
+
1308
+ def _edit_model_guidance(ref: str) -> str:
1309
+ """`/model set` 在非 TUI 通道的答复。
1310
+
1311
+ 后端没有掩码输入口,不能在这里收密钥:命令正文会被当成普通消息
1312
+ 落库并送往模型(打错一个字就不再是命令)。真正编辑在 TUI 的
1313
+ 编辑面板,或桌面端端配置页。
1314
+ """
1315
+ ref = str(ref or "").strip()
1316
+ if not ref:
1317
+ return tr("使用 /model set <编号|配置名|id> 修改现有配置。")
1318
+ entry = _resolve_model_ref(ref)
1319
+ if entry is None:
1320
+ return _model_ref_error(ref)
1321
+ return tr("要修改「%s」:在 TUI 里直接使用 /model set(会弹出编辑面板);"
1322
+ "桌面端在「端配置」页编辑;没有界面时运行 crannia setup。") % (
1323
+ entry.get("name") or entry.get("id"))
1168
1324
 
1169
1325
 
1170
- def _switch_session_model(session_key: str, ref: str) -> str:
1171
- """`/model <配置名|id|默认>` —— 把这一段换成那条配置。
1326
+ def _switch_session_model(session_key: str, ref: str, *, pool=None,
1327
+ provider=None) -> str:
1328
+ """`/model <编号|配置名|id|默认>` —— 把这一段换成那条配置。
1172
1329
 
1173
1330
  三条纪律(与 `/effort` 同族):
1174
1331
  ① 先试装、后落盘 —— 装不上就不写(`preflight`,与"设为默认"相同)。
@@ -1182,22 +1339,61 @@ def _switch_session_model(session_key: str, ref: str) -> str:
1182
1339
 
1183
1340
  if ref in ("默认", "跟随", "default", "follow"):
1184
1341
  _sm.follow_default(session_key)
1185
- return tr("已切回跟随默认")
1342
+ return tr("已切回跟随默认") + _compact_after_model_switch(
1343
+ session_key, pool, provider)
1186
1344
 
1187
- entry = _mc.find_by_ref(ref)
1345
+ entry = _resolve_model_ref(ref)
1188
1346
  if not entry:
1189
- clash = _mc.name_clashes(ref)
1190
- if clash:
1191
- return tr("存在重名配置,%s,使用/model id 以指定") % ref
1192
- rows = _mc.list_names()
1193
- avail = ("、".join(f"「{n}」" for n, _i, _c, _m in rows) if rows
1194
- else tr("(空)"))
1195
- return trf("没有找到此配置,已配置列表:{avail}", avail)
1347
+ return _model_ref_error(ref)
1196
1348
  why = _mc.preflight(entry["id"])
1197
1349
  if why:
1198
1350
  return tr("此配置异常,请前往端配置页检查配置")
1199
1351
  _sm.set_for(session_key, entry["id"])
1200
- return tr("已切换,下一条消息起生效。")
1352
+ return tr("已切换,下一条消息起生效。") + _compact_after_model_switch(
1353
+ session_key, pool, provider)
1354
+
1355
+
1356
+ def _compact_after_model_switch(session_key: str, pool, provider=None) -> str:
1357
+ """切换模型后立刻按新窗口重算;超阈值就压一次。
1358
+
1359
+ 为什么不等下一轮:窗口变小之后,下一轮会在溢出检查里自救 —— 但那次
1360
+ 请求已经带着装不下的历史出门(先失败再压,或者上游直接 400)。
1361
+ 切换是用户明说"换模型"的那一刻,也是唯一能在他发下一条消息之前
1362
+ 做这件事的点。
1363
+
1364
+ 只做"超阈值才压":没超就一个字节不动,不替用户付一次摘要调用。
1365
+ 压不成的真实原因原样带出来(`last_skip_note`),不编一句"已完成"。
1366
+ """
1367
+ if pool is None:
1368
+ return ""
1369
+ try:
1370
+ _sid, msgs = pool.get_or_create(session_key, provider)
1371
+ if not msgs:
1372
+ return ""
1373
+ usage = pool.get_context_usage(session_key, msgs)
1374
+ threshold = int(usage.get("threshold_tokens") or 0)
1375
+ estimated = int(usage.get("estimated_tokens") or 0)
1376
+ if threshold <= 0 or estimated < threshold:
1377
+ return ""
1378
+ compacted, was_done = pool.compact(session_key, msgs)
1379
+ if not was_done:
1380
+ why = str(getattr(pool, "last_skip_note", "") or "").strip()
1381
+ return tr("(新模型窗口较小,但这次没压成:%s)") % (
1382
+ why or tr("原因没拿到"))
1383
+ # 与 `/compact` 同一条:会话池缓存的是对象引用 —— 不写回的话,
1384
+ # 下一轮拿回的还是压缩前那份。
1385
+ if session_key in pool._loaded:
1386
+ pool._loaded[session_key] = (pool._loaded[session_key][0], compacted)
1387
+ from core.memory.compressor import progress_payload
1388
+ note = str(progress_payload(
1389
+ pool.last_compression or {},
1390
+ usage.get("context_window")).get("message") or "").strip()
1391
+ return tr("(新模型窗口较小,已立即压缩:%s)") % (
1392
+ note or tr("完成"))
1393
+ except Exception as exc: # noqa: BLE001
1394
+ # 切换本身已经成功了;这里失败不该把整条命令说成失败。
1395
+ return tr("(切换成功;按新窗口检查失败:%s: %s —— 下一轮会自行处理)") % (
1396
+ type(exc).__name__, exc)
1201
1397
 
1202
1398
 
1203
1399
  def _handle_language(parts: list, session_key: str) -> str:
@@ -1330,6 +1526,32 @@ def _handle_effort(parts: list, session_key: str) -> str:
1330
1526
  return tr("已切换,下一条消息起生效(仅当前对话)。")
1331
1527
 
1332
1528
 
1529
+ def _handle_takeover(parts: list, session_key: str) -> str:
1530
+ """`/takeover on|off` —— 开关接管(无参 = 看状态)。
1531
+
1532
+ 与 GUI 那颗按钮、与 `/api/computer-use/{enable,disable}` 是同一件事:
1533
+ 真值都在 `core.computer.session`,这里只做入口与措辞。
1534
+ """
1535
+ from core import modes
1536
+ from core.computer import session as _cs
1537
+
1538
+ arg = parts[1].strip().lower() if len(parts) >= 2 else ""
1539
+ if arg not in ("on", "off"):
1540
+ state = tr("已开启") if _cs.enabled_for(session_key) else tr("未开启")
1541
+ return tr("当前接管状态:%s。用法:/takeover on|off") % state
1542
+ if arg == "off":
1543
+ # 只关自己持有的那一次 —— 别的会话开着的不替它关。
1544
+ if _cs.disable_for_session(session_key, "user"):
1545
+ return tr("已关闭接管模式。")
1546
+ return tr("当前会话没有在接管,无需关闭。")
1547
+ if modes.frozen_mode(session_key) != "full_access":
1548
+ return tr("接管模式仅在完全权限下支持,请先切换至完全权限后重试")
1549
+ ok, msg = _cs.enable(session_key)
1550
+ if not ok:
1551
+ return tr("启用接管失败:%s") % msg
1552
+ return tr("已启用接管模式,使用/takeover off以取消")
1553
+
1554
+
1333
1555
  def _handle_mode(parts: list, session_key: str) -> str:
1334
1556
  """`/mode` —— 看或改模式。
1335
1557
 
@@ -1496,7 +1718,7 @@ def _handle_resume(parts, ctx, session_key: str, pool) -> str:
1496
1718
  """
1497
1719
  threads = _visible_threads(pool.list_threads(session_key, limit=_RESUME_LIMIT))
1498
1720
  if not threads:
1499
- return (tr("这条通道还没有归档的对话。使用 `/clear` 之后,上一段会出现在这里。"))
1721
+ return (tr("此通道还没有归档的对话。使用 `/clear` 之后,上一段会出现在这里。"))
1500
1722
 
1501
1723
  arg = parts[1].strip() if len(parts) > 1 else ""
1502
1724
  if not arg:
@@ -2014,21 +2236,24 @@ _COMMANDS: tuple = (
2014
2236
  _CommandSpec("/context", "查看当前上下文的构成与占用", "_cmd_context"),
2015
2237
  _CommandSpec("/skill", "检查与启用技能", "_cmd_skill", MATCH_PREFIX),
2016
2238
  # 这一条必须排在 `/mode` 前面(见本表抬头)
2017
- _CommandSpec("/model", "查看或切换模型", "_cmd_model", MATCH_PREFIX),
2239
+ _CommandSpec("/model", "查看或切换模型(/model more 看全部,/model set 修改)",
2240
+ "_cmd_model", MATCH_PREFIX),
2018
2241
  _CommandSpec("/change", "查看 / 切换接入的对话(/change [编号])", "_cmd_change",
2019
2242
  MATCH_PREFIX),
2020
2243
  _CommandSpec("/effort", "调整模型档位", "_cmd_effort", MATCH_PREFIX),
2021
2244
  _CommandSpec("/language", "切换模型的回答语言(仅本次对话)",
2022
2245
  "_cmd_language", MATCH_PREFIX),
2023
- _CommandSpec("/mode", "切换模式(手动 / 自动 / 计划)", "_cmd_mode",
2246
+ _CommandSpec("/mode", "切换模式(手动 / 自动 / 计划 / 完全权限)", "_cmd_mode",
2024
2247
  MATCH_PREFIX),
2248
+ _CommandSpec("/takeover", "开启或关闭接管模式(/takeover on|off)",
2249
+ "_cmd_takeover", MATCH_PREFIX),
2025
2250
  _CommandSpec("/btw", "顺带问一句,不进入主对话与历史", "_cmd_btw",
2026
2251
  MATCH_PREFIX),
2027
2252
  _CommandSpec("/recap", "回顾最近的对话进度", "_cmd_recap"),
2028
2253
  _CommandSpec("/resume", "切换回以前的对话(/resume 查看列表)",
2029
2254
  "_cmd_resume", MATCH_BOTH),
2030
2255
  _CommandSpec("/fork", "复制当前对话为新线程", "_cmd_fork"),
2031
- _CommandSpec("/rewind", "退回到第 N 轮之前(对话与工作区文件一起回退)",
2256
+ _CommandSpec("/rewind", "退回至第 N 轮之前(对话与工作区文件一起回退)",
2032
2257
  "_cmd_rewind", MATCH_BOTH),
2033
2258
  _CommandSpec("/remember", "把一句话展开为完整提示词后执行",
2034
2259
  "_cmd_remember", MATCH_PREFIX, CMD_REWRITE),
@@ -2171,6 +2396,8 @@ _APPROVAL_KINDS = (
2171
2396
  # 出网与命令执行共用同一套派发/结算代码 —— 这正是重点:走现成的路,
2172
2397
  # 而不是各长一套流程。
2173
2398
  ("egress", "pending_egress"),
2399
+ # SSH 主机密钥信任(TOFU)- 自己一格(一格只许一个 kind 用)。
2400
+ ("ssh_hostkey", "pending_ssh_hostkey"),
2174
2401
  ("command", "pending_command"),
2175
2402
  # 兜底闸:不可逆、而自身没有审批发射点的工具。
2176
2403
  ("destructive", "pending_destructive"),
@@ -2308,10 +2535,10 @@ def _audit_approval(kind: str, subject: str, key: str, ask_index: int,
2308
2535
  guard = _security_guard_or_none()
2309
2536
  if guard is not None:
2310
2537
  guard.record_approval(kind, subject, str(key), outcome, rule)
2311
- print("[approval] %s %s(subject=%s key=%s rule=%s)"
2538
+ print("[approval] %s %s (subject=%s key=%s rule=%s)"
2312
2539
  % (kind, outcome, subject[:60] or "-", key, rule or "none"))
2313
2540
  except Exception as exc: # noqa: BLE001
2314
- print("[approval] 审批审计写入失败(%s: %s)—— 结算本身已发生"
2541
+ print("[approval] approval audit write failed (%s: %s) - settlement already happened"
2315
2542
  % (type(exc).__name__, exc))
2316
2543
 
2317
2544
 
@@ -2357,7 +2584,7 @@ def _answer_ask_user(pend: dict, user_input: str, ctx):
2357
2584
  # 对上了一部分、另一些不在表里 —— 不猜,也不结算。
2358
2585
  return _ask_keep_pending(
2359
2586
  pend, ctx,
2360
- tr("「%s」不在这次的选项里。回数字,或者直接说你自己的想法。")
2587
+ tr("「%s」不在这次的选项里。回数字,或者直接说您自己的想法。")
2361
2588
  % "、".join(unknown))
2362
2589
  if not multi and len(chosen) > 1:
2363
2590
  return _ask_keep_pending(
@@ -2369,7 +2596,7 @@ def _answer_ask_user(pend: dict, user_input: str, ctx):
2369
2596
  # 其余 = 用户想先聊(这正是那段回传文案定义的场景)。
2370
2597
  if unknown and all(t.isdigit() for t in unknown):
2371
2598
  return _ask_keep_pending(
2372
- pend, ctx, tr("「%s」不在这次的选项里。回数字,或者直接说你自己的想法。")
2599
+ pend, ctx, tr("「%s」不在这次的选项里。回数字,或者直接说您自己的想法。")
2373
2600
  % "、".join(unknown))
2374
2601
  pend["_free_text"] = text or tr("(用户没有作答)")
2375
2602
  return _SETTLERS["ask_user"]("", pend, ctx)
@@ -2853,16 +3080,40 @@ def _settle_delete_bulk(key: str, pend: dict, ctx):
2853
3080
  # 被审批物在 `pend["subject"]` 里(域名 / 收件人 / 命令文本)。两半授权都是
2854
3081
  # 按目标的;见 `WorkspaceManager.grant_target_once`。
2855
3082
 
3083
+ def _option_for_pend(kind: str, key: str, pend: dict):
3084
+ """用户回的那个键,在这一次真给出的选项表里是哪一项。
3085
+
3086
+ 取不到返回 None(那个键不存在 - 什么都不结算,退回重问)。
3087
+ ask_index / rule 都从载荷里取:升级项按当时那个下标才出现过。
3088
+ """
3089
+ from core.approval import find_option
3090
+ n = max(1, int(pend.get("ask_index") or 1))
3091
+ rule = str(pend.get("rule") or "")
3092
+ return find_option(kind, str(key), n, rule=rule)
3093
+
3094
+
2856
3095
  def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2857
3096
  approve_msg: str, deny_msg: str, all_msg: str = ""):
2858
3097
  subject = str(pend.get("subject") or "")
2859
- # 规则也必须在 `_drop_pending` 之前抓取 —— 那是 `pend.clear()`,
3098
+ # 规则也必须在 `_drop_pending` 之前抓取 - 那是 `pend.clear()`,
2860
3099
  # 读晚了就是空串(与下面的 `_replay` 同一个坑)。
2861
3100
  _rule = str(pend.get("rule") or "")
2862
3101
  # 在 `_drop_pending`(`pend.clear()`)之前抓取。
2863
3102
  _replay = _replay_of(pend)
2864
3103
 
2865
- if key == "1":
3104
+ # 键 -> 这一次真给出的那一项。按语义分派,不按数字 -
3105
+ # 各表的键位含义不同(出网四选项的 3 是"永久信任",命令表的是"不同意")。
3106
+ _opt = _option_for_pend(kind, key, pend)
3107
+ if _opt is None:
3108
+ return None
3109
+
3110
+ if _opt.stage:
3111
+ pend["stage"] = _opt.stage
3112
+ ctx.metadata["stop"] = True
3113
+ ctx.response = tr("有什么需要告诉 Crannia 的?")
3114
+ return ctx
3115
+
3116
+ if _opt.grant == GRANT_ONCE:
2866
3117
  _drop_pending(pend)
2867
3118
  _grant_target(ctx, kind, subject)
2868
3119
  ctx.user_message = approve_msg
@@ -2871,8 +3122,8 @@ def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2871
3122
  ctx.approval_replay = dict(_replay, fallback=approve_msg)
2872
3123
  return None
2873
3124
 
2874
- if key == "2":
2875
- # "本对话内不再询问这个目标" —— 只加这一个(不是 `"*"`)。
3125
+ if _opt.grant == GRANT_SESSION and not _opt.session_all:
3126
+ # "本对话内不再询问这个目标" - 只加这一个(不是 "*")。
2876
3127
  #
2877
3128
  # 对命令域来说,"这一个"是一条规则。两半有意不同,
2878
3129
  # 不要合并:
@@ -2889,22 +3140,19 @@ def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2889
3140
  ctx.approval_replay = dict(_replay, fallback=approve_msg)
2890
3141
  return None
2891
3142
 
2892
- if key == "3":
2893
- # 这是唯一接上"用户拒绝"头的地方 —— 出网 / 命令 / 兜底闸共用
3143
+ if _opt.grant == GRANT_NONE:
3144
+ # 这是唯一接上"用户拒绝"头的地方 - 出网 / 命令 / 兜底闸共用
2894
3145
  # 这个分支;它们的 `deny_msg` 动词不同,头是同一句。
2895
3146
  _drop_pending(pend)
2896
3147
  ctx.user_message = "[系统] " + outcome_line("rejected", deny_msg)
2897
3148
  ctx.approval_replay = _deny_of(_replay, ctx.user_message)
2898
3149
  return None
2899
3150
 
2900
- if key == "4":
2901
- pend["stage"] = "await_other"
2902
- ctx.metadata["stop"] = True
2903
- ctx.response = tr("有什么需要告诉 Crannia 的?")
2904
- return ctx
3151
+ # 自由文本那一支(stage=await_other)在上面统一处理 -
3152
+ # 这里不再按键位分支(出网四选项里没有这一项,命令表里有)。
2905
3153
 
2906
- if key == "5":
2907
- # 升级项:"本对话内所有目标自动放行" —— 存成通配符 `"*"`。
3154
+ if _opt.session_all:
3155
+ # 升级项:"本对话内所有目标自动放行" - 存成通配符 "*"。
2908
3156
  #
2909
3157
  # 会话级,绝不落盘。
2910
3158
  #
@@ -2934,21 +3182,20 @@ def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2934
3182
  ctx.approval_replay = dict(_replay, fallback=ctx.user_message)
2935
3183
  return None
2936
3184
 
2937
- if key == "6":
2938
- # "信任此站点,不再询问" —— 全仓唯一一处由弹窗写入
2939
- # `data/allowlist.json` 的地方。
3185
+ if _opt.grant == GRANT_PERSIST:
3186
+ # "信任此目标(永久)" - 全仓唯一一处由弹窗写入 data/allowlist.json
3187
+ # 的地方(出网四选项的第 3 项)。
2940
3188
  #
2941
3189
  # 这是对一条旧规则的例外("对话里点出来的东西不写那个文件")。
2942
- # 理由必须有正式记录,不能只留在代码注释中。
3190
+ # 理由必须有正式记录,不能只留在代码注释中。
2943
3191
  #
2944
- # fail-closed:只许 `egress`。其他 kind 走到这一支,说明
2945
- # 选项表配错了(今天只有 `egress` 有键 6),拒掉这一次,
2946
- # 什么都不记。宁可退化成"再问一次",也不要持久放行一个从未被
2947
- # 设计为可持久的东西(对 `command` 来说,持久化等于一张空头
2948
- # 支票:它按整条命令精确匹配)。
3192
+ # fail-closed:只许 egress。其他 kind 走到这一支,说明选项表配错了,
3193
+ # 拒掉这一次,什么都不记。宁可退化成"再问一次",也不要持久放行一个
3194
+ # 从未被设计为可持久的东西(命令那张表按整条精确匹配,持久化等于
3195
+ # 一张空头支票)。
2949
3196
  if kind != "egress":
2950
- print(f"[approval] kind={kind!r} 收到选项 6(信任此站点)—— "
2951
- f"**只有 egress 有这一档**,这次不记,退回重问")
3197
+ print(f"[approval] kind={kind!r} got persistent trust tier - "
3198
+ f"only egress has it; not recording, asking again")
2952
3199
  return None
2953
3200
  _drop_pending(pend)
2954
3201
  # 两半都发(与选项 2 同一条规矩):本轮重新提交能过 + 下一轮起生效。
@@ -2960,12 +3207,12 @@ def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2960
3207
  _ok = _wl_add("egress", subject)
2961
3208
  # 没写进去也要出声:`add` 是幂等的(已存在返回 False),
2962
3209
  # 而"点了信任、下次还问"必须能一眼看出是哪种情况。
2963
- print(f"[approval] 信任此站点:{subject} —— "
2964
- + ("已写进 data/allowlist.json" if _ok else "本来就在白名单里"))
3210
+ print(f"[approval] trusting this site: {subject} - "
3211
+ + ("written to data/allowlist.json" if _ok else "already in allowlist"))
2965
3212
  except Exception as exc: # noqa: BLE001
2966
3213
  # 写盘失败不回滚:两半已经发出,用户这一下是有效的;
2967
3214
  # 回滚只会让他再点一次,而那次同样会失败。如实报告就够了。
2968
- print(f"[approval] 信任此站点写盘失败(本次仍放行,但下次还会问):"
3215
+ print(f"[approval] failed to persist site trust (allowed this time, will ask again): "
2969
3216
  f"{type(exc).__name__}: {exc}")
2970
3217
  ctx.user_message = approve_msg
2971
3218
  ctx.approval_replay = dict(_replay, fallback=approve_msg)
@@ -2975,11 +3222,12 @@ def _settle_target(kind: str, key: str, pend: dict, ctx, *,
2975
3222
 
2976
3223
 
2977
3224
  def _settle_egress(key: str, pend: dict, ctx):
2978
- """出网:1 同意 / 2 本对话内不再问此目标 / 3 不同意 / 4 我有话说 /
2979
- 5 全部放行 / 6 信任此站点(落盘)。
3225
+ """出网:四选项(core/approval.py 的 EGRESS_OPTIONS)-
3226
+ 1 同意本次 / 2 本对话内不再问此目标 / 3 永久信任此目标 / 4 不同意。
2980
3227
 
2981
- `cross_zone` 的键含义不同(`2` = 缩小范围,`3` = 不同意)——
2982
- 不要跨表照抄 `1/2/3`;各表的定义在 `core/approval.py`。
3228
+ 结算走 _settle_target,但按选项语义分派(见那里):出网表的 3 与
3229
+ 命令表的 3 含义相反,按数字推断会把拒绝记成同意。
3230
+ cross_zone 的键含义又不同(2 = 缩小范围,3 = 不同意)- 不要跨表照抄。
2983
3231
  """
2984
3232
  return _settle_target(
2985
3233
  "egress", key, pend, ctx,
@@ -2998,6 +3246,48 @@ def _settle_egress(key: str, pend: dict, ctx):
2998
3246
  )
2999
3247
 
3000
3248
 
3249
+ def _settle_ssh_hostkey(key: str, pend: dict, ctx):
3250
+ """SSH 主机密钥信任:1 信任并继续 / 2 不信任。
3251
+
3252
+ 同意则把载荷里那一行写进框架自己的 data/runtime/ssh/known_hosts
3253
+ (不碰 ~/.ssh/known_hosts),然后重放那次调用 - 重放时主机密钥已经
3254
+ 在表里,连接才能过严格校验。
3255
+
3256
+ 它不经过 _settle_target:那一套发的是"目标的授权",而这里真正生效
3257
+ 的是 known_hosts 那一行。选项 1 的 GRANT_ONCE 只是"这次算同意"。
3258
+ """
3259
+ _replay = _replay_of(pend)
3260
+ _line = str(pend.get("host_key_line") or "")
3261
+ _subject = str(pend.get("subject") or "")
3262
+
3263
+ _opt = _option_for_pend("ssh_hostkey", key, pend)
3264
+ if _opt is not None and _opt.grant == GRANT_ONCE:
3265
+ _drop_pending(pend)
3266
+ try:
3267
+ from core.ssh_config import add_known_host
3268
+ _ok = add_known_host(_line)
3269
+ print(f"[approval] SSH host key recorded: {_subject} - "
3270
+ + ("written to data/runtime/ssh/known_hosts" if _ok
3271
+ else "already in table"))
3272
+ except Exception as exc: # noqa: BLE001
3273
+ # 写失败不回滚:用户这一下是有效的,但重放会再次撞上未知主机。
3274
+ # 如实出声 - "点了信任、下次还问"必须能一眼看出是哪种情况。
3275
+ print(f"[approval] failed to write SSH host key (replay will hit unknown host again): "
3276
+ f"{type(exc).__name__}: {exc}")
3277
+ ctx.user_message = ("[系统] 用户已信任此主机。"
3278
+ "请重新发起刚才那个 SSH 调用,框架会放行。")
3279
+ ctx.approval_replay = dict(_replay, fallback=ctx.user_message)
3280
+ return None
3281
+
3282
+ _drop_pending(pend)
3283
+ ctx.user_message = "[系统] " + outcome_line(
3284
+ "rejected",
3285
+ "用户没有信任这台主机的主机密钥。请告知用户这次连接没有建立;"
3286
+ "不要重试、也不要换个写法重试。")
3287
+ ctx.approval_replay = _deny_of(_replay, ctx.user_message)
3288
+ return None
3289
+
3290
+
3001
3291
  def _settle_destructive(key: str, pend: dict, ctx):
3002
3292
  """兜底闸:不可逆、而工具自身没有审批发射点的那些操作。
3003
3293
 
@@ -3062,7 +3352,7 @@ def _settle_write_outside(key: str, pend: dict, ctx):
3062
3352
  # —— 所以正常情况下模型不需要再发一次;这句话是退路。
3063
3353
  approve_msg=("[系统] 用户已同意把文件写到工作区之外的 `%s`。"
3064
3354
  "请**继续刚才那一步**。"
3065
- % (str(pend.get("subject") or "") or tr("那个目录"))),
3355
+ % (str(pend.get("subject") or "") or tr("该目录"))),
3066
3356
  deny_msg=(tr("本次没有写入任何文件。要写入该目录,可以:① 把产物放进工作区;② 在设置页把该目录加入工作区列表(长期有效);③ 在对话中同意这一次。")),
3067
3357
  all_msg=("[系统] 用户已同意:**本次对话内**往工作区之外写文件不再询问。"
3068
3358
  "请**继续刚才那一步**。"),
@@ -3152,7 +3442,7 @@ def _leave_plan_mode(ctx) -> None:
3152
3442
  # 数(让稀疏提醒过早或过晚触发)。
3153
3443
  reset_turn_index(sid)
3154
3444
  except Exception as exc:
3155
- print("[plan] 退出计划模式失败:%s" % exc)
3445
+ print("[plan] failed to exit plan mode: %s" % exc)
3156
3446
 
3157
3447
 
3158
3448
  def _grant_target(ctx, kind: str, subject: str) -> None:
@@ -3395,12 +3685,12 @@ def _settle_ice(key: str, pend: dict, ctx):
3395
3685
 
3396
3686
  def _emit_ice_downgraded(session_id: str) -> None:
3397
3687
  """说出"保护已降级"(标签不许说谎,界面必须一直看得见)。"""
3398
- print("[ice] 信息层在**本会话**内已降级(用户 §6.9 选项 2)—— /clear 回收")
3688
+ print("[ice] info layer downgraded for THIS session - /clear restores")
3399
3689
  try:
3400
3690
  from core.events import EVT_ICE_DOWNGRADED, get_event_bus
3401
3691
  get_event_bus().emit(EVT_ICE_DOWNGRADED, session_key=session_id)
3402
3692
  except Exception as exc: # noqa: BLE001
3403
- print("[ice] 降级事件发失败(%s: %s)" % (type(exc).__name__, exc))
3693
+ print("[ice] failed to emit downgrade event (%s: %s)" % (type(exc).__name__, exc))
3404
3694
 
3405
3695
 
3406
3696
  _SETTLERS = {
@@ -3410,6 +3700,8 @@ _SETTLERS = {
3410
3700
  # (见 `_settle_delete_bulk`)。
3411
3701
  "delete_bulk": _settle_delete_bulk,
3412
3702
  "egress": _settle_egress,
3703
+ # SSH 主机密钥信任:只写框架自己的 known_hosts,然后重放那次调用。
3704
+ "ssh_hostkey": _settle_ssh_hostkey,
3413
3705
  "command": _settle_command,
3414
3706
  "destructive": _settle_destructive,
3415
3707
  # 工作区之外写文件 —— 与出网/命令同一种结算器形状