@hfyjq/crannia 1.0.0 → 1.1.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 (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -1,22 +1,22 @@
1
- """Built-in MCP servers — run in-process, tools bridged to bus/registry."""
2
-
3
- #: 内置 MCP 服务器的名字 —— 一处定义。
4
- #:
5
- #: 真值来源:`mcpx/servers/<名>.py` 里那个 `register_tools()` 会把它的工具挂在
6
- #: owner `mcp:<名>` 上(`web_search.py` 那两处 `register_tool(..., owner=...)`)。
7
- #:
8
- #: 谁读它:
9
- #: · `mcpx/manager.py::load_builtin_servers` —— 按这份名单去 import
10
- #: · `GET /api/mcp/servers` —— 哪几条要打「内置」黄标、哪几条不能真删(只许停用)
11
- #: · `bus/mcp_disabled.py` —— 停用是按 owner 走的,这一份是它的展示名
12
- #:
13
- #: 不要再手抄这个数(例如在 `manager.get_status` 里写 `"builtin_servers": 1`)——
14
- #: 多份手抄会各自漂移,而名单只有一条时看不出来。
15
- #: 读者 `tests/test_mcp_servers.py` 两向钉着:名单里的每个都要真有一个
16
- #: `mcpx/servers/<名>.py`,且它注册出来的 owner 就是 `mcp:<名>`。
17
- BUILTIN_SERVERS: tuple[str, ...] = ("web_search",)
18
-
19
-
20
- def owner_of(server_name: str) -> str:
21
- """内置服务器名 → 归属键。与 `bus/quarantine.owner_for_mcp` 逐字同形。"""
22
- return "mcp:" + str(server_name)
1
+ """Built-in MCP servers — run in-process, tools bridged to bus/registry."""
2
+
3
+ #: 内置 MCP 服务器的名字 —— 一处定义。
4
+ #:
5
+ #: 真值来源:`mcpx/servers/<名>.py` 里那个 `register_tools()` 会把它的工具挂在
6
+ #: owner `mcp:<名>` 上(`web_search.py` 那两处 `register_tool(..., owner=...)`)。
7
+ #:
8
+ #: 谁读它:
9
+ #: · `mcpx/manager.py::load_builtin_servers` —— 按这份名单去 import
10
+ #: · `GET /api/mcp/servers` —— 哪几条要打「内置」黄标、哪几条不能真删(只许停用)
11
+ #: · `bus/mcp_disabled.py` —— 停用是按 owner 走的,这一份是它的展示名
12
+ #:
13
+ #: 不要再手抄这个数(例如在 `manager.get_status` 里写 `"builtin_servers": 1`)——
14
+ #: 多份手抄会各自漂移,而名单只有一条时看不出来。
15
+ #: 读者 `tests/test_mcp_servers.py` 两向钉着:名单里的每个都要真有一个
16
+ #: `mcpx/servers/<名>.py`,且它注册出来的 owner 就是 `mcp:<名>`。
17
+ BUILTIN_SERVERS: tuple[str, ...] = ("web_search",)
18
+
19
+
20
+ def owner_of(server_name: str) -> str:
21
+ """内置服务器名 → 归属键。与 `bus/quarantine.owner_for_mcp` 逐字同形。"""
22
+ return "mcp:" + str(server_name)
@@ -17,6 +17,7 @@ from __future__ import annotations
17
17
  import json
18
18
  import re
19
19
  import html as html_mod
20
+ from pathlib import Path
20
21
  from typing import Any
21
22
 
22
23
 
@@ -418,10 +419,66 @@ def _have_curl_cffi() -> bool:
418
419
  return False
419
420
 
420
421
 
421
- def _http_get_once(url: str, timeout: int = 15):
422
+ class _ResponseTooLarge(Exception):
423
+ """响应超过单次上限 —— 在读的过程中就抛,不把整包读进来。"""
424
+
425
+ def __init__(self, size, cap):
426
+ self.size = int(size or 0)
427
+ self.cap = int(cap or 0)
428
+ super().__init__(
429
+ "响应超过单次上限(上限 %d 字节,约 %.1f MB;本次 %d 字节)—— 没有保存。"
430
+ "换一个更小的来源,或确认这个地址是不是一份文档。"
431
+ % (self.cap, self.cap / 1048576.0, self.size))
432
+
433
+
434
+ def _declared_length(headers):
435
+ """`Content-Length`(读不到或不是整数就 `None`)。"""
436
+ for k, v in (headers or {}).items():
437
+ if str(k).lower() == "content-length":
438
+ try:
439
+ return int(str(v))
440
+ except (TypeError, ValueError):
441
+ return None
442
+ return None
443
+
444
+
445
+ def _check_declared_length(headers, max_bytes) -> None:
446
+ """声明就超了:连读都不读,直接抛。"""
447
+ n = _declared_length(headers)
448
+ if max_bytes and n is not None and n > max_bytes:
449
+ raise _ResponseTooLarge(n, max_bytes)
450
+
451
+
452
+ def _read_capped(read_fn, max_bytes):
453
+ """读最多 `max_bytes` 字节,多出一个字节就抛。
454
+
455
+ `read_fn(n)` 与 `urllib` 的 `Response.read(n)` 同形;`max_bytes` 为空 = 不限。
456
+ """
457
+ if not max_bytes:
458
+ return read_fn()
459
+ data = read_fn(int(max_bytes) + 1)
460
+ if len(data) > max_bytes:
461
+ raise _ResponseTooLarge(len(data), max_bytes)
462
+ return data
463
+
464
+
465
+ def _read_stream(chunks, max_bytes):
466
+ """把字节块累加到上限;超了立刻抛(后面的块不再读)。"""
467
+ buf = bytearray()
468
+ for chunk in chunks:
469
+ buf += chunk
470
+ if max_bytes and len(buf) > max_bytes:
471
+ raise _ResponseTooLarge(len(buf), max_bytes)
472
+ return bytes(buf)
473
+
474
+
475
+ def _http_get_once(url: str, timeout: int = 15, max_bytes=None):
422
476
  """一次 GET,不跟随重定向。返回 `(status, headers, body_bytes)`。
423
477
 
424
478
  不跟随是刻意的 —— 跳转由 :func:`_web_fetch` 自己走,好让每一跳都过地板。
479
+
480
+ *max_bytes*:读的上限。给了就边读边判(声明先看一眼,读的过程中
481
+ 累计超过立刻抛 `_ResponseTooLarge`)—— 读完再比保护不了内存。
425
482
  """
426
483
  from core import net_proxy as _np
427
484
  _curl_proxies = _np.curl_proxies() # 同 `_http_json`:curl 用这张表
@@ -429,8 +486,17 @@ def _http_get_once(url: str, timeout: int = 15):
429
486
  from curl_cffi import requests as _cr
430
487
  kw = {"proxies": _curl_proxies} if _curl_proxies is not None else {}
431
488
  r = _cr.get(url, headers=_HEADERS, impersonate="chrome",
432
- timeout=timeout, allow_redirects=False, **kw)
433
- return r.status_code, dict(r.headers), r.content
489
+ timeout=timeout, allow_redirects=False, stream=True, **kw)
490
+ headers = dict(r.headers)
491
+ try:
492
+ _check_declared_length(headers, max_bytes)
493
+ body = _read_stream(r.iter_content(chunk_size=65536), max_bytes)
494
+ finally:
495
+ try:
496
+ r.close()
497
+ except Exception: # noqa: BLE001
498
+ pass
499
+ return r.status_code, headers, body
434
500
 
