@hfyjq/crannia 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +48 -45
  3. package/README.md +1 -1
  4. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  5. package/THIRD-PARTY-PYTHON-linux.md +174 -0
  6. package/THIRD-PARTY-PYTHON.md +176 -162
  7. package/THIRD-PARTY.md +323 -316
  8. package/apps/desktop/quotes.txt +56 -56
  9. package/bus/core.py +677 -671
  10. package/bus/loaders/channel_loader.py +64 -64
  11. package/bus/loaders/provider_loader.py +4 -7
  12. package/bus/loaders/skill_loader.py +46 -27
  13. package/bus/loaders/skill_md.py +9 -9
  14. package/bus/mcp_disabled.py +4 -6
  15. package/bus/quarantine.py +10 -13
  16. package/bus/registry.py +2315 -2284
  17. package/bus/skill_state.py +124 -124
  18. package/channels/cli_channel/handler.py +3 -3
  19. package/channels/cli_channel/manifest.yaml +5 -5
  20. package/channels/dingtalk_channel/handler.py +32 -32
  21. package/channels/dingtalk_channel/manifest.yaml +12 -12
  22. package/channels/feishu_channel/handler.py +33 -33
  23. package/channels/feishu_channel/manifest.yaml +12 -12
  24. package/channels/qq_bot_channel/__init__.py +1 -1
  25. package/channels/qq_bot_channel/handler.py +24 -24
  26. package/channels/qq_bot_channel/manifest.yaml +4 -4
  27. package/channels/telegram_channel/__init__.py +1 -1
  28. package/channels/telegram_channel/handler.py +21 -21
  29. package/channels/telegram_channel/manifest.yaml +4 -4
  30. package/channels/telegram_channel/media.py +231 -231
  31. package/channels/textfmt.py +58 -58
  32. package/channels/wechat_channel/__init__.py +1 -1
  33. package/channels/wechat_channel/converter.py +1 -1
  34. package/channels/wechat_channel/handler.py +8 -8
  35. package/channels/wechat_channel/manifest.yaml +5 -5
  36. package/channels/wechat_channel/media.py +178 -178
  37. package/core/activity.py +753 -709
  38. package/core/agent_loop.py +7673 -7522
  39. package/core/allowlist.py +2 -3
  40. package/core/approval.py +34 -24
  41. package/core/approval_timeout.py +256 -228
  42. package/core/artifacts.py +3 -3
  43. package/core/attachment_gc.py +21 -0
  44. package/core/auto_review.py +2 -2
  45. package/core/browser/cdp.py +5 -2
  46. package/core/browser/discover.py +55 -19
  47. package/core/browser/session.py +4 -4
  48. package/core/cache_break_detector.py +97 -0
  49. package/core/cache_breakpoints.py +103 -0
  50. package/core/cache_policies.py +255 -0
  51. package/core/cancellation.py +3 -3
  52. package/core/channel_configs.py +3 -3
  53. package/core/channel_turns.py +13 -13
  54. package/core/child_approval.py +2 -3
  55. package/core/code_intel.py +11 -11
  56. package/core/command_policy.py +13 -7
  57. package/core/computer/annotate.py +231 -11
  58. package/core/computer/capture.py +140 -1
  59. package/core/computer/guard.py +7 -4
  60. package/core/computer/input.py +452 -26
  61. package/core/computer/session.py +563 -381
  62. package/core/computer/tools.py +2170 -928
  63. package/core/computer/uia.py +100 -1
  64. package/core/computer/watch.py +1 -1
  65. package/core/computer/win32.py +302 -7
  66. package/core/config_requirements.py +205 -205
  67. package/core/cron/runner.py +4 -4
  68. package/core/daily_log.py +2 -2
  69. package/core/dedup.py +2 -2
  70. package/core/egress_channels.py +326 -0
  71. package/core/egress_gate.py +96 -8
  72. package/core/egress_preapproved.py +59 -3
  73. package/core/endpoint.py +141 -141
  74. package/core/events.py +17 -8
  75. package/core/extension.py +2 -2
  76. package/core/file_history.py +10 -10
  77. package/core/file_tools.py +3 -3
  78. package/core/github_config.py +1 -1
  79. package/core/group_digest.py +3 -4
  80. package/core/group_minutes.py +5 -5
  81. package/core/group_reply.py +24 -0
  82. package/core/groups.py +5 -9
  83. package/core/hooks.py +15 -15
  84. package/core/i18n.py +2 -2
  85. package/core/ice/canary.py +3 -3
  86. package/core/ice/net_heuristics.py +2 -2
  87. package/core/im_routing.py +2 -2
  88. package/core/image_input.py +183 -43
  89. package/core/inbound.py +3 -3
  90. package/core/jobs.py +6 -6
  91. package/core/last_good.py +150 -150
  92. package/core/leaf_md.py +3 -3
  93. package/core/llm_errors.py +36 -27
  94. package/core/mail_config.py +2 -2
  95. package/core/memory/compressor.py +8 -8
  96. package/core/memory/manager.py +30 -45
  97. package/core/memory/session_memory.py +1 -2
  98. package/core/memory/short_term.py +4 -4
  99. package/core/memory_extract.py +1 -1
  100. package/core/memory_organize.py +8 -8
  101. package/core/memory_store.py +7 -9
  102. package/core/memory_transfer.py +2 -2
  103. package/core/model_capabilities.py +2 -2
  104. package/core/model_configs.py +219 -68
  105. package/core/model_profiles.py +333 -0
  106. package/core/modes.py +12 -11
  107. package/core/net_proxy.py +3 -3
  108. package/core/pipeline/scheduler.py +48 -43
  109. package/core/pipeline/stage.py +3 -0
  110. package/core/pipeline/stages/agent_loop.py +36 -15
  111. package/core/pipeline/stages/group_reply.py +22 -20
  112. package/core/pipeline/stages/post_process.py +7 -7
  113. package/core/pipeline/stages/pre_process.py +360 -68
  114. package/core/prompt_assembler.py +13 -4
  115. package/core/recycle.py +227 -16
  116. package/core/response_language.py +1 -1
  117. package/core/retention.py +2 -2
  118. package/core/rg.py +4 -3
  119. package/core/security.py +26 -8
  120. package/core/services.py +8 -8
  121. package/core/session_model.py +3 -5
  122. package/core/session_pool.py +35 -5
  123. package/core/session_recap.py +40 -3
  124. package/core/session_workspace.py +2 -3
  125. package/core/settings_baseline.py +2 -2
  126. package/core/settings_transfer.py +25 -1
  127. package/core/shell.py +52 -20
  128. package/core/side_call.py +3 -3
  129. package/core/skill_config.py +164 -0
  130. package/core/skill_factory.py +2 -2
  131. package/core/skill_guidance.py +2 -4
  132. package/core/skill_index.py +3 -4
  133. package/core/skill_settings.py +1 -1
  134. package/core/skill_sources.py +7 -7
  135. package/core/ssh_config.py +129 -0
  136. package/core/state_registry.py +67 -5
  137. package/core/subagent.py +28 -5
  138. package/core/subagent_defs.py +3 -3
  139. package/core/summarizer.py +4 -5
  140. package/core/tasks_notify.py +6 -6
  141. package/core/tiers.py +2 -2
  142. package/core/todos.py +1 -1
  143. package/core/token_calibrator.py +1 -4
  144. package/core/tool_outcome.py +108 -108
  145. package/core/touched_files.py +1 -1
  146. package/core/trace.py +12 -3
  147. package/core/unlock.py +4 -4
  148. package/core/update_tui.py +184 -158
  149. package/core/updater.py +5 -3
  150. package/core/version.py +14 -14
  151. package/core/vision_budget.py +235 -0
  152. package/core/web_cache.py +152 -152
  153. package/core/web_request.py +474 -0
  154. package/core/window_estimate.py +1 -1
  155. package/core/workspace.py +56 -26
  156. package/crannia_tray.py +278 -278
  157. package/licenses/GPL-3.0.txt +619 -619
  158. package/licenses/LGPL-2.1.txt +502 -502
  159. package/licenses/LGPL-3.0.txt +165 -165
  160. package/licenses/MIT-chat-on-wechat.txt +18 -18
  161. package/licenses/MIT-deepseek-harness.txt +21 -21
  162. package/licenses/Molio-LICENSE.txt +44 -44
  163. package/locales/en.json +1876 -1755
  164. package/main.py +154 -154
  165. package/mcpx/client.py +12 -1
  166. package/mcpx/manager.py +530 -522
  167. package/mcpx/servers/web_search.py +5 -13
  168. package/package.json +15 -23
  169. package/providers/anthropic/client.py +35 -33
  170. package/providers/base.py +13 -13
  171. package/providers/cache_policies.json +294 -0
  172. package/providers/cost_table.json +3779 -3779
  173. package/providers/lmstudio/client.py +2 -2
  174. package/providers/model_capabilities.json +6665 -6665
  175. package/providers/model_profiles.json +629 -0
  176. package/providers/ollama/client.py +2 -2
  177. package/providers/openai_compat.py +37 -16
  178. package/providers/openrouter/client.py +2 -2
  179. package/providers/qwen/__init__.py +1 -1
  180. package/providers/qwen/client.py +2 -2
  181. package/providers/qwen/manifest.yaml +16 -16
  182. package/providers/rate_limiter.py +2 -2
  183. package/providers/siliconflow/client.py +2 -2
  184. package/providers/validation.py +171 -171
  185. package/providers/vision_profiles.json +89 -0
  186. package/providers/window_table.json +8909 -8909
  187. package/requirements.txt +59 -51
  188. package/sbom-linux-x64.json +4580 -0
  189. package/sbom.json +4600 -4413
  190. package/skills/diagram/SKILL.md +47 -0
  191. package/skills/diagram/__init__.py +1 -0
  192. package/skills/diagram/handler.py +294 -0
  193. package/skills/diagram/layout.py +174 -0
  194. package/skills/diagram/manifest.yaml +106 -0
  195. package/skills/diagram/mermaid.py +170 -0
  196. package/skills/diagram/svg.py +223 -0
  197. package/skills/entertainment/SKILL.md +35 -35
  198. package/skills/entertainment/__init__.py +1 -1
  199. package/skills/entertainment/handler.py +91 -91
  200. package/skills/entertainment/manifest.yaml +26 -26
  201. package/skills/file_parser/GUIDANCE.md +10 -10
  202. package/skills/file_parser/handler.py +33 -11
  203. package/skills/github/SKILL.md +32 -32
  204. package/skills/github/__init__.py +1 -1
  205. package/skills/mail_parser/SKILL.md +68 -68
  206. package/skills/mail_parser/__init__.py +1 -1
  207. package/skills/mail_parser/handler.py +1 -1
  208. package/skills/media_gen/GUIDANCE.md +19 -19
  209. package/skills/media_gen/SKILL.md +43 -43
  210. package/skills/media_gen/__init__.py +1 -1
  211. package/skills/media_gen/handler.py +1 -1
  212. package/skills/media_gen/manifest.yaml +93 -93
  213. package/skills/netops/SKILL.md +45 -0
  214. package/skills/netops/__init__.py +1 -0
  215. package/skills/netops/handler.py +418 -0
  216. package/skills/netops/manifest.yaml +118 -0
  217. package/skills/office_parser/_excel_io.py +3 -3
  218. package/skills/office_parser/handler.py +2 -2
  219. package/skills/office_parser/ppt_tools.py +1 -1
  220. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  221. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  222. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  223. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  224. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  225. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  226. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  227. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  228. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  229. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  230. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  231. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  232. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  233. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/utils.py +40 -21
  234. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  235. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  236. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  237. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  238. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  239. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  240. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  241. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  242. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  243. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  244. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  245. package/skills/office_parser/references/layout_library.md +816 -816
  246. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  247. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  248. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  249. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  250. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  251. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  252. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  253. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  254. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  255. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  256. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  257. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  258. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  259. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  260. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  261. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  262. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  263. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  264. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  265. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  266. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  267. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  268. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  269. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  270. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  271. package/skills/office_parser/references/spec_lock.md +235 -235
  272. package/skills/office_parser/soffice.py +68 -68
  273. package/skills/office_parser/word_tools.py +3 -3
  274. package/skills/ssh/SKILL.md +81 -0
  275. package/skills/ssh/__init__.py +1 -0
  276. package/skills/ssh/handler.py +609 -0
  277. package/skills/ssh/manifest.yaml +182 -0
  278. package/tui/crannia.cmd +134 -134
  279. package/tui/crannia.sh +82 -0
  280. package/tui/crannia_tui/__init__.py +1 -1
  281. package/tui/crannia_tui/app.py +240 -17
  282. package/tui/crannia_tui/app.tcss +21 -0
  283. package/tui/crannia_tui/clipboard.py +78 -10
  284. package/tui/crannia_tui/commands.py +37 -0
  285. package/tui/crannia_tui/events.py +6 -0
  286. package/tui/crannia_tui/i18n.py +164 -164
  287. package/tui/crannia_tui/locales/en.json +31 -6
  288. package/tui/crannia_tui/paths.py +4 -1
  289. package/tui/crannia_tui/profile.py +178 -169
  290. package/tui/crannia_tui/settings.py +134 -134
  291. package/tui/crannia_tui/setup.py +44 -5
  292. package/tui/crannia_tui/ui.py +156 -16
  293. package/tui/crannia_tui/update.py +393 -389
  294. package/vendor/ripgrep/COPYING.txt +3 -3
  295. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  296. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  297. package/vendor/ripgrep/README.md +30 -14
  298. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  299. package/vendor/ripgrep/linux-x64/rg +0 -0
  300. package/vendor/ripgrep/package-source.json +15 -16
  301. package/web/__main__.py +12 -15
  302. package/web/server.py +8481 -8594
  303. package/web/static/img/channel-telegram.svg +1 -1
  304. package/web/static/img/channel-wechat.svg +1 -1
  305. package/web/templates/logs.html +49 -49
  306. package/web/templates/models.html +46 -46
