@hfyjq/crannia 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +45 -45
  3. package/THIRD-PARTY-FRONTEND.md +5266 -5266
  4. package/THIRD-PARTY-PYTHON.md +162 -153
  5. package/THIRD-PARTY.md +316 -316
  6. package/apps/desktop/quotes.txt +56 -56
  7. package/bus/core.py +671 -671
  8. package/bus/loaders/channel_loader.py +64 -64
  9. package/bus/loaders/skill_md.py +676 -676
  10. package/bus/skill_state.py +124 -124
  11. package/channels/cli_channel/manifest.yaml +5 -5
  12. package/channels/dingtalk_channel/manifest.yaml +12 -12
  13. package/channels/feishu_channel/manifest.yaml +12 -12
  14. package/channels/qq_bot_channel/__init__.py +1 -1
  15. package/channels/qq_bot_channel/handler.py +881 -881
  16. package/channels/qq_bot_channel/manifest.yaml +4 -4
  17. package/channels/telegram_channel/__init__.py +1 -1
  18. package/channels/telegram_channel/handler.py +813 -813
  19. package/channels/telegram_channel/manifest.yaml +4 -4
  20. package/channels/telegram_channel/media.py +231 -231
  21. package/channels/textfmt.py +58 -58
  22. package/channels/wechat_channel/__init__.py +1 -1
  23. package/channels/wechat_channel/auth.py +23 -5
  24. package/channels/wechat_channel/manifest.yaml +5 -5
  25. package/channels/wechat_channel/media.py +178 -178
  26. package/config.yaml +2 -2
  27. package/core/activity.py +3 -0
  28. package/core/agent_loop.py +390 -55
  29. package/core/approval.py +17 -6
  30. package/core/artifacts.py +7 -0
  31. package/core/auto_review.py +23 -5
  32. package/core/channel_configs.py +34 -2
  33. package/core/channel_turns.py +759 -759
  34. package/core/child_approval.py +150 -0
  35. package/core/config_requirements.py +205 -0
  36. package/core/cron/runner.py +118 -6
  37. package/core/cron/store.py +14 -5
  38. package/core/cron/tools.py +17 -5
  39. package/core/endpoint.py +141 -0
  40. package/core/events.py +23 -0
  41. package/core/i18n.py +329 -329
  42. package/core/ice/store.py +191 -191
  43. package/core/inbound.py +193 -193
  44. package/core/jobs.py +19 -3
  45. package/core/last_good.py +150 -150
  46. package/core/llm_errors.py +227 -227
  47. package/core/llm_retry.py +230 -230
  48. package/core/memory/compressor.py +1214 -1214
  49. package/core/memory/manager.py +14 -0
  50. package/core/model_configs.py +80 -0
  51. package/core/pipeline/scheduler.py +2 -2
  52. package/core/pipeline/stages/agent_loop.py +24 -4
  53. package/core/pipeline/stages/pre_process.py +58 -7
  54. package/core/prompt_assembler.py +680 -680
  55. package/core/rg.py +255 -255
  56. package/core/security.py +1544 -1544
  57. package/core/settings_baseline.py +70 -1
  58. package/core/shell.py +5 -17
  59. package/core/skill_settings.py +7 -2
  60. package/core/state_registry.py +19 -0
  61. package/core/subagent.py +64 -3
  62. package/core/task_tool.py +1 -1
  63. package/core/tasks_notify.py +69 -4
  64. package/core/tiers.py +9 -3
  65. package/core/tool_outcome.py +108 -0
  66. package/core/update_tui.py +158 -0
  67. package/core/version.py +2 -2
  68. package/core/web_cache.py +152 -0
  69. package/crannia_tray.py +278 -278
  70. package/creators/models.json +4 -4
  71. package/data/settings.example.json +67 -0
  72. package/licenses/GPL-3.0.txt +619 -619
  73. package/licenses/LGPL-2.1.txt +502 -502
  74. package/licenses/LGPL-3.0.txt +165 -165
  75. package/licenses/MIT-chat-on-wechat.txt +18 -18
  76. package/licenses/MIT-deepseek-harness.txt +21 -21
  77. package/licenses/Molio-LICENSE.txt +44 -44
  78. package/locales/en.json +9 -4
  79. package/main.py +154 -154
  80. package/mcpx/manager.py +522 -522
  81. package/mcpx/servers/__init__.py +22 -22
  82. package/mcpx/servers/web_search.py +321 -33
  83. package/package.json +14 -9
  84. package/providers/anthropic/client.py +772 -772
  85. package/providers/cost_table.json +3779 -3779
  86. package/providers/deepseek/client.py +20 -20
  87. package/providers/deepseek/manifest.yaml +2 -2
  88. package/providers/factory.py +136 -136
  89. package/providers/lmstudio/client.py +2 -2
  90. package/providers/metadata.py +80 -80
  91. package/providers/model_capabilities.json +6665 -6665
  92. package/providers/moonshot/client.py +12 -12
  93. package/providers/ollama/client.py +2 -2
  94. package/providers/openai/client.py +13 -13
  95. package/providers/openrouter/client.py +2 -2
  96. package/providers/qwen/__init__.py +1 -1
  97. package/providers/qwen/client.py +2 -2
  98. package/providers/qwen/manifest.yaml +16 -16
  99. package/providers/rate_limiter.py +144 -144
  100. package/providers/siliconflow/client.py +2 -2
  101. package/providers/validation.py +171 -171
  102. package/providers/window_table.json +8909 -8909
  103. package/sbom.json +4413 -4296
  104. package/skills/entertainment/SKILL.md +35 -35
  105. package/skills/entertainment/__init__.py +1 -1
  106. package/skills/entertainment/handler.py +91 -91
  107. package/skills/entertainment/manifest.yaml +26 -26
  108. package/skills/file_parser/GUIDANCE.md +10 -10
  109. package/skills/file_parser/handler.py +177 -4
  110. package/skills/file_parser/manifest.yaml +22 -1
  111. package/skills/github/SKILL.md +32 -32
  112. package/skills/github/__init__.py +1 -1
  113. package/skills/github/manifest.yaml +5 -0
  114. package/skills/mail_parser/SKILL.md +68 -68
  115. package/skills/mail_parser/__init__.py +1 -1
  116. package/skills/mail_parser/handler.py +806 -806
  117. package/skills/mail_parser/manifest.yaml +5 -0
  118. package/skills/media_gen/GUIDANCE.md +19 -19
  119. package/skills/media_gen/SKILL.md +43 -43
  120. package/skills/media_gen/__init__.py +1 -1
  121. package/skills/media_gen/handler.py +430 -430
  122. package/skills/media_gen/manifest.yaml +93 -88
  123. package/skills/office_parser/cell_validation.py +127 -127
  124. package/skills/office_parser/excel_transform.py +936 -936
  125. package/skills/office_parser/layout_spec.py +243 -243
  126. package/skills/office_parser/pptx_export/console_encoding.py +27 -27
  127. package/skills/office_parser/pptx_export/resource_paths.py +88 -88
  128. package/skills/office_parser/pptx_export/svg_finalize/__init__.py +12 -12
  129. package/skills/office_parser/pptx_export/svg_finalize/align_embed_images.py +575 -575
  130. package/skills/office_parser/pptx_export/svg_finalize/crop_images.py +366 -366
  131. package/skills/office_parser/pptx_export/svg_finalize/embed_icons.py +498 -498
  132. package/skills/office_parser/pptx_export/svg_finalize/embed_images.py +288 -288
  133. package/skills/office_parser/pptx_export/svg_finalize/fix_image_aspect.py +388 -388
  134. package/skills/office_parser/pptx_export/svg_finalize/flatten_tspan.py +818 -818
  135. package/skills/office_parser/pptx_export/svg_finalize/svg_rect_to_path.py +345 -345
  136. package/skills/office_parser/pptx_export/svg_to_pptx/__init__.py +14 -14
  137. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/__init__.py +1 -1
  138. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/context.py +186 -186
  139. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/converter.py +781 -781
  140. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/elements.py +2490 -2490
  141. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/paths.py +429 -429
  142. package/skills/office_parser/pptx_export/svg_to_pptx/drawingml/styles.py +656 -656
  143. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/__init__.py +1 -1
  144. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/builder.py +1267 -1267
  145. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/dimensions.py +155 -155
  146. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/discovery.py +101 -101
  147. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/media.py +141 -141
  148. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/narration.py +236 -236
  149. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/notes.py +257 -257
  150. package/skills/office_parser/pptx_export/svg_to_pptx/pptx_package/slide_xml.py +136 -136
  151. package/skills/office_parser/pptx_export/svg_to_pptx/tspan_flattener.py +44 -44
  152. package/skills/office_parser/pptx_export/svg_to_pptx/use_expander.py +129 -129
  153. package/skills/office_parser/references/LICENSE-Office-Word-MCP-Server.txt +20 -20
  154. package/skills/office_parser/references/LICENSE-excel-mcp-server.txt +21 -21
  155. package/skills/office_parser/references/layout_library.md +816 -816
  156. package/skills/office_parser/references/ppt-master/LICENSE +21 -21
  157. package/skills/office_parser/references/ppt-master/references/executor-base.md +474 -474
  158. package/skills/office_parser/references/ppt-master/references/shared-standards.md +1002 -1002
  159. package/skills/office_parser/references/ppt-master/references/strategist.md +880 -880
  160. package/skills/office_parser/references/ppt-master/references/template-designer.md +402 -402
  161. package/skills/office_parser/references/ppt-master/references/visual-review.md +240 -240
  162. package/skills/office_parser/references/ppt-master/references/visual-styles/_index.md +106 -106
  163. package/skills/office_parser/references/ppt-master/references/visual-styles/blueprint.md +37 -37
  164. package/skills/office_parser/references/ppt-master/references/visual-styles/brutalist.md +38 -38
  165. package/skills/office_parser/references/ppt-master/references/visual-styles/chalkboard.md +36 -36
  166. package/skills/office_parser/references/ppt-master/references/visual-styles/dark-tech.md +37 -37
  167. package/skills/office_parser/references/ppt-master/references/visual-styles/data-journalism.md +36 -36
  168. package/skills/office_parser/references/ppt-master/references/visual-styles/editorial.md +38 -38
  169. package/skills/office_parser/references/ppt-master/references/visual-styles/glassmorphism.md +36 -36
  170. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-notes.md +37 -37
  171. package/skills/office_parser/references/ppt-master/references/visual-styles/ink-wash.md +36 -36
  172. package/skills/office_parser/references/ppt-master/references/visual-styles/memphis.md +37 -37
  173. package/skills/office_parser/references/ppt-master/references/visual-styles/paper-cut.md +36 -36
  174. package/skills/office_parser/references/ppt-master/references/visual-styles/photo-editorial.md +38 -38
  175. package/skills/office_parser/references/ppt-master/references/visual-styles/pixel-art.md +36 -36
  176. package/skills/office_parser/references/ppt-master/references/visual-styles/sketch-notes.md +36 -36
  177. package/skills/office_parser/references/ppt-master/references/visual-styles/soft-rounded.md +37 -37
  178. package/skills/office_parser/references/ppt-master/references/visual-styles/swiss-minimal.md +38 -38
  179. package/skills/office_parser/references/ppt-master/references/visual-styles/vintage-poster.md +36 -36
  180. package/skills/office_parser/references/ppt-master/references/visual-styles/zine.md +37 -37
  181. package/skills/office_parser/references/spec_lock.md +235 -235
  182. package/skills/office_parser/soffice.py +68 -68
  183. package/skills/office_parser/word_tools.py +2909 -2909
  184. package/tui/crannia.cmd +134 -0
  185. package/tui/crannia_tui/__init__.py +1 -0
  186. package/tui/crannia_tui/__main__.py +223 -0
  187. package/tui/crannia_tui/app.py +1318 -0
  188. package/tui/crannia_tui/app.tcss +153 -0
  189. package/tui/crannia_tui/approval.py +85 -0
  190. package/tui/crannia_tui/backend.py +279 -0
  191. package/tui/crannia_tui/channel.py +472 -0
  192. package/tui/crannia_tui/client.py +125 -0
  193. package/tui/crannia_tui/clipboard.py +62 -0
  194. package/tui/crannia_tui/commands.py +65 -0
  195. package/tui/crannia_tui/doctor.py +304 -0
  196. package/tui/crannia_tui/events.py +84 -0
  197. package/tui/crannia_tui/headless.py +152 -0
  198. package/tui/crannia_tui/i18n.py +164 -0
  199. package/tui/crannia_tui/locales/en.json +263 -0
  200. package/tui/crannia_tui/outcome.py +62 -0
  201. package/tui/crannia_tui/paths.py +181 -0
  202. package/tui/crannia_tui/probe.py +53 -0
  203. package/tui/crannia_tui/profile.py +169 -0
  204. package/tui/crannia_tui/render.py +209 -0
  205. package/tui/crannia_tui/settings.py +134 -0
  206. package/tui/crannia_tui/setup.py +380 -0
  207. package/tui/crannia_tui/term.py +116 -0
  208. package/tui/crannia_tui/ui.py +1236 -0
  209. package/tui/crannia_tui/update.py +389 -0
  210. package/vendor/ripgrep/COPYING.txt +3 -3
  211. package/vendor/ripgrep/LICENSE-MIT.txt +21 -21
  212. package/vendor/ripgrep/NOTICE-vscode-ripgrep.txt +13 -13
  213. package/vendor/ripgrep/README.md +51 -51
  214. package/vendor/ripgrep/UNLICENSE.txt +24 -24
  215. package/vendor/ripgrep/package-source.json +19 -19
  216. package/web/__main__.py +15 -0
  217. package/web/server.py +168 -19
  218. package/web/static/img/channel-telegram.svg +1 -1
  219. package/web/static/img/channel-wechat.svg +1 -1
  220. package/web/templates/logs.html +49 -49
  221. package/web/templates/models.html +46 -46