435
501
  # 退回 urllib:自己把重定向处理器关掉
436
502
  # 不能靠"捕获 HTTPError 3xx"来判断"这是个重定向" ——
@@ -455,10 +521,14 @@ def _http_get_once(url: str, timeout: int = 15):
455
521
  try:
456
522
  with opener.open(urllib.request.Request(url, headers=_HEADERS),
457
523
  timeout=timeout) as resp:
458
- return resp.status, dict(resp.headers), resp.read()
524
+ headers = dict(resp.headers)
525
+ _check_declared_length(headers, max_bytes)
526
+ return resp.status, headers, _read_capped(resp.read, max_bytes)
459
527
  except urllib.error.HTTPError as e:
460
528
  # 3xx 会走这里:处理器拒绝跟随后,HTTPErrorProcessor 把它当成未处理的错误
461
- return e.code, dict(e.headers or {}), (e.read() or b"")
529
+ headers = dict(e.headers or {})
530
+ _check_declared_length(headers, max_bytes)
531
+ return e.code, headers, _read_capped(e.read, max_bytes)
462
532
  except urllib.error.URLError as e:
463
533
  raise RuntimeError(f"Network error: {e.reason}") from e
464
534
 
@@ -487,6 +557,226 @@ def _same_site(a: str, b: str) -> bool:
487
557
  return norm(pa) == norm(pb)