@@ -21,9 +21,10 @@
21
21
  3. 大类隐含协议 —— `claude` 卡 = Anthropic 协议,**其余(含「其他」)=
22
22
  OpenAI 兼容**,没有单独的"协议"字段。
23
23
  若某个服务两种协议都不沾,今天没有落点。
24
- 4. 凭据与配置分两个文件 —— 配置可以随便看、将来要能导出;
25
- 凭据不行。本模块只有一个出口把明文交出去(`api_for`),
26
- 其余读取者拿到的都是打码过的(`has_api` + 尾 4 位)。
24
+ 4. 存储是一份文件(2026-11-19 放宽:账本与 `api` 同文件,用户能手改)。
25
+ 但内存层仍分离 —— 条目出本模块时不带 `api`,导出与界面在结构上
26
+ 拿不到明文;明文只有 `api_for` 一个出口,其余读取者拿 `masked()`
27
+ (`has_api` + 尾 4 位)。代价:整份复制那个文件 = 带着密钥走。
27
28
  5. 超限拒、不截断(截断改的是用户起的名)。
28
29
  6. id 是铸出来的(`m` + 8 位十六进制),不是会话键 ——
29
30
  `/clear` 会复用会话键。
@@ -52,12 +53,14 @@ from pathlib import Path
52
53
  # 落点
