femo-plugin 1.0.1 → 1.0.2

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 (217) hide show
  1. package/FEMO_logo.svg +55 -0
  2. package/FEMO_logo_slogan.svg +29 -0
  3. package/_tmp/fallback/driver2.py +176 -0
  4. package/_tmp/fallback/events.jsonl +108 -0
  5. package/_tmp/fallback/gateway_ui.py +325 -0
  6. package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +1 -0
  7. package/_tmp/fallback/outbox/r1.done +1 -0
  8. package/_tmp/fallback/outbox/r2.done +1 -0
  9. package/_tmp/fallback/outbox/r3.done +1 -0
  10. package/_tmp/fallback/outbox/r4.done +1 -0
  11. package/_tmp/fallback/outbox/r5.done +1 -0
  12. package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +3 -2
  13. package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +112 -9
  14. package/hostAdapter/dshAdapter/client/client-ui/styles.ts +17 -0
  15. package/hostAdapter/dshAdapter/client/fa-icons.tsx +3 -0
  16. package/hostAdapter/dshAdapter/host/engine-events.ts +4 -1
  17. package/hostAdapter/dshAdapter/host/index.ts +5 -0
  18. package/hostAdapter/dshAdapter/host/preset-install.ts +59 -0
  19. package/hostAdapter/dshAdapter/host/projection-input.ts +14 -6
  20. package/hostAdapter/dshAdapter/lib/client.js +124 -5
  21. package/hostAdapter/dshAdapter/lib/client.js.map +3 -3
  22. package/hostAdapter/dshAdapter/lib/index.js +58 -18
  23. package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
  24. package/hostAdapter/dshAdapter/package.json +1 -5
  25. package/hostAdapter/dshAdapter/preset/agent.cordis.yml +220 -0
  26. package/hostAdapter/dshAdapter/preset/preset.yml +3 -0
  27. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +1 -0
  28. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +3 -0
  29. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +10 -0
  30. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +11 -0
  31. package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +11 -0
  32. package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -0
  33. package/hostAdapter/zcodeAdapter/README.md +61 -0
  34. package/hostAdapter/zcodeAdapter/commands/femo.md +9 -0
  35. package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +23 -0
  36. package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +201 -0
  37. package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +635 -0
  38. package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +9 -0
  39. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +4 -0
  40. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +156 -0
  41. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +69 -0
  42. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +1515 -0
  43. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +437 -0
  44. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +77 -0
  45. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +555 -0
  46. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +163 -0
  47. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +1 -0
  48. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +56 -0
  49. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
  50. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +247 -0
  51. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +308 -0
  52. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +198 -0
  53. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +35 -0
  54. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +278 -0
  55. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +163 -0
  56. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +396 -0
  57. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +2468 -0
  58. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +3630 -0
  59. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +209 -0
  60. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +1 -0
  61. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +86 -0
  62. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +441 -0
  63. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +485 -0
  64. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +401 -0
  65. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +68 -0
  66. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +767 -0
  67. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +126 -0
  68. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +402 -0
  69. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +544 -0
  70. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +19 -0
  71. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +113 -0
  72. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +686 -0
  73. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +567 -0
  74. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +303 -0
  75. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +157 -0
  76. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +245 -0
  77. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
  78. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
  79. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
  80. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo +38 -0
  81. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +29 -0
  82. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
  83. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +70 -0
  84. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +23 -0
  85. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
  86. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
  87. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
  88. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
  89. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
  90. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
  91. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
  92. package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +393 -0
  93. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +3 -0
  94. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +16 -0
  95. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +59 -0
  96. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +3 -0
  97. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +3 -0
  98. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +3 -0
  99. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
  100. package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
  101. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +192 -0
  102. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +258 -0
  103. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +429 -0
  104. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +163 -0
  105. package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +294 -0
  106. package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +93 -0
  107. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +26 -0
  108. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +157 -0
  109. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +107 -0
  110. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +111 -0
  111. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +107 -0
  112. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +130 -0
  113. package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +144 -0
  114. package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +5 -0
  115. package/hostAdapter/zcodeAdapter/femo-zcode-dist//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
  116. package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
  117. package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +3 -0
  118. package/hostAdapter/zcodeAdapter/hooks/hooks.json +16 -0
  119. package/hostAdapter/zcodeAdapter/hooks/lib.mjs +59 -0
  120. package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +3 -0
  121. package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +3 -0
  122. package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +3 -0
  123. package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +192 -0
  124. package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +258 -0
  125. package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +429 -0
  126. package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +163 -0
  127. package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +294 -0
  128. package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +93 -0
  129. package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +26 -0
  130. package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +157 -0
  131. package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +107 -0
  132. package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +111 -0
  133. package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +107 -0
  134. package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +130 -0
  135. package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +144 -0
  136. package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +5 -0
  137. package/hostAdapter/zcodeAdapter//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
  138. package/package.json +1 -1
  139. package/scripts/diag-find-redblue.mjs +38 -0
  140. package/scripts/diag-god-log.mjs +31 -0
  141. package/scripts/diag-god-log2.mjs +39 -0
  142. package/scripts/diag-god-log3.mjs +35 -0
  143. package/scripts/diag-god-log4.mjs +59 -0
  144. package/scripts/diag-god-log4b.mjs +39 -0
  145. package/scripts/diag-redblue-god.mjs +39 -0
  146. package/scripts/diag-redblue-log.mjs +37 -0
  147. package/scripts/diag-redblue-span.mjs +41 -0
  148. package/scripts/diag-stage-1017.mjs +63 -0
  149. package/scripts/dump_session.py +36 -0
  150. package/scripts/link-workspace.ps1 +51 -0
  151. package/scripts/list_souls.py +18 -0
  152. package/scripts/probe-composer-refresh.mjs +197 -0
  153. package/scripts/seed_story_souls.py +86 -0
  154. package/scripts/sync-zcode-dist.ps1 +55 -0
  155. package/scripts/theme-tokenize/color-extract.txt +288 -0
  156. package/scripts/theme-tokenize/round1-quoted.ps1 +149 -0
  157. package/scripts/theme-tokenize/round2-bare.ps1 +138 -0
  158. package/scripts/theme-tokenize/round3-shape.ps1 +110 -0
  159. package/tests/_diag_r4_join.femo +32 -0
  160. package/tests/conftest.py +95 -0
  161. package/tests/diag-subagent-dir-3081.mjs +101 -0
  162. package/tests/femoGenerator.test.mjs +3909 -0
  163. package/tests/femoParser.test.mjs +4813 -0
  164. package/tests/femogen_notice.test.mjs +109 -0
  165. package/tests/femoparser_validation.test.mjs +84 -0
  166. package/tests/main-delivery-queue.test.mjs +329 -0
  167. package/tests/pre-step-gate.test.mjs +282 -0
  168. package/tests/read-subagent-model.mjs +24 -0
  169. package/tests/run-script-tests.py +97 -0
  170. package/tests/safe-steer.test.mjs +59 -0
  171. package/tests/strip_comments.test.mjs +164 -0
  172. package/tests/test_actor_failed.py +92 -0
  173. package/tests/test_compile_warnings.py +99 -0
  174. package/tests/test_debug_log_bus.py +108 -0
  175. package/tests/test_debugger_module_mode.py +141 -0
  176. package/tests/test_error_buckets.py +117 -0
  177. package/tests/test_error_dispatcher.py +261 -0
  178. package/tests/test_exec_ai_retry.py +155 -0
  179. package/tests/test_exec_human_retry.py +159 -0
  180. package/tests/test_file_resolve.py +104 -0
  181. package/tests/test_flow_events.py +311 -0
  182. package/tests/test_flow_ref_validation.py +92 -0
  183. package/tests/test_func_dict_fallback.py +39 -0
  184. package/tests/test_job_lifecycle.py +236 -0
  185. package/tests/test_job_manager.py +424 -0
  186. package/tests/test_mind.py +99 -0
  187. package/tests/test_module_call_args.py +258 -0
  188. package/tests/test_module_visibility.py +238 -0
  189. package/tests/test_notice.py +143 -0
  190. package/tests/test_out_whitelist.py +83 -0
  191. package/tests/test_par_if_dispatch.py +64 -0
  192. package/tests/test_par_nested_for.py +78 -0
  193. package/tests/test_parser.py +494 -0
  194. package/tests/test_pause.py +102 -0
  195. package/tests/test_pause_contract.py +135 -0
  196. package/tests/test_protocol_transcript.py +158 -0
  197. package/tests/test_scope_self.py +202 -0
  198. package/tests/test_source_validate.py +113 -0
  199. package/tests/test_task_world.py +447 -0
  200. package/tests/test_town_structure.py +70 -0
  201. package/tests/test_v2_checkpoint.py +115 -0
  202. package/tests/test_v2_env.py +383 -0
  203. package/tests/test_v2_evaluator.py +227 -0
  204. package/tests/test_v2_join.py +315 -0
  205. package/tests/test_v2_join_wiring.py +429 -0
  206. package/tests/test_v2_merge.py +167 -0
  207. package/tests/test_v2_model.py +143 -0
  208. package/tests/test_v2_resume_e2e.py +472 -0
  209. package/tests/test_var_decls.py +271 -0
  210. package/tests/verify-model-functions.mjs +90 -0
  211. package/tests/verify-subagent-model-3081.mjs +153 -0
  212. package//346/226/275/345/267/245/346/270/205/345/215/225/node-notice-/346/226/275/345/267/245/346/270/205/345/215/225.md +395 -0
  213. package//346/226/275/345/267/245/346/270/205/345/215/225//344/270/244/344/270/252/345/276/205/350/247/243/345/206/263/347/232/204/351/227/256/351/242/230.MD +66 -0
  214. package//346/226/275/345/267/245/346/270/205/345/215/225//345/201/234/346/255/242/351/223/276/344/277/256/345/244/215-/346/226/275/345/267/245/346/270/205/345/215/225.md +475 -0
  215. package//346/226/275/345/267/245/346/270/205/345/215/225//345/217/230/351/207/217/344/270/216task/347/263/273/347/273/237/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225-v2.md +847 -0
  216. package//346/226/275/345/267/245/346/270/205/345/215/225//350/277/220/350/241/214/347/212/266/346/200/201/351/223/276/350/267/257/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225v4.md +654 -0
  217. package//346/226/275/345/267/245/346/270/205/345/215/225//351/224/231/350/257/257/346/263/250/345/205/245/347/273/255/350/201/212-/346/226/275/345/267/245/346/270/205/345/215/225.md +471 -0