@@ -0,0 +1,134 @@
1
+ """TUI 读的那一列设置键,以及启动时的播种 / 坏文件处置。
2
+
3
+ 三条口径:
4
+
5
+ 1. 一份文件,各读各的。`data/settings.json` 与 GUI 共用;TUI 只读下面
6
+ 白名单这一列,其余键存在但不读,砍掉的功能不靠删键,靠不读。
7
+ 2. 首次启动播种。缺文件就用出厂基准写一份(`core/settings_baseline.py`
8
+ 的基准文件);坏 JSON 就先备份再按默认重建。所以这里走一次子进程,
9
+ TUI 不 import `core`(两套安装各自更新)。
10
+ 3. 坏值回默认并出声。读的时候类型不对就退回基准值、把那一格记进
11
+ `problems`,由启动路径打一行;不写回文件(用户的文件由用户改)。
12
+
13
+ 模型那一格不在设置里 —— 它住在端配置(`data/runtime/model_configs.json`),
14
+ TUI 从 `/api/status` 读到的是生效后的模型名。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from pathlib import Path
21
+
22
+ from .doctor import make_data_root_query, query
23
+ from .i18n import t
24
+
25
+ #: TUI 支持的键。`type` 或一组可接受的类型;`int` 键**不许是 bool**
26
+ #: (`isinstance(True, int)` 是 True,不单独判会把 `true` 读成 1)。
27
+ SUPPORTED_KEYS: dict[str, tuple] = {
28
+ "effort_level": (int,),
29
+ "default_mode": (str,),
30
+ "approval_timeout_seconds": (int,),
31
+ "auto_approve": (bool,),
32
+ "cross_zone_enabled": (bool,),
33
+ "relax_command_tier": (bool,),
34
+ "no_ask_readonly": (bool,),
35
+ "full_access_unlock": (bool,),
36
+ "interface_language": (str, type(None)),
37
+ "response_language": (str, type(None)),
38
+ "trace_full": (bool,),
39
+ "workspace": (str,),
40
+ #: 通道与定时任务是否随这个后端跑。TUI 首启播种为关。
41
+ "background_services": (bool,),
42
+ }
43
+
44
+ #: 首次播种时改写的几格 —— 只影响"这一次新建出来的文件",
45
+ #: 已有文件里是用户的决定(`heal()` 那一支直接返回 `ok`,不会走到这里)。
46
+ _SEED_OVERRIDES: dict = {"background_services": False}
47
+
48
+ _SETTINGS_REL = Path("data") / "settings.json"
49
+ _BASELINE_REL = Path("data") / "settings.example.json"
50
+
51
+ #: 播种 / 修复要问核心的那一句。返回 `heal()` 的报告(JSON)。
52
+ _HEAL_CODE = (
53
+ "import json; from pathlib import Path; "
54
+ "from core.settings_baseline import heal; "
55
+ "print(json.dumps(heal(Path(%r), overrides=json.loads(%r)), "
56
+ "ensure_ascii=False))")
57
+
58
+
59
+ def load_baseline(home: Path) -> dict:
60
+ """读出厂基准(去掉 `_comment` 一类下划线键)。读不到返回空 dict。"""
61
+ try:
62
+ raw = json.loads((Path(home) / _BASELINE_REL).read_text(encoding="utf-8"))
63
+ except (OSError, ValueError):
64
+ return {}
65
+ return {k: v for k, v in raw.items() if not k.startswith("_")} \
66
+ if isinstance(raw, dict) else {}
67
+
68
+
69
+ def _type_ok(key: str, value) -> bool:
70
+ kinds = SUPPORTED_KEYS[key]
71
+ if isinstance(value, bool) and bool not in kinds:
72
+ return False
73
+ return isinstance(value, kinds)
74
+
75
+
76
+ def read(path: Path, baseline: dict) -> tuple[dict, list[str]]:
77
+ """只读白名单那一列。返回 `(值, 问题行)`。
78
+
79
+ 文件不存在 / 读不出来就返回 `({}, [])`:文件层面的处置归 `ensure()`,
80
+ 这里重复报一次只会让同一条坏文件说两遍。
81
+ """
82
+ try:
83
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
84
+ except (OSError, ValueError):
85
+ return {}, []
86
+ if not isinstance(data, dict):
87
+ return {}, []
88
+ out: dict = {}
89
+ problems: list[str] = []
90
+ for key in SUPPORTED_KEYS:
91
+ if key not in data:
92
+ continue
93
+ value = data[key]
94
+ if _type_ok(key, value):
95
+ out[key] = value
96
+ continue
97
+ want = "/".join(t.__name__ for t in SUPPORTED_KEYS[key])
98
+ problems.append(t("%s=%r 不是 %s,按默认 %r")
99
+ % (key, value, want, baseline.get(key)))
100
+ out[key] = baseline.get(key)
101
+ return out, problems
102
+
103
+
104
+ def ensure(python: Path, home: Path, *, query_fn=None,
105
+ root_fn=None) -> list[str]:
106
+ """启动时确保设置文件可用;返回给人看的几行(不抛、不挡启动)。
107
+
108
+ `query_fn` / `root_fn` 可注入 —— 测试不必真起子进程。
109
+ """
110
+ try:
111
+ root = (root_fn or make_data_root_query(python, home))()
112
+ except Exception as exc: # noqa: BLE001
113
+ return [t("[settings] 数据根读取失败(%s)—— 跳过设置检查") % exc]
114
+ path = Path(root) / _SETTINGS_REL
115
+ run = query_fn or (lambda code: query(python, home, code))
116
+ try:
117
+ report = json.loads(
118
+ run(_HEAL_CODE % (str(path), json.dumps(_SEED_OVERRIDES))))
119
+ except Exception as exc: # noqa: BLE001
120
+ return [t("[settings] 设置检查失败(%s)—— 继续启动") % exc]
121
+
122
+ action = str(report.get("action") or "")
123
+ lines: list[str] = []
124
+ if action == "seeded":
125
+ lines.append(t("[settings] 首次启动:已写入默认设置 %s") % path)
126
+ elif action == "backup":
127
+ lines.append(t("[settings] 设置文件读取失败,已备份到 %s,并按默认重建")
128
+ % (report.get("backup") or t("(未记下路径)")))
129
+ elif action == "error":
130
+ lines.append(t("[settings] 设置文件处置失败(%s)—— 继续启动")
131
+ % (report.get("error") or t("原因未知")))
132
+ _, problems = read(path, load_baseline(home))
133
+ lines.extend("[settings] " + p for p in problems)
134
+ return lines
@@ -0,0 +1,380 @@
1
+ """`crannia setup`:首次引导 —— 配一条能用的模型 API。
2
+
3
+ 引导按这个顺序走:
4
+
5
+ 1. 选提供商卡(决定默认地址;回车 = 「其他」/ OpenAI 兼容,选它才问地址)
6
+ 2. 配置名称 → 模型名 → API Key(掩码输入)
7
+ 3. 自动联通测试(一次最小请求,短超时)
8
+ 成功:「已确认」;失败:保留已填值,只让人改错的那一项
9
+
10
+ 不 import `core`:与 `profile` / `channel` 同一条路,账本操作走一次子进程。
11
+ 这条命令要终端(密钥要从键盘读),非交互环境直接拒。
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import getpass
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ from .doctor import PREPARE, query
22
+ from .i18n import t
23
+
24
+ #: 每张卡的默认值(名称 / 地址 / 默认模型)全在后端读 manifest ——
25
+ #: 界面不抄一份(抄了就是第二套真相,卡片一改就漂)。
26
+ _CARDS_CODE = (
27
+ "import json\n"
28
+ "from core import model_configs as mc\n"
29
+ "print(json.dumps(mc.card_defaults(), ensure_ascii=False))\n")
30
+
31
+ _STATE_CODE = PREPARE + (
32
+ "import json\n"
33
+ "from core import model_configs as mc\n"
34
+ "cid = mc.default_id()\n"
35
+ "e = mc.get(cid) if cid else None\n"
36
+ "print(json.dumps({'default': cid,"
37
+ " 'name': (e or {}).get('name', ''),"
38
+ " 'model': (e or {}).get('model', '')}, ensure_ascii=False))\n")
39
+
40
+ _CREATE_CODE = PREPARE + (
41
+ "import json\n"
42
+ "from core import model_configs as mc\n"
43
+ "try:\n"
44
+ " row = mc.create(card=%r, name=%r, model=%r, base_url=%r, api=%r)\n"
45
+ " out = {'ok': True, 'id': row.get('id')}\n"
46
+ "except Exception as exc:\n"
47
+ " out = {'ok': False, 'error': str(exc)}\n"
48
+ "print(json.dumps(out, ensure_ascii=False))\n")
49
+
50
+ _UPDATE_CODE = PREPARE + (
51
+ "import json\n"
52
+ "from core import model_configs as mc\n"
53
+ "try:\n"
54
+ " mc.update(%r, **json.loads(%r))\n"
55
+ " out = {'ok': True}\n"
56
+ "except Exception as exc:\n"
57
+ " out = {'ok': False, 'error': str(exc)}\n"
58
+ "print(json.dumps(out, ensure_ascii=False))\n")
59
+
60
+ _DEFAULT_CODE = PREPARE + (
61
+ "import json\n"
62
+ "from core import model_configs as mc\n"
63
+ "try:\n"
64
+ " mc.set_default(%r)\n"
65
+ " out = {'ok': True}\n"
66
+ "except Exception as exc:\n"
67
+ " out = {'ok': False, 'error': str(exc)}\n"
68
+ "print(json.dumps(out, ensure_ascii=False))\n")
69
+
70
+ _PROBE_CODE = PREPARE + (
71
+ "import json\n"
72
+ "from core import model_configs as mc\n"
73
+ "ok, kind, why = mc.probe(%r)\n"
74
+ "print(json.dumps({'ok': ok, 'kind': kind, 'error': why},"
75
+ " ensure_ascii=False))\n")
76
+
77
+ #: 联通测试给多长。上游默认超时是 120 秒(`providers/openai_compat.py` 的
78
+ #: httpx 客户端),引导里等不了那么久 —— 子进程整体掐在这里。
79
+ PROBE_TIMEOUT = 25.0
80
+
81
+ #: 有后端在跑时走它的端点(`model_configs` 有内存镜像,在别的进程里直接改文件
82
+ #: 会让它的镜像与磁盘打架 —— `profile` 早就按这条判据走了,本命令跟上)。
83
+ def _live_endpoint(python: Path, home: Path):
84
+ try:
85
+ from .profile import endpoint
86
+ return endpoint(python, home)
87
+ except Exception: # noqa: BLE001 - 探测失败就当没有
88
+ return None
89
+
90
+
91
+ def _post(ep, path: str, payload: dict) -> dict:
92
+ from .profile import http_json
93
+
94
+ got = http_json(ep, path, payload)
95
+ if not isinstance(got, dict):
96
+ return {"ok": False, "error": t("后端未响应,未更改任何配置")}
97
+ return got
98
+
99
+
100
+ def _create_config(python: Path, home: Path, ep, values: dict, *, query_fn=None) -> dict:
101
+ if ep is not None:
102
+ got = _post(ep, "/api/model-configs/create", values)
103
+ entry = got.get("entry") or {}
104
+ if got.get("ok") and entry.get("id"):
105
+ return {"ok": True, "id": str(entry["id"])}
106
+ return {"ok": False, "error": got.get("error") or t("配置设置失败")}
107
+ return _run(python, home, _CREATE_CODE % (
108
+ values["card"], values["name"], values["model"],
109
+ values["base_url"], values["api"]), query_fn=query_fn)
110
+
111
+
112
+ def _update_config(python: Path, home: Path, ep, cid: str, fields: dict,
113
+ *, query_fn=None) -> dict:
114
+ if ep is not None:
115
+ return _post(ep, "/api/model-configs/update",
116
+ {"id": cid, **fields})
117
+ return _run(python, home, _UPDATE_CODE % (
118
+ cid, json.dumps(fields, ensure_ascii=False)), query_fn=query_fn)
119
+
120
+
121
+ def _set_default(python: Path, home: Path, ep, cid: str, *, query_fn=None) -> dict:
122
+ if ep is not None:
123
+ return _post(ep, "/api/model-configs/default", {"id": cid})
124
+ return _run(python, home, _DEFAULT_CODE % (cid,), query_fn=query_fn)
125
+
126
+ #: 失败类别 -> (给人看的标签, 建议先改哪一项)。
127
+ #: 类别来自 `core.model_configs.classify_probe_error`(认证 / 限流那一套判据
128
+ #: 复用 `providers/base.py`,全仓只有一份)。
129
+ _ERROR_HINTS: dict[str, tuple[str, str]] = {
130
+ "auth": ("密钥被拒绝", "3"),
131
+ "balance": ("账户余额不足", "3"),
132
+ "rate_limit": ("API已被限流,请稍后重试", "0"),
133
+ "region": ("地区受限", "1"),
134
+ "content": ("请求被内容审核拦下", "0"),
135
+ "too_large": ("请求体被拒", "2"),
136
+ "context_overflow": ("上下文超长", "2"),
137
+ "request": ("请求被拒", "2"),
138
+ "server_fault": ("上游故障", "0"),
139
+ "server_busy": ("上游繁忙", "0"),
140
+ "server_other": ("上游异常", "0"),
141
+ "timeout": ("连接错误", "1"),
142
+ "connection": ("连接错误", "1"),
143
+ "model": ("模型名错误", "2"),
144
+ "address": ("地址错误", "1"),
145
+ "install": ("配置错误", "0"),
146
+ "unknown": ("未知错误", "1"),
147
+ }
148
+
149
+
150
+ def _hint(kind: str) -> tuple[str, str]:
151
+ label, item = _ERROR_HINTS.get(kind, _ERROR_HINTS["unknown"])
152
+ return t(label), item
153
+
154
+
155
+ def _ask(prompt: str) -> str:
156
+ try:
157
+ return input(prompt)
158
+ except EOFError:
159
+ print()
160
+ return ""
161
+
162
+
163
+ def _secret(prompt: str) -> str:
164
+ try:
165
+ return getpass.getpass(prompt)
166
+ except EOFError:
167
+ print()
168
+ return ""
169
+
170
+
171
+ def _run(python: Path, home: Path, code: str, *, timeout: float = 25.0,
172
+ query_fn=None) -> dict:
173
+ run = query_fn or (lambda c, timeout=timeout: query(python, home, c,
174
+ timeout=timeout))
175
+ return json.loads(run(code, timeout=timeout))
176
+
177
+
178
+ def needs_setup(python: Path, home: Path, *, query_fn=None) -> bool:
179
+ """还没有默认模型配置 —— 进界面前该先走引导。
180
+
181
+ 查不出来就给 `False`(不挡启动;`doctor` 会把真实原因说出来)。
182
+ """
183
+ try:
184
+ state = _run(python, home, _STATE_CODE, query_fn=query_fn)
185
+ except Exception: # noqa: BLE001
186
+ return False
187
+ return not bool(state.get("default"))
188
+
189
+
190
+ def _pick_card(cards: list[dict], ask) -> dict:
191
+ """选卡。回车 = 「其他」(OpenAI 兼容)。"""
192
+ default_id = "other" if any(c["id"] == "other" for c in cards) else \
193
+ (cards[0]["id"] if cards else "")
194
+ while True:
195
+ answer = (ask(t("输入对应编号以开始配置(直接回车 = 其他 / OpenAI 兼容): "))
196
+ or "").strip()
197
+ if not answer:
198
+ for c in cards:
199
+ if c["id"] == default_id:
200
+ return c
201
+ return cards[0] if cards else {}
202
+ if answer.isdigit():
203
+ n = int(answer)
204
+ if 1 <= n <= len(cards):
205
+ return cards[n - 1]
206
+ for c in cards:
207
+ if answer.lower() in (c["id"].lower(), str(c["label"]).lower()):
208
+ return c
209
+ print(t("没有「%s」。请填写编号或直接回车。") % answer)
210
+
211
+
212
+ def _probe(python: Path, home: Path, cid: str, *, query_fn=None) -> dict:
213
+ try:
214
+ return _run(python, home, _PROBE_CODE % (cid,),
215
+ timeout=PROBE_TIMEOUT, query_fn=query_fn)
216
+ except Exception as exc: # noqa: BLE001
217
+ return {"ok": False, "kind": "unknown",
218
+ "error": t("测试未完成:%s") % exc}
219
+
220
+
221
+ def _fix_loop(python: Path, home: Path, cid: str, *, ask, secret,
222
+ ep=None, query_fn=None, suggest: str = "1") -> bool:
223
+ """联通测试失败后"只改错的那一项",直到通过或用户选择跳过。
224
+
225
+ *suggest* 是第一次的默认项(由失败类别来);之后每失败一次都按新类别更新。
226
+ """
227
+ rep: dict | None = None
228
+ while True:
229
+ if rep is not None:
230
+ #: 与第一次失败**同一个呈现** —— 不另起一种"还是不通"的口吻。
231
+ label, suggest = _hint(str(rep.get("kind") or ""))
232
+ print(t("API 异常(%s):%s")
233
+ % (label, rep.get("error") or t("未知错误")))
234
+ choice = (ask(
235
+ t("选择更改条目(直接回车以更改推荐条目) "
236
+ "1 地址 · 2 模型 · 3 密钥 · 0 保留并退出 [%s]: ") % suggest)
237
+ or "").strip() or suggest
238
+ if choice == "0":
239
+ return False
240
+ fields: dict = {}
241
+ if choice == "1":
242
+ value = (ask(t("新的请求地址: ")) or "").strip()
243
+ if value:
244
+ fields["base_url"] = value
245
+ elif choice == "2":
246
+ value = (ask(t("新的模型名: ")) or "").strip()
247
+ if value:
248
+ fields["model"] = value
249
+ elif choice == "3":
250
+ fields["api"] = secret(t("新的 API Key: "))
251
+ else:
252
+ continue
253
+ if not fields:
254
+ continue
255
+ try:
256
+ upd = _update_config(python, home, ep, cid, fields,
257
+ query_fn=query_fn)
258
+ except Exception as exc: # noqa: BLE001
259
+ print(t("未更改:%s") % exc)
260
+ continue
261
+ if not upd.get("ok"):
262
+ print(upd.get("error") or t("未更改"))
263
+ continue
264
+ rep = _probe(python, home, cid, query_fn=query_fn)
265
+ if rep.get("ok"):
266
+ return True
267
+
268
+
269
+ def setup_command(*, python: Path, home: Path, query_fn=None,
270
+ ask=None, secret=None, interactive: bool | None = None) -> int:
271
+ """`crannia setup` 的入口。返回退出码。"""
272
+ if interactive is None:
273
+ interactive = sys.stdin.isatty()
274
+ if not interactive and ask is None:
275
+ print(t("setup 需要在终端中启用,"
276
+ "请在 Windows Terminal 里执行 `crannia setup`。"))
277
+ return 2
278
+ ask_ = ask or _ask
279
+ sec_ = secret or _secret
280
+ ep = _live_endpoint(python, home)
281
+
282
+ try:
283
+ state = _run(python, home, _STATE_CODE, query_fn=query_fn)
284
+ except Exception as exc: # noqa: BLE001
285
+ print(t("模型配置读取失败:%s") % exc)
286
+ return 2
287
+
288
+ if state.get("default"):
289
+ print(t("默认:「%s」(模型 %s)")
290
+ % (state.get("name") or state["default"],
291
+ state.get("model") or t("?(未填写)")))
292
+ if (ask_(t("重新配置?[y/N] ")) or "").strip().lower() not in (
293
+ "y", "yes", "是"):
294
+ return 0
295
+
296
+ try:
297
+ cards = _run(python, home, _CARDS_CODE, query_fn=query_fn)
298
+ except Exception as exc: # noqa: BLE001
299
+ print(t("供应商读取错误:%s") % exc)
300
+ return 2
301
+ if not isinstance(cards, list) or not cards:
302
+ print(t("供应商错误,此程序遇到了一些问题,请先运行 `crannia doctor`尝试修复"))
303
+ return 2
304
+
305
+ print(t("欢迎!看起来这是您的首次使用,让我们从配置您的首个API开始"))
306
+ ask_(t("按下enter以继续…"))
307
+ print(t("模型列表:"))
308
+ for i, c in enumerate(cards, 1):
309
+ #: 空地址 = 由 SDK 决定(Anthropic 原生 SDK 自己补
310
+ #: `https://api.anthropic.com` + `/v1/messages`);留空会看起来像坏了。
311
+ #: 「其他」不显示地址 —— 它的地址在选中之后才问。
312
+ if c.get("base_url"):
313
+ suffix = " " + c["base_url"]
314
+ elif c["id"] == "other":
315
+ suffix = ""
316
+ else:
317
+ suffix = t("(地址由 SDK 决定)")
318
+ print(" %2d. %s%s" % (i, c["label"], suffix))
319
+ card = _pick_card(cards, ask_)
320
+
321
+ name = (ask_(t("配置名称 [eg:%s]: ") % card["label"]) or "").strip() \
322
+ or card["label"]
323
+ #: 「其他」没有自己的 manifest —— 它的默认值是 OpenAI 那一份,拿它当提示
324
+ #: 会把人往错的方向带(那家的模型名与地址都不同)。
325
+ hint_model = "" if card["id"] == "other" else card.get("default_model", "")
326
+ #: 例子前面写 `eg:`,否则方括号里的字看起来像"只能填这个"。
327
+ #: 「其他」没有例子可给,就不摆一对空括号。
328
+ model_prompt = (t("模型名 [eg:%s]: ") % hint_model
329
+ if hint_model else t("模型名: "))
330
+ model = (ask_(model_prompt) or "").strip() or hint_model
331
+ if not model:
332
+ print(t("模型名不能为空"))
333
+ return 1
334
+
335
+ base = str(card.get("base_url") or "")
336
+ if card["id"] == "other":
337
+ base = (ask_(t("请求地址(例如 https://…/v1): "))
338
+ or "").strip()
339
+ if not base:
340
+ print(t("「其他」需要一个请求地址。"))
341
+ return 1
342
+
343
+ api = (sec_(t("API Key(此字段不可见,请直接粘贴;本地模型可直接回车跳过): "))
344
+ or "").strip()
345
+
346
+ try:
347
+ created = _create_config(
348
+ python, home, ep,
349
+ {"card": card["id"], "name": name, "model": model,
350
+ "base_url": base, "api": api},
351
+ query_fn=query_fn)
352
+ except Exception as exc: # noqa: BLE001
353
+ print(t("配置失败:%s") % exc)
354
+ return 1
355
+ if not created.get("ok"):
356
+ print(created.get("error") or t("配置设置失败"))
357
+ return 1
358
+ cid = created["id"]
359
+
360
+ print(t("最小请求联通测试…"))
361
+ rep = _probe(python, home, cid, query_fn=query_fn)
362
+ if not rep.get("ok"):
363
+ label, suggest = _hint(str(rep.get("kind") or ""))
364
+ print(t("API 异常(%s):%s")
365
+ % (label, rep.get("error") or t("未知错误")))
366
+ if not _fix_loop(python, home, cid, ask=ask_, secret=sec_, ep=ep,
367
+ query_fn=query_fn, suggest=suggest):
368
+ print(t("已保留,联通测试未通过"))
369
+
370
+ try:
371
+ done = _set_default(python, home, ep, cid, query_fn=query_fn)
372
+ if not done.get("ok"):
373
+ print(t("更改默认失败:%s") % (done.get("error") or t("原因未知")))
374
+ return 1
375
+ except Exception as exc: # noqa: BLE001
376
+ print(t("更改默认失败:%s") % exc)
377
+ return 1
378
+
379
+ print(t("已确认。运行 `crannia` 开始使用。"))
380
+ return 0
@@ -0,0 +1,116 @@
1
+ """终端能力准备。
2
+
3
+ 主循环和临时区都直接发 ANSI 序列,所以终端**必须**认得它们。Windows 上
4
+ 这件事不是默认成立的:控制台有自己的一套 API,ANSI 支持要显式打开
5
+ (`ENABLE_VIRTUAL_TERMINAL_PROCESSING`)。没打开时渲染出来的不是颜色和光标
6
+ 移动,而是一串字面量 —— 屏幕上看到 `?[2m` 就是 ESC 被当成了普通字符。
7
+
8
+ 关掉它也有代价:临时区靠 `\\x1b[NA` 上移、`\\x1b[2K` 清行,不生效的话每一帧
9
+ 都会往下堆,几分钟就把历史冲掉。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import sys
16
+
17
+ from .i18n import t
18
+
19
+ #: `ENABLE_PROCESSED_OUTPUT`。和 VT 一起开:只开 VT 不开它,部分宿主
20
+ #: 会把 `\\r` 的处理也交给应用,光标回到行首那一步就没了。
21
+ _ENABLE_PROCESSED_OUTPUT = 0x0001
22
+ _ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
23
+
24
+ _STD_OUTPUT_HANDLE = -11
25
+
26
+
27
+ def enable_ansi() -> bool:
28
+ """让当前控制台解释 ANSI。返回"现在能不能用"。
29
+
30
+ 非 Windows 上 ANSI 本来就有,直接回 True。
31
+
32
+ 这里不判断"是不是 Windows Terminal":Windows Terminal 的 VT 一直是开的,
33
+ 再开一次是幂等的;而 conhost(`cmd.exe` 那个黑窗口)默认没开,正是要救的
34
+ 那一个。分不清楚就别分 —— 统一开一遍,失败也无害。
35
+ """
36
+ if os.name != "nt":
37
+ return True
38
+
39
+ try:
40
+ import ctypes
41
+ from ctypes import wintypes
42
+
43
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
44
+ handle = kernel32.GetStdHandle(_STD_OUTPUT_HANDLE)
45
+ if handle in (0, -1):
46
+ return False
47
+
48
+ mode = wintypes.DWORD()
49
+ if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
50
+ # 输出被重定向到文件/管道时走到这里,是正常情况。
51
+ return False
52
+
53
+ want = (mode.value
54
+ | _ENABLE_PROCESSED_OUTPUT
55
+ | _ENABLE_VIRTUAL_TERMINAL_PROCESSING)
56
+ if want == mode.value:
57
+ return True
58
+ return bool(kernel32.SetConsoleMode(handle, want))
59
+ except Exception: # noqa: BLE001
60
+ # 这里失败不该让程序起不来:最坏的结果是没有颜色和原地刷新,
61
+ # 而定稿内容仍然照常打印。
62
+ return False
63
+
64
+
65
+ def ansi_passthrough_ok() -> bool:
66
+ """我们写出去的转义序列,终端会不会当控制符解释。
67
+
68
+ **这里宁可判错成"不支持"。** 猜错的两种代价不对称:
69
+ · 猜成不支持(其实支持)→ 少一点颜色,功能全在;
70
+ · 猜成支持(其实不支持)→ 屏幕上全是 `?[2m`,整个界面没法看。
71
+
72
+ 为什么不能靠能力探测:遇到过这样的窗口 —— `create_output()` 给出
73
+ `Windows10_Output`(意为"透传 ANSI"),`GetConsoleMode` 的
74
+ `ENABLE_VIRTUAL_TERMINAL_PROCESSING` 位也是 1,而屏幕上仍然是 `?[2m`。
75
+ 探测全绿、实际不解,这条路走不通。
76
+
77
+ 所以只认两种"确定支持"的情形:
78
+ · 非 Windows;
79
+ · `WT_SESSION` 存在(Windows Terminal 一定解释 ANSI)。
80
+ 其余的 Windows 控制台一律走 win32 设色 —— rich 那条路不产生转义序列,
81
+ 所以不可能出现字面量,代价只是颜色退到 16 色、临时区关掉。
82
+
83
+ 想要颜色就设 `CRANNIA_TUI_ANSI=1`,那是使用者自己的判断,比程序猜可靠。
84
+ """
85
+ if os.name != "nt":
86
+ return True
87
+ if os.environ.get("CRANNIA_TUI_ANSI", "") not in ("", "0"):
88
+ return True
89
+ if not os.environ.get("WT_SESSION"):
90
+ return False
91
+ return enable_ansi()
92
+
93
+
94
+ def terminal_width(default: int = 80) -> int:
95
+ """当前终端列数。取不到就给个保守值。
96
+
97
+ `shutil.get_terminal_size` 已经查了 `COLUMNS` 和 ioctl;Windows 上它走
98
+ 的是 `GetConsoleScreenBufferInfo`,conhost 与 Terminal 都认。这里只补一个
99
+ "返回 0 时别把宽度算成 0"的兜底 —— 宽度为 0 的话折行函数会死循环。
100
+ """
101
+ import shutil
102
+
103
+ try:
104
+ cols = shutil.get_terminal_size((default, 24)).columns
105
+ except OSError:
106
+ return default
107
+ return cols if cols > 0 else default
108
+
109
+
110
+ def warn_no_ansi(stream=None) -> None:
111
+ """走不了 ANSI 时说一句,别让人对着满屏 `?[2m` 猜。"""
112
+ out = stream or sys.stderr
113
+ print(t("提示:这个窗口用不了 ANSI,颜色退到 16 色、底部实时区关掉(功能都在)。"),
114
+ file=out)
115
+ print(t("想恢复:换 Windows Terminal 跑,或设 CRANNIA_TUI_ANSI=1 强制开启。"),
116
+ file=out)