488
558
 
489
559
 
560
+ #: 单次抓取的内容上限。年报这类文件常见几十 MB(英文版尤其大),
561
+ #: 64 MB 覆盖得住;再大就不是"一次抓取"该干的事了。
562
+ #: 判在读的过程中(`_http_get_once` 的 `max_bytes`),不是读完再比 ——
563
+ #: 读完整包再判保护不了内存。
564
+ _MAX_BINARY_BYTES = 64 * 1024 * 1024
565
+
566
+ #: 一次抓取的超时。与常见抓取工具的取值一致(60 秒);
567
+ #: 这里的 60 秒是整次请求的,不是每块。
568
+ _FETCH_TIMEOUT_S = 60
569
+
570
+ #: 明确是文本的那些声明前缀(`+json` / `+xml` 后缀按文本处理)。
571
+ _TEXTUAL_PREFIXES = ("text/", "application/json", "application/xml",
572
+ "application/javascript", "application/xhtml")
573
+
574
+ #: 魔数 -> 扩展名。只认强特征:`PK` 那类压缩容器分不出 docx / xlsx / zip,
575
+ #: 不在这一格猜 —— 交给声明的子树名(见 :func:`_binary_ext_of`)。
576
+ _MAGIC_EXT = ((b"%PDF-", "pdf"),)
577
+
578
+ #: 精确 mime -> 扩展名。只收"从子类型推不出来"的那几族(Office 的
579
+ #: `vnd.openxmlformats-…` 现推出来是一串没意义的字母)。其余一律按
580
+ #: 子类型现推 —— 枚举 mime 必然漏(同"分类,不枚举"那条判据)。
581
+ _MIME_EXT = {
582
+ "application/zip": "zip",
583
+ "application/msword": "doc",
584
+ "application/vnd.ms-excel": "xls",
585
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
586
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
587
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
588
+ }
589
+
590
+ #: 子类型 -> 扩展名的别名(标准子类型与常见扩展名不同名的那几个)。
591
+ #: 空串 = 类型本身没有信息,交给 URL 后缀。
592
+ _SUB_ALIASES = {
593
+ "jpeg": "jpg", "pjpeg": "jpg",
594
+ "tiff": "tif",
595
+ "svg+xml": "svg",
596
+ "x-icon": "ico", "vnd.microsoft.icon": "ico", "x-ms-bmp": "bmp",
597
+ "x-photoshop": "psd", "vnd.adobe.photoshop": "psd",
598
+ "quicktime": "mov", "x-matroska": "mkv",
599
+ "x-rar-compressed": "rar", "vnd.rar": "rar",
600
+ "x-7z-compressed": "7z", "gzip": "gz", "x-gzip": "gz",
601
+ "x-tar": "tar", "x-bzip2": "bz2", "zstd": "zst", "x-xz": "xz",
602
+ "x-flac": "flac", "x-m4a": "m4a", "x-wav": "wav",
603
+ "msword": "doc", "vnd.ms-excel": "xls",
604
+ "octet-stream": "",
605
+ }
606
+
607
+
608
+ def _safe_ext(name: str) -> str:
609
+ """把任意字符串收成一个安全的扩展名(小写字母数字,最多 8 位)。"""
610
+ s = re.sub(r"\+.*$", "", str(name or ""))
611
+ s = re.sub(r"^(x-|vnd\.)", "", s)
612
+ return re.sub(r"[^a-z0-9]+", "", s)[:8]
613
+
614
+
615
+ def _url_ext(url: str) -> str:
616
+ """URL 路径最后那段的后缀(没有就空串)。"""
617
+ from urllib.parse import urlsplit
618
+ try:
619
+ name = (urlsplit(url).path or "").rsplit("/", 1)[-1]
620
+ except Exception: # noqa: BLE001
621
+ name = ""
622
+ m = re.search(r"\.([A-Za-z0-9]{1,8})$", name or "")
623
+ return m.group(1).lower() if m else ""
624
+
625
+
626
+ def _ext_from_subtype(sub: str) -> str:
627
+ if sub in _SUB_ALIASES:
628
+ return _SUB_ALIASES[sub]
629
+ # 相机 RAW 常写成 x-厂商-扩展名(x-canon-cr2 / x-nikon-nef):取最后一段。
630
+ if sub.startswith("x-") and sub.count("-") >= 2:
631
+ return _safe_ext(sub.rsplit("-", 1)[-1])
632
+ return _safe_ext(sub)
633
+
634
+
635
+ def _binary_ext_of(content_type: str, raw: bytes, url: str = "") -> str | None:
636
+ """这份响应是不是二进制?是就回扩展名,不是回 `None`。
637
+
638
+ 三层,前面的赢:
639
+ 1. 魔数:PDF,以及 `core.artifacts.sniff` 认得出的图片 / 音视频;
640
+ 2. `Content-Type`:先查精确表,再按子类型现推;
641
+ 3. URL 后缀(声明成 `application/octet-stream` 的常是这一类)。
642
+ 都推不出来才回 `bin` —— 不枚举 mime。
643
+ """
644
+ for magic, ext in _MAGIC_EXT:
645
+ if raw.startswith(magic):
646
+ return ext
647
+ try:
648
+ from core.artifacts import ext_for_mime, sniff
649
+ _sniffed = sniff(raw)
650
+ if _sniffed:
651
+ _ext = ext_for_mime(_sniffed)
652
+ if _ext:
653
+ return _ext
654
+ except Exception: # noqa: BLE001
655
+ pass
656
+ ct = (content_type or "").split(";")[0].strip().lower()
657
+ if not ct:
658
+ return None
659
+ if ct.startswith(_TEXTUAL_PREFIXES) or ct.endswith(("+json", "+xml")):
660
+ return None
661
+ if ct in _MIME_EXT:
662
+ return _MIME_EXT[ct]
663
+ ext = _ext_from_subtype(ct.split("/", 1)[-1])
664
+ if not ext:
665
+ ext = _url_ext(url)
666
+ return ext or "bin"
667
+
668
+
669
+ def _url_stem(url: str) -> str:
670
+ """从 URL 最后一段取一个安全的文件名主干。取不到就叫 `download`。"""
671
+ from urllib.parse import urlsplit
672
+ try:
673
+ name = (urlsplit(url).path or "").rsplit("/", 1)[-1]
674
+ except Exception: # noqa: BLE001
675
+ name = ""
676
+ name = re.sub(r"\.[A-Za-z0-9]{1,8}$", "", name or "")
677
+ name = "".join(c if c.isalnum() or c in "_-" else "_" for c in name)
678
+ return (name[:40].strip("_") or "download")
679
+
680
+
681
+ def _save_fetched_binary(url: str, raw: bytes, content_type: str,
682
+ ext: str) -> dict:
683
+ """把二进制响应落盘,回一条"去读本地文件"的回执。
684
+
685
+ 落点是 `data/workdata/tool_results/` —— 与超长文本那边同一处
686
+ (机器可读的那条指针就指向它)。目录的唯一来源是
687
+ `core.agent_loop._resolve_tool_output_dir`,这里不另写一个路径字面量。
688
+ """
689
+ if len(raw) > _MAX_BINARY_BYTES:
690
+ return {
691
+ "success": False,
692
+ "url": url,
693
+ "content_type": content_type,
694
+ "error": ("下载内容 %.1f MB,超过单次上限 %.0f MB —— 没有保存。"
695
+ "换一个更小的来源,或确认这个地址是不是一份文档。"
696
+ % (len(raw) / 1048576.0, _MAX_BINARY_BYTES / 1048576.0)),
697
+ }
698
+ from datetime import datetime
699
+
700
+ from core.agent_loop import _resolve_tool_output_dir
701
+
702
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
703
+ out_path = _resolve_tool_output_dir() / ("%s_%s.%s" % (ts, _url_stem(url), ext))
704
+ with open(out_path, "wb") as f:
705
+ f.write(raw)
706
+ shown = str(out_path).replace("\\", "/")
707
+ print(f"[web_fetch] 二进制响应已落盘:{shown}({len(raw)} 字节,{content_type})")
708
+ return {
709
+ "success": True,
710
+ "url": url,
711
+ "content_type": content_type,
712
+ "saved_path": shown,
713
+ "bytes": len(raw),
714
+ "note": ("这是一份二进制文件(不是网页文本),已经保存到本地。"
715
+ "用对应的解析工具读它 —— PDF 用 `read_pdf_pages` 按页读,"
716
+ "或 `parse_pdf` + `search_chunks`;不要把它当文本读。"),
717
+ }
718
+
719
+
720
+ def _render_response(url: str, status: int, content_type: str, raw: bytes) -> dict:
721
+ """把一份成功响应变成回执:二进制落盘,文本抽正文。
722
+
723
+ 抓取那一刻与缓存命中那一刻走的是同一段 —— 缓存里存的就是它的产物。
724
+ """
725
+ # 二进制(PDF 等)不按文本解码 —— 解出来是一墙替换字符,模型只能放弃。
726
+ # 落盘 + 回路径,由解析类工具接手(`parse_pdf` / `read_pdf_pages` 那一族)。
727
+ # 判据两条:声明不是文本族;或者魔数认得出(服务端常把 PDF 标成
728
+ # `application/octet-stream`,光看声明会漏)。
729
+ _bin_ext = _binary_ext_of(content_type, raw, url)
730
+ if _bin_ext is not None:
731
+ return _save_fetched_binary(url, raw, content_type, _bin_ext)
732
+
733
+ encoding = "utf-8"
734
+ for part in content_type.split(";"):
735
+ if "charset=" in part.lower():
736
+ encoding = part.split("=")[-1].strip().strip('"').strip("'")
737
+ break
738
+
739
+ try:
740
+ html = raw.decode(encoding, errors="replace")
741
+ except LookupError:
742
+ html = raw.decode("utf-8", errors="replace")
743
+
744
+ # Extract text
745
+ text = _html_to_text(html)
746
+
747
+ # Truncate for context protection
748
+ truncated = text[:8000]
749
+ if len(text) > 8000:
750
+ truncated += f"\n\n... (truncated, original length: {len(text)} chars)"
751
+
752
+ return {
753
+ "success": True,
754
+ "url": url,
755
+ "content_type": content_type,
756
+ "text": truncated,
757
+ "length": len(truncated),
758
+ "original_length": len(text),
759
+ }
760
+
761
+
762
+ def _cached_result(url: str, hit: dict) -> dict:
763
+ """缓存命中的回执:复用上次那份结果,加上"这是缓存"的两个字段。
764
+
765
+ 二进制那份复用同一个 `saved_path`(不重复落盘);那份文件若已被清掉
766
+ (留档清理),就从缓存的原始字节重新渲染一次。
767
+ """
768
+ out = hit.get("result")
769
+ saved = str((out or {}).get("saved_path") or "")
770
+ if not out or (saved and not Path(saved).is_file()):
771
+ out = _render_response(url, int(hit.get("status") or 200),
772
+ hit.get("content_type") or "",
773
+ hit.get("raw") or b"")
774
+ out = dict(out)
775
+ out["cached"] = True
776
+ out["cache_age_s"] = int(max(0.0, float(hit.get("age_s") or 0.0)))
777
+ return out
778
+
779
+
490
780
  def _web_fetch(url: str) -> dict:
491
781
  """
492
782
  Fetch a web page and extract its readable text content.
@@ -496,11 +786,15 @@ def _web_fetch(url: str) -> dict:
496
786
  2. 传输 —— `curl_cffi` 浏览器指纹(见本节开头那张表)
497
787
  3. 跳转 —— 同站跟随、跨站交回模型
498
788
 
789
+ 同一个地址 30 分钟内再抓一次不出网,走 `core.web_cache`(命中时
790
+ 回执带 `cached: true` 与 `cache_age_s`)。
791
+
499
792
  Strips HTML tags, scripts, and styles. Returns plain text
500
793
  limited to 8000 characters to protect LLM context.
501
794
  """
502
795
  from urllib.parse import urljoin
503
796
 
797
+ from core import web_cache as _web_cache
504
798
  from core.security import UrlEgressError, check_url_egress
505
799
  # 域名级审批闸 —— 与地板成对出现(地板管"能不能",它管"该不该")。
506
800
  from core.egress_gate import egress_gate
@@ -508,6 +802,9 @@ def _web_fetch(url: str) -> dict:
508
802
  current = (url or "").strip()
509
803
  if not current:
510
804
  return {"success": False, "error": "URL 为空"}
805
+ # 缓存键用模型给的这一个地址,不是跳转之后那一个 ——
806
+ # 模型下一次问的还是同一个地址,命中要发生在第一跳上。
807
+ requested = current
511
808
 
