@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
@@ -7,7 +7,8 @@
7
7
 
8
8
  | 读者 | 什么时候 |
9
9
  |---|---|
10
- | ~~新装环境~~ | 没有这个读者(不播种)—— `data/settings.json` 不存在时,各模块的 inline 兜底生效,「缺键 = 出厂默认」这条语义因此活着(以后改默认值,已装用户拿得到) |
10
+ | TUI 首次启动 | `heal()` 在文件不存在 / 坏了时按这份播种(GUI 侧仍不播种,走 inline 兜底) |
11
+ | ~~新装环境~~ | 没有这个读者(GUI 不播种)—— `data/settings.json` 不存在时,各模块的 inline 兜底生效,「缺键 = 出厂默认」这条语义因此活着(以后改默认值,已装用户拿得到) |
11
12
  | 「恢复默认设置」 | 以它为准覆盖回去 —— 这就是本模块要的东西 |
12
13
 
13
14
  ## 为什么要把它提出来:「出厂默认」没有一处能回答
@@ -43,6 +44,8 @@
43
44
  from __future__ import annotations
44
45
 
45
46
  import json
47
+ import os
48
+ import time
46
49
  from pathlib import Path
47
50
  from typing import Optional
48
51
 
@@ -132,3 +135,69 @@ def plan_restore(current: Optional[dict] = None,
132
135
  changed[k] = [cur.get(k), v]
133
136
  new[k] = v
134
137
  return new, changed, skipped
138
+
139
+
140
+ def _atomic_write(path: Path, data: dict) -> None:
141
+ """同目录临时文件 + replace —— 读侧永远看不到半截 JSON。"""
142
+ path.parent.mkdir(parents=True, exist_ok=True)
143
+ tmp = path.with_name(path.name + ".tmp")
144
+ tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n",
145
+ encoding="utf-8")
146
+ os.replace(tmp, path)
147
+
148
+
149
+ def _backup(path: Path, stamp: Optional[str] = None) -> Path:
150
+ """把坏文件挪走。不覆盖既有备份(同一秒坏两次也不丢第一份)。"""
151
+ base = stamp or time.strftime("%Y%m%d-%H%M%S")
152
+ target = path.with_name(path.name + ".bad-" + base)
153
+ n = 1
154
+ while target.exists():
155
+ n += 1
156
+ target = path.with_name(path.name + ".bad-" + base + "-%d" % n)
157
+ os.replace(path, target)
158
+ return target
159
+
160
+
161
+ def heal(path: Path, *, baseline_path: Optional[Path] = None,
162
+ stamp: Optional[str] = None,
163
+ overrides: Optional[dict] = None) -> dict:
164
+ """确保设置文件可用:缺文件就用基准播种;坏了就先备份再用基准重建;好的不动。
165
+
166
+ 这是 TUI 首次启动那一步。GUI 侧的口径仍是"不播种":
167
+ 不存在的文件照旧走各模块的 inline 兜底。
168
+ 两边不冲突,一份完整的基准快照与"缺键 = 出厂默认"读到的是同一组值。
169
+
170
+ `overrides` 只在这一次播种时改写基准里的那几格 —— TUI 用它把
171
+ `background_services` 关掉(TUI 首启不跑通道与定时任务)。
172
+ 已有文件一个字节也不动:那里面是用户的决定,不是我们的默认值。
173
+
174
+ 返回 `{"action": "ok"|"seeded"|"backup"|"error", "backup": <路径或空>,
175
+ "error": <原因或空>}`。写不进去不抛:设置文件处置失败不该挡住启动。
176
+ """
177
+ p = Path(path)
178
+ backup = ""
179
+ if p.exists():
180
+ try:
181
+ data = json.loads(p.read_text(encoding="utf-8"))
182
+ if isinstance(data, dict):
183
+ return {"action": "ok", "backup": "", "error": ""}
184
+ except (OSError, ValueError):
185
+ pass
186
+ try:
187
+ backup = str(_backup(p, stamp))
188
+ except OSError as exc:
189
+ return {"action": "error", "backup": "",
190
+ "error": "坏文件备份失败:%s" % exc}
191
+ base = baseline(baseline_path)
192
+ if not base:
193
+ return {"action": "error", "backup": backup, "error": "出厂基准读不到"}
194
+ if overrides:
195
+ base = {**base, **{k: v for k, v in overrides.items()
196
+ if not str(k).startswith("_")}}
197
+ try:
198
+ _atomic_write(p, base)
199
+ except OSError as exc:
200
+ return {"action": "error", "backup": backup,
201
+ "error": "写入设置失败:%s" % exc}
202
+ return {"action": "backup" if backup else "seeded",
203
+ "backup": backup, "error": ""}
package/core/shell.py CHANGED
@@ -926,7 +926,9 @@ def _background_receipt(job, *, by_user: bool = False, timed_out: bool = False)
926
926
  # 只有通知链真的接通了,回执才敢承诺"会收到回报"(标签不许说谎)。