53
54
  # ----------------------------------------------------------------------
54
55
 
55
- #: 账本。运行数据一律进 `data/runtime/`。
56
+ #: 单文件存储:账本 + 每条的 `api` 同一份,用户能手改。
57
+ #: 它同时要进 `core/security.py::DEFAULT_FORBIDDEN_PATHS` —— 否则模型
58
+ #: 读得到自己的 key(兜底那一档翻成 `READ_ONLY` 之后,那份清单就是
59
+ #: "读不到"的唯一依据)。
56
60
  LEDGER_PATH = Path("data/runtime/model_configs.json")
57
61
 
58
- #: 凭据单独一个文件(判据 4)。它同时要进
59
- #: `core/security.py::DEFAULT_FORBIDDEN_PATHS` —— 否则模型读得到自己的 key
60
- #: (兜底那一档翻成 `READ_ONLY` 之后,那份清单就是"读不到"的唯一依据)。
62
+ #: 老形状的凭据文件(单文件之前那份)。只用于迁移读取 ——
63
+ #: `load()` 把它并进单文件后删掉;第二处明文不许留着。
61
64
  CREDS_PATH = Path("data/runtime/provider_credentials.json")
62
65
 
63
66
 
@@ -96,6 +99,17 @@ CARD_IDS: tuple[str, ...] = tuple(c[0] for c in CARDS)
96
99
  CARD_LABEL: dict[str, str] = {c[0]: c[1] for c in CARDS}
