codebee 0.1.68 → 0.1.70

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 (133) hide show
  1. package/CHANGELOG.md +580 -543
  2. package/LICENSE +21 -21
  3. package/README.md +11 -0
  4. package/app/browser-final-1440.png +0 -0
  5. package/app/browser-final-390.png +0 -0
  6. package/app/browser-google-fallback.png +0 -0
  7. package/app/browser-google-test.png +0 -0
  8. package/app/browser-workbench-1440.png +0 -0
  9. package/app/browser-workbench-390.png +0 -0
  10. package/app/browser-workspace-google.png +0 -0
  11. package/app/browser-workspace-smoke.png +0 -0
  12. package/app/browser-workspace.png +0 -0
  13. package/app/core/acceptance.py +100 -100
  14. package/app/core/aiflavor.py +197 -197
  15. package/app/core/artifacts.py +148 -148
  16. package/app/core/assets.py +110 -110
  17. package/app/core/attachments.py +623 -623
  18. package/app/core/audit.py +30 -0
  19. package/app/core/automation.py +853 -758
  20. package/app/core/backup.py +470 -470
  21. package/app/core/beekeeper.py +183 -183
  22. package/app/core/benchstore.py +95 -0
  23. package/app/core/board.py +209 -209
  24. package/app/core/bookmeta.py +935 -930
  25. package/app/core/bookmeta_catalog.py +180 -180
  26. package/app/core/branching.py +137 -137
  27. package/app/core/builtin_agent.py +1673 -1234
  28. package/app/core/capability.py +144 -144
  29. package/app/core/catalog.py +7 -1
  30. package/app/core/chaptersafe.py +32 -32
  31. package/app/core/cleanup.py +303 -303
  32. package/app/core/compaction.py +201 -201
  33. package/app/core/covergen.py +356 -356
  34. package/app/core/defectretro.py +43 -43
  35. package/app/core/diagnostics.py +114 -114
  36. package/app/core/dispatch.py +190 -173
  37. package/app/core/dispatch_log.py +128 -128
  38. package/app/core/env_scrub.py +85 -85
  39. package/app/core/error_codes.py +33 -24
  40. package/app/core/errorlog.py +137 -137
  41. package/app/core/evalbench.py +720 -0
  42. package/app/core/evaluation.py +174 -174
  43. package/app/core/failure_notify.py +290 -290
  44. package/app/core/flows.py +228 -3
  45. package/app/core/goal_service.py +167 -167
  46. package/app/core/health.py +374 -374
  47. package/app/core/history.py +38 -38
  48. package/app/core/hooks.py +162 -162
  49. package/app/core/jobs.py +51 -30
  50. package/app/core/manager.py +2143 -2122
  51. package/app/core/market.py +362 -362
  52. package/app/core/market_remote.py +10 -0
  53. package/app/core/mcp_client.py +287 -0
  54. package/app/core/mocks.py +64 -64
  55. package/app/core/modelhub.py +193 -10
  56. package/app/core/notify.py +201 -106
  57. package/app/core/novel_quality.py +189 -0
  58. package/app/core/operations.py +228 -228
  59. package/app/core/paihang.py +138 -138
  60. package/app/core/paths.py +6 -2
  61. package/app/core/pipeline.py +426 -28
  62. package/app/core/planner.py +243 -22
  63. package/app/core/plugins.py +525 -0
  64. package/app/core/portguard.py +111 -111
  65. package/app/core/preview.py +293 -293
  66. package/app/core/publish/__init__.py +7 -7
  67. package/app/core/publish/auto.py +367 -367
  68. package/app/core/publish/browser.py +655 -539
  69. package/app/core/publish/fanqie.py +165 -159
  70. package/app/core/publish/flow.py +589 -440
  71. package/app/core/publish/flows-fanqie-calibrated.json +336 -332
  72. package/app/core/publish/ledger.py +229 -203
  73. package/app/core/publish/manager.py +824 -692
  74. package/app/core/publish/qimao.py +146 -141
  75. package/app/core/publish/ws.py +139 -139
  76. package/app/core/redact.py +38 -38
  77. package/app/core/remotesync.py +121 -0
  78. package/app/core/repeat_guard.py +129 -129
  79. package/app/core/router.py +398 -398
  80. package/app/core/runner.py +2142 -2067
  81. package/app/core/selfupdate.py +384 -384
  82. package/app/core/session_log.py +161 -161
  83. package/app/core/sessions.py +312 -312
  84. package/app/core/settings.py +186 -149
  85. package/app/core/settings_schema.py +270 -262
  86. package/app/core/share_page.py +114 -114
  87. package/app/core/skill_scan.py +122 -122
  88. package/app/core/skillpacks/fanqie-novel.md +80 -80
  89. package/app/core/skillpacks/market/character-bible.md +66 -66
  90. package/app/core/skillpacks/market/code-risk-checklist.md +58 -58
  91. package/app/core/skillpacks/market/git-workflow.md +57 -57
  92. package/app/core/skillpacks/market/release-notes.md +72 -72
  93. package/app/core/skillpacks/market/weekly-report.md +71 -71
  94. package/app/core/skillpacks/market/worldview-consistency.md +70 -70
  95. package/app/core/step_runner.py +132 -132
  96. package/app/core/store.py +104 -82
  97. package/app/core/task_compile.py +199 -199
  98. package/app/core/telemetry.py +292 -292
  99. package/app/core/tlsctx.py +64 -64
  100. package/app/core/token_meter.py +147 -147
  101. package/app/core/tracing.py +144 -144
  102. package/app/core/upstream.py +41 -41
  103. package/app/core/usage.py +1035 -862
  104. package/app/core/volumes.py +389 -389
  105. package/app/core/wxdigest.py +858 -858
  106. package/app/core/zentao.py +2614 -2465
  107. package/app/current-browser.png +0 -0
  108. package/app/main.py +3245 -2981
  109. package/app/mcp_server.py +175 -0
  110. package/app/pet.py +82 -21
  111. package/app/pick_dialog.py +110 -110
  112. package/app/plugins/code-review-helper/.codex-plugin/plugin.json +18 -0
  113. package/app/plugins/code-review-helper/skills/review.md +16 -0
  114. package/app/ui/app.js +15706 -14399
  115. package/app/ui/artdiff.js +74 -74
  116. package/app/ui/board.html +162 -162
  117. package/app/ui/board.js +305 -305
  118. package/app/ui/i18n.js +3012 -2770
  119. package/app/ui/icons/bee.svg +79 -79
  120. package/app/ui/index.html +277 -13
  121. package/app/ui/manifest.json +16 -16
  122. package/app/ui/qrcode.js +2297 -2297
  123. package/app/ui/style.css +802 -16
  124. package/bin/tutti.js +147 -147
  125. package/package.json +47 -46
  126. package/tools/wx_reader.py +261 -261
  127. package/app/.playwright-cli/console-2026-09-23T08-26-03-635Z.log +0 -88
  128. package/app/.playwright-cli/page-2026-09-23T08-26-03-845Z.yml +0 -126
  129. package/app/.playwright-cli/page-2026-09-23T08-29-44-203Z.png +0 -0
  130. package/app/.playwright-cli/page-2026-09-23T08-35-42-046Z.yml +0 -210
  131. package/app/.playwright-cli/page-2026-09-23T08-36-52-858Z.png +0 -0
  132. package/app/.playwright-cli/page-2026-09-23T08-37-33-938Z.png +0 -0
  133. package/app/.playwright-cli/run-detail-after.png +0 -0