927
927
  try:
928
928
  from core.tasks_notify import is_installed as _notify_on
929
- _promise = "完成时会收到一条后台任务回报;" if _notify_on() else ""
929
+ # 回报的投递判据是会话空闲 —— 这一轮还在跑的时候它送不到。
930
+ # 回执必须把这件事说清(同 `agent_loop._hand_off` 那句)。
931
+ _promise = "完成后的回报要等这一轮结束才送得到;" if _notify_on() else ""
930
932
  except Exception: # noqa: BLE001
931
933
  _promise = ""
932
934
  if timed_out:
@@ -1434,22 +1436,8 @@ def run_command(command: str = "", cwd: str = "", timeout_ms: int = 0,
1434
1436
  # 档位只决定默认值,不另开一个上限口径。
1435
1437
  timeout_ms = spec.command_timeout_ms
1436
1438
 
1437
- # 配额(设计 §6.4):每会话后台命令 ≤ 3 —— 拒,并给路线
1438
- # 只对模型显式请求(`background=true`)生效:超时降级是"别白干",
1439
- # 不能被配额杀掉(那样等于回到"到点就杀")。用户 Ctrl+B 也不在这里拒
1440
- # —— 那条路是"已经在前台跑的命令",拒了也不能让它停下来。
1441
- if background:
1442
- from core import jobs as _jobs
1443
- _qkey = _snap.session_id if _snap is not None else ""
1444
- if _jobs.running_count_for(_qkey, _jobs.KIND_COMMAND) >= 3:
1445
- return {
1446
- "success": False,
1447
- "denied": True,
1448
- "tier": "quota",
1449
- "error": ("**后台命令已经到上限了**(这个会话已有 3 条在后台跑)—— "
1450
- "这一条**没有执行**。先用 `task(action=\"status\")` 看谁还在跑、"
1451
- "`action=\"wait\"` 等一个回来,或者直接前台跑(会等到它结束)。"),
1452
- }
1439
+ # 后台命令不设条数配额:一次请求跑几条由模型自己决定,
1440
+ # 真要限制它的成本应落在单条命令的时长与输出上,不在这里按条数拒。
1453
1441
 
1454
1442
  # 档位只能收窄上面那个开关 —— `effective_approval` 是全仓唯一
1455
1443
  # 的收窄点(`min(用户的选择, 这一档的上限)`)。判据:
@@ -42,14 +42,19 @@ import json
42
42
  from pathlib import Path
43
43
  from typing import Any
44
44
 
45
- __all__ = ["available", "schema_for", "storage_for", "load", "public", "save",
46
- "MASK"]
45
+ __all__ = ["available", "manifest_of", "schema_for", "storage_for", "load",
46
+ "public", "save", "MASK"]
47
47
 
48
48
  MASK = "****"
49
49
 
50
50
  _SCALARS = (str, int, float, bool)
51
51
 
52
52
 
53
+ def manifest_of(skill_name: str) -> dict:
54
+ """读 `skills/<name>/manifest.yaml`;读不到,空表(不抛)。"""
55
+ return _manifest(skill_name)
56
+
57
+
53
58
  def _manifest(skill_name: str) -> dict:
54
59
  """读 `skills/<name>/manifest.yaml`;读不到,空表(不抛)。
55
60
 
@@ -118,6 +118,13 @@ SESSION_SCOPED: Tuple[SessionState, ...] = (
118
118
  "todos", "core/todos.py::_todos", "purge_session",
119
119
  _lazy("core.todos", "forget"),
120
120
  "不清:下一段对话一开口就看见上一段任务的清单"),
121
+ SessionState(
122
+ # 「凭据会进历史」只提醒一次。不清的话,下一段对话第一次写配置
123
+ # 时不再提醒(用户换了一段对话,理应重新被告知一次)。
124
+ "secret_fill_noted", "core/config_requirements.py::_fill_noted",
125
+ "purge_session",
126
+ _lazy("core.config_requirements", "forget_session"),
127
+ "不清:下一段第一次写配置时不再提醒"),
121
128
  SessionState(
122
129
  # 常驻 shell:不清的话,上一段对话起的 bash 进程会一直活着
123
130
  # (连同里面的变量 / venv),而新一段对话第一条命令会沿用它的 cwd。
@@ -268,6 +275,12 @@ SESSION_SCOPED: Tuple[SessionState, ...] = (
268
275
  _lazy("core.jobs", "forget_foreground"),
269
276
  "前台命令的 Ctrl+B 事件(按会话键)。不清:上一段对话的 proc 登记会留到"
270
277
  "下一次转后台时被错误地置事件 —— 而那条命令早就结束了"),
278
+ SessionState(
279
+ # 子代理的就地审批:`/clear` 要把还在等的那几条放走 ——
280
+ # 那些子线程正阻塞在一个不会再有人回答的弹窗上。
281
+ "child_approvals", "core/child_approval.py::_QUEUES", "purge_session",
282
+ _lazy("core.child_approval", "cancel_session"),
283
+ "不清:等在审批上的子线程一直挂着;下一段对话还会看到上一段的待批"),
271
284
  SessionState(
272
285
  "background_pending", "core/tasks_notify.py::_pending", "purge_session",
273
286
  _lazy("core.tasks_notify", "forget"),
@@ -844,6 +857,12 @@ PROCESS_SHARED: Tuple[ProcessState, ...] = (
844
857
  "_meta_cache", "core/model_capabilities.py::_meta_cache",
845
858
  "无锁(与 `_table_cache` 同一次读填好)",
846
859
  "能力表的 `source` / `fetched` 元数据(同上,全局只读,不挂 `/clear`)"),
860
+ ProcessState(
861
+ "_ITEMS", "core/web_cache.py::_ITEMS",
862
+ "`core.web_cache._LOCK` 护着(读、写、清、淘汰都在锁内)",
863
+ "抓取响应的进程级缓存(键是归一化后的 URL,30 分钟 / 256 MiB)。"
864
+ "它不是会话态:同一份内容被哪一段对话读过不影响它,"
865
+ "所以 `/clear` 不清(清了只是下一次重新出网)"),
847
866
  ProcessState(
848
867
  "_cache", "core/model_configs.py::_cache",
849
868
  "`core/model_configs._LOCK` 护着(同 `core/groups._cache`)",
package/core/subagent.py CHANGED
@@ -59,7 +59,7 @@ FORK_PLACEHOLDER = "已派遣子代理,结果稍后返回"
59
59
  EMPTY_OUTPUT = "(子 agent 跑完了,但没有返回任何内容。)"
60
60
 
61
61
  #: 子 agent 的轮次预算在这里没有常量 —— 它由档位给
62
- #: (`TierSpec.subagent_turns`;档 3 是 8)。
62
+ #: (`TierSpec.subagent_turns`,值在 `core/tiers.py::SUBAGENT_TURNS`)。
63
63
  #: 理由同 `_MAX_TOOL_CONCURRENCY`:某一档的值只能在一处定义。
64
64
  #:`run_child` 必须收到 `max_turns=`(没有默认值:有默认值就等于留了一条
65
65
  #: "忘了传、于是静默用旧值"的路)。
@@ -352,7 +352,10 @@ def run_child(*, snapshot, assistant_msg: dict, task: str, provider,
352
352
  directive: str | None = None,
353
353
  cancel_check: Callable[[], bool] | None = None,
354
354
  workspace: str | None = None,
355
- tool_allowlist: frozenset | None = None) -> dict:
355
+ tool_allowlist: frozenset | None = None,
356
+ on_tokens: Callable[[int, int], None] | None = None,
357
+ ask: Callable[[dict], str] | None = None,
358
+ origin: str = "") -> dict:
356
359
  """跑一个子 agent,只把最终文本交回父。
357
360
 
358
361
  返回 `{"success": bool, "output": str, ...}` —— 形状与别的工具一致(会被
@@ -414,6 +417,49 @@ def run_child(*, snapshot, assistant_msg: dict, task: str, provider,
414
417
  if workspace:
415
418
  text_directive += ("\n\n★ 你的工作目录是 `%s`(独立的工作树):"
416
419
  "读写都用这个目录下的路径。" % workspace)
420
+
421
+ # ---- 子 agent 的上下文策略 ----
422
+ #
423
+ # 阶段那套压缩是"每个用户请求一次",子绕过了阶段;子只活在这一次循环里,
424
+ # 所以两档都在这里接:
425
+ # · 80%:收缩旧工具输出,并且真改 `messages`(`_inplace_trim`)——
426
+ # 只改发出去的副本,下一条请求又原样涨回来;
427
+ # · 95% / 溢出:摘要压缩。不落库 —— 子和父共用一个 `session_id`,
428
+ # 落库会改写父的历史;状态键也用子自己的,压缩器的熔断器按它记账。
429
+ import uuid as _uuid
430
+
431
+ from core.context_pressure import FORCE_RATIO as _FORCE_RATIO
432
+ from core.memory.compressor import Compressor as _Compressor
433
+ from core.memory.compressor import forget_breaker as _forget_breaker
434
+
435
+ _ctx_key = "child:%s" % _uuid.uuid4().hex[:8]
436
+ _child_comp = _Compressor(threshold=_FORCE_RATIO, keep_recent_turns=3)
437
+
438
+ def _compact_child(msgs: list, *, force: bool) -> list | None:
439
+ window = getattr(provider, "context_window", None)
440
+ if not window:
441
+ return None
442
+ try:
443
+ new, done = _child_comp.check_and_compress(
444
+ _ctx_key, msgs, provider, window,
445
+ session_note=None, mode="auto",
446
+ system=snapshot.system, tools=snapshot.tools,
447
+ force=force, threshold=_FORCE_RATIO)
448
+ except Exception as exc: # noqa: BLE001 —— 压缩失败不该弄挂子这一趟
449
+ print(f"[subagent] 上下文压缩失败({type(exc).__name__}: {exc})")
450
+ return None
451
+ return new if done else None
452
+
453
+ def _compact_now() -> list | None:
454
+ return _compact_child(prefix, force=False)
455
+
456
+ def _rescue(msgs: list) -> bool:
457
+ new = _compact_child(msgs, force=True)
458
+ if not new:
459
+ return False
460
+ msgs[:] = new
461
+ return True
462
+
417
463
  with _DepthGuard(), guard, request_snapshot.preserved(), ws_ctx:
418
464
  try:
419
465
  content, _msgs, _chunks, tokens = agent_loop(
@@ -440,10 +486,25 @@ def run_child(*, snapshot, assistant_msg: dict, task: str, provider,
440
486
  cancel_check=cancel_check,
441
487
  # 子 agent 定义声明的工具白名单;None 表示不限制。
442
488
  _tool_allowlist=tool_allowlist,
489
+ # 上下文策略:95% 摘要压缩 + 溢出后压一次重发 + 80% 真裁剪。
490
+ compact_cb=_compact_now,
491
+ _on_overflow=_rescue,
492
+ _inplace_trim=True,
493
+ # 两个累计读数报给任务表(面板用):计费量 + 输出量。
494
+ # 观测件,不参与判定。
495
+ _on_progress=on_tokens,
496
+ # 审批:子就地申请(`None` = 老行为,一律拒)。
497
+ _child_ask=ask,
498
+ # 定时任务那一轮不许开审批 —— 子要继承同一个来源。
499
+ _origin=origin,
443
500
  )
444
501
  except Exception as exc: # noqa: BLE001 —— 判据:异常一律算失败
445
502
  return {"success": False,
446
503
  "error": f"子 agent 失败:{type(exc).__name__}: {exc}"}
504
+ finally:
505
+ # 压缩器的熔断器是模块级的、按状态键记 —— 子这一趟结束就收掉,
506
+ # 不让它按子会话无限攒。
507
+ _forget_breaker(_ctx_key)
447
508
 
448
509
  text = (content or "").strip()
449
510
  if not text:
@@ -485,7 +546,7 @@ SUBAGENT_TOOL_SCHEMA: dict = {
485
546
  "background": {
486
547
  "type": "boolean",
487
548
  "description": ("true = 转到后台跑,你立刻拿回执、先做别的;"
488
- "结果回来时会收到一条后台任务回报。"),
549
+ "结果会以一条后台回报送来(要等你这一轮结束后)。"),
489
550
  },
490
551
  "isolate": {
491
552
  "type": "boolean",
package/core/task_tool.py CHANGED
@@ -121,7 +121,7 @@ def task_tool(task_id: str = "", action: str = "status",
121
121
  if snap.get("status") == "running":
122
122
  out["retrieval_status"] = "timeout"
123
123
  out["note"] = ("等了 %d 毫秒还没结束 —— 它还在跑。可以再等,"
124
- "或者先做别的,完成时会收到后台任务回报。" % ms)
124
+ "或者先做别的:回报要等你这一轮结束才送得到。" % ms)
125
125
  else:
126
126
  out["retrieval_status"] = "success"
127
127
  out["note"] = "已经结束。要细节就看 output_file(或 action=output)。"
@@ -49,6 +49,10 @@ from core.session_key import group_id_of
49
49
  #: 单独一格是为了不让同一个前缀在两个文件里各写一遍。
50
50
  NOTIFICATION_PREFIX = "[后台任务回报"
51
51
 
52
+ #: 定时任务的回报前缀 —— 与后台任务分开:那边是"你刚才派出去的活",
53
+ #: 这边是"用户早就设好的闹钟 / 取回",模型看到的第一句话就不一样。混用一个前缀会让模型把定时任务当成刚发生的工具结果。
54
+ CRON_NOTIFICATION_PREFIX = "[定时任务回报"
55
+
52
56
  #: 用户停止活动多久之后才允许起自动轮(秒)。
53
57
  #: 不是"优先级队列",只是不抢正在发生的对话(判据见模块 docstring)。
54
58
  QUIET_SECONDS = 1.0
@@ -72,6 +76,7 @@ _KIND_LABELS = {
72
76
  jobs.KIND_COMMAND: "命令",
73
77
  jobs.KIND_SUBAGENT: "子 agent",
74
78
  jobs.KIND_SKILL: "技能任务",
79
+ jobs.KIND_CRON: "定时任务",
75
80
  }
76
81
 
77
82
 
@@ -79,6 +84,39 @@ def _kind_label(job) -> str:
79
84
  return _KIND_LABELS.get(job.kind, "后台任务")
80
85
 
81
86
 
87
+ def cron_note_text(*, title: str, kind: str, status: str = "已完成",
88
+ body: str = "") -> str:
89
+ """给模型看的定时任务回报(第一行必须点明"这是用户的预设定时任务")。
90
+
91
+ 两支分开写:闹钟只要提一句,取回类要把内容转达。模型看到"这不是用户
92
+ 刚说的话"就不会自己去查一遍,也不会把它当成一条新指令去做。
93
+ """
94
+ title = sanitize_text(str(title or ""))[:200] or "(未命名)"
95
+ kind = "alarm" if str(kind or "") == "alarm" else "report"
96
+ head = CRON_NOTIFICATION_PREFIX + " · 这是用户的预设定时任务,不是用户刚说的话]"
97
+ body = sanitize_text(str(body or ""))
98
+ if kind == "alarm":
99
+ line = "定时任务「%s」(kind: alarm · %s):%s" % (
100
+ title, status, body[:1000])
101
+ tail = "到点了,提醒用户一句即可;不要自己再去查,也不要把这件事当成新任务去做。"
102
+ return "\n".join([head, line, tail])
103
+ line = "定时任务「%s」(kind: report · %s) 取回的内容如下。" % (title, status)
104
+ parts = [head, line]
105
+ if body:
106
+ parts.append("内容:\n" + body[:4000])
107
+ parts.append("把内容转达给用户;这是已经取回的结果,不要自己再查一遍。")
108
+ return "\n".join(parts)
109
+
110
+
111
+ def cron_notification_text(job) -> str:
112
+ """一个跑完的 `KIND_CRON` 作业 -> 回报文案。"""
113
+ status = {"done": "已完成", "failed": "失败",
114
+ "timeout": "超时被收尾", "killed": "已取消"}.get(job.status, job.status)
115
+ return cron_note_text(title=job.description or job.command,
116
+ kind=getattr(job, "cron_kind", "") or "report",
117
+ status=str(status or ""), body=job.result or "")
118
+
119
+
82
120
  def notification_text(job) -> str:
83
121
  """给模型看的那段话。第一行必须说明它是谁说的(否则模型会当用户提问)。"""
84
122
  desc = (job.description or job.command or "").strip()
@@ -122,12 +160,16 @@ def _session_for_key(key: str) -> MessageSession:
122
160
  )
123
161
 
124
162
 
125
- def build_event(session_key: str, text: str, task_id: str = "") -> MessageEvent:
163
+ def build_event(session_key: str, text: str, task_id: str = "",
164
+ origin: str = "background") -> MessageEvent:
126
165
  """手搓一条 `MessageEvent`(形状照 `core/cron/runner.py::_build_event`)。
127
166
 
128
167
  `origin="background"` 让 `im_routing` 立刻放过(否则"≥2 条活跃,
129
168
  问编号"会把一条后台回报扣在一个到点不在场的人身上);
130
169
  `routed_session_key` 指定它进哪条会话。
170
+
171
+ `origin="cron"` 时这一轮也不许开审批(到点没人能批)—— 定时任务的
172
+ 回报轮按这一支走。
131
173
  """
132
174
  session = _session_for_key(session_key)
133
175
  msg = ChannelMessage(
@@ -142,7 +184,7 @@ def build_event(session_key: str, text: str, task_id: str = "") -> MessageEvent:
142
184
  message=msg,
143
185
  platform_meta=ChannelMetadata(
144
186
  name="background", description="后台任务", platform_type=session.platform),
145
- extras={"origin": "background", "task_id": task_id,
187
+ extras={"origin": str(origin or "background"), "task_id": task_id,
146
188
  "routed_session_key": session_key},
147
189
  )
148
190
 
@@ -185,12 +227,34 @@ def _on_finish(job) -> None:
185
227
  return
186
228
  if not jobs.mark_notified(job.id):
187
229
  return
188
- item = {"task_id": job.id, "text": notification_text(job)}
230
+ if job.kind == jobs.KIND_CRON:
231
+ item = {"task_id": job.id, "text": cron_notification_text(job),
232
+ "origin": "cron"}
233
+ else:
234
+ item = {"task_id": job.id, "text": notification_text(job),
235
+ "origin": "background"}
189
236
  with _lock:
190
237
  _pending.setdefault(key, []).append(item)
191
238
  _wake.set()
192
239
 
193
240
 
241
+ def enqueue_note(session_key: str, text: str, *, origin: str = "background",
242
+ task_id: str = "") -> bool:
243
+ """把一条要给模型看的回报排进某个会话(不开线程、不等轮)。
244
+
245
+ 定时任务的闹钟那类没有执行体 —— 它只有一句提醒,直接走这里排队,
246
+ 下一轮与其它后台回报同一条路出去。
247
+ """
248
+ key = str(session_key or "")
249
+ if not key or not str(text or "").strip():
250
+ return False
251
+ with _lock:
252
+ _pending.setdefault(key, []).append(
253
+ {"task_id": task_id, "text": text, "origin": origin})
254
+ _wake.set()
255
+ return True
256
+
257
+
194
258
  def _ready_keys(scheduler, now: Optional[float] = None) -> list[str]:
195
259
  """哪些会话现在可以起通知轮(纯判定,测试直接调它)。"""
196
260
  now = time.monotonic() if now is None else now
@@ -217,7 +281,8 @@ def _ready_keys(scheduler, now: Optional[float] = None) -> list[str]:
217
281
 
218
282
 
219
283
  def _run_turn(key: str, item: dict, scheduler, deliver) -> None:
220
- event = build_event(key, item["text"], item.get("task_id", ""))
284
+ event = build_event(key, item["text"], item.get("task_id", ""),
285
+ origin=str(item.get("origin") or "background"))
221
286
  try:
222
287
  text = asyncio.run(scheduler.execute(event))
223
288
  try:
package/core/tiers.py CHANGED
@@ -67,7 +67,7 @@
67
67
  | 旋钮 | 值 | 出处 |
68
68
  |---|---|---|
69
69
  | `tool_concurrency` | 10 | 没有出处:沿用接入时的取值 |
70
- | `subagent_turns` | 8 | `core/subagent.py`(`SUBAGENT_MAX_TURNS`) |
70
+ | `subagent_turns` | 180 | 本文件的常量(`SUBAGENT_TURNS`)—— 只当兜底上限,不按旧值掐活 |
71
71
  | `max_turns` | `None` = 不设限 | 转圈由重复/循环断路器管,不该由轮数上限兼职管"任务多大" |
72
72
  | `tool_result_max_chars` | 50000 | 唯一源就是本文件的常量(`config.yaml:162` 那个值已不生效,阶段会打一行出声)。对齐常见的 50k |
73
73
  | `command_timeout_ms` | 30000 | `core/shell.py::DEFAULT_TIMEOUT_MS` —— 实际中位 39ms,120 秒的默认值从没派上用场,撞上就是白等两分钟 |
@@ -218,12 +218,18 @@ class TierSpec:
218
218
  #: | 旋钮 | 值 | 生产里那个常量 |
219
219
  #: |---|---|---|
220
220
  #: | `tool_concurrency` | 10 | 没有出处:沿用接入时的取值 |
221
- #: | `subagent_turns` | 8 | `core/subagent.py`(`SUBAGENT_MAX_TURNS`) |
221
+ #: | `subagent_turns` | 180 | 本文件的常量(`SUBAGENT_TURNS`)—— 只当兜底上限,不按旧值掐活 |
222
222
  #: | `max_turns` | `None` = 不设限 | 见下面 `TIERS` 之前那一段 |
223
223
  #: | `tool_result_max_chars` | 50000 | 唯一源是本文件的常量 —— `config.yaml:162` 那个值已不生效(阶段会打一行出声)。对齐常见的 50k |
224
224
  #: | `command_timeout_ms` | 30000 | `core/shell.py::DEFAULT_TIMEOUT_MS` —— 实际中位 39ms,120 秒的默认值从没派上用场 |
225
225
  TOOL_CONCURRENCY = 10
226
- SUBAGENT_TURNS = 8
226
+ #: 子 agent 的轮次上限 —— 只当兜底:正常任务不该撞上它。
227
+ #:
228
+ #: 判据与主循环同一条:轮次不该兼职管"任务多大"。
229
+ #: 子代理没有"下一条用户请求"来触发阶段那套压缩,所以防跑疯靠的是
230
+ #: 循环内的上下文策略(80% 收缩 / 95% 压缩 / 溢出自救,见
231
+ #: `core/subagent.py::run_child`),不是把轮次压低。
232
+ SUBAGENT_TURNS = 180
227
233
  #: `max_turns` 的默认不设限 —— 值写在 `TIERS` 那六格里(都是 `None`)。
228
234
  #:
229
235
  #: ## 为什么
@@ -0,0 +1,108 @@
1
+ """一次工具调用的结局 —— `EVT_TOOL_END` 的 `outcome` / `reason` 词表。
2
+
3
+ ## 治的是什么
4
+
5
+ `EVT_TOOL_END` 原来只带 `ok`,而 `ok=True` 盖住了几种完全不同的情况:
6
+ 顺利跑完、挂起等审批、自动审查拦下、用户拒绝、框架拒绝。
7
+ 客户端只能猜:TUI 原来靠拉轨迹正文去认"被拒绝",而"等审批"根本认不出来,
8
+ 卡片会把一个什么都没执行的调用显示成"已完成"。
9
+
10
+ ## 两格,不是一个
11
+
12
+ `outcome` 决定圆点颜色,`reason` 决定文案 —— 一个字段装不下:
13
+ 同一个 `rejected` 下面有"未采纳 / 未执行 / 被拒绝"三句话,
14
+ 同一个 `error` 下面有"失败 / 未执行"两句。
15
+
16
+ `reason` 永远存在,`completed` / `waiting` 时是空串。不要用"字段在不在"
17
+ 表达"不适用":那会让"读不到"和"没有"长得一样。
18
+
19
+ ## 词表只此一处
20
+
21
+ `core/auto_review.py` 的 `OUTCOME_*` 是审计口径(只记"没跑成"的四种),
22
+ 不抢它的名字 —— 这里负责把它们映射成事件口径,映射表在 `_BY_REVIEW`。
23
+
24
+ ## 判据顺序(承重)
25
+
26
+ 结算语义(调用方当场知道的)> 挂起 > 失败 > 拒绝 > 回执内容 > 完成。
27
+
28
+ 结算语义排第一:结算器知道用户点了什么,回执只是它的渲染 ——
29
+ 让一个已经知道答案的调用方去从文字里认,是在制造第二个真相源。
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from core import auto_review as _AR
35
+
36
+ #: 结局。客户端按它决定颜色。
37
+ OUTCOME_COMPLETED = "completed"
38
+ OUTCOME_WAITING = "waiting"
39
+ OUTCOME_ERROR = "error"
40
+ OUTCOME_DENIED = "denied"
41
+ OUTCOME_REJECTED = "rejected"
42
+
43
+ #: 细分。客户端按它决定文案。
44
+ REASON_FAILED = "failed"
45
+ REASON_REFUSED = "refused"
46
+ REASON_AUTO_REVIEW_BLOCKED = "auto-review-blocked"
47
+ REASON_AUTO_REVIEW_UNAVAILABLE = "auto-review-unavailable"
48
+ REASON_CANCELLED = "cancelled"
49
+ REASON_RECUSED = "recused"
50
+ REASON_USER = "user"
51
+ REASON_UNAVAILABLE = "unavailable"
52
+
53
+ #: 审批结算的四种语义 → 事件口径。四种都归 `rejected`(都没有得到批准),
54
+ #: 区别只在文案。颜色由客户端按 `reason` 再分一次:`cancelled` / `recused`
55
+ #: 是框架侧或"用户没说不"的形状,用白点;其余用红点。
56
+ _BY_SETTLEMENT = {
57
+ "rejected": REASON_USER,
58
+ "cancelled": REASON_CANCELLED,
59
+ "unavailable": REASON_UNAVAILABLE,
60
+ "recused": REASON_RECUSED,
61
+ }
62
+
63
+ #: 自动审查那条线的四个审计值 → 事件口径。
64
+ _BY_REVIEW = {
65
+ _AR.OUTCOME_AUTO_REVIEW_BLOCKED: (OUTCOME_DENIED, REASON_AUTO_REVIEW_BLOCKED),
66
+ _AR.OUTCOME_AUTO_REVIEW_UNAVAILABLE: (OUTCOME_REJECTED,
67
+ REASON_AUTO_REVIEW_UNAVAILABLE),
68
+ _AR.OUTCOME_REJECTED_BY_USER: (OUTCOME_REJECTED, REASON_USER),
69
+ _AR.OUTCOME_PENDING_APPROVAL: (OUTCOME_WAITING, ""),
70
+ }
71
+
72
+
73
+ def of_settlement(token: str) -> tuple[str, str]:
74
+ """审批结算语义 → `(outcome, reason)`。
75
+
76
+ 认不出来的 token 按"用户拒绝"收口:`outcome_line` 对未知语义直接抛,
77
+ 所以线上到不了这里;留这一手只是不想让事件层自己炸掉一轮。
78
+ """
79
+ return OUTCOME_REJECTED, _BY_SETTLEMENT.get(str(token or ""), REASON_USER)
80
+
81
+
82
+ def of_settlement_receipt(content) -> tuple[str, str]:
83
+ """结算回执(信封 + `APPROVAL_HEAD` + `<token>(…)`)→ `(outcome, reason)`。"""
84
+ return of_settlement(_AR.settlement_outcome_of(content))
85
+
86
+
87
+ def classify(content, *, failed: bool = False, refused: bool = False,
88
+ pending: bool = False, settlement: str = "") -> tuple[str, str]:
89
+ """算出一次调用的 `(outcome, reason)`。
90
+
91
+ *failed* / *refused* / *pending* 由调用方按自己已经有的判据传入
92
+ (它们都不是从回执正文里猜出来的);*content* 只用于认回执头。
93
+ """
94
+ if settlement:
95
+ return of_settlement(settlement)
96
+ if pending:
97
+ return OUTCOME_WAITING, ""
98
+ if failed:
99
+ return OUTCOME_ERROR, REASON_FAILED
100
+ if refused:
101
+ return OUTCOME_ERROR, REASON_REFUSED
102
+ token = _AR.settlement_outcome_of(content)
103
+ if token in _BY_SETTLEMENT:
104
+ return OUTCOME_REJECTED, _BY_SETTLEMENT[token]
105
+ review = _AR.outcome_of_tool_result(content)
106
+ if review in _BY_REVIEW:
107
+ return _BY_REVIEW[review]
108
+ return OUTCOME_COMPLETED, ""