512
809
  hops: list[str] = []
513
810
  status = 0
@@ -539,6 +836,16 @@ def _web_fetch(url: str) -> dict:
539
836
  return {"success": False, "error": str(e),
540
837
  "blocked": True, "url": current}
541
838
 
839
+ # ①.2 响应缓存 —— 命中就到此为止,这一次一个字节都不发。
840
+ #
841
+ # 位置承重:在审批闸之前。闸问的是"该不该把这次请求发出去",
842
+ # 而没有发出去的就不该问(判据在 `core/web_cache.py`)。
843
+ # 地板与金丝雀排在它前面:那两条只看地址,不看网络,
844
+ # 缓存命中它们照样要过。
845
+ _hit = _web_cache.get(current)
846
+ if _hit is not None:
847
+ return _cached_result(current, _hit)
848
+
542
849
  # ①.5 域名级审批闸 —— 在发请求之前
543
850
  #
544
851
  # 位置承重:地板之后、`_http_get_once` 之前。
@@ -554,7 +861,11 @@ def _web_fetch(url: str) -> dict:
554
861
 
555
862
  # ② 传输
556
863
  try:
557
- status, headers, raw = _http_get_once(current)
864
+ status, headers, raw = _http_get_once(
865
+ current, timeout=_FETCH_TIMEOUT_S,
866
+ max_bytes=_MAX_BINARY_BYTES)
867
+ except _ResponseTooLarge as e:
868
+ return {"success": False, "error": str(e), "url": current}
558
869
  except RuntimeError as e:
559
870
  return {"success": False, "error": str(e), "url": current}
560
871
  except Exception as e:
@@ -595,37 +906,14 @@ def _web_fetch(url: str) -> dict:
595
906
 
596
907
  content_type = headers.get("Content-Type", "") or headers.get("content-type", "")
597
908
 
598
- encoding = "utf-8"
599
- for part in content_type.split(";"):
600
- if "charset=" in part.lower():
601
- encoding = part.split("=")[-1].strip().strip('"').strip("'")
602
- break
603
-
604
- try:
605
- html = raw.decode(encoding, errors="replace")
606
- except LookupError:
607
- html = raw.decode("utf-8", errors="replace")
608
-
609
- # Extract text
610
- text = _html_to_text(html)
611
-
612
- # Truncate for context protection
613
- truncated = text[:8000]
614
- if len(text) > 8000:
615
- truncated += f"\n\n... (truncated, original length: {len(text)} chars)"
616
-
617
- out = {
618
- "success": True,
619
- "url": current,
620
- "content_type": content_type,
621
- "text": truncated,
622
- "length": len(truncated),
623
- "original_length": len(text),
624
- }
909
+ out = _render_response(current, status, content_type, raw)
625
910
  # 只在真的跟过跳转时才带这一格 —— 免得给模型增加每轮都得读的噪声