97
100
  CARD_PROVIDER: dict[str, str] = {c[0]: c[2] for c in CARDS}
98
101
 
102
+ #: 可以不带 key 的那两张卡。
103
+ #:
104
+ #: `ollama` 是本地端点(`providers/ollama/manifest.yaml` 自带 localhost 地址),
105
+ #: `other` 指向用户自建/中转的服务,可能压根不验 key。其余十张都要 key。
106
+ #:
107
+ #: 这个集合只回答"建的时候允不允许空着",不改变建的动作 ——
108
+ #: `api` 留空依然是合法的(见 `_api_of`)。它挡的是拿空 key 去联网:
109
+ #: 那一次请求会带着 `not-needed` 占位串出门(`providers/openai_compat.py`),
110
+ #: 上游回一句"你的 key 末四位 eded 无效",而用户手里那把 key 一个字符都没存进去。
111
+ KEYLESS_CARDS: frozenset[str] = frozenset({"ollama", "other"})
112
+
99
113
  #: 判据 1。每张卡各自一条上限(不是全局)。
100
114
  MAX_PER_CARD = 10
101
115
 
@@ -195,7 +209,7 @@ def _read(path: Path) -> dict:
195
209
  # 读不动,当空。判据同 `groups._read`:宁可让用户重配一次,
196
210
  # 不可凭一个读不动的文件把界面上那几张卡渲染成半截。
197
211
  # 但不重播种 —— 重播会把用户删掉的条目复活(见 `load()`)。
198
- print(f"[model_configs] 账本读不动({type(exc).__name__}: {exc})—— 按空账本走")
212
+ print(f"[model_configs] ledger unreadable ({type(exc).__name__}: {exc}) - treating as empty")
199
213
  return {}
200
214
  return raw if isinstance(raw, dict) else {}
201
215
 
@@ -222,6 +236,44 @@ def _empty() -> dict:
222
236
  return {"configs": {}, "default": "", "seeded_at": 0.0}
223
237
 
224
238
 
239
+ def _split_api(configs: dict) -> tuple[dict, dict]:
240
+ """把 `api` 从条目里剥出来(`configs 不含 api`, `creds = {id: api}`)。
241
+
242
+ 内存层仍分离(判据 4 的后半条没有放宽):`all_entries()` /
243
+ `_snapshot()` 交出去的条目一个都不带 `api`,所以导出包与界面
244
+ 在结构上拿不到明文,不必靠"记得剔"。
245
+ """
246
+ clean: dict = {}
247
+ apis: dict = {}
248
+ for cid, entry in (configs or {}).items():
249
+ if not isinstance(entry, dict):
250
+ continue
251
+ one = dict(entry)
252
+ api = str(one.pop("api", "") or "")
253
+ if api:
254
+ apis[str(cid)] = api
255
+ clean[cid] = one
256
+ return clean, apis
257
+
258
+
259
+ def _write_store(ledger: dict, creds: dict) -> None:
260
+ """单文件落盘:账本 + 每条的 `api`。
261
+
262
+ 条目里已有的 `api` 先剥掉再按 `creds` 补 —— 两处写同一个键
263
+ 会让"改了 api 却没落盘"看起来成功。
264
+ """
265
+ doc = {"configs": {}, "default": ledger.get("default", ""),
266
+ "seeded_at": ledger.get("seeded_at", 0.0)}
267
+ for cid, entry in (ledger.get("configs") or {}).items():
268
+ one = dict(entry)
269
+ one.pop("api", None)
270
+ api = str((creds or {}).get(cid) or "")
271
+ if api:
272
+ one["api"] = api
273
+ doc["configs"][cid] = one
274
+ _write(LEDGER_PATH, doc)
275
+
276
+
225
277
  def _normalise(raw: dict) -> dict:
226
278
  """把读回来的东西收成账本该有的形状(坏一格不许放倒整本)。
227
279
 
@@ -254,9 +306,19 @@ def _normalise(raw: dict) -> dict:
254
306
 
255
307
 
256
308
  def _ledger_now() -> dict:
257
- """当前账本的一份可改副本(调用方在锁里改它)。"""
309
+ """当前账本的一份可改副本(调用方在锁里改它)。
310
+
311
+ `_cache is None`(没 `load()` 过)时顺手把 `_creds` 也读出来 ——
312
+ 否则写入路径会拿一本"有 api 的账本 + 空的 `_creds`"去落盘,
313
+ 把别的条目的密钥一起冲掉(单文件之前那条路靠两份文件天然分开)。
314
+ """
315
+ global _creds
258
316
  if _cache is None:
259
- return _normalise(_read(LEDGER_PATH))
317
+ led = _normalise(_read(LEDGER_PATH))
318
+ led["configs"], creds = _split_api(led["configs"])
319
+ if _creds is None:
320
+ _creds = _migrate_legacy_creds(creds, led["configs"])
321
+ return led
260
322
  return {"configs": dict(_cache["configs"]), "default": _cache["default"],
261
323
  "seeded_at": _cache["seeded_at"]}
262
324
 
@@ -286,29 +348,70 @@ def load(*, seed: bool = False) -> dict:
286
348
  #: `_read` 对"不存在"与"读不动"都回 `{}`(它俩在它那层长得一样),
287
349
  #: 所以这里必须另外用 `exists` 把两者分开。
288
350
  readable = (not exists) or isinstance(raw.get("configs"), dict)
289
- if seed and readable and not _normalise(raw)["seeded_at"]:
351
+ cache = _normalise(raw)
352
+ #: 单文件里的 `api` 剥进 `_creds` —— 内存层仍分离(见 `_split_api`)。
353
+ cache["configs"], creds = _split_api(cache["configs"])
354
+ creds = _migrate_legacy_creds(creds, cache["configs"])
355
+ if seed and readable and not cache["seeded_at"]:
290
356
  seeded = _seed_from_config()
291
357
  if seeded is not None:
292
358
  # 并进已有条目(用户可能已经先建过几条)—— 不是覆盖。
293
- merged = _normalise(raw)
294
- merged["configs"].update(seeded["configs"])
295
- if not merged["default"]:
296
- merged["default"] = seeded["default"]
297
- merged["seeded_at"] = seeded["seeded_at"]
359
+ cache["configs"].update(seeded["configs"])
360
+ if not cache["default"]:
361
+ cache["default"] = seeded["default"]
362
+ cache["seeded_at"] = seeded["seeded_at"]
363
+ for cid, api in (seeded.get("_creds") or {}).items():
364
+ creds.setdefault(cid, api)
298
365
  try:
299
- _write(LEDGER_PATH, merged)
366
+ _write_store(cache, creds)
300
367
  except Exception as exc: # noqa: BLE001
301
- print(f"[model_configs] 播种写不进去({type(exc).__name__}: {exc})"
302
- f" —— 本次运行**仍然有**这些配置")
303
- raw = merged
304
- _cache = _normalise(raw)
305
- _creds = _read(CREDS_PATH)
306
- if not isinstance(_creds, dict):
307
- _creds = {}
368
+ print(f"[model_configs] seeding write failed ({type(exc).__name__}: {exc}) - configs still active for this run")
369
+ _cache, _creds = cache, creds
370
+ #: 迁移只在"老凭据文件还在"时写盘一次;写成功才删(见函数 docstring)。
371
+ _retire_legacy_creds()
308
372
  return {"configs": dict(_cache["configs"]), "default": _cache["default"],
309
373
  "seeded_at": _cache["seeded_at"]}
310
374
 
311
375
 
376
+ def _migrate_legacy_creds(creds: dict, known: dict) -> dict:
377
+ """把老凭据文件并进 `creds`(单文件里已有的优先)。
378
+
379
+ 老文件是单文件存储之前那份 `provider_credentials.json`。
380
+ 合并方向:先铺老的,再盖新的 —— 否则"用户在单文件里改过 key"会被旧文件复活。
381
+ 只收账本里还有条目的 id:孤儿 key 既不写盘也会在下次装载时消失,
382
+ 留着它只会让这一轮 `api_for` 回一个"落不了盘的答案"。
383
+ """
384
+ try:
385
+ if not CREDS_PATH.exists():
386
+ return creds
387
+ legacy = _read(CREDS_PATH)
388
+ except Exception as exc: # noqa: BLE001
389
+ print(f"[model_configs] old credential file unreadable ({type(exc).__name__}: {exc}) - skipping migration")
390
+ return creds
391
+ if not isinstance(legacy, dict) or not legacy:
392
+ return creds
393
+ merged = {str(k): str(v) for k, v in legacy.items()
394
+ if isinstance(v, str) and v and str(k) in (known or {})}
395
+ merged.update({k: v for k, v in (creds or {}).items() if v})
396
+ return merged
397
+
398
+
399
+ def _retire_legacy_creds() -> None:
400
+ """老凭据文件已并入单文件,写一次盘、删掉它(第二处明文不许留)。
401
+
402
+ 只在"新凭据真的落到了单文件里"之后才删:删掉一份没备份的明文
403
+ 是不可逆的,而"下次启动再试"是免费的。
404
+ """
405
+ if not CREDS_PATH.exists():
406
+ return
407
+ try:
408
+ _write_store(_cache or _empty(), _creds or {})
409
+ CREDS_PATH.unlink()
410
+ print("[model_configs] old credential file merged into model_configs.json, original removed")
411
+ except Exception as exc: # noqa: BLE001
412
+ print(f"[model_configs] old credential migration incomplete ({type(exc).__name__}: {exc}) - will retry on next load")
413
+
414
+
312
415
  def all_entries() -> dict:
313
416
  """当前全部配置条目(懒加载)。返回副本。"""
314
417
  led = _snapshot()
@@ -389,6 +492,33 @@ def merge_ledger(entries: dict, default: str = "") -> dict:
389
492
  "bad": bad, "default": out_default}
390
493
 
391
494
 
495
+ def import_apis(mapping: dict) -> int:
496
+ """把设置包加密段里的密钥写回账本(`settings_transfer` 专用)。
497
+
498
+ 只认账本里已有的 id —— 不认识的丢掉:导入的 `model_configs` 段
499
+ 结构上不含 api(见 `_split_api`),所以密钥必须靠这段单独搬;
500
+ 但一个外来包不许往账本里加行。
501
+ """
502
+ global _creds
503
+ if not isinstance(mapping, dict):
504
+ return 0
505
+ n = 0
506
+ with _LOCK:
507
+ ledger = _ledger_now()
508
+ known = ledger["configs"]
509
+ creds = dict(_creds or {})
510
+ for cid, api in mapping.items():
511
+ cid = str(cid or "").strip()
512
+ api = str(api or "").strip()
513
+ if cid in known and api:
514
+ creds[cid] = api
515
+ n += 1
516
+ if n:
517
+ _creds = creds
518
+ _persist(ledger, creds)
519
+ return n
520
+
521
+
392
522
  def _snapshot() -> dict:
393
523
  if _cache is None:
394
524
  return load()
@@ -423,12 +553,40 @@ def default_id() -> str:
423
553
  return str(_snapshot().get("default") or "")
424
554
 
425
555
 
556
+ def _env_name_of(cid: str) -> str:
557
+ """配置名 → 环境变量后缀(大写,非字母数字变 `_`)。认不出回空串。"""
558
+ entry = (_snapshot().get("configs") or {}).get(str(cid or "")) or {}
559
+ return re.sub(r"[^A-Za-z0-9]+", "_", str(entry.get("name") or "")).strip("_").upper()
560
+
561
+
562
+ def _env_override(cid: str, base: str) -> str:
563
+ """环境变量覆盖:`<BASE>_<配置名>` 优先,裸 `<BASE>` 兜底。
564
+
565
+ "一族"= api / 地址 / 模型名三格各一根;脚本与 CI 用。
566
+ 带名字的更具体,必须先查 —— 否则默认档的裸名会盖掉具体档。
567
+ """
568
+ names = []
569
+ nm = _env_name_of(cid)
570
+ if nm:
571
+ names.append("%s_%s" % (base, nm))
572
+ names.append(base)
573
+ for n in names:
574
+ v = os.environ.get(n)
575
+ if v and v.strip():
576
+ return v.strip()
577
+ return ""
578
+
579
+
426
580
  def api_for(cid: str) -> str:
427
581
  """取一条的 api 明文。这是全模块唯一一个明文出口(判据 4)。
