@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.
- package/LICENSE +201 -201
- package/NOTICE +48 -45
- package/README.md +1 -1
- package/THIRD-PARTY-FRONTEND.md +5266 -5266
- package/THIRD-PARTY-PYTHON-linux.md +174 -0
- package/THIRD-PARTY-PYTHON.md +176 -162
- package/THIRD-PARTY.md +323 -316
- package/apps/desktop/quotes.txt +56 -56
- package/bus/core.py +677 -671
- package/bus/loaders/channel_loader.py +64 -64
- package/bus/loaders/provider_loader.py +4 -7
- package/bus/loaders/skill_loader.py +46 -27
- package/bus/loaders/skill_md.py +9 -9
- package/bus/mcp_disabled.py +4 -6
- package/bus/quarantine.py +10 -13
- package/bus/registry.py +2315 -2284
- package/bus/skill_state.py +124 -124
- package/channels/cli_channel/handler.py +3 -3
- package/channels/cli_channel/manifest.yaml +5 -5
- package/channels/dingtalk_channel/handler.py +32 -32
- package/channels/dingtalk_channel/manifest.yaml +12 -12
- package/channels/feishu_channel/handler.py +33 -33
- package/channels/feishu_channel/manifest.yaml +12 -12
- package/channels/qq_bot_channel/__init__.py +1 -1
- package/channels/qq_bot_channel/handler.py +24 -24
- package/channels/qq_bot_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/__init__.py +1 -1
- package/channels/telegram_channel/handler.py +21 -21
- package/channels/telegram_channel/manifest.yaml +4 -4
- package/channels/telegram_channel/media.py +231 -231
- package/channels/textfmt.py +58 -58
- package/channels/wechat_channel/__init__.py +1 -1
- package/channels/wechat_channel/converter.py +1 -1
- package/channels/wechat_channel/handler.py +8 -8
- package/channels/wechat_channel/manifest.yaml +5 -5
- package/channels/wechat_channel/media.py +178 -178
- package/core/activity.py +753 -709
- package/core/agent_loop.py +7673 -7523
- package/core/allowlist.py +2 -3
- package/core/approval.py +36 -26
- package/core/approval_timeout.py +256 -228
- package/core/artifacts.py +3 -3
- package/core/attachment_gc.py +21 -0
- package/core/auto_review.py +2 -2
- package/core/browser/cdp.py +5 -2
- package/core/browser/discover.py +55 -19
- package/core/browser/session.py +4 -4
- package/core/cache_break_detector.py +97 -0
- package/core/cache_breakpoints.py +103 -0
- package/core/cache_policies.py +255 -0
- package/core/cancellation.py +3 -3
- package/core/channel_configs.py +3 -3
- package/core/channel_turns.py +13 -13
- package/core/child_approval.py +2 -3
- package/core/code_intel.py +11 -11
- package/core/command_policy.py +13 -7
- package/core/computer/annotate.py +231 -11
- package/core/computer/capture.py +140 -1
- package/core/computer/guard.py +7 -4
- package/core/computer/input.py +452 -26
- package/core/computer/session.py +563 -381
- package/core/computer/tools.py +2170 -928
- package/core/computer/uia.py +100 -1
- package/core/computer/watch.py +1 -1
- package/core/computer/win32.py +302 -7
- package/core/config_requirements.py +205 -205
- package/core/cron/runner.py +4 -4
- package/core/daily_log.py +2 -2
- package/core/dedup.py +2 -2
- package/core/egress_channels.py +326 -0
- package/core/egress_gate.py +96 -8
- package/core/egress_preapproved.py +59 -3
- package/core/endpoint.py +141 -141
- package/core/events.py +17 -8
- package/core/extension.py +2 -2
- package/core/file_history.py +15 -15
- package/core/file_tools.py +3 -3
- package/core/github_config.py +1 -1
- package/core/group_digest.py +3 -4
- package/core/group_minutes.py +5 -5
- package/core/group_reply.py +24 -0
- package/core/groups.py +5 -9
- package/core/hooks.py +15 -15
- package/core/i18n.py +2 -2
- package/core/ice/canary.py +3 -3
- package/core/ice/net_heuristics.py +2 -2
- package/core/im_routing.py +3 -3
- package/core/image_input.py +183 -43
- package/core/inbound.py +3 -3
- package/core/jobs.py +6 -6
- package/core/last_good.py +150 -150
- package/core/leaf_md.py +3 -3
- package/core/llm_errors.py +37 -28
- package/core/mail_config.py +2 -2
- package/core/memory/compressor.py +8 -8
- package/core/memory/manager.py +30 -45
- package/core/memory/session_memory.py +1 -2
- package/core/memory/short_term.py +4 -4
- package/core/memory_extract.py +1 -1
- package/core/memory_organize.py +8 -8
- package/core/memory_store.py +7 -9
- package/core/memory_transfer.py +2 -2
- package/core/model_capabilities.py +2 -2
- package/core/model_configs.py +219 -68
- package/core/model_profiles.py +333 -0
- package/core/modes.py +12 -11
- package/core/net_proxy.py +3 -3
- package/core/pipeline/scheduler.py +48 -43
- package/core/pipeline/stage.py +3 -0
- package/core/pipeline/stages/agent_loop.py +36 -15
- package/core/pipeline/stages/group_reply.py +22 -20
- package/core/pipeline/stages/post_process.py +7 -7
- package/core/pipeline/stages/pre_process.py +369 -77
- package/core/prompt_assembler.py +13 -4
- package/core/recycle.py +227 -16
- package/core/response_language.py +1 -1
- package/core/retention.py +2 -2
- package/core/rg.py +4 -3
- package/core/security.py +26 -8
- package/core/services.py +8 -8
- package/core/session_model.py +3 -5
- package/core/session_pool.py +35 -5
- package/core/session_recap.py +40 -3
- package/core/session_workspace.py +2 -3
- package/core/settings_baseline.py +2 -2
- package/core/settings_transfer.py +25 -1
- package/core/shell.py +52 -20
- package/core/side_call.py +3 -3
- package/core/skill_config.py +164 -0
- package/core/skill_factory.py +2 -2
- package/core/skill_guidance.py +2 -4
- package/core/skill_index.py +3 -4
- package/core/skill_settings.py +1 -1
- package/core/skill_sources.py +7 -7
- package/core/ssh_config.py +129 -0
- package/core/state_registry.py +67 -5
- package/core/subagent.py +28 -5
- package/core/subagent_defs.py +3 -3
- package/core/summarizer.py +4 -5
- package/core/tasks_notify.py +6 -6
- package/core/tiers.py +2 -2
- package/core/todos.py +1 -1
- package/core/token_calibrator.py +1 -4
- package/core/tool_outcome.py +108 -108
- package/core/touched_files.py +1 -1
- package/core/trace.py +12 -3
- package/core/unlock.py +4 -4
- package/core/update_tui.py +184 -158
- package/core/updater.py +5 -3
- package/core/version.py +14 -14
- package/core/vision_budget.py +235 -0
- package/core/web_cache.py +152 -152
- package/core/web_request.py +474 -0
- package/core/window_estimate.py +1 -1
- package/core/workspace.py +56 -26
- package/crannia_tray.py +278 -278
- package/licenses/GPL-3.0.txt +619 -619
- package/licenses/LGPL-2.1.txt +502 -502
- package/licenses/LGPL-3.0.txt +165 -165
- package/licenses/MIT-chat-on-wechat.txt +18 -18
- package/licenses/MIT-deepseek-harness.txt +21 -21
- package/licenses/Molio-LICENSE.txt +44 -44
- package/locales/en.json +1876 -1762
- package/main.py +154 -154
- package/mcpx/client.py +12 -1
- package/mcpx/manager.py +530 -522
- package/mcpx/servers/web_search.py +5 -13
- package/package.json +15 -23
- package/providers/anthropic/client.py +35 -33
- package/providers/base.py +13 -13
- package/providers/cache_policies.json +294 -0
- package/providers/cost_table.json +3779 -3779
- package/providers/lmstudio/client.py +2 -2
- package/providers/model_capabilities.json +6665 -6665
- package/providers/model_profiles.json +629 -0
- package/providers/ollama/client.py +2 -2
- package/providers/openai_compat.py +37 -16
- package/providers/openrouter/client.py +2 -2
- package/providers/qwen/__init__.py +1 -1
- package/providers/qwen/client.py +2 -2
- package/providers/qwen/manifest.yaml +16 -16
- package/providers/rate_limiter.py +2 -2
- package/providers/siliconflow/client.py +2 -2
- package/providers/validation.py +171 -171
- package/providers/vision_profiles.json +89 -0
- package/providers/window_table.json +8909 -8909
- package/requirements.txt +59 -51
- package/sbom-linux-x64.json +4580 -0
- package/sbom.json +4600 -4413
- package/skills/diagram/SKILL.md +47 -0
- package/skills/diagram/__init__.py +1 -0
- package/skills/diagram/handler.py +294 -0
- package/skills/diagram/layout.py +174 -0
- package/skills/diagram/manifest.yaml +106 -0
- package/skills/diagram/mermaid.py +170 -0
- package/skills/diagram/svg.py +223 -0
- package/skills/entertainment/SKILL.md +35 -35
- package/skills/entertainment/__init__.py +1 -1
- package/skills/entertainment/handler.py +91 -91
- package/skills/entertainment/manifest.yaml +26 -26
- package/skills/file_parser/GUIDANCE.md +10 -10
- package/skills/file_parser/handler.py +33 -11
- package/skills/github/SKILL.md +32 -32
- package/skills/github/__init__.py +1 -1
- package/skills/mail_parser/SKILL.md +68 -68
- package/skills/mail_parser/__init__.py +1 -1
- package/skills/mail_parser/handler.py +1 -1
- package/skills/media_gen/GUIDANCE.md +19 -19
- package/skills/media_gen/SKILL.md +43 -43
- package/skills/media_gen/__init__.py +1 -1
- package/skills/media_gen/handler.py +1 -1
- package/skills/media_gen/manifest.yaml +93 -93
- package/skills/netops/SKILL.md +45 -0
- package/skills/netops/__init__.py +1 -0
- package/skills/netops/handler.py +418 -0
- package/skills/netops/manifest.yaml +118 -0
- package/skills/office_parser/_excel_io.py +3 -3
- package/skills/office_parser/handler.py +2 -2
- package/skills/office_parser/ppt_tools.py +1 -1
- package/skills/office_parser/pptx_export/console_encoding.py +27 -27
- package/skills/office_parser/pptx_export/resource_paths.py +88 -88
- package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
- package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
- package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
- package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
- package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
- package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
- package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
- package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
- package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
- package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
- package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
- package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
- package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
- package/skills/office_parser/references/layout_library.md +816 -816
- package/skills/office_parser/references/ppt-master/LICENSE +21 -21
- package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
- package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
- package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
- package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
- package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
- package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
- package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
- package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
- package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
- package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
- package/skills/office_parser/references/spec_lock.md +235 -235
- package/skills/office_parser/soffice.py +68 -68
- package/skills/office_parser/word_tools.py +3 -3
- package/skills/ssh/SKILL.md +81 -0
- package/skills/ssh/__init__.py +1 -0
- package/skills/ssh/handler.py +609 -0
- package/skills/ssh/manifest.yaml +182 -0
- package/tui/crannia.cmd +134 -134
- package/tui/crannia.sh +82 -0
- package/tui/crannia_tui/__init__.py +1 -1
- package/tui/crannia_tui/app.py +240 -17
- package/tui/crannia_tui/app.tcss +21 -0
- package/tui/crannia_tui/clipboard.py +78 -10
- package/tui/crannia_tui/commands.py +37 -0
- package/tui/crannia_tui/events.py +6 -0
- package/tui/crannia_tui/i18n.py +164 -164
- package/tui/crannia_tui/locales/en.json +32 -7
- package/tui/crannia_tui/paths.py +4 -1
- package/tui/crannia_tui/profile.py +178 -169
- package/tui/crannia_tui/settings.py +134 -134
- package/tui/crannia_tui/setup.py +44 -5
- package/tui/crannia_tui/ui.py +156 -16
- package/tui/crannia_tui/update.py +393 -389
- package/vendor/ripgrep/COPYING.txt +3 -3
- package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
- package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
- package/vendor/ripgrep/README.md +30 -14
- package/vendor/ripgrep/UNLICENSE.txt +24 -24
- package/vendor/ripgrep/linux-x64/rg +0 -0
- package/vendor/ripgrep/package-source.json +15 -16
- package/web/__main__.py +12 -15
- package/web/server.py +8481 -8594
- package/web/static/img/channel-telegram.svg +1 -1
- package/web/static/img/channel-wechat.svg +1 -1
- package/web/templates/logs.html +49 -49
- package/web/templates/models.html +46 -46
package/core/updater.py
CHANGED
|
@@ -531,7 +531,7 @@ def mark_pending(manifest, downloaded_path) -> None:
|
|
|
531
531
|
"at": time.time(),
|
|
532
532
|
}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
533
533
|
except OSError as exc:
|
|
534
|
-
print("[update]
|
|
534
|
+
print("[update] cannot write pending install marker: %s" % exc)
|
|
535
535
|
|
|
536
536
|
|
|
537
537
|
def clear_pending(remove_file: bool = False) -> None:
|
|
@@ -760,7 +760,7 @@ def mark_pending_code_pack(manifest, new_dir, app_dir, backup_dir) -> None:
|
|
|
760
760
|
"at": time.time(),
|
|
761
761
|
}, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
762
762
|
except OSError as exc:
|
|
763
|
-
print("[update]
|
|
763
|
+
print("[update] cannot write pending code-pack install marker: %s" % exc)
|
|
764
764
|
|
|
765
765
|
|
|
766
766
|
def pending_code_pack() -> dict | None:
|
|
@@ -1438,7 +1438,9 @@ class UpdateInstaller:
|
|
|
1438
1438
|
|
|
1439
1439
|
if sys.platform != "win32":
|
|
1440
1440
|
_update_state["status"] = "error"
|
|
1441
|
-
|
|
1441
|
+
#: 拒,但要给路线:本平台没有内置换装器,去 Releases 下新版本。
|
|
1442
|
+
_update_state["error"] = (
|
|
1443
|
+
"内置更新只支持 Windows 安装包;本平台请到 Releases 页面下载新版本。")
|
|
1442
1444
|
_UPDATING = False
|
|
1443
1445
|
return
|
|
1444
1446
|
|
package/core/version.py
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"""
|
|
2
|
-
Crannia version — single source of truth.
|
|
3
|
-
|
|
4
|
-
Import this module wherever the app version is needed:
|
|
5
|
-
from core.version import __version__, __version_tuple__, __build__
|
|
6
|
-
|
|
7
|
-
For the build system (pyproject.toml / hatchling), this file is also the
|
|
8
|
-
canonical source. Keep pyproject.toml `version` field in sync manually
|
|
9
|
-
or use [tool.hatch.version] path = "core/version.py".
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
__version__ = "1.
|
|
13
|
-
__version_tuple__ = (1,
|
|
14
|
-
__build__ = ""
|
|
1
|
+
"""
|
|
2
|
+
Crannia version — single source of truth.
|
|
3
|
+
|
|
4
|
+
Import this module wherever the app version is needed:
|
|
5
|
+
from core.version import __version__, __version_tuple__, __build__
|
|
6
|
+
|
|
7
|
+
For the build system (pyproject.toml / hatchling), this file is also the
|
|
8
|
+
canonical source. Keep pyproject.toml `version` field in sync manually
|
|
9
|
+
or use [tool.hatch.version] path = "core/version.py".
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "1.2.0"
|
|
13
|
+
__version_tuple__ = (1, 2, 0)
|
|
14
|
+
__build__ = ""
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""接管截图的图预算与可见性判定 —— 一张表 + 三级回落。
|
|
2
|
+
|
|
3
|
+
## 为什么单开一张表
|
|
4
|
+
|
|
5
|
+
`providers/model_capabilities.json` 是 refetch 脚本整份覆盖的(`fetched` / `snapshot`
|
|
6
|
+
都在里面),手工加字段下一次刷新就没了。而「这张图给多大」是我们自己的取舍,
|
|
7
|
+
不是上游数据,所以放在 `providers/vision_profiles.json`,由这里读。
|
|
8
|
+
新增一家供应商 = 表里加一行,不改代码。
|
|
9
|
+
|
|
10
|
+
## 为什么判不出来要往「能看图」那边倒
|
|
11
|
+
|
|
12
|
+
与 `providers/base.py::accepts_images` 同一方向:判错的代价是一次上游 400(可诊断、
|
|
13
|
+
可恢复、用户改一个开关就好),而默认 False 会让绝大多数用户的接管静默残废。
|
|
14
|
+
差别在于这里必须留下依据:`VisionProfile.confirmed` 为 False 时,调用方要把
|
|
15
|
+
"没确认这个模型能不能看图"说出来,而不是像现在那样把图发出去当没事。
|
|
16
|
+
|
|
17
|
+
## 回落的顺序
|
|
18
|
+
|
|
19
|
+
- 图预算按 provider 查(缩放是它做的),顺序:显式入参 → `config.yaml` 的
|
|
20
|
+
`model.provider` → 表的 `_default` → 内置兜底。
|
|
21
|
+
- 可见性按 model 查,顺序:`config.yaml` 的 `model.supports_vision`(用户显式声明
|
|
22
|
+
赢过一切)→ 能力表里该模型的 `input` → 判不出(fail-open,且 `confirmed=False`)。
|
|
23
|
+
- 模型名取 `request_snapshot` 里刚发出去的那条(`/model` 换过之后跟着变),
|
|
24
|
+
拿不到才退到 `config.yaml`。
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import threading
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
#: 内置兜底 —— 表读不到、字段写坏时用。与改这张表之前的现状对齐(`MAX_EDGE_PX`)。
|
|
35
|
+
_FALLBACK_EDGE = 2000
|
|
36
|
+
_FALLBACK_PIXELS = 4_000_000
|
|
37
|
+
|
|
38
|
+
#: 合理的上下界。表是用户可编辑的文件,写个 0 或 99999 不该让截图链路失控。
|
|
39
|
+
_MIN_EDGE = 256
|
|
40
|
+
_MAX_EDGE = 4096
|
|
41
|
+
|
|
42
|
+
_LOCK = threading.Lock()
|
|
43
|
+
#: 路径 -> (mtime, 解析后的 dict)
|
|
44
|
+
_CACHE: dict[str, tuple[float, dict]] = {}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class VisionProfile:
|
|
49
|
+
"""一次接管观察要用的图参数 + 它凭什么这么判。"""
|
|
50
|
+
|
|
51
|
+
can_see: bool
|
|
52
|
+
#: False 表示"没有这个模型的视觉能力记录" —— 调用方要把这句话说出去。
|
|
53
|
+
confirmed: bool
|
|
54
|
+
provider: str
|
|
55
|
+
model: str
|
|
56
|
+
max_edge: int
|
|
57
|
+
max_pixels: int
|
|
58
|
+
#: 判定依据(诊断/测试用,不是给模型的文案)
|
|
59
|
+
source: str
|
|
60
|
+
budget_note: str = ""
|
|
61
|
+
|
|
62
|
+
def scale_for(self, width: int, height: int) -> float:
|
|
63
|
+
"""这张图要缩到几倍(1.0 = 不动)。等比,比例坐标不受影响。"""
|
|
64
|
+
longest = max(int(width or 0), int(height or 0))
|
|
65
|
+
if longest <= 0:
|
|
66
|
+
return 1.0
|
|
67
|
+
k = 1.0
|
|
68
|
+
if longest > self.max_edge:
|
|
69
|
+
k = self.max_edge / float(longest)
|
|
70
|
+
pixels = int(width or 0) * int(height or 0)
|
|
71
|
+
if pixels > 0 and pixels * k * k > self.max_pixels:
|
|
72
|
+
k = (self.max_pixels / float(pixels)) ** 0.5
|
|
73
|
+
return min(1.0, max(0.01, k))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _read_json(name: str) -> dict:
|
|
77
|
+
"""读 `providers/<name>`,按 mtime 缓存;读坏了退回上一次成功的副本。
|
|
78
|
+
|
|
79
|
+
路径只走 `paths.asset_dir` —— `providers/` 是代码资产,安装版的 cwd
|
|
80
|
+
在数据根(`%APPDATA%/Crannia`),那里没有 providers 目录。写成相对路径
|
|
81
|
+
在开发树全绿、装出来必崩(`tests/test_paths.py` 有一条按源码反查的断言)。
|
|
82
|
+
"""
|
|
83
|
+
try:
|
|
84
|
+
from core import paths
|
|
85
|
+
path = Path(paths.asset_dir("providers")) / name
|
|
86
|
+
except Exception: # noqa: BLE001
|
|
87
|
+
return {}
|
|
88
|
+
try:
|
|
89
|
+
mtime = path.stat().st_mtime
|
|
90
|
+
except OSError:
|
|
91
|
+
return {}
|
|
92
|
+
key = str(path)
|
|
93
|
+
with _LOCK:
|
|
94
|
+
hit = _CACHE.get(key)
|
|
95
|
+
if hit is not None and hit[0] == mtime:
|
|
96
|
+
return hit[1]
|
|
97
|
+
try:
|
|
98
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
99
|
+
except Exception: # noqa: BLE001
|
|
100
|
+
# 解析失败不算"表里没有":保住上一份,别让一次手滑把预算打回兜底
|
|
101
|
+
with _LOCK:
|
|
102
|
+
hit = _CACHE.get(key)
|
|
103
|
+
return hit[1] if hit is not None else {}
|
|
104
|
+
if not isinstance(data, dict):
|
|
105
|
+
return {}
|
|
106
|
+
with _LOCK:
|
|
107
|
+
_CACHE[key] = (mtime, data)
|
|
108
|
+
return data
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _model_config() -> dict:
|
|
112
|
+
"""`config.yaml` 的 `model` 段(按 mtime 缓存)。读不到就是空。"""
|
|
113
|
+
path = Path("config.yaml")
|
|
114
|
+
try:
|
|
115
|
+
mtime = path.stat().st_mtime
|
|
116
|
+
except OSError:
|
|
117
|
+
return {}
|
|
118
|
+
key = str(path.resolve())
|
|
119
|
+
with _LOCK:
|
|
120
|
+
hit = _CACHE.get(key)
|
|
121
|
+
if hit is not None and hit[0] == mtime:
|
|
122
|
+
return hit[1]
|
|
123
|
+
try:
|
|
124
|
+
from bus.core import load_config
|
|
125
|
+
cfg = load_config(path)
|
|
126
|
+
except Exception: # noqa: BLE001
|
|
127
|
+
return {}
|
|
128
|
+
section = cfg.get("model") if isinstance(cfg, dict) else None
|
|
129
|
+
section = section if isinstance(section, dict) else {}
|
|
130
|
+
with _LOCK:
|
|
131
|
+
_CACHE[key] = (mtime, section)
|
|
132
|
+
return section
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _current_model(explicit: str = "") -> str:
|
|
136
|
+
if explicit:
|
|
137
|
+
return str(explicit)
|
|
138
|
+
try:
|
|
139
|
+
from core import request_snapshot
|
|
140
|
+
snap = request_snapshot.get_current()
|
|
141
|
+
if snap is not None and snap.model:
|
|
142
|
+
return str(snap.model)
|
|
143
|
+
except Exception: # noqa: BLE001
|
|
144
|
+
pass
|
|
145
|
+
return str(_model_config().get("model_name") or "")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _active_provider(explicit: str = "") -> str:
|
|
149
|
+
if explicit:
|
|
150
|
+
return str(explicit)
|
|
151
|
+
return str(_model_config().get("provider") or "")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _int_in(value, low: int, high: int, default: int) -> int:
|
|
155
|
+
try:
|
|
156
|
+
n = int(value)
|
|
157
|
+
except (TypeError, ValueError):
|
|
158
|
+
return default
|
|
159
|
+
return n if low <= n <= high else default
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _budget_for(provider: str) -> tuple[int, int, str]:
|
|
163
|
+
table = _read_json("vision_profiles.json")
|
|
164
|
+
row = table.get(provider) if provider else None
|
|
165
|
+
if not isinstance(row, dict):
|
|
166
|
+
row = table.get("_default")
|
|
167
|
+
if not isinstance(row, dict):
|
|
168
|
+
return _FALLBACK_EDGE, _FALLBACK_PIXELS, "内置兜底(表里没有这一家)"
|
|
169
|
+
edge = _int_in(row.get("max_edge"), _MIN_EDGE, _MAX_EDGE, _FALLBACK_EDGE)
|
|
170
|
+
pixels = _int_in(row.get("max_pixels"), 1, 100_000_000, _FALLBACK_PIXELS)
|
|
171
|
+
return edge, pixels, str(row.get("note") or "")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _inputs_of(provider: str, model: str):
|
|
175
|
+
"""能力表里这个模型的 input 列表;找不到返回 None(不等于"只能收文本")。"""
|
|
176
|
+
if not model:
|
|
177
|
+
return None
|
|
178
|
+
rows = _read_json("model_capabilities.json").get("providers")
|
|
179
|
+
if not isinstance(rows, dict):
|
|
180
|
+
return None
|
|
181
|
+
order = [provider] if provider else []
|
|
182
|
+
order += [name for name in rows if name not in order]
|
|
183
|
+
# openrouter / siliconflow 这类聚合商会带 `vendor/model` 前缀,精确查不到就试尾巴
|
|
184
|
+
names = [model]
|
|
185
|
+
if "/" in model:
|
|
186
|
+
names.append(model.split("/")[-1])
|
|
187
|
+
for name in order:
|
|
188
|
+
bucket = rows.get(name)
|
|
189
|
+
if not isinstance(bucket, dict):
|
|
190
|
+
continue
|
|
191
|
+
for candidate in names:
|
|
192
|
+
row = bucket.get(candidate)
|
|
193
|
+
if isinstance(row, dict):
|
|
194
|
+
got = row.get("input")
|
|
195
|
+
if isinstance(got, list):
|
|
196
|
+
return [str(x).lower() for x in got]
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _visibility(provider: str, model: str) -> tuple[bool, bool, str]:
|
|
201
|
+
cfg = _model_config()
|
|
202
|
+
declared = cfg.get("supports_vision")
|
|
203
|
+
if isinstance(declared, bool):
|
|
204
|
+
return declared, True, "config.yaml 的 model.supports_vision"
|
|
205
|
+
|
|
206
|
+
inputs = _inputs_of(provider, model)
|
|
207
|
+
if inputs is not None:
|
|
208
|
+
return ("image" in inputs), True, "能力表 providers/model_capabilities.json"
|
|
209
|
+
|
|
210
|
+
# 没有记录:往"能看图"那边倒,但把不确定说出来(调用方负责出声)
|
|
211
|
+
return True, False, "没有这个模型的视觉能力记录"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def resolve(provider: str = "", model: str = "") -> VisionProfile:
|
|
215
|
+
"""当前这一轮该给多大的图、能不能给。读表失败也返回可用值(不抛)。"""
|
|
216
|
+
prov = _active_provider(provider)
|
|
217
|
+
mdl = _current_model(model)
|
|
218
|
+
edge, pixels, note = _budget_for(prov)
|
|
219
|
+
can_see, confirmed, source = _visibility(prov, mdl)
|
|
220
|
+
return VisionProfile(
|
|
221
|
+
can_see=can_see,
|
|
222
|
+
confirmed=confirmed,
|
|
223
|
+
provider=prov,
|
|
224
|
+
model=mdl,
|
|
225
|
+
max_edge=edge,
|
|
226
|
+
max_pixels=pixels,
|
|
227
|
+
source=source,
|
|
228
|
+
budget_note=note,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def reset_cache() -> None:
|
|
233
|
+
"""只给测试用:表被改写后强制重读。"""
|
|
234
|
+
with _LOCK:
|
|
235
|
+
_CACHE.clear()
|
package/core/web_cache.py
CHANGED
|
@@ -1,152 +1,152 @@
|
|
|
1
|
-
"""`web_fetch` 的响应缓存。
|
|
2
|
-
|
|
3
|
-
一张按 URL 的表:30 分钟内同一个地址再抓一次,不再出网。
|
|
4
|
-
|
|
5
|
-
判据:
|
|
6
|
-
|
|
7
|
-
- 键是归一化后的 URL:scheme 与主机小写、去掉默认端口与 `#` 片段,
|
|
8
|
-
查询串原样保留(它可能就是"另一页")。主机名里的 `www.` 不剥
|
|
9
|
-
—— 那是另一个主机名,服务端可以给出不同的内容。
|
|
10
|
-
- 只缓存成功响应。跳转与 4xx / 5xx 不缓存:跳转链会变,
|
|
11
|
-
存一条 302 会把人钉在旧地址上;失败多数是临时的。
|
|
12
|
-
- 时效从抓取那一刻算起,不滑动。缓存回答的是"这条内容有多旧",
|
|
13
|
-
与"谁最近读过它"无关。
|
|
14
|
-
- 总量 256 MiB,按最近使用淘汰。过期条目在每次读 / 写时顺手清掉。
|
|
15
|
-
- 它是进程级的网络缓存,不是会话态:键是 URL,与哪条会话读过它无关,
|
|
16
|
-
`/clear` 不清它(登记在 `core/state_registry.py` 的进程级那张表里)。
|
|
17
|
-
|
|
18
|
-
命中时不做任何出网动作,所以 `web_fetch` 把出网审批闸放在命中判断之后:
|
|
19
|
-
闸问的是"该不该把这次请求发出去",没有发出去的就不该问。地板与金丝雀
|
|
20
|
-
仍然逐次跑 —— 它们只看地址,不看网络。
|
|
21
|
-
"""
|
|
22
|
-
|
|
23
|
-
from __future__ import annotations
|
|
24
|
-
|
|
25
|
-
import hashlib
|
|
26
|
-
import threading
|
|
27
|
-
import time
|
|
28
|
-
from typing import Any, Dict, Optional
|
|
29
|
-
from urllib.parse import urlsplit, urlunsplit
|
|
30
|
-
|
|
31
|
-
__all__ = [
|
|
32
|
-
"TTL_SECONDS", "MAX_TOTAL_BYTES",
|
|
33
|
-
"normalize", "key_of", "get", "put", "clear", "stats",
|
|
34
|
-
]
|
|
35
|
-
|
|
36
|
-
#: 一条内容活多久。网页的新鲜度以分钟计,不是以天计。
|
|
37
|
-
TTL_SECONDS = 30 * 60
|
|
38
|
-
|
|
39
|
-
#: 整个缓存的上限。单次抓取本身封在 64 MiB,这里能装下几份大的。
|
|
40
|
-
MAX_TOTAL_BYTES = 256 * 1024 * 1024
|
|
41
|
-
|
|
42
|
-
_DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
43
|
-
|
|
44
|
-
_LOCK = threading.RLock()
|
|
45
|
-
|
|
46
|
-
#: 键 -> {status, content_type, raw, result, at, used}。
|
|
47
|
-
_ITEMS: Dict[str, Dict[str, Any]] = {}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def normalize(url: str) -> str:
|
|
51
|
-
"""缓存键用的 URL 形状(判据见模块 docstring)。"""
|
|
52
|
-
raw = str(url or "").strip()
|
|
53
|
-
try:
|
|
54
|
-
parts = urlsplit(raw)
|
|
55
|
-
except ValueError:
|
|
56
|
-
return raw
|
|
57
|
-
scheme = (parts.scheme or "").lower()
|
|
58
|
-
host = (parts.hostname or "").lower()
|
|
59
|
-
if ":" in host:
|
|
60
|
-
host = "[%s]" % host
|
|
61
|
-
try:
|
|
62
|
-
port = parts.port
|
|
63
|
-
except ValueError:
|
|
64
|
-
port = None
|
|
65
|
-
if port is not None and _DEFAULT_PORTS.get(scheme) == port:
|
|
66
|
-
port = None
|
|
67
|
-
netloc = host if port is None else "%s:%d" % (host, port)
|
|
68
|
-
path = parts.path or "/"
|
|
69
|
-
return urlunsplit((scheme, netloc, path, parts.query, ""))
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def key_of(url: str) -> str:
|
|
73
|
-
"""归一化之后的 URL 的短摘要(URL 本身可能很长)。"""
|
|
74
|
-
return hashlib.sha256(normalize(url).encode("utf-8")).hexdigest()[:24]
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
def _total_bytes() -> int:
|
|
78
|
-
"""当前占用(按响应体计)。调用方持锁。"""
|
|
79
|
-
return sum(len(item.get("raw") or b"") for item in _ITEMS.values())
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def _drop_expired(now: float) -> None:
|
|
83
|
-
"""清掉过期的条目。调用方持锁。"""
|
|
84
|
-
expired = [k for k, item in _ITEMS.items()
|
|
85
|
-
if now - float(item.get("at") or 0.0) > TTL_SECONDS]
|
|
86
|
-
for key in expired:
|
|
87
|
-
_ITEMS.pop(key, None)
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def get(url: str) -> Optional[dict]:
|
|
91
|
-
"""命中返回一份副本,未命中或已过期返回 `None`。
|
|
92
|
-
|
|
93
|
-
副本里的 `age_s` 是这一份内容被缓存了多久 —— 回执要把它如实给模型,
|
|
94
|
-
"这是刚抓的"与"这是半小时前的"不能长得一样。
|
|
95
|
-
"""
|
|
96
|
-
key = key_of(url)
|
|
97
|
-
now = time.monotonic()
|
|
98
|
-
with _LOCK:
|
|
99
|
-
item = _ITEMS.get(key)
|
|
100
|
-
if item is None:
|
|
101
|
-
return None
|
|
102
|
-
if now - float(item.get("at") or 0.0) > TTL_SECONDS:
|
|
103
|
-
_ITEMS.pop(key, None)
|
|
104
|
-
return None
|
|
105
|
-
item["used"] = now
|
|
106
|
-
return {
|
|
107
|
-
"status": item.get("status"),
|
|
108
|
-
"content_type": item.get("content_type") or "",
|
|
109
|
-
"raw": item.get("raw") or b"",
|
|
110
|
-
"result": dict(item["result"]) if item.get("result") else None,
|
|
111
|
-
"age_s": now - float(item.get("at") or now),
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def put(url: str, *, status, content_type: str, raw: bytes, result: dict) -> None:
|
|
116
|
-
"""存一份抓取结果。装不下就悄悄不存(缓存是加速,不是账本)。
|
|
117
|
-
|
|
118
|
-
先清过期、再按最近使用淘汰,腾够了才写 —— 新这一份不会被自己挤掉。
|
|
119
|
-
"""
|
|
120
|
-
body = bytes(raw or b"")
|
|
121
|
-
key = key_of(url)
|
|
122
|
-
now = time.monotonic()
|
|
123
|
-
with _LOCK:
|
|
124
|
-
_drop_expired(now)
|
|
125
|
-
_ITEMS.pop(key, None)
|
|
126
|
-
if len(body) > MAX_TOTAL_BYTES:
|
|
127
|
-
return
|
|
128
|
-
while _ITEMS and _total_bytes() + len(body) > MAX_TOTAL_BYTES:
|
|
129
|
-
oldest = min(_ITEMS, key=lambda k: float(_ITEMS[k].get("used") or 0.0))
|
|
130
|
-
_ITEMS.pop(oldest, None)
|
|
131
|
-
if _total_bytes() + len(body) > MAX_TOTAL_BYTES:
|
|
132
|
-
return
|
|
133
|
-
_ITEMS[key] = {
|
|
134
|
-
"status": int(status or 0),
|
|
135
|
-
"content_type": str(content_type or ""),
|
|
136
|
-
"raw": body,
|
|
137
|
-
"result": dict(result or {}),
|
|
138
|
-
"at": now,
|
|
139
|
-
"used": now,
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
def clear() -> None:
|
|
144
|
-
"""全清(测试与排障用;生产路径不调它)。"""
|
|
145
|
-
with _LOCK:
|
|
146
|
-
_ITEMS.clear()
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def stats() -> dict:
|
|
150
|
-
"""当前读数:条数与占用字节(`/api` 与测试用)。"""
|
|
151
|
-
with _LOCK:
|
|
152
|
-
return {"entries": len(_ITEMS), "bytes": _total_bytes()}
|
|
1
|
+
"""`web_fetch` 的响应缓存。
|
|
2
|
+
|
|
3
|
+
一张按 URL 的表:30 分钟内同一个地址再抓一次,不再出网。
|
|
4
|
+
|
|
5
|
+
判据:
|
|
6
|
+
|
|
7
|
+
- 键是归一化后的 URL:scheme 与主机小写、去掉默认端口与 `#` 片段,
|
|
8
|
+
查询串原样保留(它可能就是"另一页")。主机名里的 `www.` 不剥
|
|
9
|
+
—— 那是另一个主机名,服务端可以给出不同的内容。
|
|
10
|
+
- 只缓存成功响应。跳转与 4xx / 5xx 不缓存:跳转链会变,
|
|
11
|
+
存一条 302 会把人钉在旧地址上;失败多数是临时的。
|
|
12
|
+
- 时效从抓取那一刻算起,不滑动。缓存回答的是"这条内容有多旧",
|
|
13
|
+
与"谁最近读过它"无关。
|
|
14
|
+
- 总量 256 MiB,按最近使用淘汰。过期条目在每次读 / 写时顺手清掉。
|
|
15
|
+
- 它是进程级的网络缓存,不是会话态:键是 URL,与哪条会话读过它无关,
|
|
16
|
+
`/clear` 不清它(登记在 `core/state_registry.py` 的进程级那张表里)。
|
|
17
|
+
|
|
18
|
+
命中时不做任何出网动作,所以 `web_fetch` 把出网审批闸放在命中判断之后:
|
|
19
|
+
闸问的是"该不该把这次请求发出去",没有发出去的就不该问。地板与金丝雀
|
|
20
|
+
仍然逐次跑 —— 它们只看地址,不看网络。
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import threading
|
|
27
|
+
import time
|
|
28
|
+
from typing import Any, Dict, Optional
|
|
29
|
+
from urllib.parse import urlsplit, urlunsplit
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"TTL_SECONDS", "MAX_TOTAL_BYTES",
|
|
33
|
+
"normalize", "key_of", "get", "put", "clear", "stats",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
#: 一条内容活多久。网页的新鲜度以分钟计,不是以天计。
|
|
37
|
+
TTL_SECONDS = 30 * 60
|
|
38
|
+
|
|
39
|
+
#: 整个缓存的上限。单次抓取本身封在 64 MiB,这里能装下几份大的。
|
|
40
|
+
MAX_TOTAL_BYTES = 256 * 1024 * 1024
|
|
41
|
+
|
|
42
|
+
_DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
43
|
+
|
|
44
|
+
_LOCK = threading.RLock()
|
|
45
|
+
|
|
46
|
+
#: 键 -> {status, content_type, raw, result, at, used}。
|
|
47
|
+
_ITEMS: Dict[str, Dict[str, Any]] = {}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def normalize(url: str) -> str:
|
|
51
|
+
"""缓存键用的 URL 形状(判据见模块 docstring)。"""
|
|
52
|
+
raw = str(url or "").strip()
|
|
53
|
+
try:
|
|
54
|
+
parts = urlsplit(raw)
|
|
55
|
+
except ValueError:
|
|
56
|
+
return raw
|
|
57
|
+
scheme = (parts.scheme or "").lower()
|
|
58
|
+
host = (parts.hostname or "").lower()
|
|
59
|
+
if ":" in host:
|
|
60
|
+
host = "[%s]" % host
|
|
61
|
+
try:
|
|
62
|
+
port = parts.port
|
|
63
|
+
except ValueError:
|
|
64
|
+
port = None
|
|
65
|
+
if port is not None and _DEFAULT_PORTS.get(scheme) == port:
|
|
66
|
+
port = None
|
|
67
|
+
netloc = host if port is None else "%s:%d" % (host, port)
|
|
68
|
+
path = parts.path or "/"
|
|
69
|
+
return urlunsplit((scheme, netloc, path, parts.query, ""))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def key_of(url: str) -> str:
|
|
73
|
+
"""归一化之后的 URL 的短摘要(URL 本身可能很长)。"""
|
|
74
|
+
return hashlib.sha256(normalize(url).encode("utf-8")).hexdigest()[:24]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _total_bytes() -> int:
|
|
78
|
+
"""当前占用(按响应体计)。调用方持锁。"""
|
|
79
|
+
return sum(len(item.get("raw") or b"") for item in _ITEMS.values())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _drop_expired(now: float) -> None:
|
|
83
|
+
"""清掉过期的条目。调用方持锁。"""
|
|
84
|
+
expired = [k for k, item in _ITEMS.items()
|
|
85
|
+
if now - float(item.get("at") or 0.0) > TTL_SECONDS]
|
|
86
|
+
for key in expired:
|
|
87
|
+
_ITEMS.pop(key, None)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def get(url: str) -> Optional[dict]:
|
|
91
|
+
"""命中返回一份副本,未命中或已过期返回 `None`。
|
|
92
|
+
|
|
93
|
+
副本里的 `age_s` 是这一份内容被缓存了多久 —— 回执要把它如实给模型,
|
|
94
|
+
"这是刚抓的"与"这是半小时前的"不能长得一样。
|
|
95
|
+
"""
|
|
96
|
+
key = key_of(url)
|
|
97
|
+
now = time.monotonic()
|
|
98
|
+
with _LOCK:
|
|
99
|
+
item = _ITEMS.get(key)
|
|
100
|
+
if item is None:
|
|
101
|
+
return None
|
|
102
|
+
if now - float(item.get("at") or 0.0) > TTL_SECONDS:
|
|
103
|
+
_ITEMS.pop(key, None)
|
|
104
|
+
return None
|
|
105
|
+
item["used"] = now
|
|
106
|
+
return {
|
|
107
|
+
"status": item.get("status"),
|
|
108
|
+
"content_type": item.get("content_type") or "",
|
|
109
|
+
"raw": item.get("raw") or b"",
|
|
110
|
+
"result": dict(item["result"]) if item.get("result") else None,
|
|
111
|
+
"age_s": now - float(item.get("at") or now),
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def put(url: str, *, status, content_type: str, raw: bytes, result: dict) -> None:
|
|
116
|
+
"""存一份抓取结果。装不下就悄悄不存(缓存是加速,不是账本)。
|
|
117
|
+
|
|
118
|
+
先清过期、再按最近使用淘汰,腾够了才写 —— 新这一份不会被自己挤掉。
|
|
119
|
+
"""
|
|
120
|
+
body = bytes(raw or b"")
|
|
121
|
+
key = key_of(url)
|
|
122
|
+
now = time.monotonic()
|
|
123
|
+
with _LOCK:
|
|
124
|
+
_drop_expired(now)
|
|
125
|
+
_ITEMS.pop(key, None)
|
|
126
|
+
if len(body) > MAX_TOTAL_BYTES:
|
|
127
|
+
return
|
|
128
|
+
while _ITEMS and _total_bytes() + len(body) > MAX_TOTAL_BYTES:
|
|
129
|
+
oldest = min(_ITEMS, key=lambda k: float(_ITEMS[k].get("used") or 0.0))
|
|
130
|
+
_ITEMS.pop(oldest, None)
|
|
131
|
+
if _total_bytes() + len(body) > MAX_TOTAL_BYTES:
|
|
132
|
+
return
|
|
133
|
+
_ITEMS[key] = {
|
|
134
|
+
"status": int(status or 0),
|
|
135
|
+
"content_type": str(content_type or ""),
|
|
136
|
+
"raw": body,
|
|
137
|
+
"result": dict(result or {}),
|
|
138
|
+
"at": now,
|
|
139
|
+
"used": now,
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def clear() -> None:
|
|
144
|
+
"""全清(测试与排障用;生产路径不调它)。"""
|
|
145
|
+
with _LOCK:
|
|
146
|
+
_ITEMS.clear()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def stats() -> dict:
|
|
150
|
+
"""当前读数:条数与占用字节(`/api` 与测试用)。"""
|
|
151
|
+
with _LOCK:
|
|
152
|
+
return {"entries": len(_ITEMS), "bytes": _total_bytes()}
|