@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/prompt_assembler.py
CHANGED
|
@@ -284,7 +284,6 @@ def _runtime_line() -> str:
|
|
|
284
284
|
# ------------------------------------------------------------------
|
|
285
285
|
|
|
286
286
|
_CORE_INSTRUCTIONS = r"""{IDENTITY}
|
|
287
|
-
{TODAY}
|
|
288
287
|
{RUNTIME}
|
|
289
288
|
{WORKSPACE}
|
|
290
289
|
|
|
@@ -478,7 +477,7 @@ def _leaf_text() -> str:
|
|
|
478
477
|
return _load_leaf_md()[0]
|
|
479
478
|
except Exception as exc: # noqa: BLE001
|
|
480
479
|
# 读不到不许弄挂一轮 —— 那会把"某份文件编码坏了"升级成"整轮失败"。
|
|
481
|
-
print("[leaf]
|
|
480
|
+
print("[leaf] instruction file load failed (treated as absent): %s: %s"
|
|
482
481
|
% (type(exc).__name__, exc))
|
|
483
482
|
return ""
|
|
484
483
|
|
|
@@ -580,8 +579,8 @@ def assemble_system_prompt(memory_context: str = "",
|
|
|
580
579
|
|
|
581
580
|
# 1. Core behavioural instructions (framework-agnostic)
|
|
582
581
|
core = _CORE_INSTRUCTIONS.replace("{IDENTITY}", _identity_line(model_name))
|
|
583
|
-
#
|
|
584
|
-
|
|
582
|
+
# 日期那一行挪到整段 system 的末尾(见本函数结尾那一段)——
|
|
583
|
+
# 它是前缀里唯一每天会变的东西,放在核心指令里会让稳定段每天断一次缓存。
|
|
585
584
|
# 环境那一行:也每请求替换,但值本身是进程内常量 ——
|
|
586
585
|
# 所以它不违反前缀稳定性(只有 `{TODAY}` 那种真会变的东西才要小心)。
|
|
587
586
|
core = core.replace("{RUNTIME}",
|
|
@@ -677,4 +676,14 @@ def assemble_system_prompt(memory_context: str = "",
|
|
|
677
676
|
if memory_context:
|
|
678
677
|
sections.append(memory_context)
|
|
679
678
|
|
|
679
|
+
# 7. 当前日期 —— 唯一每天会变的一行,放在最后。
|
|
680
|
+
#
|
|
681
|
+
# 它原来在核心指令第二段(紧挨身份行),跨天一个字节的变化会让整个
|
|
682
|
+
# 稳定 system 前缀断掉。挪到这里之后,变点在最末尾:稳定段照命中,
|
|
683
|
+
# 只有它自己与之后的内容需要重算。对所有供应商都安全,不依赖某家的缓存规则。
|
|
684
|
+
# 仍然每次组装现取(`_today_line` -> `date_line`),不冻成模块常量。
|
|
685
|
+
date_section = _today_line()
|
|
686
|
+
if date_section:
|
|
687
|
+
sections.append(date_section)
|
|
688
|
+
|
|
680
689
|
return "\n\n".join(sections)
|
package/core/recycle.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""把文件送进系统回收站(Windows / Linux)。
|
|
2
2
|
|
|
3
3
|
## 它是什么,不是什么
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
`
|
|
5
|
+
是什么:两个平台各一个薄壳,都零依赖 —— Windows 用 `ctypes` 直调
|
|
6
|
+
`shell32!SHFileOperationW` + `FOF_ALLOWUNDO`;Linux 按 freedesktop 的 Trash
|
|
7
|
+
规范写 `.trashinfo` 再搬进 `Trash/files`。用户在文件管理器里自己还原,
|
|
8
|
+
我们零新界面。
|
|
7
9
|
|
|
8
10
|
不是什么:它不是一道闸。 `run_command` 的 `rm -rf` 照旧直接删,
|
|
9
11
|
「bash 的写权限不受 `validate_path` 约束」对回收站同样成立。
|
|
@@ -47,7 +49,11 @@
|
|
|
47
49
|
from __future__ import annotations
|
|
48
50
|
|
|
49
51
|
import ctypes
|
|
52
|
+
import os
|
|
53
|
+
import stat
|
|
50
54
|
import sys
|
|
55
|
+
import time
|
|
56
|
+
import urllib.parse
|
|
51
57
|
from dataclasses import dataclass, field
|
|
52
58
|
from pathlib import Path
|
|
53
59
|
from typing import Iterable
|
|
@@ -121,15 +127,26 @@ def _lib():
|
|
|
121
127
|
return None
|
|
122
128
|
|
|
123
129
|
|
|
130
|
+
_xdg_error = ""
|
|
131
|
+
|
|
132
|
+
|
|
124
133
|
def available() -> bool:
|
|
125
134
|
"""这台机器上能不能用系统回收站。"""
|
|
126
|
-
|
|
135
|
+
if sys.platform == "win32":
|
|
136
|
+
return _lib() is not None
|
|
137
|
+
if sys.platform.startswith("linux"):
|
|
138
|
+
return _xdg_available()
|
|
139
|
+
return False
|
|
127
140
|
|
|
128
141
|
|
|
129
142
|
def unavailable_reason() -> str:
|
|
130
143
|
"""为什么用不了 —— 给回执用的一句话(拿不到原因时给空串)。"""
|
|
131
|
-
|
|
132
|
-
|
|
144
|
+
if sys.platform == "win32":
|
|
145
|
+
_lib()
|
|
146
|
+
return _load_error
|
|
147
|
+
if sys.platform.startswith("linux"):
|
|
148
|
+
return "" if _xdg_available() else (_xdg_error or "回收站目录不可用")
|
|
149
|
+
return "本平台没有接入系统回收站(目前 Windows 与 Linux)"
|
|
133
150
|
|
|
134
151
|
|
|
135
152
|
# 回收站条目数(判据 ③:进出前后比一比)
|
|
@@ -213,13 +230,8 @@ class RecycleOutcome:
|
|
|
213
230
|
return self.bin_delta < len(self.moved)
|
|
214
231
|
|
|
215
232
|
|
|
216
|
-
def
|
|
217
|
-
"""
|
|
218
|
-
|
|
219
|
-
[!] 这个函数只负责送:送不成的它不动(不替调用方决定要不要硬删)。
|
|
220
|
-
"送不进就退回首删"是调用方的策略,而且必须出声。
|
|
221
|
-
"""
|
|
222
|
-
items = [str(p) for p in paths]
|
|
233
|
+
def _win_send_to_trash(items: list[str]) -> RecycleOutcome:
|
|
234
|
+
"""Windows 那半:逐条交给 `SHFileOperationW`(判据见模块 docstring)。"""
|
|
223
235
|
out = RecycleOutcome()
|
|
224
236
|
lib = _lib()
|
|
225
237
|
if lib is None:
|
|
@@ -242,6 +254,204 @@ def send_to_recycle_bin(paths: Iterable[str | Path]) -> RecycleOutcome:
|
|
|
242
254
|
return out
|
|
243
255
|
|
|
244
256
|
|
|
257
|
+
# ---------------------------------------------------------------- Linux (XDG)
|
|
258
|
+
#
|
|
259
|
+
# freedesktop.org 的 Trash 规范。为什么自己实现、不调 `gio trash`:`gio` 是
|
|
260
|
+
# GLib 的命令行工具,精简镜像不一定有;而这条能力挂在"删文件"这条路上,
|
|
261
|
+
# 缺一个工具就退回永久删 —— 与 Windows 那半"零依赖"同一条判据。
|
|
262
|
+
#
|
|
263
|
+
# 规范里两处承重:
|
|
264
|
+
# · 回收站必须与文件在同一个文件系统里(跨设备是拷贝不是移动,语义就变了);
|
|
265
|
+
# 家目录回收站收不了别的挂载点,那就退到那个挂载点的 `.Trash-$uid`。
|
|
266
|
+
# · `info/<名字>.trashinfo` 里写原始绝对路径(URL 编码)与删除时间 ——
|
|
267
|
+
# 文件管理器就是靠它还原。所以"写进 files/ 了"不等于"能还原":
|
|
268
|
+
# 两样都在,才算。
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _xdg_data_home() -> Path:
|
|
272
|
+
env = (os.environ.get("XDG_DATA_HOME") or "").strip()
|
|
273
|
+
return Path(env) if env else Path.home() / ".local" / "share"
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _xdg_home_trash(data_home: Path | None = None) -> Path:
|
|
277
|
+
return (data_home or _xdg_data_home()) / "Trash"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _dev_of(p: Path) -> int | None:
|
|
281
|
+
"""*p* 所在文件系统的设备号;路径还不存在就沿父级往上找(读不到给 `None`)。"""
|
|
282
|
+
cur = p
|
|
283
|
+
while True:
|
|
284
|
+
try:
|
|
285
|
+
return cur.stat().st_dev
|
|
286
|
+
except OSError:
|
|
287
|
+
if cur.parent == cur:
|
|
288
|
+
return None
|
|
289
|
+
cur = cur.parent
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _mount_topdir(path: Path) -> Path:
|
|
293
|
+
"""*path* 所在挂载点(规范里的 topdir):往上走,直到 `st_dev` 变了。"""
|
|
294
|
+
start = path if path.is_dir() else path.parent
|
|
295
|
+
dev = _dev_of(start)
|
|
296
|
+
if dev is None:
|
|
297
|
+
return start
|
|
298
|
+
cur = start
|
|
299
|
+
while cur.parent != cur and _dev_of(cur.parent) == dev:
|
|
300
|
+
cur = cur.parent
|
|
301
|
+
return cur
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _xdg_uid() -> int:
|
|
305
|
+
return os.getuid() if hasattr(os, "getuid") else 0
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _topdir_trash(topdir: Path) -> Path | None:
|
|
309
|
+
"""挂载点上的回收站:优先共享的 `.Trash/$uid`(须 sticky),否则 `.Trash-$uid`。"""
|
|
310
|
+
shared = topdir / ".Trash"
|
|
311
|
+
try:
|
|
312
|
+
st = shared.lstat()
|
|
313
|
+
except OSError:
|
|
314
|
+
st = None
|
|
315
|
+
if (st is not None and stat.S_ISDIR(st.st_mode)
|
|
316
|
+
and not stat.S_ISLNK(st.st_mode)
|
|
317
|
+
and st.st_mode & stat.S_ISVTX):
|
|
318
|
+
mine = shared / str(_xdg_uid())
|
|
319
|
+
try:
|
|
320
|
+
mine.mkdir(exist_ok=True)
|
|
321
|
+
return mine
|
|
322
|
+
except OSError:
|
|
323
|
+
return None
|
|
324
|
+
mine = topdir / (".Trash-%d" % _xdg_uid())
|
|
325
|
+
try:
|
|
326
|
+
mine.mkdir(exist_ok=True)
|
|
327
|
+
return mine
|
|
328
|
+
except OSError:
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _xdg_trash_for(path: Path, *, data_home: Path | None = None) -> tuple[Path | None, str]:
|
|
333
|
+
"""这个文件该进哪个回收站:家目录的,还是它所在挂载点的。"""
|
|
334
|
+
home = _xdg_home_trash(data_home)
|
|
335
|
+
p_dev = _dev_of(path)
|
|
336
|
+
if p_dev is not None and _dev_of(home) == p_dev:
|
|
337
|
+
return home, ""
|
|
338
|
+
top = _mount_topdir(path)
|
|
339
|
+
got = _topdir_trash(top)
|
|
340
|
+
if got is None:
|
|
341
|
+
return None, "这个挂载点(%s)不允许建回收站目录" % top
|
|
342
|
+
return got, ""
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _xdg_unique_name(base: str, trash: Path) -> str:
|
|
346
|
+
name = base
|
|
347
|
+
n = 0
|
|
348
|
+
while ((trash / "files" / name).exists()
|
|
349
|
+
or (trash / "info" / (name + ".trashinfo")).exists()):
|
|
350
|
+
n += 1
|
|
351
|
+
name = "%s.%d" % (base, n)
|
|
352
|
+
return name
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _xdg_send_one(src: Path, *, trash: Path, name: str) -> tuple[bool, str]:
|
|
356
|
+
"""先写 `.trashinfo`、再搬文件;搬失败就把那份 info 收回来。
|
|
357
|
+
|
|
358
|
+
顺序是有意的:info 先落,文件管理器才不会看到一个没有出生证明的条目;
|
|
359
|
+
而搬之前文件还在原处,失败也只丢一份 info。
|
|
360
|
+
"""
|
|
361
|
+
info = trash / "info" / (name + ".trashinfo")
|
|
362
|
+
dest = trash / "files" / name
|
|
363
|
+
body = ("[Trash Info]\nPath=%s\nDeletionDate=%s\n"
|
|
364
|
+
% (urllib.parse.quote(os.path.abspath(src), safe="/"),
|
|
365
|
+
time.strftime("%Y-%m-%dT%H:%M:%S")))
|
|
366
|
+
try:
|
|
367
|
+
with open(info, "x", encoding="utf-8", newline="\n") as fh:
|
|
368
|
+
fh.write(body)
|
|
369
|
+
except OSError as exc:
|
|
370
|
+
return False, "%s: %s" % (type(exc).__name__, exc)
|
|
371
|
+
try:
|
|
372
|
+
os.rename(src, dest)
|
|
373
|
+
except OSError as exc:
|
|
374
|
+
try:
|
|
375
|
+
info.unlink()
|
|
376
|
+
except OSError:
|
|
377
|
+
pass
|
|
378
|
+
return False, "%s: %s" % (type(exc).__name__, exc)
|
|
379
|
+
return True, ""
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _xdg_send_to_trash(items: list[str], *,
|
|
383
|
+
data_home: Path | None = None) -> RecycleOutcome:
|
|
384
|
+
"""Linux 那半:按 XDG Trash 规范逐条搬(`data_home` 只为测试留口)。"""
|
|
385
|
+
out = RecycleOutcome()
|
|
386
|
+
home = _xdg_home_trash(data_home)
|
|
387
|
+
try:
|
|
388
|
+
(home / "files").mkdir(parents=True, exist_ok=True)
|
|
389
|
+
(home / "info").mkdir(parents=True, exist_ok=True)
|
|
390
|
+
except OSError as exc:
|
|
391
|
+
out.unavailable = True
|
|
392
|
+
out.reason = "建不了回收站目录(%s)" % exc
|
|
393
|
+
out.failed = ["%s: %s" % (p, out.reason) for p in items]
|
|
394
|
+
return out
|
|
395
|
+
|
|
396
|
+
moved = 0
|
|
397
|
+
for raw in items:
|
|
398
|
+
src = Path(raw)
|
|
399
|
+
if not src.exists() and not src.is_symlink():
|
|
400
|
+
out.failed.append("%s: 不存在" % raw)
|
|
401
|
+
continue
|
|
402
|
+
trash, why = _xdg_trash_for(src, data_home=data_home)
|
|
403
|
+
if trash is None:
|
|
404
|
+
out.failed.append("%s: %s" % (raw, why))
|
|
405
|
+
continue
|
|
406
|
+
try:
|
|
407
|
+
(trash / "files").mkdir(parents=True, exist_ok=True)
|
|
408
|
+
(trash / "info").mkdir(parents=True, exist_ok=True)
|
|
409
|
+
except OSError as exc:
|
|
410
|
+
out.failed.append("%s: %s" % (raw, exc))
|
|
411
|
+
continue
|
|
412
|
+
name = _xdg_unique_name(src.name, trash)
|
|
413
|
+
ok, why = _xdg_send_one(src, trash=trash, name=name)
|
|
414
|
+
if ok:
|
|
415
|
+
out.moved.append(raw)
|
|
416
|
+
moved += 1
|
|
417
|
+
else:
|
|
418
|
+
out.failed.append("%s: %s" % (raw, why))
|
|
419
|
+
if items:
|
|
420
|
+
#: 与 Windows 的"条目数净增"同义:确认能还原的个数。
|
|
421
|
+
#: info 与 files 两样都在才算 —— 只有文件没有 info 是还原不了的。
|
|
422
|
+
out.bin_delta = moved
|
|
423
|
+
return out
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _xdg_available() -> bool:
|
|
427
|
+
global _xdg_error
|
|
428
|
+
try:
|
|
429
|
+
(_xdg_home_trash() / "files").mkdir(parents=True, exist_ok=True)
|
|
430
|
+
(_xdg_home_trash() / "info").mkdir(parents=True, exist_ok=True)
|
|
431
|
+
return True
|
|
432
|
+
except OSError as exc:
|
|
433
|
+
_xdg_error = "建不了回收站目录(%s)" % exc
|
|
434
|
+
return False
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def send_to_recycle_bin(paths: Iterable[str | Path]) -> RecycleOutcome:
|
|
438
|
+
"""把 *paths* 逐个送进系统回收站。逐条调(见模块 docstring 判据 ②)。
|
|
439
|
+
|
|
440
|
+
[!] 这个函数只负责送:送不成的它不动(不替调用方决定要不要硬删)。
|
|
441
|
+
"送不进就退回首删"是调用方的策略,而且必须出声。
|
|
442
|
+
"""
|
|
443
|
+
items = [str(p) for p in paths]
|
|
444
|
+
if sys.platform == "win32":
|
|
445
|
+
return _win_send_to_trash(items)
|
|
446
|
+
if sys.platform.startswith("linux"):
|
|
447
|
+
return _xdg_send_to_trash(items)
|
|
448
|
+
out = RecycleOutcome()
|
|
449
|
+
out.unavailable = True
|
|
450
|
+
out.reason = "本平台没有接入系统回收站(目前 Windows 与 Linux)"
|
|
451
|
+
out.failed = ["%s: %s" % (p, out.reason) for p in items]
|
|
452
|
+
return out
|
|
453
|
+
|
|
454
|
+
|
|
245
455
|
def _drive_root(path: str) -> str:
|
|
246
456
|
"""`C:\\a\\b` → `C:\\\\`;取不到盘符就退到进程所在盘。"""
|
|
247
457
|
try:
|
|
@@ -280,12 +490,13 @@ def explain(outcome: RecycleOutcome, *, permanent_ok: int = 0) -> str:
|
|
|
280
490
|
parts.append("已把 %d 个文件送进系统回收站,但**读不到回收站的条目数**,"
|
|
281
491
|
"所以**无法确认**它们能不能还原。" % n)
|
|
282
492
|
elif n and outcome.bin_delta < n:
|
|
283
|
-
parts.append("[!] 送进去 %d
|
|
284
|
-
"**有 %d
|
|
493
|
+
parts.append("[!] 送进去 %d 个,而回收站只确认了 %d 个 —— "
|
|
494
|
+
"**有 %d 个没能进回收站**(配额满了,或这一步失败了),"
|
|
285
495
|
"那些是**永久删除**,**还原不了**。"
|
|
286
496
|
% (n, outcome.bin_delta, n - outcome.bin_delta))
|
|
287
497
|
elif n:
|
|
288
|
-
|
|
498
|
+
where = "资源管理器" if sys.platform == "win32" else "文件管理器"
|
|
499
|
+
parts.append("已把 %d 个文件送进**系统回收站**(可从%s还原)。" % (n, where))
|
|
289
500
|
else:
|
|
290
501
|
parts.append("没有文件被送进回收站。")
|
|
291
502
|
|
|
@@ -127,7 +127,7 @@ def configured_language() -> str | None:
|
|
|
127
127
|
lang = normalize(val)
|
|
128
128
|
if lang is None and not _bad_noted:
|
|
129
129
|
_bad_noted = True
|
|
130
|
-
print("[language]
|
|
130
|
+
print("[language] configured %s=%r unrecognized - following system"
|
|
131
131
|
% (SETTING_KEY, val))
|
|
132
132
|
return lang
|
|
133
133
|
|
package/core/retention.py
CHANGED
|
@@ -110,7 +110,7 @@ def prune_archived_notes(sessions_dir, days: Optional[int] = None,
|
|
|
110
110
|
if _unlink_if_old(p, cutoff):
|
|
111
111
|
removed += 1
|
|
112
112
|
if removed:
|
|
113
|
-
print("[retention]
|
|
113
|
+
print("[retention] removed %d archived session notes older than %d days" % (removed, days))
|
|
114
114
|
return removed
|
|
115
115
|
|
|
116
116
|
|
|
@@ -191,7 +191,7 @@ def prune_runtime_dirs(now: Optional[datetime] = None) -> dict:
|
|
|
191
191
|
removed += 1
|
|
192
192
|
out[directory] = removed
|
|
193
193
|
if removed:
|
|
194
|
-
print("[retention] %s
|
|
194
|
+
print("[retention] %s: removed %d files older than %d days"
|
|
195
195
|
% (directory, removed, use_days))
|
|
196
196
|
return out
|
|
197
197
|
|
package/core/rg.py
CHANGED
|
@@ -49,10 +49,11 @@ __all__ = [
|
|
|
49
49
|
_APP_ROOT = Path(__file__).resolve().parent.parent
|
|
50
50
|
|
|
51
51
|
#: `(sys.platform, 机器架构)` → `vendor/ripgrep/` 下的目录名。
|
|
52
|
-
#:
|
|
52
|
+
#: 发了 Windows x64 与 Linux x64;别的平台没有二进制 —— 那就明说,不假装能用。
|
|
53
53
|
_PLATFORM_DIRS = {
|
|
54
54
|
("win32", "amd64"): "win32-x64",
|
|
55
55
|
("win32", "x86_64"): "win32-x64",
|
|
56
|
+
("linux", "x86_64"): "linux-x64",
|
|
56
57
|
}
|
|
57
58
|
|
|
58
59
|
|
|
@@ -74,7 +75,7 @@ def platform_dir() -> str:
|
|
|
74
75
|
name = _PLATFORM_DIRS.get(key)
|
|
75
76
|
if not name:
|
|
76
77
|
raise RgUnavailable(
|
|
77
|
-
"这个平台(%s/%s)**没有随包的 ripgrep** ——
|
|
78
|
+
"这个平台(%s/%s)**没有随包的 ripgrep** —— 只发了 Windows x64 与 Linux x64。"
|
|
78
79
|
"要么换一台 Windows x64 的机器,要么用 `CRANNIA_RG` 指定一个 "
|
|
79
80
|
"ripgrep 可执行文件的绝对路径。" % (sys.platform, key[1] or "?"))
|
|
80
81
|
return name
|
|
@@ -248,7 +249,7 @@ class RgRun:
|
|
|
248
249
|
yield ev
|
|
249
250
|
if time.monotonic() > deadline:
|
|
250
251
|
self.timed_out = True
|
|
251
|
-
print("[rg]
|
|
252
|
+
print("[rg] exceeded %.1fs - stopping (results so far kept)" % self._timeout)
|
|
252
253
|
return
|
|
253
254
|
finally:
|
|
254
255
|
if time.monotonic() > deadline:
|
package/core/security.py
CHANGED
|
@@ -90,6 +90,9 @@ DEFAULT_FORBIDDEN_PATHS: list[str] = [
|
|
|
90
90
|
# 唯一依据。漏一条 = 模型读得到自己的 key,而没有任何东西会红。
|
|
91
91
|
# `web/server.py::_API_KEYS_PATH` 指向的是同一类账本。
|
|
92
92
|
"data/api_keys.json",
|
|
93
|
+
# 单文件存储(2026-11-26):账本与模型 api 同一份。
|
|
94
|
+
"data/runtime/model_configs.json",
|
|
95
|
+
# 老形状的凭据文件 —— 只在迁移期可能存在;迁完就删,留着这条不亏。
|
|
93
96
|
"data/runtime/provider_credentials.json",
|
|
94
97
|
# QQ 机器人的 appId / appSecret。读到它就能冒充那个机器人发消息。
|
|
95
98
|
# 旧的那份单文件(升级后由配置条目账本接管,文件可能还在)。
|
|
@@ -317,8 +320,7 @@ def _resolve_public_addresses(hostname: str) -> list[str]:
|
|
|
317
320
|
# 判据刻意只看这一段(RFC 2544 基准段,正常公网不会出现)——
|
|
318
321
|
# 不按"有没有配代理"放宽,因为 DNS 是系统做的、跟我们那档设置无关。
|
|
319
322
|
if all(_is_fake_ip(a) for a in addrs):
|
|
320
|
-
print(f"[egress] {hostname} -> {addrs[0]}
|
|
321
|
-
f"(代理的 DNS 模式)—— 跳过 IP 段判定")
|
|
323
|
+
print(f"[egress] {hostname} -> {addrs[0]} is a fake-ip placeholder address (proxy DNS mode) - skipping IP range check")
|
|
322
324
|
return addrs
|
|
323
325
|
|
|
324
326
|
for addr in addrs:
|
|
@@ -538,7 +540,7 @@ def _note_touched(resolved_path: str) -> None:
|
|
|
538
540
|
from core.file_history import snapshot_before
|
|
539
541
|
snapshot_before(sid, resolved_path, turn=_current_turn(sid))
|
|
540
542
|
except Exception as exc: # noqa: BLE001
|
|
541
|
-
print("[touched]
|
|
543
|
+
print("[touched] wiring failed (does not affect writes): %s: %s" % (type(exc).__name__, exc))
|
|
542
544
|
|
|
543
545
|
|
|
544
546
|
def _current_turn(channel_key: str) -> int:
|
|
@@ -588,12 +590,12 @@ def _note_command_duplicate(command: str) -> None:
|
|
|
588
590
|
_recent_commands.pop(next(iter(_recent_commands)))
|
|
589
591
|
if n == 2:
|
|
590
592
|
print(
|
|
591
|
-
"[w28]
|
|
592
|
-
"
|
|
593
|
-
"
|
|
593
|
+
"[w28] within %.0f s the same command was seen %d times - attribution unknown"
|
|
594
|
+
" (model retry vs framework re-dispatch, different fixes). Check whether its `tool_call_id` "
|
|
595
|
+
"is the same; command: %s" % (_DUP_COMMAND_WINDOW_S, n, key[:120])
|
|
594
596
|
)
|
|
595
597
|
except Exception as exc: # noqa: BLE001
|
|
596
|
-
print("[w28]
|
|
598
|
+
print("[w28] duplicate command probe itself failed (does not affect execution): %s: %s"
|
|
597
599
|
% (type(exc).__name__, exc))
|
|
598
600
|
|
|
599
601
|
|
|
@@ -855,7 +857,7 @@ class SecurityGuard:
|
|
|
855
857
|
# 设置只决定"钉不钉得成",两处各读一次会分叉。
|
|
856
858
|
# 代价:`.env` 这类密钥读得到、系统目录也读得到。
|
|
857
859
|
if _unlock_bypassing():
|
|
858
|
-
print("[unlock]
|
|
860
|
+
print("[unlock] protected path allowed: %s" % resolved)
|
|
859
861
|
return resolved, PathLevel.READ_WRITE
|
|
860
862
|
return resolved, PathLevel.FORBIDDEN
|
|
861
863
|
|
|
@@ -1319,6 +1321,22 @@ class SecurityGuard:
|
|
|
1319
1321
|
matched_rule or "none")
|
|
1320
1322
|
self._audit(action, target)
|
|
1321
1323
|
|
|
1324
|
+
def record_egress(self, channel: str, target: str, action: str,
|
|
1325
|
+
grant: str = "", verdict: str = "") -> None:
|
|
1326
|
+
"""把一次出网调用写进审计(不论工具权限档是 read 还是 write)。
|
|
1327
|
+
|
|
1328
|
+
出网是"数据离开这台机器",风险与工具权限档无关:net_ports 只读,
|
|
1329
|
+
但它告诉模型哪台机器开着哪个口。事后要回答"什么、何时、发到哪" -
|
|
1330
|
+
少一行就回答不了。
|
|
1331
|
+
|
|
1332
|
+
grant 是这次凭什么放行(session / file / prompt);
|
|
1333
|
+
verdict 是结果(ok / error / asked)。凭据只记条目名,永不记值。
|
|
1334
|
+
"""
|
|
1335
|
+
target_s = "channel=%s | target=%s | action=%s | grant=%s | verdict=%s" % (
|
|
1336
|
+
channel or "?", target or "-", action or "-",
|
|
1337
|
+
grant or "none", verdict or "-")
|
|
1338
|
+
self._audit("EGRESS", target_s)
|
|
1339
|
+
|
|
1322
1340
|
def record_ice(self, action: str, detail: str) -> None:
|
|
1323
1341
|
"""把一次 `ICE` 信息侧的读数写进同一个审计日志。
|
|
1324
1342
|
|
package/core/services.py
CHANGED
|
@@ -53,7 +53,7 @@ def start_for(names: Iterable[str],
|
|
|
53
53
|
module = load(key)
|
|
54
54
|
except Exception as exc: # noqa: BLE001
|
|
55
55
|
failed.append((key, "import: %s: %s" % (type(exc).__name__, exc)))
|
|
56
|
-
print("[service] %s
|
|
56
|
+
print("[service] %s load failed: %s: %s" % (key, type(exc).__name__, exc))
|
|
57
57
|
continue
|
|
58
58
|
start = getattr(module, "start", None)
|
|
59
59
|
if start is None:
|
|
@@ -64,17 +64,17 @@ def start_for(names: Iterable[str],
|
|
|
64
64
|
ctx = get_context(key)
|
|
65
65
|
except Exception as exc: # noqa: BLE001
|
|
66
66
|
failed.append((key, "context: %s: %s" % (type(exc).__name__, exc)))
|
|
67
|
-
print("[service] %s
|
|
67
|
+
print("[service] %s context unavailable: %s: %s" % (key, type(exc).__name__, exc))
|
|
68
68
|
continue
|
|
69
69
|
|
|
70
70
|
# 数据版本:不兼容就不启动,并把原因说清楚。
|
|
71
71
|
_chk = ctx.check_data(getattr(module, "migrate", None))
|
|
72
72
|
if not _chk.get("ok"):
|
|
73
73
|
failed.append((key, "data: " + str(_chk.get("error") or "")))
|
|
74
|
-
print("[service] %s
|
|
74
|
+
print("[service] %s not started: %s" % (key, _chk.get("error") or ""))
|
|
75
75
|
continue
|
|
76
76
|
if _chk.get("migrated"):
|
|
77
|
-
print("[service] %s
|
|
77
|
+
print("[service] %s data migrated from v%s to v%s"
|
|
78
78
|
% (key, _chk.get("found"), _chk.get("ours")))
|
|
79
79
|
|
|
80
80
|
rec = {
|
|
@@ -92,7 +92,7 @@ def start_for(names: Iterable[str],
|
|
|
92
92
|
_start(_ctx)
|
|
93
93
|
except Exception as exc: # noqa: BLE001
|
|
94
94
|
_rec["error"] = "%s: %s" % (type(exc).__name__, exc)
|
|
95
|
-
print("[service] %s
|
|
95
|
+
print("[service] %s start failed: %s: %s"
|
|
96
96
|
% (_key, type(exc).__name__, exc))
|
|
97
97
|
|
|
98
98
|
thread = threading.Thread(target=_run, daemon=True,
|
|
@@ -102,7 +102,7 @@ def start_for(names: Iterable[str],
|
|
|
102
102
|
_SERVICES[key] = rec
|
|
103
103
|
thread.start()
|
|
104
104
|
started.append(key)
|
|
105
|
-
print("[service]
|
|
105
|
+
print("[service] started %s" % key)
|
|
106
106
|
return {"started": started, "skipped": skipped, "failed": failed}
|
|
107
107
|
|
|
108
108
|
|
|
@@ -118,13 +118,13 @@ def stop_all(timeout: float = STOP_TIMEOUT) -> list:
|
|
|
118
118
|
try:
|
|
119
119
|
stop(rec.get("ctx"))
|
|
120
120
|
except Exception as exc: # noqa: BLE001
|
|
121
|
-
print("[service] %s
|
|
121
|
+
print("[service] %s stop failed: %s: %s"
|
|
122
122
|
% (name, type(exc).__name__, exc))
|
|
123
123
|
thread = rec.get("thread")
|
|
124
124
|
if thread is not None:
|
|
125
125
|
thread.join(timeout)
|
|
126
126
|
names.append(name)
|
|
127
|
-
print("[service]
|
|
127
|
+
print("[service] stopped %s" % name)
|
|
128
128
|
return names
|
|
129
129
|
|
|
130
130
|
|
package/core/session_model.py
CHANGED
|
@@ -110,8 +110,7 @@ def frozen(storage_key: str) -> str:
|
|
|
110
110
|
# 读不到,当没冻(fail-open,同 `_stream_enabled` 那条)。
|
|
111
111
|
# 方向是掐出来的:读不到就走默认 —— 而"读不到"最可能的时刻正是
|
|
112
112
|
# 库刚建、或换了一台机器;那时"跟随默认"就是对的答案。
|
|
113
|
-
print(f"[session_model]
|
|
114
|
-
f"{type(exc).__name__}: {exc}")
|
|
113
|
+
print(f"[session_model] frozen model read failed (treating as unfrozen): {type(exc).__name__}: {exc}")
|
|
115
114
|
return ""
|
|
116
115
|
|
|
117
116
|
|
|
@@ -155,8 +154,7 @@ def freeze(storage_key: str, config_id: str) -> bool:
|
|
|
155
154
|
st.set_session_model(key, config_id)
|
|
156
155
|
return True
|
|
157
156
|
except Exception as exc: # noqa: BLE001
|
|
158
|
-
print(f"[session_model]
|
|
159
|
-
f"{type(exc).__name__}: {exc}")
|
|
157
|
+
print(f"[session_model] freeze failed (this session will follow default): {type(exc).__name__}: {exc}")
|
|
160
158
|
return False
|
|
161
159
|
|
|
162
160
|
|
|
@@ -194,7 +192,7 @@ def follow_default(storage_key: str) -> bool:
|
|
|
194
192
|
st.clear_session_model(key)
|
|
195
193
|
return existed
|
|
196
194
|
except Exception as exc: # noqa: BLE001
|
|
197
|
-
print(f"[session_model]
|
|
195
|
+
print(f"[session_model] revert to default failed ({type(exc).__name__}: {exc})")
|
|
198
196
|
return False
|
|
199
197
|
|
|
200
198
|
|
package/core/session_pool.py
CHANGED
|
@@ -27,6 +27,16 @@ from typing import Dict, List, Tuple
|
|
|
27
27
|
MAX_LOADED_SESSIONS = 32
|
|
28
28
|
|
|
29
29
|
|
|
30
|
+
def _provider_model_key(provider) -> str:
|
|
31
|
+
"""provider 实例 → 稳定的模型指纹。读不到就是空串(不猜)。"""
|
|
32
|
+
if provider is None:
|
|
33
|
+
return ""
|
|
34
|
+
prov = str(getattr(provider, "_provider_name", "") or "")
|
|
35
|
+
model = str(getattr(provider, "_model", "") or "")
|
|
36
|
+
window = str(getattr(provider, "context_window", "") or "")
|
|
37
|
+
return f"{prov}|{model}|{window}"
|
|
38
|
+
|
|
39
|
+
|
|
30
40
|
class SessionPool:
|
|
31
41
|
"""Per-user session facade over a single MemoryManager.
|
|
32
42
|
|
|
@@ -47,6 +57,10 @@ class SessionPool:
|
|
|
47
57
|
#: 外键 → (存储 id, messages)。按最近使用排序,条数有上限
|
|
48
58
|
#: (活动会话的完整消息表常驻,是内存随使用增长的主因)。
|
|
49
59
|
self._loaded: "OrderedDict[str, Tuple[str, List[dict]]]" = OrderedDict()
|
|
60
|
+
#: 每个键装载时用的模型指纹。切换模型后缓存里的 messages 仍按旧模型的
|
|
61
|
+
#: 窗口预算装载,直接复用会让"换到小窗口模型"那一轮带着旧预算上路。
|
|
62
|
+
#: 只记指纹(provider 目录名 + 模型名),不记 provider 对象本身。
|
|
63
|
+
self._loaded_model: dict[str, str] = {}
|
|
50
64
|
#: 缓存那把锁。Web 侧是多线程的,两个会话可以同时进出:
|
|
51
65
|
#: 一个线程 `move_to_end` 时另一个正好把那个键淘汰掉,`KeyError`
|
|
52
66
|
#: 就会从一次普通的取会话里冒出来。读也加锁 —— `OrderedDict`
|
|
@@ -65,9 +79,13 @@ class SessionPool:
|
|
|
65
79
|
"""
|
|
66
80
|
with self._lock:
|
|
67
81
|
got = self._loaded.get(session_key)
|
|
68
|
-
if got is not None:
|
|
82
|
+
if got is not None and self._model_key(session_key, provider):
|
|
69
83
|
self._loaded.move_to_end(session_key) # 命中即刷新热度
|
|
70
84
|
return got
|
|
85
|
+
if got is not None:
|
|
86
|
+
# 模型变了:旧那份按旧窗口装的,不走二次检查的复用路径。
|
|
87
|
+
self._loaded.pop(session_key, None)
|
|
88
|
+
self._loaded_model.pop(session_key, None)
|
|
71
89
|
|
|
72
90
|
# 锁外加载(库 I/O 不占着缓存锁)—— 然后二次检查:
|
|
73
91
|
# 同一个键可能已经被另一个线程加载完放进去了,那就用他那份,
|
|
@@ -75,12 +93,19 @@ class SessionPool:
|
|
|
75
93
|
sid, messages = self._load_thread(session_key)
|
|
76
94
|
with self._lock:
|
|
77
95
|
got = self._loaded.get(session_key)
|
|
78
|
-
if got is not None:
|
|
96
|
+
if got is not None and self._model_key(session_key, provider):
|
|
79
97
|
self._loaded.move_to_end(session_key)
|
|
80
98
|
return got
|
|
81
99
|
self._remember_locked(session_key, (sid, messages))
|
|
100
|
+
self._loaded_model[session_key] = _provider_model_key(provider)
|
|
82
101
|
return sid, messages
|
|
83
102
|
|
|
103
|
+
def _model_key(self, session_key: str, provider) -> bool:
|
|
104
|
+
"""缓存那份是不是按当前模型装的。provider 没给时视为一致。"""
|
|
105
|
+
if provider is None:
|
|
106
|
+
return True
|
|
107
|
+
return self._loaded_model.get(session_key, "") == _provider_model_key(provider)
|
|
108
|
+
|
|
84
109
|
def _remember(self, session_key: str,
|
|
85
110
|
value: Tuple[str, List[dict]]) -> None:
|
|
86
111
|
"""写进缓存并维持上限(持锁版本,见 `_remember_locked`)。"""
|
|
@@ -97,7 +122,9 @@ class SessionPool:
|
|
|
97
122
|
self._loaded[session_key] = value
|
|
98
123
|
self._loaded.move_to_end(session_key)
|
|
99
124
|
while len(self._loaded) > MAX_LOADED_SESSIONS:
|
|
100
|
-
self._loaded.popitem(last=False)
|
|
125
|
+
old_key, _ = self._loaded.popitem(last=False)
|
|
126
|
+
# 指纹跟着消息一起走,不然这张表会随会话数一直涨。
|
|
127
|
+
self._loaded_model.pop(old_key, None)
|
|
101
128
|
|
|
102
129
|
def _load_thread(self, session_key: str) -> Tuple[str, List[dict]]:
|
|
103
130
|
"""`通道键 → (存储 id, messages)` —— 那座桥。
|
|
@@ -201,6 +228,10 @@ class SessionPool:
|
|
|
201
228
|
# (铸 id 的那一步也在那儿,两件事必须同一个事务/同一个所有者,不然会漏)。
|
|
202
229
|
sid, messages = self._mgr.new_session(old_sid, channel_key=session_key)
|
|
203
230
|
self._remember(session_key, (sid, messages))
|
|
231
|
+
# `/clear` 换了线程,那份空历史还没有"按哪个模型装载"的指纹。
|
|
232
|
+
# 不在这里编一个(没拿 provider),删掉让下一次 get_or_create 自己算。
|
|
233
|
+
with self._lock:
|
|
234
|
+
self._loaded_model.pop(session_key, None)
|
|
204
235
|
return sid, messages
|
|
205
236
|
|
|
206
237
|
def open_detached_thread(self, session_key: str, seed: str = "") -> str:
|
|
@@ -277,8 +308,7 @@ class SessionPool:
|
|
|
277
308
|
except Exception as exc: # noqa: BLE001
|
|
278
309
|
# 判不出来,不算数(fail-closed):这一格的后果是
|
|
279
310
|
# "把消息追加到另一段对话上",方向与"少切一次"不对称。
|
|
280
|
-
print(f"[memory]
|
|
281
|
-
f"{type(exc).__name__}: {exc}")
|
|
311
|
+
print(f"[memory] thread ownership lookup failed (treating as not owned): {type(exc).__name__}: {exc}")
|
|
282
312
|
return False
|
|
283
313
|
|
|
284
314
|
def fork_thread(self, channel_key: str,
|