428
582
 
429
583
  谁能调它:建 provider 实例那条路(`provider_for`)。端点与界面一律不许——
430
584
  它们走 :func:`masked`。
585
+ 环境变量优先 —— 覆盖的是"这一次跑用哪把钥匙",不落盘。
431
586
  """
587
+ env = _env_override(cid, "CRANNIA_API_KEY")
588
+ if env:
589
+ return env
432
590
  if _creds is None:
433
591
  load()
434
592
  return str((_creds or {}).get(str(cid or "").strip()) or "")
@@ -531,8 +689,7 @@ def capability_modes(entry) -> dict:
531
689
  if mode in CAP_MODES:
532
690
  out[key] = mode
533
691
  else:
534
- print(f"[model_configs] capabilities.{key}={value!r} 不认识"
535
- f"—— 按 auto 处理(只接受 auto / on / off)")
692
+ print(f"[model_configs] capabilities.{key}={value!r} not recognized - treating as auto (only auto / on / off accepted)")
536
693
  return out
537
694
 
538
695
 
@@ -575,18 +732,12 @@ def capabilities_of(raw, *, base=None) -> dict:
575
732
  # ----------------------------------------------------------------------
576
733
 
577
734
  def _persist(ledger: dict, creds: dict) -> None:
578
- """两个文件各写一次。写不进去照样算成功(本次运行内是真的)——
735
+ """单文件写一次。写不进去照样算成功(本次运行内是真的)——
579
736
  同 `groups.create` 那条;但要说出来。"""
580
737
  try:
581
- _write(LEDGER_PATH, ledger)
582
- except Exception as exc: # noqa: BLE001
583
- print(f"[model_configs] 账本写不进去({type(exc).__name__}: {exc})"
584
- f" —— 本次运行**改动仍然生效**")
585
- try:
586
- _write(CREDS_PATH, creds)
738
+ _write_store(ledger, creds)
587
739
  except Exception as exc: # noqa: BLE001
588
- print(f"[model_configs] 凭据写不进去({type(exc).__name__}: {exc})"
589
- f" —— 本次运行**改动仍然生效**")
740
+ print(f"[model_configs] storage write failed ({type(exc).__name__}: {exc}) - changes remain active for this run")
590
741
 
591
742
 