@@ -0,0 +1,2468 @@
1
+ """
2
+ FEMO Parser v5.0 — 两阶段解析器
3
+ 阶段1: 缩进块切割 (Block Builder)
4
+ 阶段2: 语义分发 (Block Evaluator) + Flow 子解析
5
+ 所有解析结果数据类及条件求值工具均在此文件。
6
+
7
+ 代码原则:所有代码不许写try静默兜底不报错,有错必须报错。
8
+
9
+ TODO(2026-09-03 拍板,日后做,与变量系统重构无关):
10
+ 编译期拦截递归 module——flow 图上检测 module 直接/间接调用自身。
11
+ 当前按"已拦好"的假设设计(变量系统帧键 = 模块名#task_id,同 task
12
+ 递归同模块在运行期帧键撞键自然 fail loud);日后 Parser 拦截落地
13
+ 后两边就都连上了。
14
+ """
15
+
16
+ import re
17
+ import ast
18
+ import os
19
+ import keyword
20
+ from dataclasses import dataclass, field
21
+ from typing import List, Optional, Dict, Any, Tuple, Callable, Set
22
+ from enum import Enum
23
+ from femoCompiler.FEMO_config import get_db_path
24
+ from femoCompiler import host_manifest
25
+ from femoBridges.getDir.get_dir import get_user_dir
26
+ from femoCompiler.vars.model import ScopeTable, build_scope_table
27
+
28
+ # ============================================================
29
+ # 1. 基础枚举与数据类(保持不变,从旧文件迁移)
30
+ # ============================================================
31
+
32
+ # ── 全局保留字段:用于解析时判断多行块结束 ──
33
+ _TOP_KEYWORDS = (
34
+ 'meta:', 'vars:', 'code:', 'actors:',
35
+ 'action ', 'module ', 'flow:', 'mainflow:',
36
+ 'memory ', 'context ',
37
+ )
38
+ _FIELD_KEYWORDS = (
39
+ 'prompt:', 'showprompt:', 'memory:', 'context:', 'scope:',
40
+ 'out:', 'in:', 'fallback:', 'resolve:',
41
+ 'interrupt:', 'timeout:', 'max_tries:',
42
+ )
43
+
44
+
45
+ class ExecutorType(Enum):
46
+ AI = "ai"
47
+ HUMAN = "human"
48
+ FUNC = "func"
49
+ ASSIGN = "assign"
50
+ MIND = "mind"
51
+ NOTICE = "notice"
52
+
53
+ class ActorType(Enum):
54
+ AI = "ai"
55
+ HUMAN = "human"
56
+ BLUEPRINT = "blueprint"
57
+
58
+ class OutType(Enum):
59
+ STRING = "string"
60
+ TEXT = "text"
61
+ BOOL = "bool"
62
+ INT = "int"
63
+ FLOAT = "float"
64
+ ARRAY = "array"
65
+ OBJECT = "object"
66
+ DROPDOWN = "dropdown"
67
+ ENUM = "enum"
68
+ ACTOR = "actor"
69
+ ASSIGN = "assign"
70
+
71
+ @dataclass(frozen=True)
72
+ class ActorRef:
73
+ name: str
74
+ attribute: Optional[str] = None
75
+ def __repr__(self):
76
+ return f"@{self.name}" + (f".{self.attribute}" if self.attribute else "")
77
+
78
+ @dataclass(frozen=True)
79
+ class VarRef:
80
+ name: str
81
+ def __repr__(self): return f"{{{self.name}}}"
82
+
83
+ @dataclass(frozen=True)
84
+ class DynamicActorRef:
85
+ var_name: str
86
+ def __repr__(self): return f"@{{{self.var_name}}}"
87
+
88
+ @dataclass
89
+ class ActorDef:
90
+ type: ActorType
91
+ ref: str
92
+ name: str
93
+ soul: Optional[str] = None
94
+ source: Optional[str] = None
95
+ tools: List[str] = field(default_factory=list)
96
+ # tools: true/false 布尔开关(None = 剧本未声明,交由宿主默认决定);
97
+ # tools: [name, ...] 仍走 tools 列表(白名单)。
98
+ tools_enabled: Optional[bool] = None
99
+ # thinking: <档位> 思考档位(词汇集见 host_manifest,解析期校验);
100
+ # None = 剧本未声明 → 请求不带 reasoning_effort(剥离继承后落到
101
+ # 部署默认档位/提供方默认,语义同宿主模型选择器的 Default 项)。
102
+ thinking: Optional[str] = None
103
+ is_blueprint: bool = False
104
+
105
+ @dataclass
106
+ class InMapping:
107
+ local_name: str
108
+ global_expr: str
109
+ bare: bool = False # 裸项(缺 "= 变量表达式" 映射)——编译期报错用(2026-09-07)
110
+
111
+ @dataclass
112
+ class OutDef:
113
+ var_name: str
114
+ dynamic_key: Optional[str] = None
115
+ out_type: OutType = OutType.STRING
116
+ label: str = ""
117
+ choices: Optional[str] = None
118
+
119
+ @dataclass
120
+ class ActionDef:
121
+ name: str
122
+ executor_type: ExecutorType
123
+ executor_param: str
124
+ as_actor: Optional[str] = None
125
+ prompt: Optional[str] = None
126
+ showprompt: Optional[str] = None
127
+ scope: str = "" # 现在存原始字符串,如 "[@God, @Diana] + my_list"
128
+ in_mappings: List[InMapping] = field(default_factory=list)
129
+ outs: List[OutDef] = field(default_factory=list)
130
+ resolve: Optional[str] = None
131
+ max_retries: int = 0
132
+ fallback: Optional[str] = None
133
+ memory: Optional[str] = None
134
+ context: Optional[str] = None
135
+ interrupt: Optional[Any] = None
136
+ resolve_args: List[str] = field(default_factory=list)
137
+
138
+ @dataclass
139
+ class MethodDef:
140
+ name: str
141
+ module_alias: str
142
+ func_name: str
143
+ in_params: List[str] = field(default_factory=list)
144
+ out_defs: List[OutDef] = field(default_factory=list)
145
+
146
+ @dataclass
147
+ class FlowNode:
148
+ id: str
149
+ type: str = "action"
150
+ label: str = ""
151
+ action_name: Optional[str] = None
152
+ module_ref: Optional[str] = None
153
+ meta: Dict[str, Any] = field(default_factory=dict)
154
+ extra_actions: List[str] = field(default_factory=list)
155
+ def __post_init__(self):
156
+ if not self.label:
157
+ self.label = self.id
158
+
159
+ @dataclass
160
+ class FlowEdge:
161
+ source: str
162
+ target: str
163
+ condition: str = ""
164
+
165
+ @dataclass
166
+ class FlowGraph:
167
+ nodes: Dict[str, FlowNode] = field(default_factory=dict)
168
+ edges: List[FlowEdge] = field(default_factory=list)
169
+
170
+ @property
171
+ def entry(self) -> str:
172
+ # 优先使用 [START] 或 [IN] 节点
173
+ for special in ('[START]', '[IN]'):
174
+ if special in self.nodes:
175
+ return special
176
+ targets = {e.target for e in self.edges}
177
+ for nid in self.nodes:
178
+ if nid not in targets:
179
+ return nid
180
+ return ""
181
+
182
+ def add_node(self, node: FlowNode):
183
+ if node.id not in self.nodes:
184
+ self.nodes[node.id] = node
185
+
186
+ def add_edge(self, src, tgt, condition=""):
187
+ if src and tgt and src != tgt:
188
+ # 同 (src, tgt, condition) 只注册一条。for/par 的出口行接另一个
189
+ # 控制块时(`-> [A] -> [B] -> for ...:`),解析器会经「出口行
190
+ # 预解析的 tail」与「主循环 ctrl_match 的 pre_tail」两条路径触达
191
+ # 同一条链,重复边会被 _execute_flow 的多出边 fork 语义扇出成
192
+ # 两个分支、下游节点双跑(2026-09-12 实锤:模块内投票 6 票跑成
193
+ # 10 票)。真正的多分支语义靠不同 target 表达。
194
+ for e in self.edges:
195
+ if e.source == src and e.target == tgt and e.condition == condition:
196
+ return
197
+ self.edges.append(FlowEdge(source=src, target=tgt, condition=condition))
198
+
199
+ @dataclass
200
+ class ModuleDef:
201
+ name: str
202
+ params: List[str] = field(default_factory=list)
203
+ locals: Dict[str, Any] = field(default_factory=dict)
204
+ actions: Dict[str, ActionDef] = field(default_factory=dict)
205
+ modules: Dict[str, 'ModuleDef'] = field(default_factory=dict) # 嵌套子模块
206
+ memories: Dict[str, MethodDef] = field(default_factory=dict)
207
+ contexts: Dict[str, MethodDef] = field(default_factory=dict)
208
+ flow: Optional[FlowGraph] = None
209
+ meta: Dict[str, Any] = field(default_factory=dict)
210
+
211
+ @dataclass
212
+ class Script:
213
+ meta: Dict[str, Any] = field(default_factory=dict)
214
+ vars: Dict[str, Any] = field(default_factory=dict)
215
+ # 变量声明注册表(步骤 B,2026-09-04):声明/词法可见域/初值装配的单一
216
+ # 权威,由 build_scope_table 从 script.vars + 各模块 vars(书写嵌套)建成
217
+ scope_table: Optional[ScopeTable] = None
218
+ code: Dict[str, str] = field(default_factory=dict)
219
+ actors: Dict[str, ActorDef] = field(default_factory=dict)
220
+ actions: Dict[str, ActionDef] = field(default_factory=dict)
221
+ modules: Dict[str, ModuleDef] = field(default_factory=dict)
222
+ memories: Dict[str, MethodDef] = field(default_factory=dict)
223
+ contexts: Dict[str, MethodDef] = field(default_factory=dict)
224
+ flow: Optional[FlowGraph] = None
225
+ # 编译期 warning 收集(2026-09-07 warning 桶):校验器对「值得作者知道但
226
+ # 不阻断」的观察在此累积({'where': 位置, 'message': 提示}),parse_script
227
+ # 照常返回 Script;随 check/job_start 回执上浮宿主。真正的错误仍 raise。
228
+ warnings: List[Dict[str, str]] = field(default_factory=list)
229
+
230
+ # ============================================================
231
+ # 2. 块切割器 (Block Builder)
232
+ # ============================================================
233
+
234
+ @dataclass
235
+ class Block:
236
+ type: str # 'meta', 'vars', 'action', 'module', 'flow', ...
237
+ header: str # 原始头行
238
+ indent: int
239
+ daughters: List['Block'] = field(default_factory=list)
240
+ content_lines: List[str] = field(default_factory=list) # 自身内容行(不含子块)
241
+
242
+ def _strip_comment(line: str) -> str:
243
+ in_str, qc = False, None
244
+ i = 0
245
+ while i < len(line):
246
+ c = line[i]
247
+ if in_str:
248
+ if c == qc:
249
+ in_str = False
250
+ else:
251
+ if c in ('"', "'"):
252
+ in_str, qc = True, c
253
+ elif c == '#':
254
+ return line[:i].rstrip()
255
+ elif line[i:i+2] == '//':
256
+ return line[:i].rstrip()
257
+ i += 1
258
+ return line
259
+
260
+ def normalize_symbols(line: str) -> str:
261
+ """只对 FEMO 语法行替换中文符号,不影响文本内容。
262
+ 注意:-- -> -> 不在全局替换(文档约定仅 flow/mainflow 区等价,由 eval_flow 单独做)。"""
263
+ line = line.replace(':', ':').replace(',', ',')
264
+ line = line.replace('“', '"').replace('”', '"')
265
+ line = line.replace('(', '(').replace(')', ')')
266
+ line = line.replace('【', '[').replace('】', ']')
267
+ line = line.replace('|', '|')
268
+ return line
269
+
270
+ def _is_blank_or_comment(line: str) -> bool:
271
+ s = line.strip()
272
+ return s == '' or s.startswith('#') or s.startswith('//')
273
+
274
+ def _indent_of(line: str) -> int:
275
+ return len(line) - len(line.lstrip())
276
+
277
+ def _detect_type(line: str) -> str:
278
+ s = line.strip()
279
+ s = s.replace(':', ':') # 中文冒号等价
280
+ if s.startswith('meta:'): return 'meta'
281
+ if s.startswith('vars:'): return 'vars'
282
+ if s.startswith('code:'): return 'code'
283
+ if s.startswith('actors:'): return 'actors'
284
+ if re.match(r'^module\s+\w+', s): return 'module'
285
+ if re.match(r'^action\s+', s): return 'action'
286
+ if re.match(r'^memory\s+', s): return 'memory'
287
+ if re.match(r'^context\s+', s): return 'context'
288
+ if s.startswith('flow:') or s.startswith('mainflow:'): return 'flow'
289
+ return 'unknown'
290
+
291
+ def _find_multiline_ranges(lines: List[str]) -> List[Tuple[int, int]]:
292
+ """找出多行文本块的行区间 [start, end):prompt: | / showprompt: | / key = |。
293
+ 键名前缀支持 @ / $@ / $(D 收尾 2026-09-05 补:$x = | 多行初值此前不被
294
+ 识别,块内注释豁免失效会剥坏内容——与前端 femoParser.jsx 同形对齐)。
295
+ 块内注释豁免(# 和 // 是文本内容)。"""
296
+ ranges = []
297
+ i = 0
298
+ n = len(lines)
299
+ while i < n:
300
+ m = re.match(
301
+ r'^\s*(?:(?:prompt|showprompt):\s*[||]|(?:@|\$@|\$)?[\w\u4e00-\u9fff]+\s*=\s*[||])\s*(?:#.*)?$',
302
+ lines[i],
303
+ )
304
+ if m:
305
+ base = len(lines[i]) - len(lines[i].lstrip())
306
+ j = i + 1
307
+ while j < n:
308
+ if not lines[j].strip():
309
+ j += 1
310
+ continue # 空行算块内容
311
+ if len(lines[j]) - len(lines[j].lstrip()) <= base:
312
+ break # 缩进回到字段层 → 块结束
313
+ j += 1
314
+ ranges.append((i + 1, j))
315
+ i = j
316
+ continue
317
+ i += 1
318
+ return ranges
319
+
320
+ def build_blocks(text: str, base_indent: int = 0) -> List[Block]:
321
+ """将脚本文本按缩进切分为块树,支持模块递归"""
322
+ raw_lines = text.split('\n')
323
+ prompt_ranges = _find_multiline_ranges(raw_lines)
324
+ lines = []
325
+ for idx, raw in enumerate(raw_lines):
326
+ if any(s <= idx < e for s, e in prompt_ranges):
327
+ # prompt 块内:原样保留(注释豁免,不剥 # //)
328
+ content = raw.strip()
329
+ if content:
330
+ indent = len(raw) - len(raw.lstrip())
331
+ lines.append((indent, content))
332
+ continue
333
+ stripped = raw.rstrip()
334
+ if _is_blank_or_comment(stripped):
335
+ continue
336
+ indent = len(raw) - len(raw.lstrip())
337
+ content = _strip_comment(raw).strip()
338
+ lines.append((indent, content))
339
+
340
+ blocks: List[Block] = []
341
+ i = 0
342
+ while i < len(lines):
343
+ indent, content = lines[i]
344
+ if indent < base_indent:
345
+ break
346
+ btype = _detect_type(content)
347
+ header = content
348
+ block = Block(type=btype, header=header, indent=indent)
349
+
350
+ if btype == 'module':
351
+ inner_lines = []
352
+ j = i + 1
353
+ while j < len(lines) and lines[j][0] > indent:
354
+ inner_lines.append(lines[j])
355
+ j += 1
356
+ if inner_lines:
357
+ # 相对缩进:子行缩进 - 当前行缩进 - 1(保证至少1个空格)
358
+ inner_text = '\n'.join(
359
+ ' ' * max(0, il[0] - indent - 1) + il[1]
360
+ for il in inner_lines
361
+ )
362
+ block.daughters = build_blocks(inner_text, base_indent=0)
363
+ blocks.append(block)
364
+ i = j
365
+ else:
366
+ j = i + 1
367
+ while j < len(lines) and lines[j][0] > indent:
368
+ # 保留原始缩进(空格 + 内容),多行文本依赖此缩进判断
369
+ original_line = ' ' * lines[j][0] + lines[j][1]
370
+ block.content_lines.append(original_line)
371
+ j += 1
372
+ blocks.append(block)
373
+ i = j
374
+
375
+ return blocks
376
+
377
+ # ============================================================
378
+ # 3. 语义分发器 (Block Evaluator) — 辅助函数
379
+ # ============================================================
380
+
381
+ def _parse_value(s: str) -> Any:
382
+ s = s.strip()
383
+ if s.startswith('[') and s.endswith(']'):
384
+ inner = s[1:-1].strip()
385
+ if not inner:
386
+ return []
387
+ items = _split_br(inner)
388
+ return [_parse_value(it.strip()) for it in items]
389
+ if s.startswith('{') and s.endswith('}'):
390
+ inner = s[1:-1].strip()
391
+ if not inner:
392
+ return {} # 空字典
393
+ # 非空字典:逐个键值对解析
394
+ d = {}
395
+ for pair in _split_br(inner):
396
+ if ':' in pair:
397
+ k, v = pair.split(':', 1)
398
+ key = _parse_dict_key(k.strip())
399
+ d[key] = _parse_value(v.strip())
400
+ return d
401
+ if (s.startswith('"') and s.endswith('"')) or (s.startswith("'") and s.endswith("'")):
402
+ return s[1:-1]
403
+ if s == 'true':
404
+ return True
405
+ if s == 'false':
406
+ return False
407
+ if s.startswith('@{') and s.endswith('}'):
408
+ return s # 动态引用原样保留
409
+ if s.startswith('@'):
410
+ return s # ActorRef 字符串表示
411
+ try:
412
+ if '.' in s:
413
+ return float(s)
414
+ return int(s)
415
+ except ValueError:
416
+ return s
417
+
418
+ def _parse_dict_key(k: str) -> Any:
419
+ if (k.startswith('"') and k.endswith('"')) or (k.startswith("'") and k.endswith("'")):
420
+ k = k[1:-1]
421
+ if k.startswith('@'):
422
+ return ActorRef(k[1:].split('.')[0], k[1:].split('.')[1] if '.' in k[1:] else None)
423
+ return k
424
+
425
+ def _split_br(s: str) -> List[str]:
426
+ items, depth, cur = [], 0, []
427
+ in_str, qc = False, None
428
+ for c in s:
429
+ if in_str:
430
+ cur.append(c)
431
+ if c == qc:
432
+ in_str = False
433
+ else:
434
+ if c in ('"', "'"):
435
+ in_str, qc = True, c
436
+ cur.append(c)
437
+ elif c in ('[', '{', '('):
438
+ depth += 1
439
+ cur.append(c)
440
+ elif c in (']', '}', ')'):
441
+ depth -= 1
442
+ cur.append(c)
443
+ elif c == ',' and depth == 0:
444
+ items.append(''.join(cur))
445
+ cur = []
446
+ else:
447
+ cur.append(c)
448
+ if cur:
449
+ items.append(''.join(cur))
450
+ return items
451
+
452
+ def _eval_kv_block(lines: List[str]) -> Dict[str, Any]:
453
+ d = {}
454
+ i = 0
455
+ while i < len(lines):
456
+ line = lines[i]
457
+ # 归一化当前行(可能影响等号、引号等),但保留原始行用于多行文本
458
+ norm_line = normalize_symbols(line)
459
+ if '=' in norm_line:
460
+ k, v = norm_line.split('=', 1)
461
+ k, v = k.strip(), v.strip()
462
+
463
+ # ---- 特殊处理 owner 字段:始终保留为字符串列表 ----
464
+ if k == 'owner':
465
+ raw_v = v.strip()
466
+ # 去掉外层方括号(如果有),否则保留原值
467
+ if raw_v.startswith('[') and raw_v.endswith(']'):
468
+ inner = raw_v[1:-1].strip()
469
+ else:
470
+ inner = raw_v
471
+ if not inner:
472
+ d[k] = []
473
+ else:
474
+ # 支持中文逗号、顿号,全部替换为英文逗号
475
+ inner = inner.replace(',', ',').replace('、', ',')
476
+ items = _split_br(inner)
477
+ d[k] = [it.strip().strip('"').strip("'") for it in items]
478
+ i += 1
479
+ continue
480
+ # ---- 其他键正常处理 ----
481
+
482
+ if v == '|':
483
+ i += 1
484
+ v_lines = []
485
+ # 多行文本内容不进行符号归一化,保留原样
486
+ while i < len(lines) and (lines[i].startswith(' ') or lines[i].startswith('\t')):
487
+ v_lines.append(lines[i].strip())
488
+ i += 1
489
+ v = '\n'.join(v_lines)
490
+ d[k] = v
491
+ continue
492
+ d[k] = _parse_value(v.strip())
493
+ i += 1
494
+ return d
495
+
496
+ def _parse_tools(s: str) -> List[str]:
497
+ s = s.strip()
498
+ if s.startswith('[') and s.endswith(']'):
499
+ inner = s[1:-1].strip()
500
+ if not inner:
501
+ return []
502
+ return [t.strip().strip('"').strip("'") for t in inner.split(',')]
503
+ return []
504
+
505
+
506
+ # thinking 档位词汇(A2.1 解耦):这里是内置缺省(standalone 自圆满),
507
+ # 运行期以宿主清单 host_manifest.thinking_levels() 为准——清单由接口侧
508
+ # 提供(--host-manifest),换 harness 换清单文件,引擎零改动。无 default——
509
+ # 「默认」由「不带 thinking 声明」表达(语义同宿主模型选择器的 Default 项)。
510
+ # 另接受显式 `default` 值:解析期归一化为未声明,与不传字段完全等效。
511
+ THINKING_LEVELS = host_manifest.DEFAULT_THINKING_LEVELS
512
+
513
+
514
+ def _parse_thinking(s: str) -> str:
515
+ """actor 的 thinking 档位:小写归一 + 词汇校验,非法直接编译报错
516
+ (fail loud,不静默透传给网关)。`default` 显式值 ≡ 未声明(返回空串,
517
+ 上游按「无 thinking 声明」处理,效果与不传字段完全一致)。"""
518
+ v = s.strip().strip('"').strip("'").lower()
519
+ if v == 'default':
520
+ return ''
521
+ levels = host_manifest.thinking_levels()
522
+ if v not in levels:
523
+ raise ValueError(
524
+ f"thinking 档位不合法: {v!r}(允许: default/{'/'.join(levels)})")
525
+ return v
526
+
527
+
528
+ def _parse_out_multi(s: str) -> List[OutDef]:
529
+ s = s.strip().rstrip(',').strip()
530
+ if not s:
531
+ return []
532
+ items = _split_br(s)
533
+ result = []
534
+ for item in items:
535
+ item = item.strip()
536
+ if not item:
537
+ continue
538
+ # 赋值形式($ 前缀 shared 变量同样支持:$x -= 1 / $@选中的人 = @某)
539
+ m = re.match(r'^([\w\[\].$]+)\s*([+\-]?=)\s*(.+)$', item)
540
+ if m:
541
+ var_name = m.group(1)
542
+ op = m.group(2)
543
+ value = m.group(3).strip()
544
+ result.append(OutDef(var_name=f"{var_name} {op} {value}", out_type=OutType.ASSIGN, label=""))
545
+ continue
546
+ # 函数调用形式(字符类含 $/@:$var(string, "标签") / dict.@key(string))
547
+ pm = re.match(r'^([$\w.{}@]+)\(([^)]*)\)', item)
548
+ if pm:
549
+ full_name, params_str = pm.group(1), pm.group(2)
550
+ if '.' in full_name:
551
+ parts = full_name.split('.', 1)
552
+ var_name, dynamic_key = parts[0], parts[1]
553
+ else:
554
+ var_name, dynamic_key = full_name, None
555
+ out_type, label, choices = OutType.STRING, "", None
556
+ params = _split_br(params_str)
557
+ positional_idx = 0
558
+ for p in params:
559
+ p = p.strip()
560
+ if p.startswith('choices='):
561
+ choices = p[len('choices='):].strip()
562
+ elif p.startswith('label='):
563
+ label = p[len('label='):].strip().strip('"').strip("'")
564
+ else:
565
+ if positional_idx == 0:
566
+ try:
567
+ out_type = OutType(p.lower())
568
+ except:
569
+ pass
570
+ elif positional_idx == 1:
571
+ label = p.strip().strip('"').strip("'")
572
+ positional_idx += 1
573
+ result.append(OutDef(var_name=var_name, dynamic_key=dynamic_key,
574
+ out_type=out_type, label=label, choices=choices))
575
+ continue
576
+ # 纯变量名
577
+ result.append(OutDef(var_name=item, out_type=OutType.STRING, label=""))
578
+ return result
579
+
580
+
581
+
582
+ def _parse_action_fields(block: Block) -> dict:
583
+ f = {
584
+ 'prompt': None, 'showprompt': None,
585
+ 'scope': [], 'in_mappings': [], 'outs': [],
586
+ 'resolve': None, 'max_retries': 0, 'fallback': None,
587
+ 'memory': None, 'context': None, 'interrupt': None,
588
+ }
589
+ lines = block.content_lines
590
+ i = 0
591
+ while i < len(lines):
592
+ line = lines[i].strip()
593
+ # 对语法行进行符号归一化,但保留原始行用于提取 prompt 文本
594
+ normalized_line = normalize_symbols(line)
595
+ if normalized_line.startswith('prompt:'):
596
+ pv = normalized_line[len('prompt:'):].strip()
597
+ # 支持中文竖线(|)作为多行标志
598
+ if pv in ('|', '|'):
599
+ base_indent = len(lines[i]) - len(lines[i].lstrip())
600
+ j = i + 1
601
+ plines = []
602
+ while j < len(lines):
603
+ line_j = lines[j]
604
+ stripped = line_j.lstrip()
605
+ indent = len(line_j) - len(stripped)
606
+ # 同缩进 + 二级字段关键字 → 结束
607
+ if indent == base_indent and any(stripped.startswith(k) for k in _FIELD_KEYWORDS):
608
+ break
609
+ # 缩进小于等于当前缩进,且是一级关键字 → 结束
610
+ if indent <= base_indent and any(stripped.startswith(k) for k in _TOP_KEYWORDS):
611
+ break
612
+ # 否则属于 prompt 内容
613
+ plines.append(line_j.strip())
614
+ j += 1
615
+ f['prompt'] = '\n'.join(plines)
616
+ i = j
617
+ continue
618
+ else:
619
+ f['prompt'] = pv.strip('"').strip("'")
620
+ elif normalized_line.startswith('showprompt:'):
621
+ pv = normalized_line[len('showprompt:'):].strip()
622
+ # 支持中文竖线(|)作为多行标志
623
+ if pv in ('|', '|'):
624
+ base_indent = len(lines[i]) - len(lines[i].lstrip())
625
+ j = i + 1
626
+ plines = []
627
+ while j < len(lines):
628
+ line_j = lines[j]
629
+ stripped = line_j.lstrip()
630
+ indent = len(line_j) - len(stripped)
631
+ # 同缩进 + 二级字段关键字 → 结束
632
+ if indent == base_indent and any(stripped.startswith(k) for k in _FIELD_KEYWORDS):
633
+ break
634
+ # 缩进小于等于当前缩进,且是一级关键字 → 结束
635
+ if indent <= base_indent and any(stripped.startswith(k) for k in _TOP_KEYWORDS):
636
+ break
637
+ # 否则属于 prompt 内容
638
+ plines.append(line_j.strip())
639
+ j += 1
640
+ f['showprompt'] = '\n'.join(plines)
641
+ i = j
642
+ continue
643
+ else:
644
+ f['showprompt'] = pv.strip('"').strip("'")
645
+ elif normalized_line.startswith('scope:'):
646
+ # 保留原始 scope 字符串,去掉 'scope:' 前缀并去除两端空白
647
+ raw_scope = line.strip()[len('scope:'):].strip()
648
+ f['scope'] = raw_scope
649
+ elif normalized_line.startswith('in:'):
650
+ rest = normalized_line[len('in:'):].strip()
651
+ if not rest:
652
+ base_indent = len(lines[i]) - len(lines[i].lstrip())
653
+ j = i + 1
654
+ mappings = []
655
+ while j < len(lines):
656
+ line_j = lines[j]
657
+ stripped = line_j.lstrip()
658
+ indent = len(line_j) - len(stripped)
659
+ # 同缩进 + 二级字段关键字 → 结束
660
+ if indent == base_indent and any(stripped.startswith(k) for k in _FIELD_KEYWORDS):
661
+ break
662
+ # 缩进小于等于当前缩进,且是一级关键字 → 结束
663
+ if indent <= base_indent and any(stripped.startswith(k) for k in _TOP_KEYWORDS):
664
+ break
665
+ # 处理映射行
666
+ mline = line_j.strip().rstrip(',')
667
+ if '=' in mline:
668
+ k, v = mline.split('=', 1)
669
+ mappings.append(InMapping(k.strip(), v.strip()))
670
+ else:
671
+ mappings.append(InMapping(mline, mline, bare=True))
672
+ j += 1
673
+ f['in_mappings'] = mappings
674
+ i = j
675
+ continue
676
+ else:
677
+ for mapping_str in rest.split(','):
678
+ mapping_str = mapping_str.strip()
679
+ if '=' in mapping_str:
680
+ k, v = mapping_str.split('=', 1)
681
+ f['in_mappings'].append(InMapping(k.strip(), v.strip()))
682
+ else:
683
+ f['in_mappings'].append(InMapping(mapping_str, mapping_str, bare=True))
684
+ elif normalized_line.startswith('out:'):
685
+ out_rest = normalized_line[len('out:'):].strip()
686
+ base_indent = len(lines[i]) - len(lines[i].lstrip())
687
+ j = i + 1
688
+ # 首行(若有内容)+ 后续缩进续行统一收集:
689
+ # out: x += 1 (单行 + 续行)
690
+ # y = {} (缩进续行,同样生效)
691
+ # out: (纯多行模式,首行无内容)
692
+ if out_rest:
693
+ f['outs'].extend(_parse_out_multi(out_rest))
694
+ while j < len(lines):
695
+ line_j = lines[j]
696
+ stripped = line_j.lstrip()
697
+ indent = len(line_j) - len(stripped)
698
+ # 同缩进 + 二级字段关键字 → 结束
699
+ if indent == base_indent and any(stripped.startswith(k) for k in _FIELD_KEYWORDS):
700
+ break
701
+ # 缩进小于等于当前缩进,且是一级关键字 → 结束
702
+ if indent <= base_indent and any(stripped.startswith(k) for k in _TOP_KEYWORDS):
703
+ break
704
+ ol = normalize_symbols(lines[j].strip())
705
+ if ol:
706
+ f['outs'].extend(_parse_out_multi(ol))
707
+ j += 1
708
+ i = j
709
+ continue
710
+ elif line.startswith('resolve:'):
711
+ raw = line[len('resolve:'):].strip()
712
+ m = re.match(r'^(\S+)\(([^)]*)\)$', raw)
713
+ if m:
714
+ f['resolve'] = m.group(1).strip()
715
+ f['resolve_args'] = [a.strip() for a in m.group(2).split(',') if a.strip()]
716
+ else:
717
+ f['resolve'] = raw
718
+ f['resolve_args'] = []
719
+ elif line.startswith('max_retries:'):
720
+ try:
721
+ f['max_retries'] = int(line[len('max_retries:'):].strip())
722
+ except:
723
+ pass
724
+ elif line.startswith('fallback:'):
725
+ f['fallback'] = line[len('fallback:'):].strip()
726
+ elif line.startswith('memory:'):
727
+ f['memory'] = line[len('memory:'):].strip()
728
+ elif line.startswith('context:'):
729
+ f['context'] = line[len('context:'):].strip()
730
+ elif line.startswith('interrupt:'):
731
+ f['interrupt'] = line[len('interrupt:'):].strip()
732
+ i += 1
733
+ return f
734
+
735
+ # ============================================================
736
+ # 语义分发器 — 各类型 evaluator
737
+ # ============================================================
738
+
739
+ def eval_meta(block: Block) -> Dict[str, Any]:
740
+ return _eval_kv_block(block.content_lines)
741
+
742
+ def eval_vars(block: Block) -> Dict[str, Any]:
743
+ d = _eval_kv_block(block.content_lines)
744
+ def normalize(v):
745
+ if isinstance(v, dict):
746
+ return {normalize(k): normalize(val) for k, val in v.items()}
747
+ if isinstance(v, list):
748
+ return [normalize(item) for item in v]
749
+ if isinstance(v, ActorRef):
750
+ return str(v)
751
+ return v
752
+ return {k: normalize(v) for k, v in d.items()}
753
+
754
+ def eval_code(block: Block) -> Dict[str, str]:
755
+ d = {}
756
+ for line in block.content_lines:
757
+ if '=' in line:
758
+ k, v = line.split('=', 1)
759
+ k = k.strip()
760
+ v = v.strip()
761
+ if (v.startswith('"') and v.endswith('"')) or (v.startswith("'") and v.endswith("'")):
762
+ v = v[1:-1]
763
+ d[k] = v
764
+ return d
765
+
766
+ def eval_actors(block: Block) -> Dict[str, ActorDef]:
767
+ actors = {}
768
+ lines = block.content_lines
769
+ i = 0
770
+ while i < len(lines):
771
+ line = lines[i].strip()
772
+ bm = re.match(r'^(?:blueprint\s+|@)(\w+)\s*:\s*$', line)
773
+ if bm:
774
+ name = bm.group(1)
775
+ attrs = {}
776
+ j = i + 1
777
+ while j < len(lines) and lines[j].startswith(' '):
778
+ al = lines[j].strip()
779
+ if '=' in al:
780
+ ak, av = al.split('=', 1)
781
+ ak, av = ak.strip(), av.strip().strip('"').strip("'")
782
+ if ak == 'tools':
783
+ av_l = av.strip()
784
+ if av_l in ('true', 'false'):
785
+ attrs['tools_enabled'] = av_l == 'true'
786
+ else:
787
+ attrs['tools'] = _parse_tools(av)
788
+ if not attrs['tools']:
789
+ # 显式空白名单 [] ≡ 明确禁用(tools_enabled=False)。
790
+ # 与「不写 tools」(tools_enabled=None,宿主默认全开)
791
+ # 严格区分——否则 ai_request 载荷无法区分两者
792
+ # (2026-09-12 语义修正)。
793
+ attrs['tools_enabled'] = False
794
+ elif ak == 'thinking':
795
+ attrs['thinking'] = _parse_thinking(av)
796
+ elif ak in ('soul', 'source'):
797
+ attrs[ak] = av # 保持字符串,不转数字
798
+ else:
799
+ attrs[ak] = av
800
+ j += 1
801
+ actors[name] = ActorDef(type=ActorType.BLUEPRINT, ref=name, name=name,
802
+ source=attrs.get('source'), tools=attrs.get('tools', []),
803
+ tools_enabled=attrs.get('tools_enabled'),
804
+ thinking=attrs.get('thinking'),
805
+ is_blueprint=True)
806
+ i = j
807
+ continue
808
+ if '=' in line:
809
+ left, rest = line.split('=', 1)
810
+ left_parts = left.strip().split()
811
+ if len(left_parts) >= 2 and left_parts[0] in ('ai', 'human'):
812
+ ats = left_parts[0]
813
+ nm = left_parts[1]
814
+ at = ActorType.AI if ats == 'ai' else ActorType.HUMAN
815
+ soul, source, tools, tools_enabled, thinking = None, None, [], None, None
816
+ for p in _split_br(rest):
817
+ p = p.strip()
818
+ if p.startswith('soul:'):
819
+ raw_soul = p[5:].strip().strip('"').strip("'")
820
+ soul = raw_soul if raw_soul else None
821
+ #print(f"[DEBUG eval_actors] raw_soul={raw_soul!r}, final soul={soul!r}")
822
+ elif p.startswith('source:'):
823
+ source = p[7:].strip().strip('"').strip("'")
824
+ #print(f"[DEBUG eval_actors] source={source!r}")
825
+ elif p.startswith('thinking:'):
826
+ thinking = _parse_thinking(p[len('thinking:'):])
827
+ elif p.startswith('thinking ='):
828
+ thinking = _parse_thinking(p[len('thinking ='):])
829
+ elif p.startswith('tools:'):
830
+ raw_tools = p[6:].strip()
831
+ if raw_tools in ('true', 'false'):
832
+ tools_enabled = raw_tools == 'true'
833
+ else:
834
+ tools = _parse_tools(raw_tools)
835
+ if not tools:
836
+ tools_enabled = False # 显式空列表 [] ≡ 明确禁用(≠ 不写)
837
+ elif p.startswith('tools ='):
838
+ raw_tools = p[len('tools ='):].strip()
839
+ if raw_tools in ('true', 'false'):
840
+ tools_enabled = raw_tools == 'true'
841
+ else:
842
+ tools = _parse_tools(raw_tools)
843
+ if not tools:
844
+ tools_enabled = False # 显式空列表 [] ≡ 明确禁用(≠ 不写)
845
+ actors[nm] = ActorDef(type=at, ref=nm, name=nm, soul=soul, source=source,
846
+ tools=tools, tools_enabled=tools_enabled, thinking=thinking)
847
+ #print(f"[DEBUG eval_actors] 创建 human actor: {nm}, soul={soul!r}, source={source!r}")
848
+ else:
849
+ # 裸 actor:`ai @名`(无 `=`、无属性)→ soul/source 缺省(soul 非必须;
850
+ # 无 soul 角色 = 无角色设定的裸执行者,上下文见 ContextExample 全可见语义)。
851
+ left_parts = line.strip().split()
852
+ if len(left_parts) >= 2 and left_parts[0] in ('ai', 'human'):
853
+ ats, nm = left_parts[0], left_parts[1]
854
+ at = ActorType.AI if ats == 'ai' else ActorType.HUMAN
855
+ actors[nm] = ActorDef(type=at, ref=nm, name=nm, soul=None, source=None,
856
+ tools=[], tools_enabled=None)
857
+ i += 1
858
+ return actors
859
+
860
+ def eval_action(block: Block) -> ActionDef:
861
+ header = normalize_symbols(block.header)
862
+ m = re.match(r'^action\s+(\w+)\s+@(\w+)(?:\(([^)]*)\))?\s*(?:as\s*\(([^)]*)\))?\s*:\s*$', header)
863
+ if not m:
864
+ raise ValueError(f"无法解析 action 头部: {header}")
865
+ name = m.group(1)
866
+ etype = m.group(2)
867
+ eparam = (m.group(3) or '').strip()
868
+ as_actor = m.group(4)
869
+ fields = _parse_action_fields(block)
870
+ return ActionDef(
871
+ name=name,
872
+ executor_type=ExecutorType(etype),
873
+ executor_param=eparam,
874
+ as_actor=as_actor,
875
+ **fields
876
+ )
877
+
878
+ def eval_method(block: Block) -> MethodDef:
879
+ header = normalize_symbols(block.header)
880
+ m = re.match(r'^(memory|context)\s+(\w+)\s*\(\s*(\w+)\.(\w+)\s*\)\s*:\s*$', header)
881
+ if not m:
882
+ raise ValueError(f"无法解析 method 头部: {header}")
883
+ name = m.group(2)
884
+ module_alias = m.group(3)
885
+ func_name = m.group(4)
886
+ in_params = []
887
+ out_defs = []
888
+ lines = block.content_lines
889
+ i = 0
890
+ while i < len(lines):
891
+ line = lines[i].strip()
892
+ if line.startswith('in:'):
893
+ rest = line[3:].strip()
894
+ if rest:
895
+ in_params = [p.strip() for p in rest.split(',') if p.strip()]
896
+ else:
897
+ i += 1
898
+ while i < len(lines) and lines[i].startswith(' '):
899
+ pl = lines[i].strip().rstrip(',')
900
+ if pl:
901
+ in_params.append(pl)
902
+ i += 1
903
+ continue
904
+ elif line.startswith('out:'):
905
+ rest = line[4:].strip()
906
+ if rest:
907
+ out_defs = _parse_out_multi(rest)
908
+ else:
909
+ i += 1
910
+ out_lines = []
911
+ while i < len(lines) and lines[i].startswith(' '):
912
+ out_lines.append(lines[i].strip())
913
+ i += 1
914
+ if out_lines:
915
+ out_defs = _parse_out_multi(' '.join(out_lines))
916
+ continue
917
+ i += 1
918
+ return MethodDef(name=name, module_alias=module_alias, func_name=func_name,
919
+ in_params=in_params, out_defs=out_defs)
920
+
921
+ # ============================================================
922
+ # 4. Flow 子解析 (原 FlowBuilder 完整移植)
923
+ # ============================================================
924
+
925
+ # ---- 缩进树构建 (为 flow 内部使用) ----
926
+ @dataclass
927
+ class IndentBlock:
928
+ indent: int
929
+ line: str
930
+ daughters: List['IndentBlock'] = field(default_factory=list)
931
+
932
+ def build_indent_tree(text: str) -> List[IndentBlock]:
933
+ """把 flow 文本按缩进解析成一棵树,忽略空行和注释"""
934
+ lines = []
935
+ for raw in text.split('\n'):
936
+ stripped = raw.rstrip()
937
+ if not stripped or stripped.lstrip().startswith('#') or stripped.lstrip().startswith('//'):
938
+ continue
939
+ indent = len(raw) - len(raw.lstrip())
940
+ content = raw.strip()
941
+ lines.append((indent, content))
942
+
943
+ if not lines:
944
+ return []
945
+
946
+ root_blocks: List[IndentBlock] = []
947
+ stack: List[Tuple[int, List[IndentBlock]]] = [(-1, root_blocks)]
948
+
949
+ for indent, content in lines:
950
+ block = IndentBlock(indent=indent, line=content)
951
+ while stack[-1][0] >= indent:
952
+ stack.pop()
953
+ stack[-1][1].append(block)
954
+ stack.append((indent, block.daughters))
955
+
956
+ return root_blocks
957
+
958
+ # ---- Token 解析器 ----
959
+ def tokenize_chain(line: str) -> List[dict]:
960
+ """解析一条 -> 链式行,支持嵌套括号的条件表达式"""
961
+ line = re.sub(r'(?<!\s)--(?!\s)', '->', line)
962
+ content = re.sub(r'^->\s*', '', line)
963
+
964
+ conds = []
965
+ # 使用 Python 编译器安全地提取 if (...) 中的完整表达式
966
+ def extract_conditions(s):
967
+ parts = []
968
+ i = 0
969
+ while i < len(s):
970
+ if s.startswith('if', i):
971
+ j = i + 2
972
+ while j < len(s) and s[j].isspace():
973
+ j += 1
974
+ if j < len(s) and s[j] == '(':
975
+ # 找到匹配的右括号
976
+ start = j
977
+ depth = 1
978
+ j += 1
979
+ while j < len(s) and depth > 0:
980
+ if s[j] == '(':
981
+ depth += 1
982
+ elif s[j] == ')':
983
+ depth -= 1
984
+ j += 1
985
+ if depth == 0:
986
+ expr = s[start+1:j-1].strip()
987
+ conds.append(expr)
988
+ parts.append(f'__COND_{len(conds)-1}__')
989
+ i = j
990
+ continue
991
+ parts.append(s[i])
992
+ i += 1
993
+ return ''.join(parts)
994
+
995
+ protected = extract_conditions(content)
996
+
997
+ parts = re.split(r'\s*->\s*', protected)
998
+ parts = [p.strip() for p in parts if p.strip()]
999
+
1000
+ tokens = []
1001
+ for part in parts:
1002
+ cond_match = re.match(r'^__COND_(\d+)__$', part)
1003
+ if cond_match:
1004
+ idx = int(cond_match.group(1))
1005
+ tokens.append({'type': 'cond', 'expr': conds[idx]})
1006
+ elif part == '[END]':
1007
+ tokens.append({'type': 'node', 'name': '[END]', 'ntype': 'end'})
1008
+ elif part == '[BREAK]':
1009
+ tokens.append({'type': 'node', 'name': '[BREAK]', 'ntype': 'break'})
1010
+ else:
1011
+ if part in ('for', 'par', 'fork', 'join', 'to'):
1012
+ raise SyntaxError(f"控制关键字 '{part}' 不能出现在普通链中")
1013
+ tokens.append({'type': 'node', 'name': part, 'ntype': 'action'})
1014
+ return tokens
1015
+
1016
+ def chain_tokens(g: FlowGraph, tokens: List[dict], entry: str, reg_node_fn, reg_auto_fn) -> str:
1017
+ """处理一条 token 链,返回链尾节点ID"""
1018
+ current = entry if entry is not None else None
1019
+ pending_cond = None
1020
+
1021
+ for tok in tokens:
1022
+ if tok['type'] == 'cond':
1023
+ pending_cond = tok['expr']
1024
+ elif tok['type'] == 'node':
1025
+ name = tok['name']
1026
+ if re.match(r'^\[.+\]', name):
1027
+ # 正式节点
1028
+ nid = reg_node_fn(g, name, tok.get('ntype', 'action'))
1029
+ g.add_edge(current, nid, condition=pending_cond or "")
1030
+ pending_cond = None
1031
+ current = nid
1032
+ else:
1033
+ raise SyntaxError(f"未声明的动作或模块 '{name}',请在 flow 前用 [节点]: 语法定义。")
1034
+
1035
+ return current
1036
+
1037
+ def _split_module_ref(ref: str) -> Tuple[str, Optional[str]]:
1038
+ """module_ref → (模块名, 参数原文)。'Name(a, b)' → ('Name', 'a, b');
1039
+ 'Outer.Inner(x)' → ('Outer.Inner', 'x');'Name' → ('Name', None)。
1040
+ 模块名允许点路径(嵌套模块完整路径)。运行时 _run_module 的拆参共用
1041
+ 本函数(单一事实源,两处正则曾各自为政导致点路径带参拆参失败):
1042
+ 编译期只校验模块名,参数原文由运行时求值入帧。"""
1043
+ raw = (ref or '').strip()
1044
+ m = re.match(r'^([\w\u4e00-\u9fff]+(?:\.[\w\u4e00-\u9fff]+)*)\s*\((.*)\)$', raw, re.S)
1045
+ if m:
1046
+ return m.group(1), m.group(2)
1047
+ return raw, None
1048
+
1049
+ def validate_flow_refs(
1050
+ flow: FlowGraph,
1051
+ known_actions: Dict[str, Any],
1052
+ known_modules: Optional[Dict[str, Any]],
1053
+ where: str,
1054
+ ) -> None:
1055
+ """校验 flow 中节点绑定的 action/module 均已声明。
1056
+
1057
+ 背景(2026-08-18):标准化器(FEMO_normalizer._replace_bare_in_fragment)把
1058
+ 任意裸 token 无条件替换成 [节点] 绑定,不校验是否已声明——裸名引用未声明的
1059
+ action 因此能混过编译,运行时才炸。解析器必须兜底:裸名引用必须是已声明的
1060
+ action/module;空节点([名字] 无绑定)合法。
1061
+ module 绑定允许带参(&Name(args))与点路径(&Outer.Inner)——剥参后只
1062
+ 校验模块名,参数原文由运行时 _run_module 求值入帧。known_modules 传
1063
+ None 时跳过模块校验(mainflow 的模块引用由 parse_script 尾部后置校验,
1064
+ 含嵌套点路径且不受块书写顺序影响)。"""
1065
+ if flow is None:
1066
+ return
1067
+ for node in flow.nodes.values():
1068
+ if node.action_name and node.action_name not in known_actions:
1069
+ raise SyntaxError(
1070
+ f"{where} 中引用了未声明的动作 '{node.action_name}'(节点 {node.id})。"
1071
+ f"裸名引用必须是已声明的 action;空节点请写 [名字](不绑定动作)。"
1072
+ )
1073
+ if node.module_ref and known_modules is not None:
1074
+ ref_name, _args = _split_module_ref(node.module_ref)
1075
+ if ref_name not in known_modules:
1076
+ raise SyntaxError(
1077
+ f"{where} 中引用了未声明的模块 '{node.module_ref}'(节点 {node.id})。"
1078
+ )
1079
+
1080
+
1081
+ def _collect_module_paths(mods: Dict[str, 'ModuleDef'], prefix: str,
1082
+ out: Dict[str, 'ModuleDef']) -> None:
1083
+ """收集全部嵌套模块的完整点路径('Outer.Inner')→ 定义。mainflow 点路径
1084
+ 直引内层模块的编译期可见集(运行时 _run_module 的点路径通道自
1085
+ 2026-09-12 起支持,此处对齐)。"""
1086
+ for name, mod in (mods or {}).items():
1087
+ path = f'{prefix}.{name}' if prefix else name
1088
+ out[path] = mod
1089
+ _collect_module_paths(mod.modules or {}, path, out)
1090
+
1091
+
1092
+ def validate_module_flows(mod: ModuleDef, script: 'Script',
1093
+ inherited_actions: Optional[List[Dict[str, Any]]] = None,
1094
+ inherited_modules: Optional[List[Dict[str, Any]]] = None) -> None:
1095
+ """递归校验模块 flow 的引用。
1096
+
1097
+ action 可见域与变量词法链同构(拍板 6):本模块 actions + 祖先链模块
1098
+ actions + 全局 script.actions——运行时 _execute_node_content 按
1099
+ 「模块帧 actions 优先、script.actions 兜底」查找(模块帧初值由
1100
+ _run_module/_flow_for_stack 沿 mod_path 词法链合并),校验域必须与之
1101
+ 对齐,不能比运行时更严。
1102
+ module 可见域走同一条词法链:全局 module + 全部嵌套点路径 + 祖先链
1103
+ 各层声明的直接子模块(兄弟互调 &InnerA 即母层声明的名字)+ 本模块
1104
+ 直接子模块。运行时 _run_module 沿定义链由内向外逐层解析,内外同名时
1105
+ 内层(更近祖先)胜出。兄弟的 action 仍不可见——它不是祖先声明的名字。"""
1106
+ visible: Dict[str, Any] = dict(script.actions)
1107
+ for layer in (inherited_actions or []):
1108
+ visible.update(layer)
1109
+ visible.update(mod.actions)
1110
+ if mod.flow is not None:
1111
+ known_modules = dict(script.modules)
1112
+ _collect_module_paths(script.modules, '', known_modules)
1113
+ for layer in (inherited_modules or []):
1114
+ known_modules.update(layer)
1115
+ known_modules.update(mod.modules)
1116
+ validate_flow_refs(
1117
+ mod.flow,
1118
+ visible,
1119
+ known_modules,
1120
+ f"module {mod.name}",
1121
+ )
1122
+ sub_chain_actions = (inherited_actions or []) + [mod.actions]
1123
+ sub_chain_modules = (inherited_modules or []) + [mod.modules]
1124
+ for sub in mod.modules.values():
1125
+ validate_module_flows(sub, script, sub_chain_actions, sub_chain_modules)
1126
+
1127
+
1128
+ # ---- 安全条件求值 ----
1129
+ def eval_condition(expr: str, context: dict) -> bool:
1130
+ """安全求值 Python 表达式,供运行时和流程图解析使用"""
1131
+ safe_expr = re.sub(r'@(\w+)', r'"@\1"', expr)
1132
+ try:
1133
+ tree = ast.parse(safe_expr, mode='eval')
1134
+ except SyntaxError:
1135
+ raise SyntaxError(f"条件表达式语法错误: {expr} -> 解析为 '{safe_expr}'")
1136
+
1137
+ safe_builtins = {
1138
+ 'True': True, 'False': False, 'None': None,
1139
+ 'len': len, 'int': int, 'str': str, 'float': float,
1140
+ 'bool': bool, 'abs': abs, 'min': min, 'max': max,
1141
+ 'sum': sum, 'any': any, 'all': all,
1142
+ 'isinstance': isinstance, 'hasattr': hasattr,
1143
+ 'list': list, 'dict': dict, 'set': set, 'tuple': tuple,
1144
+ 'range': range, 'enumerate': enumerate,
1145
+ }
1146
+
1147
+ namespace = {**safe_builtins, **context}
1148
+ try:
1149
+ result = eval(compile(tree, '<cond>', 'eval'), {"__builtins__": {}}, namespace)
1150
+ return bool(result)
1151
+ except Exception as e:
1152
+ raise RuntimeError(f"条件表达式求值失败: '{expr}', 上下文: {list(context.keys())}, 错误: {e}")
1153
+
1154
+ # ---- FlowBuilder 主类 ----
1155
+ class FlowBuilder:
1156
+ def __init__(self):
1157
+ self._counter = 0
1158
+ self.node_bindings: Dict[str, str] = {} # 节点绑定表 {节点名: 动作或&模块}
1159
+
1160
+ def _next_id(self, prefix: str) -> str:
1161
+ self._counter += 1
1162
+ return f"__{prefix}_{self._counter}__"
1163
+
1164
+ def _reg_auto_node(self, g: FlowGraph, action_ref: str) -> str:
1165
+ """为裸动作或模块引用自动创建节点,自动处理重名(后缀 _1, _2 ...)"""
1166
+ if action_ref.startswith('&'):
1167
+ base_label = action_ref # e.g. "&MD"
1168
+ module_ref = action_ref[1:]
1169
+ action_name = None
1170
+ else:
1171
+ base_label = action_ref
1172
+ module_ref = None
1173
+ action_name = action_ref
1174
+
1175
+ node_id = f'[{base_label}]'
1176
+ counter = 1
1177
+ while node_id in g.nodes:
1178
+ node_id = f'[{base_label}_{counter}]'
1179
+ counter += 1
1180
+
1181
+ node = FlowNode(
1182
+ id=node_id, type='action', label=base_label,
1183
+ action_name=action_name, module_ref=module_ref,
1184
+ )
1185
+ g.add_node(node)
1186
+ return node_id
1187
+
1188
+ def _reg_node(self, g: FlowGraph, name: str, ntype: str = "action") -> str:
1189
+ m = re.match(r'^\[([^\]]+)\]', name)
1190
+ if m:
1191
+ node_id = f'[{m.group(1)}]'
1192
+ label = m.group(1)
1193
+ rest = name[m.end():].lstrip(':')
1194
+ else:
1195
+ raise ValueError(f"不能将裸动作/模块注册为节点: {name}")
1196
+
1197
+ if node_id in g.nodes:
1198
+ return node_id
1199
+
1200
+ action_name = None
1201
+ module_ref = None
1202
+ # 优先从绑定字典获取(标准化器提供的声明区信息)
1203
+ node_key = m.group(1) # 节点名(不含方括号)
1204
+ binding = self.node_bindings.get(node_key, '')
1205
+ if binding:
1206
+ if binding.startswith('&'):
1207
+ module_ref = binding[1:]
1208
+ else:
1209
+ action_name = binding
1210
+ elif rest:
1211
+ rest = rest.strip()
1212
+ if rest.startswith('&'):
1213
+ module_ref = rest[1:]
1214
+ else:
1215
+ action_name = rest
1216
+
1217
+ if node_id in ('[START]', '[END]', '[BREAK]', '[IN]', '[OUT]'):
1218
+ special_map = {
1219
+ '[START]': 'start', '[END]': 'end', '[BREAK]': 'break',
1220
+ '[IN]': 'start', '[OUT]': 'end',
1221
+ }
1222
+ ntype = special_map.get(node_id, ntype)
1223
+
1224
+ node = FlowNode(
1225
+ id=node_id, type=ntype, label=label,
1226
+ action_name=action_name, module_ref=module_ref,
1227
+ )
1228
+ g.add_node(node)
1229
+ return node_id
1230
+
1231
+ def _reg_gateway(self, g: FlowGraph, prefix: str, ntype: str, meta: dict = None) -> str:
1232
+ gid = self._next_id(prefix)
1233
+ g.add_node(FlowNode(id=gid, type=ntype, meta=meta or {}))
1234
+ return gid
1235
+
1236
+
1237
+ def build_flow(self, text: str) -> FlowGraph:
1238
+ blocks = build_indent_tree(text)
1239
+ g = FlowGraph()
1240
+ self._pending_exit_candidates = {} # 临时存储 for/par 的出口候选,供出口行连接
1241
+ self._parse_flow_blocks(blocks, g, None)
1242
+ return g
1243
+
1244
+ def _parse_flow_blocks(self, blocks: List[IndentBlock], g: FlowGraph, pending_from: Optional[str]):
1245
+ """递归解析顶层或嵌套的流程块列表"""
1246
+ i = 0
1247
+ while i < len(blocks):
1248
+ block = blocks[i]
1249
+ line = block.line.strip()
1250
+
1251
+ # ── 出口行 `-> Target` ──
1252
+ if line.startswith('->') and not re.search(r'\b(for|par|fork|join)\b', line):
1253
+ # 孤立出口行不允许,除非是由外部 for/par 消费
1254
+ raise SyntaxError(f"孤立的出口行,只能紧跟在 for/par 块之后消费: {line}")
1255
+
1256
+ # ── join(...): 独立行(无前导链) ──
1257
+ if re.match(r'^join\s*(?:\((\w+)\))?\s*:\s*$', line):
1258
+ join_gw = self.parse_join(block, g)
1259
+ # 检查下一个同级块是否为 'to Target' 出口行(支持链:to [X]:ref -> [Y])
1260
+ if i + 1 < len(blocks):
1261
+ next_line = blocks[i + 1].line.strip()
1262
+ if next_line.startswith('to '):
1263
+ target_str = next_line[3:].strip()
1264
+ target_id = self.parse_single_chain(target_str, join_gw, g)
1265
+ pending_from = target_id if target_id is not None else join_gw
1266
+ i += 2
1267
+ continue
1268
+ pending_from = join_gw
1269
+ i += 1
1270
+ continue
1271
+
1272
+ # ── 控制块首行 [Node] -> for/par/fork/join ──
1273
+ ctrl_match = re.match(r'^(.+?)\s*->\s*(for|par|fork|join)\b(.*):\s*$', line)
1274
+ if ctrl_match:
1275
+ ctrl_type = ctrl_match.group(2)
1276
+ if ctrl_type == 'for':
1277
+ # 提取变量和迭代器
1278
+ params = ctrl_match.group(3).strip()
1279
+ var_m = re.match(r'(@?\w+)\s+in\s+(.+)', params)
1280
+ if not var_m:
1281
+ raise SyntaxError(f"for 语法错误: {line}")
1282
+ var_name = var_m.group(1)
1283
+ iterable = var_m.group(2)
1284
+ loop_gw = self._reg_gateway(g, "for", "gateway",
1285
+ meta={"gw_kind": "for", "var_name": var_name, "iterable": iterable})
1286
+ pre_tail = self.parse_single_chain(ctrl_match.group(1).strip(), None, g)
1287
+ if pre_tail:
1288
+ g.add_edge(pre_tail, loop_gw)
1289
+ # 处理 for 体
1290
+ nested, plain = self._separate_nested_blocks(block.daughters)
1291
+ exit_candidates = self._process_inner_single_lines(plain, loop_gw, g)
1292
+ for nest_block in nested:
1293
+ self._process_nested_control_block(nest_block, g)
1294
+ # 检查下一个同级块是否为出口行(支持链:-> [X]:ref -> [Y];
1295
+ # 若出口行同时是控制块入口(-> [A] -> [B] -> fork:),
1296
+ # 链部分建出口边,控制块行留给主循环处理)
1297
+ target_id = None
1298
+ if i + 1 < len(blocks):
1299
+ next_line = blocks[i + 1].line.strip()
1300
+ if next_line.startswith('->'):
1301
+ m_ctrl = re.search(r'\s*->\s*(for|par|fork|join)\b', next_line)
1302
+ if m_ctrl:
1303
+ chain_part = next_line[2:m_ctrl.start()].strip()
1304
+ if chain_part:
1305
+ head = self.parse_single_chain(chain_part.split('->', 1)[0].strip(), None, g)
1306
+ tail = self.parse_single_chain(chain_part, None, g)
1307
+ target_id = head if head is not None else tail
1308
+ pending_from = tail if tail is not None else target_id
1309
+ # 不消费该行:主循环会处理 -> ... -> fork: 整行
1310
+ else:
1311
+ chain_str = next_line[2:].strip()
1312
+ head = self.parse_single_chain(chain_str.split('->', 1)[0].strip(), None, g)
1313
+ tail = self.parse_single_chain(chain_str, None, g)
1314
+ target_id = head if head is not None else tail
1315
+ pending_from = tail if tail is not None else target_id
1316
+ i += 1 # 消费出口行
1317
+ # 为每个出口候选节点添加回边到循环网关
1318
+ for nid in exit_candidates:
1319
+ g.add_edge(nid, loop_gw)
1320
+ if target_id:
1321
+ g.add_edge(loop_gw, target_id) # 循环结束后的出口边(连链首)
1322
+ pending_from = pending_from if pending_from is not None else target_id
1323
+ else:
1324
+ if not exit_candidates:
1325
+ raise SyntaxError(
1326
+ f"for 循环体缺少出口标记(行末 '->'),必须至少有一个出口,或者提供出口行 -> Target"
1327
+ )
1328
+ break_id = self._reg_node(g, "[BREAK]", "break")
1329
+ g.add_edge(loop_gw, break_id)
1330
+ pending_from = break_id
1331
+
1332
+ elif ctrl_type == 'par':
1333
+ join_gw = self.parse_par(block, g)
1334
+ # 检查下一个同级块是否为出口行(支持链:-> [X]:ref -> [Y];
1335
+ # 若出口行同时是控制块入口(-> [A] -> [B] -> fork:),
1336
+ # 链部分建出口边,控制块行留给主循环处理)
1337
+ target_id = None
1338
+ if i + 1 < len(blocks):
1339
+ next_line = blocks[i + 1].line.strip()
1340
+ if next_line.startswith('->'):
1341
+ m_ctrl = re.search(r'\s*->\s*(for|par|fork|join)\b', next_line)
1342
+ if m_ctrl:
1343
+ chain_part = next_line[2:m_ctrl.start()].strip()
1344
+ if chain_part:
1345
+ head = self.parse_single_chain(chain_part.split('->', 1)[0].strip(), None, g)
1346
+ tail = self.parse_single_chain(chain_part, None, g)
1347
+ target_id = head if head is not None else tail
1348
+ pending_from = tail if tail is not None else target_id
1349
+ # 不消费该行:主循环会处理 -> ... -> fork: 整行
1350
+ else:
1351
+ chain_str = next_line[2:].strip()
1352
+ head = self.parse_single_chain(chain_str.split('->', 1)[0].strip(), None, g)
1353
+ tail = self.parse_single_chain(chain_str, None, g)
1354
+ target_id = head if head is not None else tail
1355
+ pending_from = tail if tail is not None else target_id
1356
+ i += 1
1357
+ if target_id:
1358
+ g.add_edge(join_gw, target_id) # 出口边连链首
1359
+ pending_from = pending_from if pending_from is not None else target_id
1360
+ else:
1361
+ # 如果没有出口行,默认连 [BREAK]
1362
+ break_id = self._reg_node(g, "[BREAK]", "break")
1363
+ g.add_edge(join_gw, break_id)
1364
+ pending_from = break_id
1365
+
1366
+ elif ctrl_type == 'fork':
1367
+ fork_gw = self._reg_gateway(g, "fork", "gateway", meta={"gw_kind": "fork"})
1368
+ pre_tail = self.parse_single_chain(ctrl_match.group(1).strip(), None, g)
1369
+ if pre_tail:
1370
+ g.add_edge(pre_tail, fork_gw)
1371
+ for daughter in block.daughters:
1372
+ cl = daughter.line.strip()
1373
+ if not cl.startswith('->'):
1374
+ raise SyntaxError(f"fork 体内行必须以 '->' 开头: {cl}")
1375
+ if cl.rstrip().endswith('->'):
1376
+ raise SyntaxError(f"fork 体内不允许使用出口标记 '->' : {cl}")
1377
+ core = cl[2:].lstrip()
1378
+ self.parse_single_chain(core, fork_gw, g)
1379
+ pending_from = None # fork 无统一出口
1380
+
1381
+ elif ctrl_type == 'join':
1382
+ # 带前导链的 join 实际上不允许,但根据要求不改 join,所以不支持前导链
1383
+ raise SyntaxError("join 不支持前导链,请使用 'join(...):' 独立行")
1384
+ i += 1
1385
+ continue
1386
+
1387
+ # ── 普通单链行(独立起点,不使用 pending_from)──
1388
+ if line.startswith('['):
1389
+ tail = self.parse_single_chain(line, None, g)
1390
+ # 普通链的末端作为新的 pending_from,供后续可能的控制块前导链或出口行使用
1391
+ pending_from = tail
1392
+ i += 1
1393
+ continue
1394
+
1395
+ # 其他情况报错
1396
+ raise SyntaxError(f"无法识别的流程行: {line}")
1397
+
1398
+
1399
+ # ─── 控制块解析辅助 ────────────────────────────────────────────
1400
+ def _parse_control_head(self, line: str):
1401
+ """解析 [Node] -> for/par/fork/join(...) : 行,返回 (前导链文本, 控制类型, 参数字符串)"""
1402
+ m = re.match(r'^(.+?)\s*->\s*(for|par|fork|join)\b(.*):\s*$', line)
1403
+ if not m:
1404
+ raise SyntaxError(f"无法解析控制块首行: {line}")
1405
+ pre_chain = m.group(1).strip()
1406
+ ctrl_type = m.group(2)
1407
+ params = m.group(3).strip()
1408
+ return pre_chain, ctrl_type, params
1409
+
1410
+ def _separate_nested_blocks(self, daughters: List[IndentBlock]):
1411
+ """将子块列表分为嵌套控制块和纯单链行"""
1412
+ nested = []
1413
+ plain = []
1414
+ for daughter in daughters:
1415
+ line = daughter.line.strip()
1416
+ # 嵌套控制块的首行模式:以 [Node] 开头,且包含 -> for/par/fork/join
1417
+ if re.match(r'^\[.+\]\s*->\s*(for|par|fork|join)\b', line):
1418
+ nested.append(daughter)
1419
+ else:
1420
+ plain.append(daughter)
1421
+ return nested, plain
1422
+
1423
+ def parse_single_chain(self, line: str, entry: Optional[str], g: FlowGraph):
1424
+ """解析一条普通单链,返回链尾节点ID,entry可为None"""
1425
+ tokens = tokenize_chain(line)
1426
+ if not tokens:
1427
+ return entry
1428
+ return chain_tokens(g, tokens, entry, self._reg_node, self._reg_auto_node)
1429
+
1430
+ def _process_inner_single_lines(self, plain_daughters: List[IndentBlock],
1431
+ gateway_id: str, g: FlowGraph) -> List[str]:
1432
+ """处理 for/par 体内的纯单链行,返回出口候选节点ID列表"""
1433
+ exit_candidates = []
1434
+ for daughter in plain_daughters:
1435
+ raw_line = daughter.line.strip()
1436
+ # 判断行首 -> 和行尾 ->
1437
+ starts_with_arrow = raw_line.startswith('->')
1438
+ ends_with_arrow = raw_line.rstrip().endswith('->')
1439
+
1440
+ # 剥除首尾 ->
1441
+ core = raw_line
1442
+ if starts_with_arrow:
1443
+ core = core[2:].lstrip() # 去掉开头的 '->'
1444
+ if ends_with_arrow:
1445
+ # 去掉末尾的 '->',注意可能后面有空格
1446
+ core = re.sub(r'\s*->\s*$', '', core).rstrip()
1447
+
1448
+ # 决定解析入口
1449
+ entry = gateway_id if starts_with_arrow else None
1450
+ tail = self.parse_single_chain(core, entry, g)
1451
+ if tail is None:
1452
+ continue
1453
+
1454
+ if ends_with_arrow:
1455
+ exit_candidates.append(tail)
1456
+ return exit_candidates
1457
+
1458
+ # ─── 具体控制块解析器 ─────────────────────────────────────────
1459
+ def parse_for(self, block: IndentBlock, g: FlowGraph) -> str:
1460
+ """解析 for 循环块,返回出口节点ID(或[BREAK])"""
1461
+ pre_chain, _, params = self._parse_control_head(block.line.strip())
1462
+ # 提取变量和迭代对象
1463
+ m = re.match(r'(@?\w+)\s+in\s+(.+)', params)
1464
+ if not m:
1465
+ raise SyntaxError(f"for 语法错误: {block.line}")
1466
+ var_name = m.group(1)
1467
+ iterable = m.group(2)
1468
+
1469
+ # 创建循环网关
1470
+ loop_gw = self._reg_gateway(g, "for", "gateway",
1471
+ meta={"gw_kind": "for", "var_name": var_name, "iterable": iterable})
1472
+
1473
+ # 解析前导链,连接到循环网关
1474
+ pre_tail = self.parse_single_chain(pre_chain, None, g) if pre_chain else None
1475
+ if pre_tail:
1476
+ g.add_edge(pre_tail, loop_gw)
1477
+
1478
+ # 分离嵌套块和单链行
1479
+ nested, plain = self._separate_nested_blocks(block.daughters)
1480
+ # 先处理单链行
1481
+ exit_candidates = self._process_inner_single_lines(plain, loop_gw, g)
1482
+ # 递归处理嵌套控制块(它们可能贡献更多的体内节点,也参与后续单链行的连接)
1483
+ for nest_block in nested:
1484
+ self._process_nested_control_block(nest_block, g)
1485
+
1486
+ # 出口行处理 (由外层 parse_flow_blocks 调用时处理,这里先假设没有出口行,暂连[BREAK])
1487
+ # 为保持独立性,我们在此统一:如果没有出口行,连[BREAK];出口行由外部消费,外部会调用 set_exit
1488
+ # 我们先收集 exit_candidates,并提供一个方法 set_for_exit(target) 来连接出口。
1489
+ # 但为了简化,我们把出口候选存在一个临时属性或返回出去?
1490
+ # 设计:parse_for 只处理内部并返回 (loop_gw, exit_candidates, <后续>)。由于出口行在外部被消费,我们需要让外部能访问这些信息。
1491
+ # 简便做法:在 FlowBuilder 实例上临时存储,或者返回三元组。这里我们让 parse_for 返回一个特殊对象,或者我们直接在这里连接一个默认出口([BREAK]),外部可通过在消费出口行后修改边。
1492
+ # 更优雅:parse_for 处理完内部后,不处理出口,而是将 loop_gw 和 exit_candidates 存储,然后外部调用 connect_exit 方法。但阶段四才重写 build_flow,现在我们可以先让 parse_for 始终连到 [BREAK],阶段四再由外部覆盖。
1493
+ # 现在我们按阶段三的要求,提供可用的函数,具体行为与阶段四配合。我们先假设默认连 [BREAK]。
1494
+ break_node_id = self._reg_node(g, "[BREAK]", "break")
1495
+ for nid in exit_candidates:
1496
+ g.add_edge(nid, break_node_id)
1497
+ return break_node_id # for 块出口视为 [BREAK],阶段四会用出口行覆盖
1498
+
1499
+ def parse_par(self, block: IndentBlock, g: FlowGraph) -> str:
1500
+ """解析 par 并行循环块,返回出口节点ID(或[BREAK])"""
1501
+ pre_chain, _, params = self._parse_control_head(block.line.strip())
1502
+ m = re.match(r'(@?\w+)\s+in\s+(.+)', params)
1503
+ if not m:
1504
+ raise SyntaxError(f"par 语法错误: {block.line}")
1505
+ var_name = m.group(1)
1506
+ iterable = m.group(2)
1507
+
1508
+ join_gw = self._reg_gateway(g, "par_join", "gateway",
1509
+ meta={"gw_kind": "join", "join_mode": "all"})
1510
+ fork_gw = self._reg_gateway(g, "par_fork", "gateway",
1511
+ meta={"gw_kind": "fork", "is_par_fork": True,
1512
+ "par_var": var_name, "par_iterable": iterable})
1513
+
1514
+ pre_tail = self.parse_single_chain(pre_chain, None, g) if pre_chain else None
1515
+ if pre_tail:
1516
+ g.add_edge(pre_tail, fork_gw)
1517
+
1518
+ nested, plain = self._separate_nested_blocks(block.daughters)
1519
+ exit_candidates = self._process_inner_single_lines(plain, fork_gw, g)
1520
+ for nest_block in nested:
1521
+ self._process_nested_control_block(nest_block, g)
1522
+
1523
+ for nid in exit_candidates:
1524
+ g.add_edge(nid, join_gw)
1525
+
1526
+ # 返回 join_gw 给调用方,由调用方决定出口边([BREAK] 或显式 -> Target)
1527
+ return join_gw
1528
+
1529
+ def parse_fork(self, block: IndentBlock, g: FlowGraph) -> Optional[str]:
1530
+ """解析 fork 块,无统一出口,返回 None"""
1531
+ pre_chain, _, _ = self._parse_control_head(block.line.strip())
1532
+ fork_gw = self._reg_gateway(g, "fork", "gateway", meta={"gw_kind": "fork"})
1533
+
1534
+ pre_tail = self.parse_single_chain(pre_chain, None, g) if pre_chain else None
1535
+ if pre_tail:
1536
+ g.add_edge(pre_tail, fork_gw)
1537
+
1538
+ # fork 内部只允许 -> 开头的行
1539
+ for daughter in block.daughters:
1540
+ line = daughter.line.strip()
1541
+ if not line.startswith('->'):
1542
+ raise SyntaxError(f"fork 体内行必须以 '->' 开头: {line}")
1543
+ core = line[2:].lstrip()
1544
+ self.parse_single_chain(core, fork_gw, g)
1545
+ return None # 无统一出口
1546
+
1547
+ def parse_join(self, block: IndentBlock, g: FlowGraph) -> str:
1548
+ """解析 join 块(保留原逻辑,不支持前导链)"""
1549
+ # 仅当 join 独立行时使用,即首行不包含前导链
1550
+ m = re.match(r'^join\s*(?:\((\w+)\))?\s*:\s*$', block.line.strip())
1551
+ if not m:
1552
+ raise SyntaxError(f"join 语法错误: {block.line.strip()}")
1553
+ mode = m.group(1) if m.group(1) else 'all'
1554
+ join_gw = self._reg_gateway(g, "join", "gateway",
1555
+ meta={"gw_kind": "join", "join_mode": mode})
1556
+ # 处理子块中的入边声明([Node] -> )
1557
+ for daughter in block.daughters:
1558
+ cl = daughter.line.strip()
1559
+ if not cl.startswith('['):
1560
+ raise SyntaxError(f"join 内部只能有 [Node] -> 入边声明: {cl}")
1561
+ # 去掉可能的末尾 '->'
1562
+ source_str = re.sub(r'\s*->\s*$', '', cl)
1563
+ source_id = self._reg_node(g, source_str)
1564
+ g.add_edge(source_id, join_gw)
1565
+ return join_gw
1566
+
1567
+ def _process_nested_control_block(self, block: IndentBlock, g: FlowGraph):
1568
+ """递归处理嵌套控制块"""
1569
+ line = block.line.strip()
1570
+ # 判断类型
1571
+ if re.search(r'\bfor\b', line):
1572
+ self.parse_for(block, g)
1573
+ elif re.search(r'\bpar\b', line):
1574
+ self.parse_par(block, g)
1575
+ elif re.search(r'\bfork\b', line):
1576
+ self.parse_fork(block, g)
1577
+ elif re.search(r'\bjoin\b', line):
1578
+ self.parse_join(block, g)
1579
+ else:
1580
+ raise SyntaxError(f"未知嵌套控制块: {line}")
1581
+
1582
+ # ============================================================
1583
+ # 5. 顶层解析入口
1584
+ # ============================================================
1585
+
1586
+ def eval_flow(block: Block, known_actions: Dict[str, Any] = None, known_modules: Dict[str, Any] = None) -> FlowGraph:
1587
+ # 标准化器已经把声明区提取到 mainflow 之前,此处 flow 文本只包含流程描述。
1588
+ flow_lines = block.content_lines
1589
+ flow_text = '\n'.join(flow_lines)
1590
+ flow_text = normalize_symbols(flow_text)
1591
+ # -- 仅在 flow/mainflow 区等价 ->(文档约定)
1592
+ flow_text = flow_text.replace('--', '->')
1593
+
1594
+ # 节点绑定已由标准化器处理,不再需要从 flow 内部解析。
1595
+ # 但标准化器生成的节点定义放在 mainflow 之前,解析器不会读到它们。
1596
+ # 我们需要一个方式将节点绑定传递给 FlowBuilder。
1597
+ # 暂时留空,因为我们的新语法中所有节点引用都必须已在流程中注册(通过 [Node] -> 形式出现)。
1598
+ # 事实上,标准化器生成的 [Node]: binding 被移到了脚本顶部,不属于 flow 文本。
1599
+ # 所以此时无需绑定表,流程图中的节点引用会自动通过 reg_node 注册。
1600
+ builder = FlowBuilder()
1601
+ # 忽略旧绑定表传递
1602
+ g = builder.build_flow(flow_text)
1603
+ # mainflow 引用校验。模块引用的校验不在此处(known_modules=None 跳过):
1604
+ # 内联时机早于全部 module 块解析,点路径可见集与书写顺序耦合——模块引用
1605
+ # 由 parse_script 尾部的后置校验统一做(含嵌套点路径,与块顺序无关)。
1606
+ if known_actions is not None:
1607
+ validate_flow_refs(g, known_actions, known_modules, 'mainflow')
1608
+ return g
1609
+
1610
+ def eval_module(block: Block) -> ModuleDef:
1611
+ header = normalize_symbols(block.header)
1612
+ m = re.match(r'^module\s+(\w+)(?:\s*\(([^)]*)\))?\s*:?\s*$', header)
1613
+ if not m:
1614
+ raise ValueError(f"无法解析 module 头部: {header}")
1615
+ name = m.group(1)
1616
+ params = [p.strip() for p in m.group(2).split(',') if p.strip()] if m.group(2) else []
1617
+ mod = ModuleDef(name=name, params=params)
1618
+
1619
+ for daughter in block.daughters:
1620
+ t = daughter.type
1621
+ if t == 'meta':
1622
+ mod.meta = eval_meta(daughter)
1623
+ elif t == 'vars':
1624
+ mod.locals = eval_vars(daughter)
1625
+ elif t == 'action':
1626
+ act = eval_action(daughter)
1627
+ mod.actions[act.name] = act
1628
+ elif t == 'module':
1629
+ sub = eval_module(daughter)
1630
+ mod.modules[sub.name] = sub
1631
+ elif t == 'memory':
1632
+ mem = eval_method(daughter)
1633
+ mod.memories[mem.name] = mem
1634
+ elif t == 'context':
1635
+ ctx = eval_method(daughter)
1636
+ mod.contexts[ctx.name] = ctx
1637
+ elif t == 'flow':
1638
+ mod.flow = eval_flow(daughter)
1639
+ return mod
1640
+
1641
+ def _node_is_ai_action(node: FlowNode, actions: Dict[str, ActionDef]) -> bool:
1642
+ """
1643
+ 判断 FlowNode 绑定的 Action 是否为 AI 类型。
1644
+ 仅当节点有 action_name 且 ActionDef.executor_type == AI 时返回 True。
1645
+ gateway、start、end、module_call 等节点返回 False。
1646
+ """
1647
+ if not node or not node.action_name:
1648
+ return False
1649
+ action = actions.get(node.action_name)
1650
+ is_ai = action.executor_type == ExecutorType.AI
1651
+ print(f"[parser] 🔍 节点 {node.id}: action_name={node.action_name}, executor_type={action.executor_type}, is_ai={is_ai}")
1652
+ return is_ai
1653
+
1654
+
1655
+ def inject_delay_nodes(flow: FlowGraph, actions: Dict[str, ActionDef], delay_seconds: int) -> None:
1656
+ """
1657
+ 遍历 flow 所有边,若 source 和 target 节点都绑定 AI Action,
1658
+ 在中间插入一个 delay 节点。
1659
+
1660
+ 原始边: A --(cond)--> B
1661
+ 变成: A --(cond)--> [delay_X] --()--> B
1662
+
1663
+ delay 节点 type='delay',meta 内存 is_delay_node=True 和 delay_seconds。
1664
+ 原边 condition 跟第一段走(A→delay),第二段(delay→B)无条件。
1665
+ """
1666
+ print(f"[parser] ⏱️ inject_delay_nodes: 开始, delay={delay_seconds}s, 边数={len(flow.edges)}, 节点数={len(flow.nodes)}")
1667
+
1668
+ new_edges = []
1669
+ delay_counter = 0
1670
+
1671
+ for edge in flow.edges:
1672
+ source_node = flow.nodes.get(edge.source)
1673
+ target_node = flow.nodes.get(edge.target)
1674
+
1675
+ source_is_ai = _node_is_ai_action(source_node, actions) if source_node else False
1676
+ target_is_ai = _node_is_ai_action(target_node, actions) if target_node else False
1677
+
1678
+ if source_is_ai and target_is_ai:
1679
+ delay_counter += 1
1680
+ delay_id = f"[__delay_{edge.source}_{edge.target}_{delay_counter}__]"
1681
+
1682
+ delay_node = FlowNode(
1683
+ id=delay_id,
1684
+ type='delay',
1685
+ label=f'delay({delay_seconds}s)',
1686
+ meta={'is_delay_node': True, 'delay_seconds': delay_seconds},
1687
+ )
1688
+ flow.add_node(delay_node)
1689
+
1690
+ # 第一段: source -> delay, 保留原 condition
1691
+ new_edges.append(FlowEdge(
1692
+ source=edge.source,
1693
+ target=delay_id,
1694
+ condition=edge.condition,
1695
+ ))
1696
+ # 第二段: delay -> target, 无条件
1697
+ new_edges.append(FlowEdge(
1698
+ source=delay_id,
1699
+ target=edge.target,
1700
+ condition="",
1701
+ ))
1702
+ print(f"[parser] ⏱️ 注入 delay: {edge.source} --({edge.condition or '无条件'})--> {delay_id} --()--> {edge.target}")
1703
+ else:
1704
+ new_edges.append(edge)
1705
+
1706
+ flow.edges = new_edges
1707
+ print(f"[parser] ⏱️ inject_delay_nodes: 完成, 注入 {delay_counter} 个 delay 节点, 新边数={len(flow.edges)}")
1708
+
1709
+
1710
+ def validate_actor_souls(text: str, soul_exists: Optional[Callable[[str], bool]] = None) -> None:
1711
+ """编译期校验 actors 区块的 soul 是否存在(normalize 前扫原始文本,行号对应用户所见)。
1712
+
1713
+ 报错 = 全部错误一次列出:每条含行号 + 该行原文 + soul id;末尾附可用列表
1714
+ (soul_exists 携带 _soul_ids 属性时)。soul_exists 为 None 时跳过(保持纯解析可测)。
1715
+ 裸 actor(无 soul 字段)合法——soul 非必须(用户决策:无角色设定的简单剧本可不写)。
1716
+ """
1717
+ if soul_exists is None:
1718
+ return
1719
+ lines = text.split('\n')
1720
+ in_actors = False
1721
+ errors = []
1722
+ for idx, raw in enumerate(lines):
1723
+ s = raw.strip()
1724
+ if not s or s.startswith('#') or s.startswith('//'):
1725
+ continue
1726
+ if not in_actors:
1727
+ if s.startswith('actors:') or s.startswith('actors:'):
1728
+ in_actors = True
1729
+ continue
1730
+ # actors 区块结束:回到顶层区块(无缩进非空行)
1731
+ if raw[0] != ' ' and raw[0] != '\t':
1732
+ break
1733
+ m = re.match(r'^(ai|human)\s+(@?[\w\u4e00-\u9fff]+)', s)
1734
+ if not m:
1735
+ continue
1736
+ sm = re.search(r'soul\s*[::]\s*([^\s,,]+)', s)
1737
+ if not sm:
1738
+ continue # 无 soul = 合法
1739
+ sid = sm.group(1).strip('"').strip("'")
1740
+ if sid and not soul_exists(sid):
1741
+ errors.append((idx + 1, s, sid))
1742
+ if errors:
1743
+ detail = '\n'.join(
1744
+ f"actors 第 {ln} 行: {line} → soul \"{sid}\" 不存在"
1745
+ for ln, line, sid in errors
1746
+ )
1747
+ avail = getattr(soul_exists, '_soul_ids', None)
1748
+ msg = f"编译错误:soul id 不存在。\n{detail}"
1749
+ if avail:
1750
+ msg += f"\n可用列表:{' / '.join(sorted(avail))}"
1751
+ raise ValueError(msg)
1752
+
1753
+
1754
+ def validate_actor_sources(script, models: Optional[Dict[str, Any]] = None) -> None:
1755
+ """编译期校验 AI actor 的 source 字段是否为宿主可用模型(models 缺省/为空不校验;
1756
+ models 由宿主在 job_start/check 经协议参数注入——A2.1 宿主清单/模型注入通道)。
1757
+
1758
+ source 语法(与宿主约定,见语法文档):
1759
+ - 裸 id(不含 '/')→ 必须在 models['defaultProvider'] 的模型列表中;
1760
+ - 'provider/model' → 在全部 provider 的模型列表中查。
1761
+ human(source 为数字 user 身份)与 blueprint 跳过。
1762
+ 校验失败 raise ValueError(编译错误,信息含可用模型列表)。
1763
+ """
1764
+ if not models:
1765
+ return
1766
+ default_provider = models.get('defaultProvider')
1767
+ provider_index = {}
1768
+ for p in models.get('providers', []):
1769
+ pid = p.get('id')
1770
+ if pid:
1771
+ # 模型条目容忍两种形态:纯 id 字符串,或宿主的富对象 {id, name}
1772
+ # (富对象形状是通道接通首日(2026-09-07)实测暴露的 unhashable bug)
1773
+ ids = set()
1774
+ for m in (p.get('models') or []):
1775
+ mid = m.get('id') if isinstance(m, dict) else m
1776
+ if mid:
1777
+ ids.add(str(mid))
1778
+ provider_index[pid] = ids
1779
+ if not provider_index:
1780
+ return
1781
+ for name, adef in (script.actors or {}).items():
1782
+ if adef.type != ActorType.AI:
1783
+ continue
1784
+ s = str(getattr(adef, 'source', None) or '').strip()
1785
+ if not s:
1786
+ continue
1787
+ if s == 'main':
1788
+ # 保留字:主会话本尊出演(source:main)——不是模型名,豁免模型白名单
1789
+ continue
1790
+ if '/' in s:
1791
+ pid, mid = s.split('/', 1)
1792
+ ok = mid in provider_index.get(pid, set())
1793
+ else:
1794
+ ok = default_provider is not None and s in provider_index.get(default_provider, set())
1795
+ if not ok:
1796
+ available = ', '.join(
1797
+ f"{pid}/{mid}"
1798
+ for pid, mset in provider_index.items()
1799
+ for mid in sorted(mset)
1800
+ ) or '(无可用模型)'
1801
+ raise ValueError(
1802
+ f"actors: ai @{str(name).lstrip('@')}: source \"{s}\" 不是可用模型。"
1803
+ f"可用列表:{available}(或省略 source 跟随主模型)"
1804
+ )
1805
+
1806
+
1807
+ def add_warning(script: 'Script', message: str, where: str = '') -> None:
1808
+ """编译期 warning 收集点(2026-09-07 warning 桶):不阻断编译,作者知情。
1809
+
1810
+ 与 raise 的分工——raise = 编译拒绝(作者必须改);warning = 编译放行
1811
+ (作者自行判断)。消息随 script.warnings 上浮 check/job_start 回执。"""
1812
+ script.warnings.append({'where': where, 'message': str(message)})
1813
+
1814
+
1815
+ def validate_flow_reentry(script) -> None:
1816
+ """编译期检测:回到「多条无条件出边」的节点会导致分支数爆炸。
1817
+
1818
+ 原因:每次回到该节点往下运行都会从一变成多分支(普通节点多出边 =
1819
+ 自动 fork),分支数指数增长。条件出边(if 分流)回流是安全的
1820
+ (只走评估为真的分支),不检测。排除项:for/par/fork/join 网关
1821
+ (多出边是迭代/并发语义,非爆炸模式);重复边去重(par 出口链可能
1822
+ 重复生成同一条边)。用户拍板文案。
1823
+ """
1824
+ def check(flow: Optional[FlowGraph], where: str) -> None:
1825
+ if not flow:
1826
+ return
1827
+ # 去重(par 出口链可能重复生成相同边)
1828
+ seen = set()
1829
+ uniq_edges = []
1830
+ for e in flow.edges:
1831
+ key = (e.source, e.target, e.condition)
1832
+ if key not in seen:
1833
+ seen.add(key)
1834
+ uniq_edges.append(e)
1835
+ for nid, node in flow.nodes.items():
1836
+ # 网关节点跳过(for/par/fork/join 的迭代/并发语义)
1837
+ if node.type == 'gateway' or (node.meta or {}).get('gw_kind') in ('for', 'par', 'fork', 'join'):
1838
+ continue
1839
+ unconditional_outs = [
1840
+ e for e in uniq_edges if e.source == nid and not e.condition
1841
+ ]
1842
+ # 「回到」= 入边来自流程内部;入口启动边([START]/[IN] 出发)不算
1843
+ has_in = any(
1844
+ e.target == nid and e.source not in ('[START]', '[IN]')
1845
+ for e in uniq_edges
1846
+ )
1847
+ if len(unconditional_outs) >= 2 and has_in:
1848
+ # 【2026-09-07 warning 桶落地】原 raise 阻断已退役(2026-09-07
1849
+ # 用户拍板:编译期不再阻断回流场景,坚持运行则应能跑),现按
1850
+ # WARNING 语义收集——编译放行,提示随 script.warnings 上浮
1851
+ # check/job_start 回执(原报错文案保留为提示正文)。
1852
+ add_warning(
1853
+ script,
1854
+ f"节点 [{nid}] 有多个出边,不能回到这种节点。"
1855
+ "原因是,每次回到这里往下运行都会从一变成多分支,分支数会爆炸。"
1856
+ "建议在本节点之后的分支中加空节点,让他们回到空节点。",
1857
+ where=where,
1858
+ )
1859
+
1860
+ check(script.flow, "mainflow")
1861
+ for mname, mod in (script.modules or {}).items():
1862
+ check(mod.flow, f"module {mname}")
1863
+
1864
+
1865
+ # ── 变量声明校验(2026-08-26 新增)──────────────────────────
1866
+ # 与前端 femoParser.jsx validateDeclarations 规则一致:
1867
+ # 1. for 循环变量必须在 vars:(或模块 vars:)中声明
1868
+ # 2. for 迭代器若为裸标识符(非列表/引号字符串)必须已声明
1869
+ # 3. if 条件表达式里的裸标识符(非引号字符串/数字/保留字)
1870
+ # 必须是已声明变量/actor/循环变量
1871
+ # 纯增量校验,只读 script 对象不修改,不影响现有校验流程。
1872
+
1873
+ _VAR_DECL_RESERVED = frozenset([
1874
+ 'and', 'or', 'not', 'in', 'is',
1875
+ 'True', 'False', 'None', 'true', 'false', 'TRUE', 'FALSE',
1876
+ ])
1877
+
1878
+
1879
+ def _extract_cond_identifiers(cond: str) -> list:
1880
+ """剥离字符串字面量后提取裸标识符(与前端 _extractCondIdentifiers 一致)。"""
1881
+ no_str = re.sub(r'"[^"]*"|\'[^\']*\'', '""', cond)
1882
+ return re.findall(r'@?[\w]+(?:\.[\w]+)*', no_str)
1883
+
1884
+
1885
+ def _main_ident(ident: str) -> str:
1886
+ dot = ident.find('.')
1887
+ return ident[:dot] if dot >= 0 else ident
1888
+
1889
+
1890
+ def validate_variable_declarations(script: 'Script') -> None:
1891
+ """编译期变量声明校验(步骤 B,2026-09-04 查表版)。
1892
+
1893
+ 可见域权威 = script.scope_table(词法定义链,拍板 6):名字在某 def_chain
1894
+ 下查得到声明即合法。校验规则与报错文案与旧 set 并集版逐条一致:
1895
+ 1) for 循环变量与迭代器必须在声明表可见
1896
+ 2) if 条件表达式里的裸标识符(非字面量/保留字)必须可见
1897
+ loop_vars(循环变量,运行期绑定)在声明表之外单独放行。
1898
+ 模块 flow 的 def_chain = 书写嵌套定义链('Outer.Inner' → ('Outer','Inner'),
1899
+ 与运行期调用栈无关);mainflow = ()(剧本级,只见 global)。
1900
+ """
1901
+ table = script.scope_table
1902
+ if table is None:
1903
+ raise SyntaxError('script.scope_table 未装配(parse_script 变量声明装配缺失)')
1904
+ actors = set((script.actors or {}).keys())
1905
+
1906
+ def validate_flow(flow: Optional[FlowGraph], def_chain: Tuple[str, ...],
1907
+ ctx_name: str) -> None:
1908
+ if flow is None:
1909
+ return
1910
+ loop_vars = set()
1911
+
1912
+ # 1) for 循环变量与迭代器声明检查
1913
+ for node in flow.nodes.values():
1914
+ meta = node.meta or {}
1915
+ if meta.get('gw_kind') != 'for':
1916
+ continue
1917
+ var_name = meta.get('var_name', '')
1918
+ iterable = meta.get('iterable', '')
1919
+ if not var_name:
1920
+ continue
1921
+ if table.lookup(var_name, def_chain) is None:
1922
+ raise SyntaxError(
1923
+ f'for 循环变量 "{var_name}" 未在 vars: 中声明'
1924
+ f'({ctx_name},for 条件: "for {var_name} in {iterable}")。'
1925
+ f'所有循环变量必须在 vars: 中预先声明,例如: {var_name} = ""'
1926
+ )
1927
+ loop_vars.add(var_name)
1928
+ iterable_s = iterable.strip()
1929
+ if re.match(r'^@?[\w]+$', iterable_s) and table.lookup(iterable_s, def_chain) is None:
1930
+ raise SyntaxError(
1931
+ f'for 迭代器 "{iterable_s}" 未在 vars: 中声明'
1932
+ f'({ctx_name},for 条件: "for {var_name} in {iterable}")'
1933
+ )
1934
+
1935
+ # 2) 条件表达式裸标识符检查
1936
+ def visible(name: str) -> bool:
1937
+ return (table.lookup(name, def_chain) is not None
1938
+ or name in actors or name in loop_vars)
1939
+
1940
+ for edge in flow.edges:
1941
+ if not edge.condition:
1942
+ continue
1943
+ for ident in _extract_cond_identifiers(edge.condition):
1944
+ if ident in _VAR_DECL_RESERVED:
1945
+ continue
1946
+ main = _main_ident(ident)
1947
+ if re.match(r'^\d+(\.\d+)?$', main):
1948
+ continue
1949
+ if main.startswith('@'):
1950
+ if not visible(main):
1951
+ raise SyntaxError(
1952
+ f'条件 "{edge.condition}" 引用了未声明的 actor/变量 "{main}"'
1953
+ f'({ctx_name},边 {edge.source} -> {edge.target})'
1954
+ )
1955
+ elif not visible(main):
1956
+ raise SyntaxError(
1957
+ f'条件 "{edge.condition}" 引用了未声明的变量 "{main}"'
1958
+ f'({ctx_name},边 {edge.source} -> {edge.target})。'
1959
+ f'字符串字面量请加引号,如 == "ai";所有变量须在 vars: 中声明'
1960
+ )
1961
+
1962
+ validate_flow(script.flow, (), 'mainflow')
1963
+
1964
+ # 模块 flow 可见域(词法定义链,拍板 6):def_chain = 书写嵌套
1965
+ # (子模块可见母模块 local,Python 式,不反向)——旧版 ancestor_locals
1966
+ # 沿 mod.modules 书写嵌套累积,即同一词法链,语义逐条一致。
1967
+ def walk(mod: ModuleDef, parent_chain: Tuple[str, ...], path: str) -> None:
1968
+ chain = parent_chain + (mod.name,)
1969
+ validate_flow(mod.flow, chain, f'module {path}')
1970
+ for sub_name, sub in (mod.modules or {}).items():
1971
+ walk(sub, chain, f'{path}.{sub_name}')
1972
+
1973
+ for mname, mod in (script.modules or {}).items():
1974
+ walk(mod, (), mname)
1975
+
1976
+
1977
+ # ── join 在环上的编译期警告(2026-09-07)────────────────────────
1978
+ # join(all)/join(N) 的语义是"等全部(N 个)上游到齐再放行"。若 join 节点
1979
+ # 位于流程环路上(能从自己出发绕回自己),环上的 fork 会先于 join 发生、
1980
+ # 又只有 join 放行后才会再发生——等待集永远凑不齐,剧本必然无声卡死
1981
+ # (实锤:警长版被"图到文本"自动加 join(all) 后,DayPhase 永远进不去)。
1982
+ # 循环里的合流请直接用普通多线汇入([A] -> [next] 逐条),"到即走"。
1983
+ # 不作 error:join 的代次机制在部分环形态下仍可收敛,作者知情后自行判断。
1984
+
1985
+ def validate_join_on_cycle(script) -> None:
1986
+ def check(flow, where: str) -> None:
1987
+ if flow is None:
1988
+ return
1989
+ nodes = flow.nodes or {}
1990
+ joins = [nid for nid, n in nodes.items()
1991
+ if (n.meta or {}).get('gw_kind') == 'join']
1992
+ for join_id in joins:
1993
+ # 正向 BFS:从 join 的后继出发,看能否绕回 join 自己
1994
+ frontier = [e.target for e in flow.edges if e.source == join_id]
1995
+ visited = set(frontier)
1996
+ on_cycle = False
1997
+ while frontier and not on_cycle:
1998
+ nid = frontier.pop()
1999
+ if nid == join_id:
2000
+ on_cycle = True
2001
+ break
2002
+ for e in flow.edges:
2003
+ if e.source == nid and e.target not in visited:
2004
+ visited.add(e.target)
2005
+ frontier.append(e.target)
2006
+ if on_cycle:
2007
+ add_warning(
2008
+ script,
2009
+ f"join 节点 [{join_id}] 位于流程环路上(从它出发能绕回它自己)。"
2010
+ "join 会等待上游到齐,而环路里的一部分上游只有 join 放行之后才会发生,"
2011
+ "这会让剧本永远等待下去。请把循环里的合流改成普通多线汇入"
2012
+ "(逐条 [A] -> [next],到即走),不要用 join(...):。",
2013
+ where=where,
2014
+ )
2015
+
2016
+ check(script.flow, 'mainflow')
2017
+ for mname, mod in (script.modules or {}).items():
2018
+ check(mod.flow, f'module {mname}')
2019
+
2020
+
2021
+ # ── 动作/作用域编译期硬校验(2026-09-07 猫猫拍板五类)──────────────
2022
+ # 五类语法错误此前被静默吞掉(裸 in: 变 InMapping(x,x)、@func: 空参数、
2023
+ # scope: self, @xxx 混写、scope 引用不存在的 actor、变量名撞 Python 保留字),
2024
+ # 编译放行 → 运行期才炸甚至无声悬挂。现全部编译期拒绝(FATAL 桶:错误链路
2025
+ # 里"编译/语法错"语义,job_start/check 同步拒绝,作者必须改)。
2026
+ # 前端 femoParser.jsx 的 validateActionSyntax 与本函数规则逐条对齐(两份
2027
+ # 语法检查相互独立:引擎不带前端可跑,前端不带引擎可出图)。
2028
+
2029
+ _PY_KEYWORDS = frozenset(keyword.kwlist)
2030
+
2031
+ def _strip_spec_name(name: str) -> str:
2032
+ """声明名 → 保留字比对用标识符:剥 $/@ 前缀('$alive'→'alive','@狼人'→'狼人')。"""
2033
+ return (name or '').lstrip('$@').strip()
2034
+
2035
+
2036
+ def _out_target_root(raw: str) -> str:
2037
+ """out: 项原文 → 赋值目标根名。
2038
+ 'day += 1'→'day';'vote_results.@voter(string, "")'→'vote_results';
2039
+ '@KILL(string, "击杀目标")'→'KILL'(剥 @ 后)。"""
2040
+ t = (raw or '').strip().rstrip(',').strip()
2041
+ t = re.sub(r'\([^)]*\)\s*$', '', t).strip() # 剥尾部类型标签 (bool, "xx")
2042
+ t = re.split(r'\+=|-=|=(?!=)', t, maxsplit=1)[0].strip() # 剥赋值运算符及右侧
2043
+ return _strip_spec_name(t)
2044
+
2045
+
2046
+ def _find_source_line(text: str, predicate) -> Tuple[int, str]:
2047
+ """在用户原文里定位满足 predicate 的第一行 → (行号, 原文行);找不到 → (0, '')。
2048
+ 行号对应用户所见原文(与 validate_actor_souls 同一约定)。"""
2049
+ for idx, raw in enumerate(text.split('\n')):
2050
+ s = raw.strip()
2051
+ if not s or s.startswith('#') or s.startswith('//'):
2052
+ continue
2053
+ if predicate(s):
2054
+ return idx + 1, s
2055
+ return 0, ''
2056
+
2057
+
2058
+ def _scope_line_lookup(text: str, raw_scope: str) -> Tuple[int, str]:
2059
+ """按 scope 原文定位行(normalize 差异容错:前缀 scope/:,空白)。"""
2060
+ target = raw_scope.strip()
2061
+ def pred(s: str) -> bool:
2062
+ m = re.match(r'^scope\s*[::]\s*(.+)$', normalize_symbols(s).strip())
2063
+ return bool(m and m.group(1).strip() == target)
2064
+ return _find_source_line(text, pred)
2065
+
2066
+
2067
+ def _action_line_lookup(text: str, action_name: str) -> Tuple[int, str]:
2068
+ def pred(s: str) -> bool:
2069
+ return bool(re.match(rf'^action\s+{re.escape(action_name)}\s+@', normalize_symbols(s).strip()))
2070
+ return _find_source_line(text, pred)
2071
+
2072
+
2073
+ def _vars_line_lookup(text: str, raw_name: str) -> Tuple[int, str]:
2074
+ def pred(s: str) -> bool:
2075
+ return bool(re.match(rf'^{re.escape(raw_name)}\s*=', s))
2076
+ return _find_source_line(text, pred)
2077
+
2078
+
2079
+ def _iter_module_actions(script: 'Script'):
2080
+ """遍历全部 action → (ActionDef, ctx 位置名, 词法定义链)。"""
2081
+ for ad in (script.actions or {}).values():
2082
+ yield ad, '顶层', ()
2083
+ def walk(mod: 'ModuleDef', parent_chain: Tuple[str, ...], path: str):
2084
+ chain = parent_chain + (mod.name,)
2085
+ for ad in (mod.actions or {}).values():
2086
+ yield ad, f'module {path}', chain
2087
+ for sub_name, sub in (mod.modules or {}).items():
2088
+ yield from walk(sub, chain, f'{path}.{sub_name}')
2089
+ for mname, mod in (script.modules or {}).items():
2090
+ yield from walk(mod, (), mname)
2091
+
2092
+
2093
+ def _check_scope_expr(raw_scope: str, actors: Set[str], lookup_var, ctx: str,
2094
+ loc: str, errors: List[str]) -> None:
2095
+ """scope 表达式校验(与 FEMO_scope_resolver 运行期语义对齐):
2096
+ 合法 = 空(=all) / 纯 all / 纯 self / [列表] / 裸变量 / '[列表] + 变量' 组合。"""
2097
+ s = (raw_scope or '').strip()
2098
+ if not s or s.lower() in ('all', 'self'):
2099
+ return
2100
+ # ② self 与其他目标混用(self 只能单独用)
2101
+ if re.search(r'\bself\b', s, re.IGNORECASE):
2102
+ errors.append(
2103
+ f'{ctx}{loc}: scope: {s} → "self" 只能单独使用(scope: self = 仅发言者可见);'
2104
+ f'多目标请写成方括号列表,如 scope: [@上帝, @player]'
2105
+ )
2106
+ return
2107
+ for part in re.split(r'\+', s):
2108
+ part = part.strip()
2109
+ if not part:
2110
+ continue
2111
+ if part.startswith('['):
2112
+ if not part.endswith(']'):
2113
+ errors.append(f'{ctx}{loc}: scope: {s} → 方括号不闭合,请检查列表格式')
2114
+ continue
2115
+ for item in re.split(r'[,,]', part[1:-1]):
2116
+ item = item.strip()
2117
+ if not item:
2118
+ continue
2119
+ if item.startswith('{') and item.endswith('}'):
2120
+ continue # 花括号动态项(如 {playersInPark})无法静态解析,交运行期
2121
+ # ③ 引用不存在的角色/变量(@名 必须是已声明角色或已声明 @actor 变量)
2122
+ if item.startswith('@'):
2123
+ if item not in actors and not lookup_var(item):
2124
+ errors.append(
2125
+ f'{ctx}{loc}: scope: {s} → "{item}" 不是已声明的角色,'
2126
+ f'也不是已声明的变量。可用角色:{" / ".join(sorted(actors)) or "(无)"}'
2127
+ )
2128
+ else:
2129
+ if not lookup_var(item):
2130
+ errors.append(
2131
+ f'{ctx}{loc}: scope: {s} → "{item}" 未在 vars: 中声明'
2132
+ f'(scope 列表里的名字必须是角色 @名 或已声明变量)'
2133
+ )
2134
+ else:
2135
+ # ② 裸部分含逗号 = 多目标没加方括号
2136
+ if re.search(r'[,,]', part):
2137
+ suggestion = '[' + ', '.join(x.strip() for x in re.split(r'[,,]', part)) + ']'
2138
+ errors.append(
2139
+ f'{ctx}{loc}: scope: {s} → 多个目标必须用方括号列表包裹,'
2140
+ f'请写成 scope: {suggestion}'
2141
+ )
2142
+ elif not lookup_var(part):
2143
+ errors.append(
2144
+ f'{ctx}{loc}: scope: {s} → "{part}" 未在 vars: 中声明'
2145
+ f'(裸名按变量解析,必须先在 vars: 声明;角色请带 @)'
2146
+ )
2147
+
2148
+
2149
+ def validate_action_syntax(text: str, script: 'Script') -> None:
2150
+ """编译期动作/作用域硬校验(五类,全部一次列出;任何一条 → SyntaxError):
2151
+ ① @func 缺少"模块别名.函数名"(@func: / @func() / @func(别名))
2152
+ ② in: 项缺 "= 变量表达式" 映射(裸项,多行/单行都查)
2153
+ ③ scope 引用不存在的角色(@名 不在 actors 也不是已声明变量)
2154
+ ④ scope 格式错误(self 与其他目标混用;多目标未加方括号)
2155
+ ⑤ 变量名与 Python 保留字冲突(vars:/out: 目标/in: 左侧/for·par 循环变量)
2156
+ 另:⑥ @notice 分级校验(空 prompt / out / resolve → error;惰性字段 /
2157
+ scope:self / 误填执行者 → warning 桶,见 add_warning);⑦ @assign 空 out
2158
+ → warning 桶(赋值节点什么都不赋值,运行时空过,多半不是本意)。
2159
+ 行号对应用户原文(best-effort,解析后的归一文本与原文可能有空白差异)。"""
2160
+ errors: List[str] = []
2161
+ actors: Set[str] = set((script.actors or {}).keys())
2162
+ table = script.scope_table
2163
+
2164
+ def lookup_var(name: str, chain: Tuple[str, ...] = ()) -> bool:
2165
+ if table is None:
2166
+ return False
2167
+ return table.lookup(name, chain) is not None
2168
+
2169
+ # ⑤ vars: 声明(全局 + 模块,含嵌套)
2170
+ kw_hits: List[Tuple[str, str]] = [] # (raw_name, ctx)
2171
+ for raw_name in (script.vars or {}).keys():
2172
+ if _strip_spec_name(raw_name) in _PY_KEYWORDS:
2173
+ kw_hits.append((raw_name, 'vars:'))
2174
+ def walk_kw(mod: 'ModuleDef', path: str):
2175
+ for raw_name in (mod.locals or {}).keys():
2176
+ if _strip_spec_name(raw_name) in _PY_KEYWORDS:
2177
+ kw_hits.append((raw_name, f'module {path} vars:'))
2178
+ for sub_name, sub in (mod.modules or {}).items():
2179
+ walk_kw(sub, f'{path}.{sub_name}')
2180
+ for mname, mod in (script.modules or {}).items():
2181
+ walk_kw(mod, mname)
2182
+ for raw_name, ctx in kw_hits:
2183
+ line, srcline = _vars_line_lookup(text, raw_name)
2184
+ loc = f',第 {line} 行: {srcline}' if line else ''
2185
+ errors.append(
2186
+ f'{ctx}{loc} → 变量名 "{_strip_spec_name(raw_name)}" 是 Python 保留字,'
2187
+ f'不能用作变量名,请换一个不冲突的名字'
2188
+ )
2189
+
2190
+ # ①②③⑤ 逐 action 检查
2191
+ for ad, ctx, chain in _iter_module_actions(script):
2192
+ loc_src = ''
2193
+ # ① @func 必须带 模块别名.函数名
2194
+ if ad.executor_type == ExecutorType.FUNC:
2195
+ param = (ad.executor_param or '').strip()
2196
+ if not re.match(r'^[\w\u4e00-\u9fff]+\.[\w\u4e00-\u9fff]+$', param):
2197
+ line, srcline = _action_line_lookup(text, ad.name)
2198
+ loc_src = srcline
2199
+ loc = f',第 {line} 行: {srcline}' if line else ''
2200
+ errors.append(
2201
+ f'action "{ad.name}"({ctx}{loc})→ @func 缺少"模块别名.函数名"。'
2202
+ f'必须写成 @func(模块别名.函数名),别名在 code: 区声明。'
2203
+ f'示例:@func(werewolf_utils.get_order)'
2204
+ )
2205
+ # ② in: 裸项
2206
+ bare = [im.local_name for im in (ad.in_mappings or []) if im.bare]
2207
+ if bare:
2208
+ if not loc_src:
2209
+ line, srcline = _action_line_lookup(text, ad.name)
2210
+ loc = f',第 {line} 行: {srcline}' if line else ''
2211
+ else:
2212
+ loc = f',action 头见上'
2213
+ errors.append(
2214
+ f'action "{ad.name}"({ctx}{loc})→ in: 项缺少 "= 变量表达式" 映射:'
2215
+ f'{", ".join(bare)}。in: 的每一项必须是 "参数名 = 变量表达式",'
2216
+ f'例如 in: from_ = speak_from'
2217
+ )
2218
+ # ⑤ in: 左侧保留字
2219
+ for im in (ad.in_mappings or []):
2220
+ if _strip_spec_name(im.local_name) in _PY_KEYWORDS and not im.bare:
2221
+ errors.append(
2222
+ f'action "{ad.name}"({ctx})→ in: 参数名 "{_strip_spec_name(im.local_name)}" '
2223
+ f'是 Python 保留字,不能用作参数名,请改名'
2224
+ )
2225
+ # ⑤ out: 目标保留字
2226
+ for od in (ad.outs or []):
2227
+ target = _out_target_root(od.var_name)
2228
+ if target in _PY_KEYWORDS:
2229
+ errors.append(
2230
+ f'action "{ad.name}"({ctx})→ out: 目标 "{target}" '
2231
+ f'是 Python 保留字,不能用作变量名,请改名'
2232
+ )
2233
+ # ③④ scope
2234
+ if (ad.scope or '').strip():
2235
+ line, srcline = _scope_line_lookup(text, ad.scope)
2236
+ loc = f',第 {line} 行' if line else ''
2237
+ scope_errors_before = len(errors)
2238
+ _check_scope_expr(ad.scope, actors,
2239
+ lambda n: lookup_var(n, chain), ctx, loc, errors)
2240
+ # scope 报错附上原文行(若找到了且还没在消息里)
2241
+ if line and len(errors) > scope_errors_before and srcline and srcline not in errors[-1]:
2242
+ errors[-1] = errors[-1].replace(f'({ctx},第 {line} 行', f'({ctx},第 {line} 行: {srcline}', 1)
2243
+
2244
+ # ⑥ @notice 分级校验(2026-09-07):error = 静默错误行为;warning = 惰性死配置
2245
+ if ad.executor_type == ExecutorType.NOTICE:
2246
+ def _nloc():
2247
+ l, src = _action_line_lookup(text, ad.name)
2248
+ return f',第 {l} 行: {src}' if l else ''
2249
+ # error:prompt 为空——没有内容的公告必然是写错
2250
+ if not (ad.prompt or '').strip():
2251
+ errors.append(
2252
+ f'action "{ad.name}"({ctx}{_nloc()})→ @notice 的 prompt 为空。'
2253
+ f'公告节点必须要有 prompt(它就是注入上下文的公告本体)'
2254
+ )
2255
+ # error:out/resolve——无回答者,作者期待的赋值/校验永远不会发生,
2256
+ # 下游静默读陈旧值
2257
+ if ad.outs:
2258
+ targets = ", ".join(od.var_name for od in ad.outs)
2259
+ errors.append(
2260
+ f'action "{ad.name}"({ctx}{_nloc()})→ @notice 不支持 out:({targets})。'
2261
+ f'公告节点没有回答者,out 声明的变量永远不会被赋值,'
2262
+ f'赋值请用 @assign 或让 AI/human 输出'
2263
+ )
2264
+ if (ad.resolve or '').strip():
2265
+ errors.append(
2266
+ f'action "{ad.name}"({ctx}{_nloc()})→ @notice 不支持 resolve:。'
2267
+ f'公告节点没有回答者,校验函数永远不会被调用'
2268
+ )
2269
+ # warning:惰性死配置——写了永不生效但也不破坏流程,知情即可
2270
+ def _warn(field_label: str, advice: str):
2271
+ add_warning(script,
2272
+ f'action "{ad.name}"({ctx})→ @notice 的 {field_label} '
2273
+ f'不生效:{advice}',
2274
+ where=f'action "{ad.name}"')
2275
+ if (ad.memory or '').strip():
2276
+ _warn('memory:', '公告节点不检索记忆、不收集 blocks')
2277
+ if (ad.context or '').strip():
2278
+ _warn('context:', '公告节点不提取上下文、不收集 blocks')
2279
+ if (ad.showprompt or '').strip():
2280
+ _warn('showprompt:', '公告的 prompt 本身就是可见行,showprompt 语义重复')
2281
+ if ad.max_retries:
2282
+ _warn('max_retries:', '公告节点无回答,没有重试回路')
2283
+ if (ad.fallback or '').strip():
2284
+ _warn('fallback:', '公告节点无回答,永远不会失败跳转')
2285
+ if str(ad.scope or '').strip().lower() == 'self':
2286
+ _warn('scope: self', '公告无发言者,self = 仅 meta.owner 可见')
2287
+ if (ad.executor_param or '').strip():
2288
+ _warn(f'执行者参数 (@notice({ad.executor_param}))',
2289
+ '公告没有发言者,该参数被整体忽略')
2290
+
2291
+ # ⑦ @assign 空 out 校验(2026-09-07 warning 桶,用户拍板):out 为空 =
2292
+ # 赋值节点什么都不赋值,运行时空过——惰性死配置,不阻断编译但作者应知情
2293
+ # (与 ⑥ @notice 的 warning 同级:写了不生效/缺了不报错,但多半不是本意)。
2294
+ if ad.executor_type == ExecutorType.ASSIGN and not (ad.outs or []):
2295
+ def _aloc():
2296
+ l, src = _action_line_lookup(text, ad.name)
2297
+ return f',第 {l} 行: {src}' if l else ''
2298
+ add_warning(
2299
+ script,
2300
+ f'action "{ad.name}"({ctx}{_aloc()})→ @assign 的 out: 为空。'
2301
+ f'赋值节点没有任何 out 声明,运行时会空过(什么都不赋值);'
2302
+ f'若想赋值请补 out:,若不需要赋值请考虑去掉该节点或换执行者类型',
2303
+ where=f'action "{ad.name}"',
2304
+ )
2305
+
2306
+ # ⑤ for/par 循环变量保留字
2307
+ def walk_flows(flow: Optional[FlowGraph], where: str):
2308
+ if flow is None:
2309
+ return
2310
+ for node in flow.nodes.values():
2311
+ meta = node.meta or {}
2312
+ if meta.get('gw_kind') in ('for', 'par'):
2313
+ var_name = meta.get('var_name') or meta.get('par_var') or ''
2314
+ if _strip_spec_name(var_name) in _PY_KEYWORDS:
2315
+ errors.append(
2316
+ f'{where} 循环变量 "{_strip_spec_name(var_name)}" '
2317
+ f'是 Python 保留字,不能用作循环变量名,请改名'
2318
+ )
2319
+ walk_flows(script.flow, 'mainflow')
2320
+ for mname, mod in (script.modules or {}).items():
2321
+ walk_flows(mod.flow, f'module {mname}')
2322
+
2323
+ if errors:
2324
+ raise SyntaxError(
2325
+ '编译错误:剧本语法检查未通过(共 '
2326
+ f'{len(errors)} 处)。\n' + '\n'.join(f' {i}. {e}' for i, e in enumerate(errors, 1))
2327
+ )
2328
+
2329
+
2330
+ # ── 变量声明装配(步骤 B,2026-09-04)────────────────────────
2331
+ # 声明/词法可见域/初值的单一权威 = femoCompiler.vars.model.build_scope_table
2332
+ # ($ 剥名/规范名冲突拦截/定义链登记全部在表内);parser 只负责把书写嵌套的
2333
+ # 模块 vars 收成扁平路径字典('Outer' / 'Outer.Inner')喂给它。
2334
+ # 两个维度正交(猫猫拍板):owner=维度 B 词法可见性,shared=维度 A 并发复制——
2335
+ # **模块 vars: 声明 $ 完全合法**,编译期对 $ 的声明位置不做任何限制。
2336
+ # script.vars 原样保留($ 键不剥,旧路径零影响)。
2337
+
2338
+ def _collect_module_vars(mod: ModuleDef, path: str,
2339
+ out: Dict[str, Dict[str, Any]]) -> None:
2340
+ """沿书写嵌套收集模块 vars 块 → {模块完整路径: locals 字典}。
2341
+ 空 locals 的模块也登记(ScopeTable 定义链注册需要,拍板 6 词法链)。"""
2342
+ out[path] = mod.locals or {}
2343
+ for sub_name, sub in (mod.modules or {}).items():
2344
+ _collect_module_vars(sub, f'{path}.{sub_name}', out)
2345
+
2346
+
2347
+ # ── join/fork 编译期零配对限制(2026-09-03 猫猫二次拍板)────────
2348
+ # fork 与 join 完全解耦、互不干涉:fork 只管分叉(原 task 停 → 几个新 task
2349
+ # 往下跑,后面 join 不 join 与它无关);join 只管把到达的 task 停掉汇成一个
2350
+ # 新主支继续跑(分支从哪儿来、来自几个 fork、嵌不嵌套,与它无关)。
2351
+ # 剧本作者写多嵌套多自由,编译器按规定的跑法执行即可——编译期不做任何
2352
+ # join/fork 配对限制(此前的"配对唯一 fork/禁嵌套/禁多接收端"校验已回滚)。
2353
+ # 运行期 join 协调器(步骤 3):到达即签到,凑齐判定=沿 join 入边反向上溯
2354
+ # 图拓扑收集等待集合(详见施工清单 v3 §3.3)。
2355
+
2356
+
2357
+ def parse_script(text: str, base_dir: str = ".", models: Optional[Dict[str, Any]] = None,
2358
+ soul_checker: Optional[Callable[[str], bool]] = None) -> Script:
2359
+ """主解析入口:文本 → Script 对象;models 非空时编译期校验 AI actor 的 source;
2360
+ soul_checker 非空时编译期校验 actors 的 soul 存在性(normalize 前执行,行号对应用户原文)。"""
2361
+
2362
+ # 编译期 soul 校验:normalize 前扫原始文本(行号对应用户所见)
2363
+ validate_actor_souls(text, soul_checker)
2364
+ raw_text = text # 动作语法校验的行号定位用原文(normalize 前)
2365
+
2366
+ # ── 前置标准化:消除语法糖、续行、裸动作等 ──
2367
+ from femoCompiler.FEMO_normalizer import FEMONormalizer
2368
+ normalizer = FEMONormalizer()
2369
+ text = normalizer.normalize(text)
2370
+
2371
+ blocks = build_blocks(text)
2372
+ script = Script()
2373
+
2374
+ for block in blocks:
2375
+ t = block.type
2376
+ if t == 'meta':
2377
+ script.meta = eval_meta(block)
2378
+ elif t == 'vars':
2379
+ script.vars = eval_vars(block)
2380
+ elif t == 'code':
2381
+ script.code = eval_code(block)
2382
+ elif t == 'actors':
2383
+ script.actors = eval_actors(block)
2384
+ elif t == 'action':
2385
+ act = eval_action(block)
2386
+ script.actions[act.name] = act
2387
+ elif t == 'module':
2388
+ mod = eval_module(block)
2389
+ script.modules[mod.name] = mod
2390
+ elif t == 'memory':
2391
+ mem = eval_method(block)
2392
+ script.memories[mem.name] = mem
2393
+ elif t == 'context':
2394
+ ctx = eval_method(block)
2395
+ script.contexts[ctx.name] = ctx
2396
+ elif t == 'flow':
2397
+ # known_modules 传 None:mainflow 的模块引用(含嵌套点路径)
2398
+ # 由下方后置校验统一做,与 mainflow/module 块的书写顺序解耦
2399
+ script.flow = eval_flow(block, script.actions)
2400
+
2401
+ # 编译期检测(2026-08-24,待议缝隙①转正):声明了 action 却解析出空流程
2402
+ # 图——几乎必然是流程区被静默吞掉或语法没接上,绝不允许空图秒跑完假报
2403
+ # ✅(实测 notify-theater 裸名 mainflow 被 normalizer 吞成空图的实锤形态)。
2404
+ # 无 action 的纯数据/工具剧本不在此列。
2405
+ if script.actions and not script.flow.nodes:
2406
+ raise SyntaxError(
2407
+ 'mainflow 是空的:剧本声明了 action,但流程图没有任何节点。'
2408
+ '请检查 mainflow 区是否漏了 [START] 标记或连线(如 [START] -> 动作 -> [END])。'
2409
+ )
2410
+
2411
+ # 模块 flow 引用校验(模块内 action/嵌套 module/全局 module)
2412
+ for mod in script.modules.values():
2413
+ validate_module_flows(mod, script)
2414
+
2415
+ # mainflow 模块引用后置校验:可见集 = 顶层裸名 + 全部嵌套点路径——
2416
+ # 主流程点路径直引内层模块(&Outer.Inner,运行时 _run_module 点路径
2417
+ # 通道 2026-09-12 起支持)在此放行;裸写内层名(不带路径,如 &Inner)
2418
+ # 仍拒绝——运行时从主流程解析不到裸内层名。后置时机同时解除了模块
2419
+ # 块必须写在 mainflow 之前的隐含顺序要求。
2420
+ mainflow_modules: Dict[str, Any] = dict(script.modules)
2421
+ _collect_module_paths(script.modules, '', mainflow_modules)
2422
+ validate_flow_refs(script.flow, script.actions, mainflow_modules, 'mainflow')
2423
+
2424
+ # 注:meta.database 解析块已移除——set_db_path 无调用点,该机制从未生效;
2425
+ # 运行时数据库路径统一由 FEMO_config.get_db_path() 解析
2426
+ # (get_user_dir()/user_data/memory/Chronica.wor)。
2427
+
2428
+ owner_val = script.meta.get('owner')
2429
+ if not owner_val:
2430
+ # owner 留空(缺失/空列表)→ 归属宿主清单的缺省用户(A2.1:
2431
+ # 默认用户是宿主环境事实,不再是编译器写死;清单缺失回落 u001)
2432
+ script.meta['owner'] = [host_manifest.default_user_id()]
2433
+ elif isinstance(owner_val, (int, float)):
2434
+ script.meta['owner'] = [str(owner_val)]
2435
+ elif isinstance(owner_val, str):
2436
+ script.meta['owner'] = [owner_val]
2437
+ elif isinstance(owner_val, list):
2438
+ script.meta['owner'] = [str(x) for x in owner_val]
2439
+
2440
+ # 编译期校验 AI actor 的 source(宿主模型白名单;models=None 跳过)
2441
+ validate_actor_sources(script, models)
2442
+
2443
+ # 编译期检测:回到「多条无条件出边」的节点(分支数爆炸模式)
2444
+ validate_flow_reentry(script)
2445
+
2446
+ # 变量声明装配(步骤 B,2026-09-04):build_scope_table 是声明/可见域/
2447
+ # 初值的单一权威($ 剥名/规范名冲突拦截/定义链登记全在表内);
2448
+ # script.vars 原样保留($ 键不剥,旧路径零影响)。
2449
+ # 两维度正交(猫猫拍板):owner=词法可见性,shared=并发复制——
2450
+ # 模块 vars: 声明 $ 完全合法,编译期对 $ 不做任何位置限制。
2451
+ module_vars: Dict[str, Dict[str, Any]] = {}
2452
+ for mod in script.modules.values():
2453
+ _collect_module_vars(mod, mod.name, module_vars)
2454
+ script.scope_table = build_scope_table(script.vars or {}, module_vars)
2455
+
2456
+ # 编译期变量声明校验(2026-08-26 建立;2026-09-04 步骤 B 改查
2457
+ # scope_table——for 循环变量/迭代器/条件裸标识符,规则与文案逐条不变)
2458
+ validate_variable_declarations(script)
2459
+
2460
+ # 编译期动作/作用域硬校验(2026-09-07 五类:@func 缺函数名 / in: 裸项 /
2461
+ # scope 引用不存在角色 / scope 格式错(self 混用·多目标无方括号)/
2462
+ # 变量名撞 Python 保留字)——此前全部静默吞掉,现编译期一次列全并拒绝
2463
+ validate_action_syntax(raw_text, script)
2464
+
2465
+ # join 在环上 → 无声卡死预警(warning 桶:编译放行,随回执上浮)
2466
+ validate_join_on_cycle(script)
2467
+
2468
+ return script