626
911
  if len(hops) > 1:
627
912
  out["redirected_from"] = hops[0]
628
913
  out["hops"] = len(hops)
914
+ # 只缓存成功响应(判据见 `core/web_cache.py`):走到这里已经是终态。
915
+ _web_cache.put(requested, status=status, content_type=content_type,
916
+ raw=raw, result=out)
629
917
  return out
630
918
 
631
919
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hfyjq/crannia",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Crannia application code pack for automatic updates",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -11,23 +11,28 @@
11
11
  "access": "public"
12
12
  },
13
13
  "crannia": {
14
- "version": "1.0.0",
14
+ "version": "1.1.0",
15
15
  "channel": "stable",
16
- "published_at": "2026-11-15T07:15:37Z",
16
+ "published_at": "2026-11-21T17:32:51Z",
17
17
  "release_notes_url": "",
18
18
  "minimum_client_version": null,
19
19
  "mandatory": false,
20
20
  "changelog": {},
21
21
  "artifacts": {
22
22
  "windows-exe": {
23
- "url": "https://github.com/hfyjq/Crannia/releases/download/v1.0.0/crannia-1.0.0-win-x64.exe",
24
- "sha256": "2c2c96653c7ef946dcbf1d609d4e8b9dabddc12041704c6735a8e84e072d0aed",
25
- "size_bytes": 267055615
23
+ "url": "https://github.com/hfyjq/Crannia/releases/download/v1.1.0/crannia-1.1.0-win-x64.exe",
24
+ "sha256": "27cf3134bbc0a15de5c174fb38851a6ffc001fbe79c40c7d12dfd2dfa57a0e7d",
25
+ "size_bytes": 268380182
26
26
  },
27
27
  "codepack": {
28
- "app_version": "1.0.0",
29
- "runtime": "61ad22fad6d84b7ac5c957e466859b736f3f391611e5d2996fdaa13cbed64a75",
30
- "shell_sha256": "89fad4ca94e696621194ee67e0dd6503c4ce811ffd7def3271df5a8c88decc7e"
28
+ "app_version": "1.1.0",
29
+ "runtime": "81c9471a1aed5e0ec6716c5447082df39b68aa3c06332dc32d44d0682dd716f6",
30
+ "shell_sha256": "295138dd2c721457812e73a18d372c91722c7f7c3dafecd9b32054812976d58e"
31
+ },
32
+ "tui": {
33
+ "url": "https://github.com/hfyjq/Crannia/releases/download/v1.1.0/crannia-tui-1.1.0-code.zip",
34
+ "sha256": "e5c8d40c2652ad036147ba2318f95dee76514abeae0b810898145076e71bb9e9",
35
+ "size_bytes": 5059723
31
36
  }
32
37
  }
33
38
  }