592
743
  def create(*, card, name, model, base_url="", api="", window=None,
@@ -786,8 +937,7 @@ def _seed_from_config() -> dict | None:
786
937
  from bus.core import load_config
787
938
  cfg = load_config("config.yaml")
788
939
  except Exception as exc: # noqa: BLE001
789
- print(f"[model_configs] 播种:config.yaml 读不动"
790
- f"({type(exc).__name__}: {exc})—— 这次不搬,下次装载再试")
940
+ print(f"[model_configs] seeding: config.yaml unreadable ({type(exc).__name__}: {exc}) - skipped, will retry on next load")
791
941
  return None
792
942
 
793
943
  if not isinstance(cfg, dict):
@@ -851,28 +1001,21 @@ def _seed_from_config() -> dict | None:
851
1001
  # 环境没就绪就不搬:老配置里有 `${VAR}`,而一条都没解出来
852
1002
  #这次跑的进程里 `os.environ` 是空的(没先 `load_dotenv`)。
853
1003
  if placeholders and not creds:
854
- print(f"[model_configs] 播种:老配置里 {placeholders} 条写的是 `${{VAR}}`,"
855
- f"而这次一条都没解开 —— **像**是环境变量还没就绪(没先 load_dotenv)。"
856
- f"这次不搬,下次装载再试")
1004
+ print(f"[model_configs] seeding: {placeholders} old configs use `${{VAR}}` and none resolved this time - env vars likely not ready; skipped, will retry on next load")
857
1005
  return None
858
1006
 
859
1007
  led["default"] = chosen or sorted(led["configs"])[0]
860
1008
  led["seeded_at"] = now
861
1009
  # 播种不改 `config.yaml`(它今天仍然是"退回时那条路"的真相源)。
862
- try:
863
- _write(CREDS_PATH, creds)
864
- except Exception as exc: # noqa: BLE001
865
- print(f"[model_configs] 播种:凭据写不进去({type(exc).__name__}: {exc})")
1010
+ #: 凭据不在这里写盘 —— 交给 `load()` 一次写单文件(`_write_store`)。
1011
+ led["_creds"] = creds
866
1012
  # 报数要连"其中几条带凭据"一起报 —— `M < N` 正是那条会静默发生的事故
867
1013
  # (跑了 / 有变化 / 缺了什么,三件事都要说)。
868
- print(f"[model_configs] 播种:从 config.yaml 搬进 {len(led['configs'])} 条配置"
869
- f",其中 {len(creds)} 条带凭据")
1014
+ print(f"[model_configs] seeded {len(led['configs'])} configs from config.yaml ({len(creds)} with credentials)")
870
1015
  if extra_keys:
871
- print(f"[model_configs] 播种:有 {extra_keys} 条老配置带**多把 key**(轮换池)——"
872
- f"只搬了第一把,其余没搬(要轮换的话请在新页面上建多条)")
1016
+ print(f"[model_configs] seeding: {extra_keys} old configs have multiple keys (rotation pool); only the first was copied")
873
1017
  if cut_names:
874
- print(f"[model_configs] 播种:{len(cut_names)} 条老配置的名字超 {MAX_NAME} 字,"
875
- f"已截短:{cut_names[:3]}")
1018
+ print(f"[model_configs] seeding: {len(cut_names)} old config names exceeded {MAX_NAME} chars, truncated: {cut_names[:3]}")
876
1019
  return led
877
1020
 
878
1021
 
@@ -900,7 +1043,10 @@ def card_defaults() -> list[dict]:
900
1043
  except Exception: # noqa: BLE001
901
1044
  pass
902
1045
  out.append({"id": cid, "label": label, "provider": dirname,
903
- "base_url": base, "default_model": model})
1046
+ "base_url": base, "default_model": model,
1047
+ #: 引导那边要据此拦一次"没读到 key 就往下走"。
1048
+ #: 判据留在这里(一处定义),界面不自己抄一张卡名表。
1049
+ "needs_key": cid not in KEYLESS_CARDS})
904
1050
  return out
905
1051
 
906
1052
 
@@ -946,6 +1092,15 @@ def probe(cid: str) -> tuple[bool, str, str]:
946
1092
  entry = get(cid)
947
1093
  if not entry:
948
1094
  return False, "unknown", "没有这条配置"
1095
+ #: 要 key 的卡而这条没存 key —— 别出门。
1096
+ #:
1097
+ #: 出门的话 provider 会带上 `not-needed` 占位串(`openai_compat` 的
1098
+ #: `_KEYLESS_PLACEHOLDER`),上游回一句 "your api key ...eded is
1099
+ #: invalid"(末四位取自那个占位串)—— 用户手里那把 key 却
1100
+ #: 一个字符都没进过账本。这句人话比那串谜语省一整轮排查。
1101
+ if (str(entry.get("card") or "") not in KEYLESS_CARDS
1102
+ and not api_for(cid)):
1103
+ return False, "auth", "这条配置没有填 API Key"
949
1104
  dirname = CARD_PROVIDER.get(str(entry.get("card") or ""))
950
1105
  if not dirname:
951
1106
  return False, "install", "这张卡不认识(%r)" % entry.get("card")
@@ -1014,7 +1169,7 @@ def cards_payload() -> dict:
1014
1169
  except Exception as exc: # noqa: BLE001
1015
1170
  # 能力读不出来不该让整页读不出来;但也不许装作"纯文本"
1016
1171
  # (读不到 ≠ 0),这一格不出现,界面就不显示 chips。