@@ -1,144 +1,144 @@
1
- # -*- coding: utf-8 -*-
2
- """能力维度(4D):按任务类型(writing/coding/reasoning/vision)选模型。
3
-
4
- 设计稿:docs/migration/05-model-seams.md §4D(按 CodeBee 实际架构落地:
5
- 不改 modelhub.py——供应商声明可选 `strengths` 字段即可被识别;
6
- 选择逻辑独立成模块,零侵入)。
7
-
8
- 供应商声明示例(data/models.json 的 providers 条目):
9
- {"id": "p1", ..., "strengths": ["writing", "reasoning"]}
10
- 未声明 strengths 的供应商视为无偏好(只做兜底)。
11
- """
12
- from __future__ import annotations
13
-
14
- import re
15
-
16
- from .dispatch import TYPE_DIMENSIONS
17
-
18
- # 能力维度(先固化清单,schema 见设计稿)
19
- DIMS = ("writing", "coding", "reasoning", "vision")
20
-
21
- # 关键词分类表(覆盖 task type / 目标文本;可按需扩充)
22
- _KEYWORDS = {
23
- "writing": ("写", "文案", "大纲", "连载", "章节", "小说", "营销", "总结", "润色",
24
- "novel", "draft", "review"),
25
- "coding": ("代码", "实现", "修复", "重构", "测试", "bug", "code", "fix",
26
- "refactor", "test", "编译", "报错"),
27
- "reasoning": ("推理", "分析", "调研", "对比", "规划", "拆解", "评审",
28
- "reason", "analyze", "plan", "orchestrate"),
29
- "vision": ("图", "图片", "识别", "视觉", "ocr", "image", "vision", "截图"),
30
- }
31
-
32
-
33
- def classify_task_type(task) -> str:
34
- """把任务分类到 DIMS 之一。task 显式带 task_type 时优先。"""
35
- explicit = str((task or {}).get("task_type") or "").strip().lower()
36
- if explicit in DIMS:
37
- return explicit
38
- preset = str((task or {}).get("type") or "").strip().lower()
39
- if preset in TYPE_DIMENSIONS:
40
- return TYPE_DIMENSIONS[preset]
41
- text = "%s %s" % ((task or {}).get("type") or "",
42
- (task or {}).get("goal") or "")
43
- scores = {}
44
- for dim, kws in _KEYWORDS.items():
45
- scores[dim] = sum(1 for kw in kws if kw in text)
46
- best = max(scores, key=lambda d: scores[d])
47
- if scores[best] > 0:
48
- return best
49
- return "coding" # 默认兜底(CodeBee 主场景)
50
-
51
-
52
- def provider_strengths(prov):
53
- """读供应商声明的能力维度(容错:非法值忽略)。"""
54
- raw = (prov or {}).get("strengths")
55
- if not isinstance(raw, list):
56
- return []
57
- return [s for s in raw if s in DIMS]
58
-
59
-
60
- def pick_by_strength(providers, task_type, *, enabled_only=True):
61
- """按能力维度挑供应商。
62
-
63
- 规则:
64
- 1. 声明了该维度的可用供应商优先(保持原有顺序);
65
- 2. 未声明的排后面(兜底);
66
- 3. 都没有声明时返回原顺序(行为同现状)。
67
- 返回 (排序后的供应商列表, 分类依据说明)。
68
- """
69
- task_type = task_type if task_type in DIMS else classify_task_type({"goal": task_type})
70
- pool = list(providers or [])
71
- if enabled_only:
72
- pool = [p for p in pool if p.get("enabled", True)]
73
- strong = [p for p in pool if task_type in provider_strengths(p)]
74
- rest = [p for p in pool if p not in strong]
75
- ranked = strong + rest
76
- reason = "%s:优先 %s" % (
77
- task_type,
78
- "、".join(p.get("id", "?") for p in strong) if strong else "(无声明,按原序兜底)")
79
- return ranked, reason
80
-
81
-
82
- def resolve_binding_by_task(task, providers, bindings):
83
- """任务 → 绑定解析(能力维度优先,回落 default)。
84
-
85
- bindings 形如 modelhub 的 {"writing": {...}, "coding": {...}, "default": {...}};
86
- 对应维度的绑定缺失/为空时回落 default。返回 (binding, task_type)。
87
- """
88
- tt = classify_task_type(task)
89
- b = (bindings or {}).get(tt)
90
- if not b:
91
- b = (bindings or {}).get("default")
92
- return b, tt
93
-
94
-
95
- # ---------------------------------------------------------------- §07 T3.1 级联
96
-
97
- TIER_ORDER = {"budget": 0, "standard": 1, "premium": 2}
98
-
99
-
100
- def cascade_reorder(agent, tier_of, *, providers=None, pricing=None,
101
- difficulty="easy", task_type="", role=""):
102
- """FrugalGPT 式便宜优先:easy 任务把 call_chain 按 tier 升序稳定重排。
103
-
104
- agent 来自 modelhub.bind_agent(可能带 call_chain);tier_of(chain_entry)
105
- 返回该条目的档位串("budget"/"standard"/"premium"或 None=standard)。
106
- 稳定排序保证同档内保持用户配置的原顺序。链长 <2 或非链式原样返回。
107
- """
108
- chain = (agent or {}).get("call_chain") or []
109
- if len(chain) < 2:
110
- return agent
111
- if providers is not None and (task_type or role):
112
- from .dispatch import rank_model_entries
113
- ranked, _decisions = rank_model_entries(
114
- chain, {p.get("id"): p for p in providers or []},
115
- pricing or {}, difficulty, task_type, role)
116
- out = dict(agent)
117
- out["call_chain"] = ranked
118
- return out
119
-
120
- def key(entry):
121
- return TIER_ORDER.get(tier_of(entry) or "standard", 1)
122
-
123
- out = dict(agent)
124
- out["call_chain"] = sorted(chain, key=key)
125
- return out
126
-
127
-
128
- def make_tier_lookup(providers):
129
- """由 providers 列表构造 chain_entry → tier 的查询函数。
130
-
131
- tier 来源(按优先级):链条目 model 在供应商 models[] 里的 tier 字段 →
132
- 供应商级 tier → None(按 standard 兜底)。缺什么都不抛。
133
- """
134
- by_id = {p.get("id"): p for p in (providers or []) if p.get("id")}
135
-
136
- def tier_of(entry):
137
- p = by_id.get((entry or {}).get("provider_id") or "")
138
- if not p:
139
- return None
140
- for m in (p.get("models") or []):
141
- if isinstance(m, dict) and m.get("name") == (entry or {}).get("model"):
142
- return m.get("tier") or p.get("tier")
143
- return p.get("tier")
144
- return tier_of
1
+ # -*- coding: utf-8 -*-
2
+ """能力维度(4D):按任务类型(writing/coding/reasoning/vision)选模型。
3
+
4
+ 设计稿:docs/migration/05-model-seams.md §4D(按 CodeBee 实际架构落地:
5
+ 不改 modelhub.py——供应商声明可选 `strengths` 字段即可被识别;
6
+ 选择逻辑独立成模块,零侵入)。
7
+
8
+ 供应商声明示例(data/models.json 的 providers 条目):
9
+ {"id": "p1", ..., "strengths": ["writing", "reasoning"]}
10
+ 未声明 strengths 的供应商视为无偏好(只做兜底)。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from .dispatch import TYPE_DIMENSIONS
17
+
18
+ # 能力维度(先固化清单,schema 见设计稿)
19
+ DIMS = ("writing", "coding", "reasoning", "vision")
20
+
21
+ # 关键词分类表(覆盖 task type / 目标文本;可按需扩充)
22
+ _KEYWORDS = {
23
+ "writing": ("写", "文案", "大纲", "连载", "章节", "小说", "营销", "总结", "润色",
24
+ "novel", "draft", "review"),
25
+ "coding": ("代码", "实现", "修复", "重构", "测试", "bug", "code", "fix",
26
+ "refactor", "test", "编译", "报错"),
27
+ "reasoning": ("推理", "分析", "调研", "对比", "规划", "拆解", "评审",
28
+ "reason", "analyze", "plan", "orchestrate"),
29
+ "vision": ("图", "图片", "识别", "视觉", "ocr", "image", "vision", "截图"),
30
+ }
31
+
32
+
33
+ def classify_task_type(task) -> str:
34
+ """把任务分类到 DIMS 之一。task 显式带 task_type 时优先。"""
35
+ explicit = str((task or {}).get("task_type") or "").strip().lower()
36
+ if explicit in DIMS:
37
+ return explicit
38
+ preset = str((task or {}).get("type") or "").strip().lower()
39
+ if preset in TYPE_DIMENSIONS:
40
+ return TYPE_DIMENSIONS[preset]
41
+ text = "%s %s" % ((task or {}).get("type") or "",
42
+ (task or {}).get("goal") or "")
43
+ scores = {}
44
+ for dim, kws in _KEYWORDS.items():
45
+ scores[dim] = sum(1 for kw in kws if kw in text)
46
+ best = max(scores, key=lambda d: scores[d])
47
+ if scores[best] > 0:
48
+ return best
49
+ return "coding" # 默认兜底(CodeBee 主场景)
50
+
51
+
52
+ def provider_strengths(prov):
53
+ """读供应商声明的能力维度(容错:非法值忽略)。"""
54
+ raw = (prov or {}).get("strengths")
55
+ if not isinstance(raw, list):
56
+ return []
57
+ return [s for s in raw if s in DIMS]
58
+
59
+
60
+ def pick_by_strength(providers, task_type, *, enabled_only=True):
61
+ """按能力维度挑供应商。
62
+
63
+ 规则:
64
+ 1. 声明了该维度的可用供应商优先(保持原有顺序);
65
+ 2. 未声明的排后面(兜底);
66
+ 3. 都没有声明时返回原顺序(行为同现状)。
67
+ 返回 (排序后的供应商列表, 分类依据说明)。
68
+ """
69
+ task_type = task_type if task_type in DIMS else classify_task_type({"goal": task_type})
70
+ pool = list(providers or [])
71
+ if enabled_only:
72
+ pool = [p for p in pool if p.get("enabled", True)]
73
+ strong = [p for p in pool if task_type in provider_strengths(p)]
74
+ rest = [p for p in pool if p not in strong]
75
+ ranked = strong + rest
76
+ reason = "%s:优先 %s" % (
77
+ task_type,
78
+ "、".join(p.get("id", "?") for p in strong) if strong else "(无声明,按原序兜底)")
79
+ return ranked, reason
80
+
81
+
82
+ def resolve_binding_by_task(task, providers, bindings):
83
+ """任务 → 绑定解析(能力维度优先,回落 default)。
84
+
85
+ bindings 形如 modelhub 的 {"writing": {...}, "coding": {...}, "default": {...}};
86
+ 对应维度的绑定缺失/为空时回落 default。返回 (binding, task_type)。
87
+ """
88
+ tt = classify_task_type(task)
89
+ b = (bindings or {}).get(tt)
90
+ if not b:
91
+ b = (bindings or {}).get("default")
92
+ return b, tt
93
+
94
+
95
+ # ---------------------------------------------------------------- §07 T3.1 级联
96
+
97
+ TIER_ORDER = {"budget": 0, "standard": 1, "premium": 2}
98
+
99
+
100
+ def cascade_reorder(agent, tier_of, *, providers=None, pricing=None,
101
+ difficulty="easy", task_type="", role=""):
102
+ """FrugalGPT 式便宜优先:easy 任务把 call_chain 按 tier 升序稳定重排。
103
+
104
+ agent 来自 modelhub.bind_agent(可能带 call_chain);tier_of(chain_entry)
105
+ 返回该条目的档位串("budget"/"standard"/"premium"或 None=standard)。
106
+ 稳定排序保证同档内保持用户配置的原顺序。链长 <2 或非链式原样返回。
107
+ """
108
+ chain = (agent or {}).get("call_chain") or []
109
+ if len(chain) < 2:
110
+ return agent
111
+ if providers is not None and (task_type or role):
112
+ from .dispatch import rank_model_entries
113
+ ranked, _decisions = rank_model_entries(
114
+ chain, {p.get("id"): p for p in providers or []},
115
+ pricing or {}, difficulty, task_type, role)
116
+ out = dict(agent)
117
+ out["call_chain"] = ranked
118
+ return out
119
+
120
+ def key(entry):
121
+ return TIER_ORDER.get(tier_of(entry) or "standard", 1)
122
+
123
+ out = dict(agent)
124
+ out["call_chain"] = sorted(chain, key=key)
125
+ return out
126
+
127
+
128
+ def make_tier_lookup(providers):
129
+ """由 providers 列表构造 chain_entry → tier 的查询函数。
130
+
131
+ tier 来源(按优先级):链条目 model 在供应商 models[] 里的 tier 字段 →
132
+ 供应商级 tier → None(按 standard 兜底)。缺什么都不抛。
133
+ """
134
+ by_id = {p.get("id"): p for p in (providers or []) if p.get("id")}
135
+
136
+ def tier_of(entry):
137
+ p = by_id.get((entry or {}).get("provider_id") or "")
138
+ if not p:
139
+ return None
140
+ for m in (p.get("models") or []):
141
+ if isinstance(m, dict) and m.get("name") == (entry or {}).get("model"):
142
+ return m.get("tier") or p.get("tier")
143
+ return p.get("tier")
144
+ return tier_of
@@ -9,6 +9,7 @@ from __future__ import annotations
9
9
 
10
10
  import copy
11
11
  import json
12
+ import os
12
13
  import re
13
14
  import sys
14
15
  import threading
@@ -430,7 +431,12 @@ def load(force=False):
430
431
  entries = json.loads(paths.CATALOG_FILE.read_text(encoding="utf-8"))
431
432
  except Exception:
432
433
  entries = copy.deepcopy(DEFAULT_CATALOG)
433
- _merge_new_defaults(entries)
434
+ # TUTTI_TEST_NO_DEFAULT_CATALOG:e2e 测试隔离开关——种盘的 catalog.json
435
+ # 就是全部条目。默认合并会把真实 CLI 条目带进测试服务,一键升级这类
436
+ # 「遍历全 catalog」的接口会把真机的 npm/winget 升级真跑一遍(2026-09-26
437
+ # e2e_upgrade_all 实弹案:codex 被真升)。
438
+ if not os.environ.get("TUTTI_TEST_NO_DEFAULT_CATALOG"):
439
+ _merge_new_defaults(entries)
434
440
  _apply_resume_patch(entries)
435
441
  _apply_launch_patch(entries)
436
442
  _apply_config_patch(entries)
@@ -1,32 +1,32 @@
1
- # -*- coding: utf-8 -*-
2
- """章节安全落盘(tmp+原子改名,inkos 安全章节工作区借鉴)。
3
-
4
- 写一半崩溃/磁盘满不会留下半章正文冒充成稿——断点续跑按「文件够长」
5
- 判定,半文件会被误当合法稿复用;.tmp 写完 os.replace 原子落位,
6
- 失败清理残渣后原样抛出。路径守卫用 pathlib resolve+parents 惯用法
7
- (同 _ms_io/_inside 口径)。pipeline._write_chapter 委托此函数。"""
8
- from __future__ import annotations
9
-
10
- from pathlib import Path
11
-
12
-
13
- def atomic_write_chapter(workdir, i, text):
14
- """第 i 章安全落盘:tmp 写入 → 原子改名。返回最终路径。"""
15
- root = Path(workdir).resolve()
16
- p = (root / ("chapter-%02d.md" % int(i))).resolve()
17
- # 守卫:目标必须在 workdir 之内且不得是 workdir 本身(".." 作 workdir
18
- # 时 resolve 到父目录,p 仍是其中一章——但那不是调用方的工作目录,
19
- # 一并拒绝:workdir 必须是已存在的目录)
20
- if root not in p.parents or not root.is_dir():
21
- raise ValueError("章节路径越界: chapter-%02d.md" % int(i))
22
- tmp = Path(str(p) + ".tmp")
23
- try:
24
- tmp.write_text(str(text), encoding="utf-8", errors="replace")
25
- tmp.replace(p)
26
- except BaseException:
27
- try:
28
- tmp.unlink(missing_ok=True)
29
- except OSError:
30
- pass
31
- raise
32
- return p
1
+ # -*- coding: utf-8 -*-
2
+ """章节安全落盘(tmp+原子改名,inkos 安全章节工作区借鉴)。
3
+
4
+ 写一半崩溃/磁盘满不会留下半章正文冒充成稿——断点续跑按「文件够长」
5
+ 判定,半文件会被误当合法稿复用;.tmp 写完 os.replace 原子落位,
6
+ 失败清理残渣后原样抛出。路径守卫用 pathlib resolve+parents 惯用法
7
+ (同 _ms_io/_inside 口径)。pipeline._write_chapter 委托此函数。"""
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+
13
+ def atomic_write_chapter(workdir, i, text):
14
+ """第 i 章安全落盘:tmp 写入 → 原子改名。返回最终路径。"""
15
+ root = Path(workdir).resolve()
16
+ p = (root / ("chapter-%02d.md" % int(i))).resolve()
17
+ # 守卫:目标必须在 workdir 之内且不得是 workdir 本身(".." 作 workdir
18
+ # 时 resolve 到父目录,p 仍是其中一章——但那不是调用方的工作目录,
19
+ # 一并拒绝:workdir 必须是已存在的目录)
20
+ if root not in p.parents or not root.is_dir():
21
+ raise ValueError("章节路径越界: chapter-%02d.md" % int(i))
22
+ tmp = Path(str(p) + ".tmp")
23
+ try:
24
+ tmp.write_text(str(text), encoding="utf-8", errors="replace")
25
+ tmp.replace(p)
26
+ except BaseException:
27
+ try:
28
+ tmp.unlink(missing_ok=True)
29
+ except OSError:
30
+ pass
31
+ raise
32
+ return p