@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,153 @@
1
+ /* 全屏布局:上中下三段固定,中间吃掉剩余高度。
2
+ *
3
+ * 样式只写在这一处。小部件里不再放 DEFAULT_CSS —— 同一个属性写两遍时,
4
+ * 外部样式表赢,而改的人往往只改了自己眼前那份,界面上没有任何报错,
5
+ * 只是"改了没反应"。这个坑已经踩过一次(header 高度),所以收成单一来源。
6
+ */
7
+
8
+ Screen {
9
+ layout: vertical;
10
+ background: $surface;
11
+ }
12
+
13
+ /* 抬头是对话区的第一块,不是固定区 —— 随内容滚走。
14
+ * 左右不再补 padding:Transcript 自己已经有一层,补两层会缩进成右移。 */
15
+ /* 标志四行 + 文字最多四行(标题 / 模型与档位 / 分隔线 / 目录)。 */
16
+ HeaderBar {
17
+ height: 8;
18
+ padding: 0;
19
+ margin-bottom: 1;
20
+ }
21
+
22
+ /* 标志宽 5 列(含左空一格)。整块居中由 ui.py 按宽度补左空白 ——
23
+ 样式表的 align-horizontal 对定宽子部件不生效(实测)。 */
24
+ HeaderBar #logo {
25
+ width: 100%;
26
+ color: $success;
27
+ }
28
+
29
+ HeaderBar #info {
30
+ width: 100%;
31
+ text-align: center;
32
+ }
33
+
34
+ Transcript {
35
+ height: 1fr;
36
+ padding: 0 1;
37
+ overflow-y: auto;
38
+ }
39
+
40
+ Transcript .user {
41
+ margin-top: 1;
42
+ }
43
+
44
+ /* 让每块之间恰好隔一行:统一给"上方留白"而不是有人给上下都有,
45
+ * 否则相邻两块会叠成两行空行。唯一的例外是连续的卡片,那个在
46
+ * `Transcript.add_card()` 里按前一块决定(一串动作应当贴紧)。 */
47
+ Transcript .agent {
48
+ margin-top: 1;
49
+ }
50
+
51
+ Transcript .note {
52
+ margin-top: 1;
53
+ color: $text-muted;
54
+ }
55
+
56
+ /* 工具卡。高度跟着内容走(失败时多一行),相邻两张之间不留空行 ——
57
+ * "一轮里连着跑七八个工具"时,留空会把它拆成七八段,看不出是一串动作。 */
58
+ Transcript .tool {
59
+ height: auto;
60
+ }
61
+
62
+ #status {
63
+ height: 1;
64
+ padding: 0 1;
65
+ color: $text-muted;
66
+ }
67
+
68
+ /* 审批面板:平时藏着,出现时**占的正是输入框那个槽** ——
69
+ * 同样的位置、同样的圆角边框,读起来是"这里暂时换了个用途",
70
+ * 而不是"弹了个窗"。选中态的标记(▌)画在内容里,颜色跟随文本。 */
71
+ ApprovalPanel {
72
+ display: none;
73
+ height: auto;
74
+ margin: 0 1;
75
+ padding: 0 1;
76
+ border: round $primary;
77
+ }
78
+
79
+ ApprovalPanel:focus {
80
+ border: round $accent;
81
+ }
82
+
83
+ /* 斜杠补全条:藏在输入框上方,输入以 / 起头时才出现。
84
+ * 高度跟着候选数走;没有候选时不占任何行。 */
85
+ SuggestBar {
86
+ display: none;
87
+ height: auto;
88
+ padding: 0 1;
89
+ color: $text-muted;
90
+ }
91
+
92
+ /* 新版本提示:贴输入框右上角。只在查到更高版本时占这一行。 */
93
+ UpdateHint {
94
+ display: none;
95
+ height: 1;
96
+ padding: 0 2;
97
+ content-align: right middle;
98
+ }
99
+
100
+ /* `/btw` 回答窗:顶上只剩一行横幅,其余全是这个蓝框。
101
+ * 打开时转写区让位(display:none),关掉之后恢复。 */
102
+ BtwPanel {
103
+ display: none;
104
+ height: 1fr;
105
+ margin: 0 1;
106
+ padding: 0 1;
107
+ border: round $accent;
108
+ }
109
+
110
+ BtwPanel #btw-text {
111
+ width: 100%;
112
+ }
113
+
114
+ /* 多行输入框:高度跟着内容走,空的时候一行。 */
115
+ #composer {
116
+ height: auto;
117
+ margin: 0 1;
118
+ border: round $primary;
119
+ }
120
+
121
+ #composer:focus {
122
+ border: round $accent;
123
+ }
124
+
125
+ StatusBar {
126
+ height: 1;
127
+ padding: 0 1;
128
+ color: $text-muted;
129
+ }
130
+
131
+ StatusBar #state {
132
+ width: auto;
133
+ }
134
+
135
+ /* 中间两格:占剩余宽度的一半并居中,落在左右两端之间。 */
136
+ StatusBar #tasks {
137
+ width: 1fr;
138
+ text-align: center;
139
+ }
140
+
141
+ StatusBar #hint {
142
+ width: 1fr;
143
+ text-align: right;
144
+ }
145
+
146
+ /* 后台任务 / 子代理的详细页:占输入框上方的槽,有内容才出现。 */
147
+ TaskDetail {
148
+ display: none;
149
+ height: auto;
150
+ margin: 0 1;
151
+ padding: 0 1;
152
+ border: round $primary;
153
+ }
@@ -0,0 +1,85 @@
1
+ """审批载荷的形状:把后端给的结构拆成 `Prompt` / `Option`。
2
+
3
+ 界面那一层在 `ui.ApprovalPanel`(全屏版)—— 这里只管"后端说了什么"。
4
+
5
+ **这一层不判断"该不该批"**。它只做三件事:把后端给的结构摆出来、把用户选的
6
+ 那个 key 原样送回去、把失败说清楚。授权语义("本会话不再询问"到底意味着什么)
7
+ 全在后端 —— 在这里再实现一遍,两边的口径迟早会分叉。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Option:
17
+ key: str
18
+ label: str
19
+ description: str = ""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Prompt:
24
+ """一次待回答的请求。字段与后端的载荷一一对应。"""
25
+
26
+ request_id: str
27
+ kind: str = ""
28
+ body: str = ""
29
+ options: tuple[Option, ...] = ()
30
+ default_key: str = ""
31
+ #: 非空表示"中间态":这一步该做的不是选一项,而是说一句话。
32
+ #: 后端那时不给选项表 —— 给了也是没人读的死数据。
33
+ expect: str = ""
34
+ multi: bool = False
35
+ extra: dict = field(default_factory=dict)
36
+
37
+ @classmethod
38
+ def from_payload(cls, raw: dict) -> "Prompt | None":
39
+ if not isinstance(raw, dict):
40
+ return None
41
+ rid = raw.get("request_id")
42
+ if not isinstance(rid, str) or not rid:
43
+ return None
44
+ opts = []
45
+ for item in raw.get("options") or ():
46
+ if not isinstance(item, dict):
47
+ continue
48
+ key = str(item.get("key") or "")
49
+ if not key:
50
+ continue
51
+ opts.append(Option(key=key,
52
+ label=str(item.get("label") or key),
53
+ description=str(item.get("description") or "")))
54
+ return cls(
55
+ request_id=rid,
56
+ kind=str(raw.get("kind") or ""),
57
+ body=str(raw.get("body") or ""),
58
+ options=tuple(opts),
59
+ default_key=str(raw.get("default_key") or ""),
60
+ expect=str(raw.get("expect") or ""),
61
+ multi=bool(raw.get("multi")),
62
+ extra={k: v for k, v in raw.items()
63
+ if k not in ("request_id", "kind", "body", "options",
64
+ "default_key", "expect", "multi")},
65
+ )
66
+
67
+ @property
68
+ def wants_text(self) -> bool:
69
+ return self.expect == "text" or not self.options
70
+
71
+ def keys(self) -> list[str]:
72
+ return [o.key for o in self.options]
73
+
74
+ def key_for_number(self, raw: str) -> str | None:
75
+ """把用户敲的序号换成选项 key。
76
+
77
+ 用户看到的是 1/2/3 这样的序号,而 key 是后端定的(可能不是数字)。
78
+ 只按位置映射,不去猜 key 的含义。
79
+ """
80
+ if not raw.isdigit():
81
+ return None
82
+ idx = int(raw) - 1
83
+ if 0 <= idx < len(self.options):
84
+ return self.options[idx].key
85
+ return None
@@ -0,0 +1,279 @@
1
+ """后端子进程的生命周期。
2
+
3
+ TUI 自己不实现 agent,它启动 crannia 的 web 后端并连上去。所以这里
4
+ 管的是"怎么起、怎么确认起来了、怎么保证死干净"。
5
+
6
+ 三条不变量:
7
+
8
+ 1. **token 由本进程生成**。后端只认 `CRANNIA_LAUNCH_TOKEN`,不认"谁先连上谁算数"——
9
+ 本机其他进程也能连 127.0.0.1,没有 token 就是公开的。
10
+ 2. **端口由本进程挑**。默认 5000 很容易被别的实例占着,占了就会连到别人的会话。
11
+ 让系统分配一个空闲端口,比"探测 5000 是否可用"更没竞态。
12
+ 3. **异常路径也要收尸**。用户 Ctrl-C、后端自己崩、Python 抛异常——
13
+ 三条路都不能留下孤儿进程。所以 stop() 是幂等的,并且在 finally 里调。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import secrets
21
+ import socket
22
+ import subprocess
23
+ import threading
24
+ import time
25
+ import urllib.error
26
+ import urllib.request
27
+ from collections import deque
28
+ from pathlib import Path
29
+
30
+ from .doctor import query as _query
31
+ from .i18n import t
32
+
33
+
34
+ #: 启动前要问后端解释器两件事:数据根(端点文件在它下面)与代码版本(握手)。
35
+ #: 与 `doctor` 同一条口径:TUI 不 import `core`,一律子进程问。
36
+ _FACTS_CODE = (
37
+ "import json; from core.paths import data_root; "
38
+ "from core.version import __version__; "
39
+ "print(json.dumps({'root': str(data_root()), 'version': __version__}))")
40
+
41
+ #: 端点文件的位置。形状与读写口径的权威在 `core/endpoint.py`;
42
+ #: 这里只读、不写 —— TUI 只可能是接入方,写端点的是后端自己。
43
+ _ENDPOINT_REL = Path("data") / "runtime" / "endpoint.json"
44
+
45
+ #: 本机地址不走环境变量里的代理(与 `core/endpoint.py` 同一个理由)。
46
+ _OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
47
+
48
+
49
+ def _read_endpoint(root: Path) -> dict | None:
50
+ """读端点文件;读不到 / 字段不像样一律 None。"""
51
+ try:
52
+ data = json.loads((Path(root) / _ENDPOINT_REL).read_text(encoding="utf-8"))
53
+ port = int(data.get("port") or 0)
54
+ pid = int(data.get("pid") or 0)
55
+ token = str(data.get("token") or "")
56
+ except (OSError, ValueError, TypeError, AttributeError):
57
+ return None
58
+ if not (0 < port < 65536) or not token or pid <= 0:
59
+ return None
60
+ return {"port": port, "token": token, "pid": pid,
61
+ "version": str(data.get("version") or "")}
62
+
63
+
64
+ def _probe(ep: dict, timeout: float = 2.0) -> dict | None:
65
+ """端点上的 `/api/status` 应答;连不上 / 令牌不对都返回 None。"""
66
+ req = urllib.request.Request(
67
+ f"http://127.0.0.1:{ep['port']}/api/status",
68
+ headers={"X-Crannia-Token": ep["token"]})
69
+ try:
70
+ with _OPENER.open(req, timeout=timeout) as resp:
71
+ if resp.status != 200:
72
+ return None
73
+ body = json.loads(resp.read().decode("utf-8"))
74
+ except (urllib.error.URLError, OSError, ValueError):
75
+ return None
76
+ return body if isinstance(body, dict) else None
77
+
78
+
79
+ def _free_port() -> int:
80
+ """让系统给一个空闲端口。
81
+
82
+ 拿到端口和真正 listen 之间有一个窗口,别的进程可能抢走。这个窗口
83
+ 在单机上窄到可以忽略;相比之下"固定 5000 再探测"的竞态更宽。
84
+ """
85
+ with socket.socket() as s:
86
+ s.bind(("127.0.0.1", 0))
87
+ return s.getsockname()[1]
88
+
89
+
90
+ class BackendError(RuntimeError):
91
+ """后端没能起来。消息里带最后几行输出 —— 起不来的原因几乎总在那里面。"""
92
+
93
+
94
+ class Backend:
95
+ def __init__(self, crannia: Path, python: Path,
96
+ port: int | None = None, token: str | None = None,
97
+ data_root: Path | None = None,
98
+ expect_version: str | None = None) -> None:
99
+ self.crannia = crannia
100
+ self.python = python
101
+ self.port = port or _free_port()
102
+ self.token = token or secrets.token_urlsafe(24)
103
+ self.base = f"http://127.0.0.1:{self.port}"
104
+ #: 接入判定用的两个口径。默认自己去问(子进程),测试与特殊部署可注入。
105
+ self.data_root = data_root
106
+ self.expect_version = expect_version
107
+ self._proc: subprocess.Popen | None = None
108
+ #: 后端 stdout/stderr 的尾巴。正常时不看,报错时是唯一线索;
109
+ #: 有界是因为它会一直涨(日志是流式写的)。
110
+ self._tail: deque[str] = deque(maxlen=80)
111
+ self._pump: threading.Thread | None = None
112
+
113
+ # -- 起 -------------------------------------------------------
114
+
115
+ def _attach(self) -> dict | None:
116
+ """有活的端点就接上去(返回 port/token),没有返回 None。
117
+
118
+ 版本必须一致:两套安装各自更新,版本错开时"能连上"不代表
119
+ "能一起用"。握手失败是硬错,不是"退回自己起" —— 同一个数据根上
120
+ 再起一个后端,正是这条要防的事。
121
+ """
122
+ root, expect = self.data_root, self.expect_version
123
+ if root is None or expect is None:
124
+ try:
125
+ facts = json.loads(_query(self.python, self.crannia, _FACTS_CODE))
126
+ root = Path(facts["root"]).expanduser()
127
+ expect = str(facts["version"])
128
+ except Exception: # noqa: BLE001
129
+ # 问不出来(解释器不对 / 树不全)就不接。照常 spawn 会撞上
130
+ # 后端的让位闸,那句"已有服务在跑"比这里猜更准。
131
+ return None
132
+ ep = _read_endpoint(root)
133
+ if ep is None:
134
+ return None
135
+ status = _probe(ep)
136
+ if status is None:
137
+ return None
138
+ got = str(status.get("version") or "")
139
+ if not got or got != expect:
140
+ raise BackendError(
141
+ t("版本不一致:TUI 是 %s,当前后端 %s。请优先升级后重试。")
142
+ % (expect, got or t("未知")))
143
+ return {"port": ep["port"], "token": ep["token"]}
144
+
145
+ def start(self) -> None:
146
+ if self._proc is not None:
147
+ return
148
+ live = self._attach()
149
+ if live is not None:
150
+ # 接上去:端口与令牌都来自端点文件;本进程没有子进程,
151
+ # `stop()` 因此不会去杀别人的后端。
152
+ self.port, self.token = live["port"], live["token"]
153
+ self.base = f"http://127.0.0.1:{self.port}"
154
+ return
155
+ env = dict(os.environ)
156
+ env.update({
157
+ "CRANNIA_LAUNCH_TOKEN": self.token,
158
+ "CRANNIA_API_PORT": str(self.port),
159
+ # 不设这一格,后端会去开系统浏览器 —— 用户点一次"起 TUI"
160
+ # 却弹出一个网页,这一格就是那个差别。
161
+ "CRANNIA_DESKTOP": "1",
162
+ "PYTHONIOENCODING": "utf-8",
163
+ "PYTHONUNBUFFERED": "1",
164
+ })
165
+ self._proc = subprocess.Popen(
166
+ [str(self.python), "-m", "web"],
167
+ cwd=str(self.crannia), env=env,
168
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
169
+ text=True, encoding="utf-8", errors="replace", bufsize=1,
170
+ )
171
+ self._pump = threading.Thread(target=self._drain, daemon=True)
172
+ self._pump.start()
173
+
174
+ def _drain(self) -> None:
175
+ """把子进程输出收进环形缓冲。
176
+
177
+ 不直接打到终端:TUI 占着屏幕,backend 的启动日志会把界面冲掉。
178
+ 留尾巴是为了"起不来"时能原样贴出来。
179
+ """
180
+ proc = self._proc
181
+ if proc is None or proc.stdout is None:
182
+ return
183
+ for line in proc.stdout:
184
+ line = line.rstrip()
185
+ if line:
186
+ self._tail.append(line)
187
+
188
+ # -- 就绪 -----------------------------------------------------
189
+
190
+ def wait_ready(self, timeout: float = 90.0) -> dict:
191
+ """轮询 health 直到起来。
192
+
193
+ 超时给到 90 秒:后端要装 bus(providers / skills / channels)和
194
+ 记忆库,冷启动十几秒是常态;给短了会把"慢"误判成"坏"。
195
+ """
196
+ deadline = time.monotonic() + timeout
197
+ last: Exception | None = None
198
+ while time.monotonic() < deadline:
199
+ if self._proc is not None and self._proc.poll() is not None:
200
+ raise BackendError(
201
+ t("后端进程已退出(code=%s)。\n") % self._proc.returncode
202
+ + self.tail_text())
203
+ try:
204
+ return self.get_json("/api/health", timeout=3)
205
+ except Exception as exc: # 连接被拒是预期内的,它还没 listen
206
+ last = exc
207
+ time.sleep(0.4)
208
+ raise BackendError(
209
+ t("后端 %ss 内未就绪(最后错误:%s)。\n")
210
+ % (f"{timeout:.0f}", last) + self.tail_text())
211
+
212
+ def start_framework(self) -> None:
213
+ """让后端把 agent 框架启起来。
214
+
215
+ 不调这一步,`/api/chat` 会回 503 —— 那个端点检查的是
216
+ `_FRAMEWORK_RUNNING`,它只在 `/api/start` 之后才为真。
217
+ """
218
+ code, body = self.post_json("/api/start", {})
219
+ if code != 200:
220
+ raise BackendError(t("/api/start 失败(%s):%s")
221
+ % (code, body[:300]))
222
+
223
+ # -- HTTP -----------------------------------------------------
224
+
225
+ def _request(self, path: str, data: bytes | None = None,
226
+ timeout: float = 30.0):
227
+ req = urllib.request.Request(
228
+ self.base + path, data=data,
229
+ method="POST" if data is not None else "GET",
230
+ headers={"X-Crannia-Token": self.token,
231
+ **({"Content-Type": "application/json"} if data else {})},
232
+ )
233
+ return urllib.request.urlopen(req, timeout=timeout)
234
+
235
+ def get_json(self, path: str, timeout: float = 10.0) -> dict:
236
+ with self._request(path, timeout=timeout) as r:
237
+ return json.loads(r.read().decode("utf-8"))
238
+
239
+ def post_json(self, path: str, payload: dict,
240
+ timeout: float = 300.0) -> tuple[int, str]:
241
+ """POST。超时给得长:一轮工具调用可能跑几分钟。
242
+
243
+ 用 300 秒而不是不设上限 —— TCP 断了之后没有超时的话,
244
+ 这个调用会一直挂着,用户看到的是"永远转圈"。
245
+ """
246
+ body = json.dumps(payload).encode("utf-8")
247
+ try:
248
+ with self._request(path, data=body, timeout=timeout) as r:
249
+ return r.status, r.read().decode("utf-8", "ignore")
250
+ except urllib.error.HTTPError as e:
251
+ return e.code, e.read().decode("utf-8", "ignore")
252
+
253
+ # -- 收 -------------------------------------------------------
254
+
255
+ def tail_text(self, n: int = 12) -> str:
256
+ lines = list(self._tail)[-n:]
257
+ return ("\n".join(" " + ln for ln in lines) if lines
258
+ else " " + t("(没有输出)"))
259
+
260
+ def stop(self) -> None:
261
+ """终止后端。幂等 —— 正常退出和异常退出都会走到这里。"""
262
+ proc, self._proc = self._proc, None
263
+ if proc is None:
264
+ return
265
+ if proc.poll() is not None:
266
+ return
267
+ try:
268
+ proc.terminate()
269
+ proc.wait(timeout=8)
270
+ except subprocess.TimeoutExpired:
271
+ # 8 秒还不退:它可能卡在某个不可中断的调用里。
272
+ # 这时候只能强杀 —— 留着它比杀掉更糟(下次启动会抢端口/锁数据)。
273
+ proc.kill()
274
+ except Exception:
275
+ proc.kill()
276
+
277
+ @property
278
+ def alive(self) -> bool:
279
+ return self._proc is not None and self._proc.poll() is None