1017
- print("[model_configs] 能力计算失败(%s: %s)—— 这条不显示能力"
1172
+ print("[model_configs] capability computation failed (%s: %s) - capability not shown for this entry"
1018
1173
  % (type(exc).__name__, exc))
1019
1174
  by_card[card].append(row)
1020
1175
  cards = []
@@ -1066,10 +1221,12 @@ def _model_cfg_of(entry: dict, cid: str) -> dict:
1066
1221
  那家自带的地址(`build_provider` 是 `model_cfg.get("base_url", 兜底)`,
1067
1222
  键在就轮不到兜底)。老 `config.yaml` 的 anthropic 那条正是留空。
1068
1223
  """
1069
- model_cfg: dict = {"model_name": str(entry.get("model") or "").strip(),
1070
- "api_key": api_for(cid)}
1071
- if entry.get("base_url"):
1072
- model_cfg["base_url"] = entry["base_url"]
1224
+ model = (_env_override(cid, "CRANNIA_MODEL")
1225
+ or str(entry.get("model") or "").strip())
1226
+ base_url = _env_override(cid, "CRANNIA_BASE_URL") or str(entry.get("base_url") or "")
1227
+ model_cfg: dict = {"model_name": model, "api_key": api_for(cid)}
1228
+ if base_url:
1229
+ model_cfg["base_url"] = base_url
1073
1230
  if entry.get("window"):
1074
1231
  model_cfg["context_window"] = entry["window"]
1075
1232
  #: 三态覆盖 → `build_provider` 认得的那两个键。
@@ -1130,7 +1287,7 @@ def instance_for(cid: str, *, fallback=None, say: bool = False):
1130
1287
  dirname, why = _dirname_model(cid)
1131
1288
  if not dirname:
1132
1289
  if say:
1133
- print(f"[model_configs] 配置条目 '{cid}' 用不了:{why}")
1290
+ print(f"[model_configs] config entry '{cid}' unusable: {why}")
1134
1291
  return fallback
1135
1292
 
1136
1293
  stamp = float(entry.get("updated_at") or 0)
@@ -1143,17 +1300,14 @@ def instance_for(cid: str, *, fallback=None, say: bool = False):
1143
1300
  instance, derived = build_provider(PROVIDERS_DIR / dirname,
1144
1301
  {"model": _model_cfg_of(entry, cid)})
1145
1302
  except Exception as exc: # noqa: BLE001
1146
- print(f"[model_configs] 配置条目 '{cid}' 装不上"
1147
- f"({type(exc).__name__}: {exc})—— 这一段对话沿用原模型")
1303
+ print(f"[model_configs] config entry '{cid}' failed to load ({type(exc).__name__}: {exc}) - this session keeps the original model")
1148
1304
  return fallback
1149
1305
 
1150
1306
  from bus.registry import register_provider
1151
1307
  register_provider(cid, instance)
1152
1308
  _INSTANCES[cid] = (stamp, instance)
1153
1309
  if say:
1154
- print(f"[model_configs] 这一段对话改用:『{entry.get('name')}』"
1155
- f"({dirname} / {entry.get('model')} / 窗口 "
1156
- f"{derived.get('window_tokens')} 来源 {derived.get('window_source')})")
1310
+ print(f"[model_configs] this session now uses: {entry.get('name')} ({dirname} / {entry.get('model')} / window {derived.get('window_tokens')} source {derived.get('window_source')})")
1157
1311
  return instance
1158
1312
 
1159
1313
 
@@ -1264,7 +1418,7 @@ def provider_for(cid: str, *, fallback=None):
1264
1418
  dirname = CARD_PROVIDER.get(str(entry.get("card") or ""))
1265
1419
  model = str(entry.get("model") or "").strip()
1266
1420
  if not dirname or not model:
1267
- print(f"[model_configs] 配置条目 '{cid}' 缺卡片或模型名 —— 退回原模型")
1421
+ print(f"[model_configs] config entry '{cid}' has no card or model name - falling back to original model")
1268
1422
  return fallback
1269
1423
 
1270
1424
  try:
@@ -1272,8 +1426,7 @@ def provider_for(cid: str, *, fallback=None):
1272
1426
  instance, derived = build_provider(PROVIDERS_DIR / dirname,
1273
1427
  {"model": _model_cfg_of(entry, cid)})
1274
1428
  except Exception as exc: # noqa: BLE001
1275
- print(f"[model_configs] 配置条目 '{cid}' 装不上"
1276
- f"({type(exc).__name__}: {exc})—— 退回 config.yaml 那个模型")
1429
+ print(f"[model_configs] config entry '{cid}' failed to load ({type(exc).__name__}: {exc}) - falling back to config.yaml model")
1277
1430
  return fallback
1278
1431
 
1279
1432
  from bus.registry import register_provider, register_provider_metadata
@@ -1282,9 +1435,7 @@ def provider_for(cid: str, *, fallback=None):
1282
1435
  if default_id() == cid:
1283
1436
  register_provider(dirname, instance)
1284
1437
  _INSTANCES[cid] = (float(entry.get("updated_at") or 0), instance)
1285
- print(f"[model_configs] 生效:『{entry.get('name')}』"
1286
- f"({dirname} / {model} / 窗口 {derived.get('window_tokens')}"
1287
- f" 来源 {derived.get('window_source')})")
1438
+ print(f"[model_configs] active: {entry.get('name')} ({dirname} / {model} / window {derived.get('window_tokens')} source {derived.get('window_source')})")
1288
1439
  return instance
1289
1440
 
1290
1441