@hfyjq/crannia 1.1.2 → 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 -7522
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +34 -24
  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 +10 -10
  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 +2 -2
  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 +36 -27
  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 +360 -68
  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 -1755
  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 +31 -6
  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
@@ -0,0 +1,609 @@
1
+ # -*- coding: utf-8 -*-
2
+ """SSH 客户端工具 —— 远端执行命令 / 传文件 / 探活。
3
+
4
+ ## 这条路的四道闸( / 出网权限重构 §3、§7)
5
+
6
+ 1. 出网审批 —— 每次调用先过 `core/egress_gate`,subject 是
7
+ `ssh:user@host`(决定 2);四选项:同意本次 / 本次对话不再问 /
8
+ 永久信任(写 `data/allowlist.json` 的 `egress` 格)/ 不同意。
9
+ 2. 主机密钥严格 —— 默认 `RejectPolicy`:未知主机拒,用户点
10
+ 「信任此主机并继续」才把指纹写进框架自己的
11
+ `data/runtime/ssh/known_hosts`(决定 4:不碰 `~/.ssh/known_hosts`);
12
+ 密钥与记录不一致(`BadHostKeyException`)一律拒,不给"警告并继续"。
13
+ 3. 路径 —— `ssh_upload` 的本地源过 `validate_path(..., "read")`
14
+ (`.env` / `data/settings.json` 读不到);`ssh_download` 的落点必须
15
+ 在工作区(`validate_path(..., "write")`)。
16
+ 4. 审计 —— 每次调用写一行 `EGRESS channel=ssh …`(`permission` 是
17
+ read 也写:出网的风险与工具权限档无关)。
18
+
19
+ ## 凭据
20
+
21
+ 私钥 / 口令 / 密码只在 `core/ssh_config` 读,绝不进工具参数;
22
+ 回执只出现条目名与主机。密码认证(决定 13)优先引导公钥,但没有密码
23
+ 认证就配不了新机器 —— 新树莓派常常只有密码。
24
+
25
+ `sudo`(决定 14):命令以 `sudo` 开头、且该条目配了 `sudo_password` 时,
26
+ 改写成 `sudo -S` 并把密码写进远端 stdin(没有 TTY 时这是唯一的路)。
27
+ 这是本工具的便利,不是命令解析器 —— 只认行首那一个词。
28
+
29
+ ## 超时与长任务(决定 15)
30
+
31
+ 超过 `timeout_s` 的命令会被中断。`apt upgrade` / 编译这类请自己用
32
+ `nohup ... > log 2>&1 &` 起、再用 `ssh_exec("tail -n 50 log")` 轮询;
33
+ P3 会把它们挂进后台作业。
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import base64
39
+ import hashlib
40
+ import time
41
+ from pathlib import Path
42
+ from typing import Any
43
+
44
+ from core import ssh_config
45
+ from core.i18n import t as tr, tr_fmt as trf
46
+
47
+ __all__ = ["init", "ssh_exec", "ssh_upload", "ssh_download", "ssh_probe"]
48
+
49
+ MAX_OUTPUT = 64 * 1024
50
+ DEFAULT_TIMEOUT = 20.0
51
+
52
+ #: 由 `bus` 在装载时注入(`init(security_guard)`)。
53
+ _guard = None
54
+
55
+
56
+ def init(security_guard=None) -> None:
57
+ global _guard
58
+ _guard = security_guard
59
+
60
+
61
+ def _ok(tool: str, data: dict, t0: float, **extra) -> dict:
62
+ out = {"success": True, "tool": tool, "data": data, "error": "",
63
+ "duration_ms": int((time.monotonic() - t0) * 1000)}
64
+ out.update(extra)
65
+ return out
66
+
67
+
68
+ def _err(tool: str, msg: str, t0: float, **extra) -> dict:
69
+ out = {"success": False, "tool": tool, "data": {}, "error": msg,
70
+ "duration_ms": int((time.monotonic() - t0) * 1000)}
71
+ out.update(extra)
72
+ return out
73
+
74
+
75
+ def _audit(action: str, target: str, grant: str = "", verdict: str = "") -> None:
76
+ """写一行 EGRESS 审计。失败不影响调用(只印一行)。"""
77
+ if _guard is None:
78
+ return
79
+ try:
80
+ _guard.record_egress("ssh", target, action, grant, verdict)
81
+ except Exception as exc: # noqa: BLE001
82
+ print(f"[ssh] audit write failed ({type(exc).__name__}: {exc})")
83
+
84
+
85
+ def _mdns_hint(host: str) -> str:
86
+ """`.local` 的解析失败在 Windows 上极常见 —— 给一句路线,不假装成功。"""
87
+ if str(host or "").lower().endswith(".local"):
88
+ return ("(`.local` 在 Windows 上常常解析不了 —— 改用 IP,"
89
+ "或安装 Bonjour / 用路由器的设备列表找地址。)")
90
+ return ""
91
+
92
+
93
+ def _gate(tool_name: str, host: str, action: str, *, user: str = "",
94
+ key_name: str = "", timeout_hint: str = ""):
95
+ """出网审批。放行返回 `None`;要问返回载荷,调用方直接返回它。
96
+
97
+ subject 由 `core.egress_gate.subject_from_args` 算 —— 与自动/完全权限
98
+ 预授权那一条同一个函数(写入与匹配同形)。
99
+ """
100
+ from core.egress_gate import subject_from_args, gate_for
101
+
102
+ args = {"host": host, "user": user, "key_name": key_name}
103
+ subj = subject_from_args(tool_name, args)
104
+ if not subj:
105
+ return None # 空目标在下面由参数校验挡掉
106
+ # 键是模板(`{host}` 这类)—— 先翻再填,英文译文才能改语序。
107
+ body = trf("Crannia 想通过 SSH 连接到 **{host}**({action})。\n"
108
+ "目标:`{target}`", host, tr(action), subj)
109
+ if timeout_hint:
110
+ body += "\n" + timeout_hint
111
+ return gate_for(subj, tool_name=tool_name, body=body)
112
+
113
+
114
+ def _hostkey_pending(tool_name: str, subject: str, host: str, port: int,
115
+ key) -> dict:
116
+ """未知主机的信任载荷(`kind=ssh_hostkey`)。"""
117
+ from core.approval import pending_payload
118
+
119
+ line = "%s %s %s" % (host, key.get_name(), key.get_base64())
120
+ fp = "SHA256:" + base64.b64encode(
121
+ hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
122
+ body = trf("Crannia 第一次连接 **{host}**。\n"
123
+ "主机密钥:{keytype}\n指纹:{fp}\n"
124
+ "核对指纹确实是你要连的那台机器,再选择信任。",
125
+ host, key.get_name(), fp)
126
+ return pending_payload(
127
+ "ssh_hostkey",
128
+ body=body,
129
+ footer=True,
130
+ subject=subject,
131
+ detail="%s %s" % (host, fp),
132
+ host=host,
133
+ port=int(port),
134
+ host_key_line=line,
135
+ fingerprint=fp,
136
+ tool=tool_name,
137
+ status="pending_ssh_hostkey_approval",
138
+ )
139
+
140
+
141
+ def _fetch_host_key(host: str, port: int, timeout: float):
142
+ """连一次取主机公钥(不认证)。取不到返回 `(None, 原因)`。"""
143
+ import paramiko
144
+ t = None
145
+ try:
146
+ t = paramiko.Transport((host, int(port)))
147
+ t.start_client(timeout=float(timeout))
148
+ return t.get_remote_server_key(), ""
149
+ except Exception as exc: # noqa: BLE001
150
+ return None, "%s: %s" % (type(exc).__name__, exc)
151
+ finally:
152
+ if t is not None:
153
+ try:
154
+ t.close()
155
+ except Exception: # noqa: BLE001
156
+ pass
157
+
158
+
159
+ def _connect(host: str, port: int, user: str, key_name: str, timeout: float,
160
+ tool_name: str):
161
+ """建连接。返回 `(client, error_msg, pending_payload)`。
162
+
163
+ `pending_payload` 非 `None` 表示"要先问用户"(未知主机密钥)——
164
+ 调用方原样把它当回执返回(`agent_loop` 认 `pending_` 前缀)。
165
+ """
166
+ try:
167
+ import paramiko # noqa: F401
168
+ except ImportError:
169
+ return None, ("缺少 paramiko(LGPL-2.1)。请 `pip install paramiko`,"
170
+ "或在设置页 → 技能 → SSH 里查看配置。"), None
171
+
172
+ entry = ssh_config.resolve_entry(str(key_name or ""))
173
+ u = str(user or entry.get("user") or "").strip()
174
+ key = str(entry.get("key_path") or "").strip()
175
+ ph = str(entry.get("passphrase") or "").strip()
176
+ pw = str(entry.get("password") or "").strip()
177
+ if not key and not pw:
178
+ return None, ("没配 SSH 凭据。去设置页 → 技能 → SSH 填私钥路径或密码"
179
+ "(不要放在工具参数里)。"), None
180
+ if key:
181
+ p = Path(key).expanduser()
182
+ if not p.is_file():
183
+ return None, "私钥文件不存在:%s(条目 %s)" % (p.name, entry.get("name")), None
184
+
185
+ import paramiko
186
+ subj = _subject_of(u, host)
187
+ cli = paramiko.SSHClient()
188
+ # 读两份:用户自己的(他手动连过的直接能用)+ 框架自己的(信任审批写的)。
189
+ try:
190
+ cli.load_system_host_keys()
191
+ except Exception as exc: # noqa: BLE001
192
+ print(f"[ssh] failed to read system known_hosts (treated as empty): {type(exc).__name__}: {exc}")
193
+ try:
194
+ kh = ssh_config.known_hosts_path()
195
+ if kh.exists():
196
+ cli.load_host_keys(str(kh))
197
+ except Exception as exc: # noqa: BLE001
198
+ print(f"[ssh] failed to read framework known_hosts (treated as empty): {type(exc).__name__}: {exc}")
199
+ # 严格:未知主机一律拒(不给"警告并继续")。
200
+ cli.set_missing_host_key_policy(paramiko.RejectPolicy())
201
+
202
+ kwargs: dict[str, Any] = {
203
+ "hostname": host, "port": int(port),
204
+ "username": u or None, "timeout": float(timeout),
205
+ "allow_agent": False, "look_for_keys": False,
206
+ }
207
+ if pw and not key:
208
+ kwargs["password"] = pw
209
+ else:
210
+ kwargs["key_filename"] = str(Path(key).expanduser())
211
+ kwargs["passphrase"] = ph or None
212
+
213
+ try:
214
+ cli.connect(**kwargs)
215
+ return cli, "", None
216
+ except paramiko.BadHostKeyException:
217
+ try:
218
+ cli.close()
219
+ except Exception: # noqa: BLE001
220
+ pass
221
+ return None, (
222
+ "主机密钥与已记录的不一致:%s。这可能是中间人攻击,也可能是"
223
+ "机器重装过。请先在终端里确认指纹;确认无误后,把 "
224
+ "data/runtime/ssh/known_hosts 里那一行删掉再重试。"
225
+ % host), None
226
+ except paramiko.SSHException as exc:
227
+ try:
228
+ cli.close()
229
+ except Exception: # noqa: BLE001
230
+ pass
231
+ if "not found in known_hosts" not in str(exc):
232
+ return None, "%s: %s" % (type(exc).__name__, exc), None
233
+ # 未知主机 —— 取指纹,问用户。取不到就给路线(不回退到不校验)。
234
+ hk, why = _fetch_host_key(host, int(port), float(timeout))
235
+ if hk is None:
236
+ return None, ("未知主机 %s,且取不到它的主机密钥(%s)。"
237
+ "可以先用终端 ssh 连一次,把指纹记下来。" % (host, why)), None
238
+ return None, "", _hostkey_pending(tool_name, subj, host, int(port), hk)
239
+ except Exception as exc: # noqa: BLE001
240
+ try:
241
+ cli.close()
242
+ except Exception: # noqa: BLE001
243
+ pass
244
+ msg = "%s: %s" % (type(exc).__name__, exc)
245
+ return None, msg + _mdns_hint(host), None
246
+
247
+
248
+ def _subject_of(user: str, host: str) -> str:
249
+ from core.egress_gate import ssh_subject
250
+ return ssh_subject(user, host)
251
+
252
+
253
+ # 工具
254
+
255
+ def ssh_exec(host: str, command: str, port: int = 22, user: str = "",
256
+ key_name: str = "", timeout_s: float = DEFAULT_TIMEOUT) -> dict:
257
+ """在远端执行一条命令,回 stdout/stderr/exit_code(输出有上限)。"""
258
+ t0 = time.monotonic()
259
+ target = str(host or "").strip()
260
+ cmd = str(command or "").strip()
261
+ if not target or not cmd:
262
+ return _err("ssh_exec", "host 与 command 都不能为空", t0)
263
+
264
+ gate = _gate("ssh_exec", target, "执行命令", user=str(user),
265
+ key_name=str(key_name))
266
+ if gate is not None:
267
+ _audit("exec", target, "", "asked")
268
+ return gate
269
+
270
+ cli, why, pend = _connect(target, int(port), str(user), str(key_name),
271
+ float(timeout_s), "ssh_exec")
272
+ if pend is not None:
273
+ _audit("exec", target, "", "asked")
274
+ return pend
275
+ if cli is None:
276
+ _audit("exec", target, "granted", "error")
277
+ return _err("ssh_exec", why, t0)
278
+
279
+ entry = ssh_config.resolve_entry(str(key_name or ""))
280
+ sudo_pw = str(entry.get("sudo_password") or "").strip()
281
+ use_sudo_stdin = bool(sudo_pw) and cmd.startswith("sudo ")
282
+ try:
283
+ if use_sudo_stdin:
284
+ # 没有 TTY 时 `sudo` 读 stdin —— `-S` 让它从管道读密码,
285
+ # `-p ''` 免得提示语混进 stderr。
286
+ cmd = "sudo -S -p '' " + cmd[len("sudo "):]
287
+ stdin, stdout, stderr = cli.exec_command(cmd, timeout=float(timeout_s))
288
+ if use_sudo_stdin:
289
+ try:
290
+ stdin.write(sudo_pw + "\n")
291
+ stdin.flush()
292
+ except Exception: # noqa: BLE001
293
+ pass
294
+ out_b = stdout.read(MAX_OUTPUT)
295
+ err_b = stderr.read(MAX_OUTPUT)
296
+ code = stdout.channel.recv_exit_status()
297
+ data = {"host": target, "command": cmd,
298
+ "stdout": out_b.decode("utf-8", "replace"),
299
+ "stderr": err_b.decode("utf-8", "replace"),
300
+ "exit_code": code}
301
+ _audit("exec", target, "granted", "ok")
302
+ return _ok("ssh_exec", data, t0,
303
+ truncated=len(out_b) >= MAX_OUTPUT or len(err_b) >= MAX_OUTPUT)
304
+ except Exception as exc: # noqa: BLE001
305
+ _audit("exec", target, "granted", "error")
306
+ msg = "%s: %s" % (type(exc).__name__, exc)
307
+ if "timed out" in msg.lower() or "timeout" in msg.lower():
308
+ msg += ("。长任务请用 `nohup <命令> > /tmp/x.log 2>&1 &` 起,"
309
+ "再用 ssh_exec(\"tail -n 50 /tmp/x.log\") 轮询。")
310
+ return _err("ssh_exec", msg, t0)
311
+ finally:
312
+ try:
313
+ cli.close()
314
+ except Exception: # noqa: BLE001
315
+ pass
316
+
317
+
318
+ def ssh_upload(host: str, local_path: str, remote_path: str,
319
+ port: int = 22, user: str = "", key_name: str = "",
320
+ timeout_s: float = DEFAULT_TIMEOUT) -> dict:
321
+ """本地文件 → 远端(SFTP),远端目录不会自动创建。"""
322
+ t0 = time.monotonic()
323
+ src = Path(str(local_path or ""))
324
+ if not src.is_file():
325
+ return _err("ssh_upload", "本地文件不存在:%s" % src.name, t0)
326
+ # 本地源过路径三级分类:`.env` 一族读不到(FORBIDDEN),
327
+ # 用户划的规避目录也不行 —— 这是"读本地文件外发"的那道闸。
328
+ try:
329
+ if _guard is not None:
330
+ _guard.validate_path(str(src), "read")
331
+ except Exception as exc: # noqa: BLE001
332
+ _audit("upload", str(host or ""), "", "error")
333
+ return _err("ssh_upload", "不能上传这个文件:%s" % exc, t0)
334
+
335
+ gate = _gate("ssh_upload", str(host or ""), "上传文件",
336
+ user=str(user), key_name=str(key_name))
337
+ if gate is not None:
338
+ _audit("upload", str(host or ""), "", "asked")
339
+ return gate
340
+
341
+ cli, why, pend = _connect(str(host or ""), int(port), str(user),
342
+ str(key_name), float(timeout_s), "ssh_upload")
343
+ if pend is not None:
344
+ _audit("upload", str(host or ""), "", "asked")
345
+ return pend
346
+ if cli is None:
347
+ _audit("upload", str(host or ""), "granted", "error")
348
+ return _err("ssh_upload", why, t0)
349
+ try:
350
+ with cli.open_sftp() as sftp:
351
+ sftp.put(str(src), str(remote_path or ""))
352
+ _audit("upload", str(host or ""), "granted", "ok")
353
+ return _ok("ssh_upload", {"host": host, "local": src.name,
354
+ "remote": remote_path,
355
+ "bytes": src.stat().st_size}, t0)
356
+ except Exception as exc: # noqa: BLE001
357
+ _audit("upload", str(host or ""), "granted", "error")
358
+ return _err("ssh_upload", "%s: %s" % (type(exc).__name__, exc), t0)
359
+ finally:
360
+ try:
361
+ cli.close()
362
+ except Exception: # noqa: BLE001
363
+ pass
364
+
365
+
366
+ def ssh_download(host: str, remote_path: str, local_path: str,
367
+ port: int = 22, user: str = "", key_name: str = "",
368
+ timeout_s: float = DEFAULT_TIMEOUT) -> dict:
369
+ """远端文件 → 本地(SFTP)。落点必须在工作区。"""
370
+ t0 = time.monotonic()
371
+ dst = Path(str(local_path or ""))
372
+ if not str(dst):
373
+ return _err("ssh_download", "local_path 不能为空", t0)
374
+ # 相对路径落在本段对话的默认输出目录(`primary_output_dir`),
375
+ # 然后把最终路径过一遍写权限 —— 区外写有它自己的一道审批。
376
+ try:
377
+ from core.workspace import primary_output_dir
378
+ if not dst.is_absolute():
379
+ dst = Path(primary_output_dir()) / dst
380
+ if _guard is not None:
381
+ _guard.validate_path(str(dst), "write")
382
+ except Exception as exc: # noqa: BLE001
383
+ _audit("download", str(host or ""), "", "error")
384
+ return _err("ssh_download", "不能写到这个位置:%s" % exc, t0)
385
+
386
+ gate = _gate("ssh_download", str(host or ""), "下载文件",
387
+ user=str(user), key_name=str(key_name))
388
+ if gate is not None:
389
+ _audit("download", str(host or ""), "", "asked")
390
+ return gate
391
+
392
+ cli, why, pend = _connect(str(host or ""), int(port), str(user),
393
+ str(key_name), float(timeout_s), "ssh_download")
394
+ if pend is not None:
395
+ _audit("download", str(host or ""), "", "asked")
396
+ return pend
397
+ if cli is None:
398
+ _audit("download", str(host or ""), "granted", "error")
399
+ return _err("ssh_download", why, t0)
400
+ try:
401
+ dst.parent.mkdir(parents=True, exist_ok=True)
402
+ with cli.open_sftp() as sftp:
403
+ sftp.get(str(remote_path), str(dst))
404
+ _audit("download", str(host or ""), "granted", "ok")
405
+ return _ok("ssh_download", {"host": host, "remote": remote_path,
406
+ "local": str(dst),
407
+ "bytes": dst.stat().st_size}, t0)
408
+ except Exception as exc: # noqa: BLE001
409
+ _audit("download", str(host or ""), "granted", "error")
410
+ return _err("ssh_download", "%s: %s" % (type(exc).__name__, exc), t0)
411
+ finally:
412
+ try:
413
+ cli.close()
414
+ except Exception: # noqa: BLE001
415
+ pass
416
+
417
+
418
+ def ssh_probe(host: str, port: int = 22, timeout_s: float = 5.0) -> dict:
419
+ """探活:TCP 可达 + SSH banner。不需要凭据(只建 socket)。"""
420
+ t0 = time.monotonic()
421
+ target = str(host or "").strip()
422
+ if not target:
423
+ return _err("ssh_probe", "host 不能为空", t0)
424
+ gate = _gate("ssh_probe", target, "探活")
425
+ if gate is not None:
426
+ _audit("probe", target, "", "asked")
427
+ return gate
428
+ import socket
429
+ try:
430
+ with socket.create_connection((target, int(port)), timeout=float(timeout_s)) as s:
431
+ s.settimeout(float(timeout_s))
432
+ banner = ""
433
+ try:
434
+ banner = s.recv(256).decode("utf-8", "replace").strip()
435
+ except OSError:
436
+ pass
437
+ _audit("probe", target, "granted", "ok")
438
+ return _ok("ssh_probe", {"host": target, "port": int(port),
439
+ "reachable": True, "banner": banner[:200]}, t0)
440
+ except Exception as exc: # noqa: BLE001
441
+ _audit("probe", target, "granted", "error")
442
+ return _ok("ssh_probe", {"host": target, "port": int(port),
443
+ "reachable": False,
444
+ "reason": "%s: %s%s" % (type(exc).__name__, exc,
445
+ _mdns_hint(target))}, t0)
446
+
447
+
448
+ def _bridge(sock_a, sock_b) -> None:
449
+ """在两个 socket-like 之间双向搬字节(任一方向结束就半关)。"""
450
+ import socket as _socket
451
+ import threading as _threading
452
+
453
+ def one_way(src, dst) -> None:
454
+ try:
455
+ while True:
456
+ data = src.recv(16384)
457
+ if not data:
458
+ break
459
+ if hasattr(dst, "sendall"):
460
+ dst.sendall(data)
461
+ else:
462
+ dst.send(data)
463
+ except Exception: # noqa: BLE001
464
+ pass
465
+ finally:
466
+ try:
467
+ if hasattr(dst, "shutdown_write"):
468
+ dst.shutdown_write()
469
+ else:
470
+ dst.shutdown(_socket.SHUT_WR)
471
+ except Exception: # noqa: BLE001
472
+ pass
473
+
474
+ t = _threading.Thread(target=one_way, args=(sock_b, sock_a), daemon=True)
475
+ t.start()
476
+ one_way(sock_a, sock_b)
477
+
478
+
479
+ def ssh_forward(host: str, remote_host: str, remote_port: int,
480
+ local_port: int = 0, port: int = 22, user: str = "",
481
+ key_name: str = "", timeout_s: float = 20.0) -> dict:
482
+ """本地端口转发:127.0.0.1:local_port → remote_host:remote_port(经 SSH)。
483
+
484
+ 工具本身立刻返回,隧道跑在统一任务表里(`task` 工具可查、可取消;
485
+ `/clear` 会停掉它)。寿限跟作业表一致(30 分钟),到点自动收。
486
+ 这是 nc / socat 的 relay 那一路的正规替身。
487
+ """
488
+ t0 = time.monotonic()
489
+ target = str(host or "").strip()
490
+ rh = str(remote_host or "").strip()
491
+ if not target or not rh:
492
+ return _err("ssh_forward", "host 与 remote_host 都不能为空", t0)
493
+ try:
494
+ rport = int(remote_port)
495
+ lport = int(local_port or 0)
496
+ except (TypeError, ValueError):
497
+ return _err("ssh_forward", "端口必须是整数", t0)
498
+ if not (1 <= rport <= 65535) or not (0 <= lport <= 65535):
499
+ return _err("ssh_forward", "端口超出范围", t0)
500
+
501
+ gate = _gate("ssh_forward", target, "建立隧道", user=str(user),
502
+ key_name=str(key_name))
503
+ if gate is not None:
504
+ _audit("forward", target, "", "asked")
505
+ return gate
506
+
507
+ cli, why, pend = _connect(target, int(port), str(user), str(key_name),
508
+ float(timeout_s), "ssh_forward")
509
+ if pend is not None:
510
+ _audit("forward", target, "", "asked")
511
+ return pend
512
+ if cli is None:
513
+ _audit("forward", target, "granted", "error")
514
+ return _err("ssh_forward", why, t0)
515
+ transport = cli.get_transport()
516
+ if transport is None or not transport.is_active():
517
+ try:
518
+ cli.close()
519
+ except Exception: # noqa: BLE001
520
+ pass
521
+ return _err("ssh_forward", "SSH 传输层没起来(连接立刻断了)", t0)
522
+
523
+ import socket as _socket
524
+ listener = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
525
+ try:
526
+ listener.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
527
+ listener.bind(("127.0.0.1", lport))
528
+ listener.listen(16)
529
+ listener.settimeout(0.5)
530
+ except Exception as exc: # noqa: BLE001
531
+ try:
532
+ listener.close()
533
+ cli.close()
534
+ except Exception: # noqa: BLE001
535
+ pass
536
+ _audit("forward", target, "granted", "error")
537
+ return _err("ssh_forward", "本地端口用不了:%s(换一个 local_port)" % exc, t0)
538
+
539
+ actual = listener.getsockname()[1]
540
+ # 任务列表里显示的就是这一句 —— 先翻模板再填值(同审批正文那两条)。
541
+ label = trf("ssh 隧道 127.0.0.1:{local} -> {remote}:{rport}(经 {host})",
542
+ actual, rh, rport, target)
543
+
544
+ from core import jobs as _jobs
545
+ try:
546
+ from core.request_snapshot import current_session_id
547
+ sid = str(current_session_id() or "")
548
+ except Exception: # noqa: BLE001
549
+ sid = ""
550
+
551
+ def _run(job) -> str:
552
+ deadline = time.monotonic() + (_jobs.JOB_MAX_LIFETIME_MS / 1000.0)
553
+ job.out.write(("%s 已开始\n" % label).encode("utf-8"))
554
+ try:
555
+ while not job.cancel_event.is_set() and time.monotonic() < deadline:
556
+ try:
557
+ conn, peer = listener.accept()
558
+ except _socket.timeout:
559
+ continue
560
+ except OSError:
561
+ break
562
+ try:
563
+ chan = transport.open_channel(
564
+ "direct-tcpip", (rh, rport), peer, timeout=float(timeout_s))
565
+ except Exception as exc: # noqa: BLE001
566
+ job.out.write(("打开通道失败:%s: %s\n"
567
+ % (type(exc).__name__, exc)).encode("utf-8"))
568
+ conn.close()
569
+ continue
570
+ import threading as _threading
571
+ _threading.Thread(target=_bridge, args=(conn, chan),
572
+ daemon=True).start()
573
+ job.out.write(("连接:%s\n" % (peer,)).encode("utf-8"))
574
+ finally:
575
+ try:
576
+ listener.close()
577
+ except Exception: # noqa: BLE001
578
+ pass
579
+ try:
580
+ transport.close()
581
+ cli.close()
582
+ except Exception: # noqa: BLE001
583
+ pass
584
+ if job.cancel_event.is_set():
585
+ return "隧道已停止(取消)。"
586
+ return "隧道到寿限(30 分钟)自动停止;要续,重新调用。"
587
+
588
+ try:
589
+ job = _jobs.start_thread(_run, kind=_jobs.KIND_SKILL, command=label,
590
+ session_key=sid, storage_id=sid,
591
+ description=label, notify=False)
592
+ except Exception as exc: # noqa: BLE001
593
+ try:
594
+ listener.close()
595
+ cli.close()
596
+ except Exception: # noqa: BLE001
597
+ pass
598
+ return _err("ssh_forward", "起不了后台任务:%s: %s"
599
+ % (type(exc).__name__, exc), t0)
600
+
601
+ _audit("forward", target, "granted", "ok")
602
+ return _ok("ssh_forward", {
603
+ "host": target,
604
+ "local": "127.0.0.1:%d" % actual,
605
+ "remote": "%s:%d" % (rh, rport),
606
+ "task_id": job.id,
607
+ "note": ("隧道在后台跑(30 分钟寿限)。用 task 工具查/停它;"
608
+ "把 local 地址给需要连它的程序即可。"),
609
+ }, t0, truncated=False)