femo-plugin 1.0.0 → 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.
- package/FEMO_logo.svg +55 -0
- package/FEMO_logo_slogan.svg +29 -0
- package/README.md +10 -2
- package/_tmp/fallback/driver2.py +176 -0
- package/_tmp/fallback/events.jsonl +108 -0
- package/_tmp/fallback/gateway_ui.py +325 -0
- package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +1 -0
- package/_tmp/fallback/outbox/r1.done +1 -0
- package/_tmp/fallback/outbox/r2.done +1 -0
- package/_tmp/fallback/outbox/r3.done +1 -0
- package/_tmp/fallback/outbox/r4.done +1 -0
- package/_tmp/fallback/outbox/r5.done +1 -0
- 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
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +112 -9
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +17 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +3 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +4 -1
- package/hostAdapter/dshAdapter/host/index.ts +5 -0
- package/hostAdapter/dshAdapter/host/preset-install.ts +59 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +14 -6
- package/hostAdapter/dshAdapter/lib/client.js +124 -5
- package/hostAdapter/dshAdapter/lib/client.js.map +3 -3
- package/hostAdapter/dshAdapter/lib/index.js +58 -18
- package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
- package/hostAdapter/dshAdapter/package.json +1 -5
- package/hostAdapter/dshAdapter/preset/agent.cordis.yml +220 -0
- package/hostAdapter/dshAdapter/preset/preset.yml +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +1 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +10 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/README.md +61 -0
- package/hostAdapter/zcodeAdapter/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +201 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +635 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +4 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +156 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +437 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +77 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +555 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +56 -0
- 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
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +247 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +308 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +35 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +278 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +396 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +2468 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +3630 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +86 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +441 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +485 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +401 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +68 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +767 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +126 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +402 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +544 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +19 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +113 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +686 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +567 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +303 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +245 -0
- 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
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +70 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- 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
- 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
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- 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
- 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
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +5 -0
- 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
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
- package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +5 -0
- 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
- package/package.json +1 -1
- package/scripts/diag-find-redblue.mjs +38 -0
- package/scripts/diag-god-log.mjs +31 -0
- package/scripts/diag-god-log2.mjs +39 -0
- package/scripts/diag-god-log3.mjs +35 -0
- package/scripts/diag-god-log4.mjs +59 -0
- package/scripts/diag-god-log4b.mjs +39 -0
- package/scripts/diag-redblue-god.mjs +39 -0
- package/scripts/diag-redblue-log.mjs +37 -0
- package/scripts/diag-redblue-span.mjs +41 -0
- package/scripts/diag-stage-1017.mjs +63 -0
- package/scripts/dump_session.py +36 -0
- package/scripts/link-workspace.ps1 +51 -0
- package/scripts/list_souls.py +18 -0
- package/scripts/probe-composer-refresh.mjs +197 -0
- package/scripts/seed_story_souls.py +86 -0
- package/scripts/sync-zcode-dist.ps1 +55 -0
- package/scripts/theme-tokenize/color-extract.txt +288 -0
- package/scripts/theme-tokenize/round1-quoted.ps1 +149 -0
- package/scripts/theme-tokenize/round2-bare.ps1 +138 -0
- package/scripts/theme-tokenize/round3-shape.ps1 +110 -0
- package/tests/_diag_r4_join.femo +32 -0
- package/tests/conftest.py +95 -0
- package/tests/diag-subagent-dir-3081.mjs +101 -0
- package/tests/femoGenerator.test.mjs +3909 -0
- package/tests/femoParser.test.mjs +4813 -0
- package/tests/femogen_notice.test.mjs +109 -0
- package/tests/femoparser_validation.test.mjs +84 -0
- package/tests/main-delivery-queue.test.mjs +329 -0
- package/tests/pre-step-gate.test.mjs +282 -0
- package/tests/read-subagent-model.mjs +24 -0
- package/tests/run-script-tests.py +97 -0
- package/tests/safe-steer.test.mjs +59 -0
- package/tests/strip_comments.test.mjs +164 -0
- package/tests/test_actor_failed.py +92 -0
- package/tests/test_compile_warnings.py +99 -0
- package/tests/test_debug_log_bus.py +108 -0
- package/tests/test_debugger_module_mode.py +141 -0
- package/tests/test_error_buckets.py +117 -0
- package/tests/test_error_dispatcher.py +261 -0
- package/tests/test_exec_ai_retry.py +155 -0
- package/tests/test_exec_human_retry.py +159 -0
- package/tests/test_file_resolve.py +104 -0
- package/tests/test_flow_events.py +311 -0
- package/tests/test_flow_ref_validation.py +92 -0
- package/tests/test_func_dict_fallback.py +39 -0
- package/tests/test_job_lifecycle.py +236 -0
- package/tests/test_job_manager.py +424 -0
- package/tests/test_mind.py +99 -0
- package/tests/test_module_call_args.py +258 -0
- package/tests/test_module_visibility.py +238 -0
- package/tests/test_notice.py +143 -0
- package/tests/test_out_whitelist.py +83 -0
- package/tests/test_par_if_dispatch.py +64 -0
- package/tests/test_par_nested_for.py +78 -0
- package/tests/test_parser.py +494 -0
- package/tests/test_pause.py +102 -0
- package/tests/test_pause_contract.py +135 -0
- package/tests/test_protocol_transcript.py +158 -0
- package/tests/test_scope_self.py +202 -0
- package/tests/test_source_validate.py +113 -0
- package/tests/test_task_world.py +447 -0
- package/tests/test_town_structure.py +70 -0
- package/tests/test_v2_checkpoint.py +115 -0
- package/tests/test_v2_env.py +383 -0
- package/tests/test_v2_evaluator.py +227 -0
- package/tests/test_v2_join.py +315 -0
- package/tests/test_v2_join_wiring.py +429 -0
- package/tests/test_v2_merge.py +167 -0
- package/tests/test_v2_model.py +143 -0
- package/tests/test_v2_resume_e2e.py +472 -0
- package/tests/test_var_decls.py +271 -0
- package/tests/verify-model-functions.mjs +90 -0
- package/tests/verify-subagent-model-3081.mjs +153 -0
- 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
- 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
- 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
- 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
- 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
- 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,567 @@
|
|
|
1
|
+
# femoCompiler/vars/evaluator.py
|
|
2
|
+
"""
|
|
3
|
+
vars/evaluator.py — 统一求值器(语言层)
|
|
4
|
+
========================================
|
|
5
|
+
施工清单 v2 §3.3。一切"运行时把表达式变成值"的唯一入口,六类动态解析场景
|
|
6
|
+
(动态键 / actor 追链 / scope 展开的取值面 / prompt 插值 / 条件与迭代器
|
|
7
|
+
表达式 / SET VARIABLE 右值)全部收敛到此——替代旧 runtime 里四套各自为政
|
|
8
|
+
的求值通道(eval_expr / _eval_condition / _eval_iterable_expr / _eval_key),
|
|
9
|
+
变量替换统一经 VarFacade(帧路由自动生效)。
|
|
10
|
+
|
|
11
|
+
- evaluate(expr, facade, strict):字面量/列表字典字面量/@引用/变量路径/
|
|
12
|
+
函数调用。strict=False(默认,对齐旧 eval_expr 宽松回退)时未声明按
|
|
13
|
+
字面量返回;strict=True 时未声明响亮报错。
|
|
14
|
+
- evaluate_condition:条件表达式安全求值(tokenize → 属性访问合并 →
|
|
15
|
+
变量替换 → in 比较规范化 → 白名单 eval),五步管线自旧 runtime 迁移,
|
|
16
|
+
逻辑等价。
|
|
17
|
+
- interpolate_prompt:{var} 插值 + in: 显式映射(含 showprompt 场景——
|
|
18
|
+
顺带修复旧 blocks 侧 showprompt 从不替换变量的 bug:hasattr 恒 False)。
|
|
19
|
+
- resolve_actor_ref / resolve_actor_attr:委托 actor_resolver(追链 10 层/
|
|
20
|
+
保留属性优先/动态属性查可见域字典——逻辑一字不动,只换数据源)。
|
|
21
|
+
|
|
22
|
+
设计约束:不 import asyncio、不发事件、不碰 IO。
|
|
23
|
+
"""
|
|
24
|
+
import ast
|
|
25
|
+
import re
|
|
26
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
27
|
+
|
|
28
|
+
from femoCompiler.vars.model import FEMOVariableError
|
|
29
|
+
from femoCompiler.actor_resolver import resolve_actor_attr, resolve_actor_var
|
|
30
|
+
|
|
31
|
+
_SAFE_BUILTINS = {
|
|
32
|
+
'True': True, 'False': False, 'None': None,
|
|
33
|
+
'len': len, 'int': int, 'str': str, 'float': float,
|
|
34
|
+
'bool': bool, 'abs': abs, 'min': min, 'max': max,
|
|
35
|
+
'sum': sum, 'any': any, 'all': all,
|
|
36
|
+
'isinstance': isinstance, 'hasattr': hasattr,
|
|
37
|
+
'list': list, 'dict': dict, 'set': set, 'tuple': tuple,
|
|
38
|
+
'range': range, 'enumerate': enumerate,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Evaluator:
|
|
43
|
+
"""统一求值器。actors = 剧本演员表(@名 → ActorDef-like,鸭子类型);
|
|
44
|
+
code_modules = PythonBridge.modules(evaluator 的函数调用分支用,
|
|
45
|
+
可 None——无 code: 区的剧本不需要)。"""
|
|
46
|
+
|
|
47
|
+
def __init__(self, actors: Optional[Dict[str, Any]] = None,
|
|
48
|
+
code_modules: Optional[Dict[str, Any]] = None):
|
|
49
|
+
self._actors = actors or {}
|
|
50
|
+
self._code_modules = code_modules or {}
|
|
51
|
+
self._func_cache: Dict[str, Any] = {}
|
|
52
|
+
|
|
53
|
+
# ── 主入口 ────────────────────────────────────────────
|
|
54
|
+
def evaluate(self, expr: Any, facade, strict: bool = False) -> Any:
|
|
55
|
+
"""表达式 → 值。语义对齐旧 FEMORunner.eval_expr:
|
|
56
|
+
复合表达式拒绝(条件判断走 evaluate_condition)。"""
|
|
57
|
+
if not isinstance(expr, str):
|
|
58
|
+
return expr
|
|
59
|
+
expr = expr.strip()
|
|
60
|
+
if any(op in expr for op in (' and ', ' or ', ' not ', ' in ', ' is ',
|
|
61
|
+
'==', '!=', '<=', '>=', '<', '>')):
|
|
62
|
+
raise FEMOVariableError(
|
|
63
|
+
f"evaluate 不支持复合表达式:{expr!r}。条件判断请使用 evaluate_condition。")
|
|
64
|
+
|
|
65
|
+
# .type 属性
|
|
66
|
+
type_match = re.match(r'^(@?\w[\w.\[\]]*)\.type$', expr)
|
|
67
|
+
if type_match:
|
|
68
|
+
val = self.evaluate(type_match.group(1), facade, strict=strict)
|
|
69
|
+
if isinstance(val, str) and val.startswith('@'):
|
|
70
|
+
actor_type = self._get_actor_type(val)
|
|
71
|
+
if actor_type is None:
|
|
72
|
+
raise FEMOVariableError(
|
|
73
|
+
f"'{val}' 不是有效的 actor 引用,无法访问 .type 属性")
|
|
74
|
+
return actor_type
|
|
75
|
+
raise FEMOVariableError(f"变量 '{type_match.group(1)}' 的值 '{val}' 不是 actor 引用")
|
|
76
|
+
|
|
77
|
+
# @ 引用(静态演员 → 名字本身;@变量 → 帧路由取值;不在此追链——
|
|
78
|
+
# 执行者解析的追链走 resolve_actor_ref)
|
|
79
|
+
if expr.startswith('@'):
|
|
80
|
+
if expr in self._actors:
|
|
81
|
+
return expr
|
|
82
|
+
if facade.has(expr):
|
|
83
|
+
return facade.get(expr)
|
|
84
|
+
if strict:
|
|
85
|
+
raise FEMOVariableError(f"未知的 actor 引用: {expr}")
|
|
86
|
+
return expr
|
|
87
|
+
|
|
88
|
+
# 引号字符串
|
|
89
|
+
if (expr.startswith('"') and expr.endswith('"') and len(expr) >= 2) or \
|
|
90
|
+
(expr.startswith("'") and expr.endswith("'") and len(expr) >= 2):
|
|
91
|
+
return expr[1:-1]
|
|
92
|
+
|
|
93
|
+
# 布尔 / None
|
|
94
|
+
if expr in ('true', 'True'):
|
|
95
|
+
return True
|
|
96
|
+
if expr in ('false', 'False'):
|
|
97
|
+
return False
|
|
98
|
+
if expr == 'None':
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
# 数字
|
|
102
|
+
try:
|
|
103
|
+
if '.' in expr:
|
|
104
|
+
return float(expr)
|
|
105
|
+
return int(expr)
|
|
106
|
+
except ValueError:
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
# 列表字面量
|
|
110
|
+
if expr.startswith('[') and expr.endswith(']'):
|
|
111
|
+
inner = expr[1:-1].strip()
|
|
112
|
+
if not inner:
|
|
113
|
+
return []
|
|
114
|
+
return [self.evaluate(it.strip(), facade, strict=strict)
|
|
115
|
+
for it in self._split_items(inner)]
|
|
116
|
+
|
|
117
|
+
# 字典字面量
|
|
118
|
+
if expr.startswith('{') and expr.endswith('}'):
|
|
119
|
+
inner = expr[1:-1].strip()
|
|
120
|
+
if not inner:
|
|
121
|
+
return {}
|
|
122
|
+
return self._parse_dict_literal(inner, facade, strict)
|
|
123
|
+
|
|
124
|
+
# 函数调用(module.func(args))
|
|
125
|
+
fc = re.match(r'^(\w+\.\w+)\(([^)]*)\)$', expr)
|
|
126
|
+
if fc:
|
|
127
|
+
return self._call_module_func(fc.group(1), fc.group(2), facade)
|
|
128
|
+
|
|
129
|
+
# 变量路径 / 简单名:命中(含帧值恰为 None)原样返回;
|
|
130
|
+
# 未声明:strict 报错 / 宽松按字面量返回(保留旧 eval_expr 宽松回退)
|
|
131
|
+
try:
|
|
132
|
+
return facade.get(expr)
|
|
133
|
+
except FEMOVariableError:
|
|
134
|
+
if strict:
|
|
135
|
+
raise
|
|
136
|
+
return expr
|
|
137
|
+
|
|
138
|
+
# ── 迭代器表达式 ──────────────────────────────────────
|
|
139
|
+
def evaluate_iterable(self, expr: str, facade) -> Any:
|
|
140
|
+
"""迭代器表达式:Python eval 优先(range(1,100)、切片等)+
|
|
141
|
+
FEMO 变量视图注入;失败回退 evaluate(FEMO 字面量语法 [@a1,@a2]),
|
|
142
|
+
再失败响亮报错。(迁移自 _eval_iterable_expr;诊断 print 段删除。)"""
|
|
143
|
+
import builtins
|
|
144
|
+
from collections import ChainMap
|
|
145
|
+
|
|
146
|
+
class _FEMOView:
|
|
147
|
+
"""FEMO 变量视图:按 facade 的帧路由供值(替代旧 FEMOVarMap)。
|
|
148
|
+
未声明转 KeyError——ChainMap 依赖 KeyError 跳到下一层 map。"""
|
|
149
|
+
def __getitem__(self, key):
|
|
150
|
+
try:
|
|
151
|
+
return facade.get(key)
|
|
152
|
+
except FEMOVariableError:
|
|
153
|
+
raise KeyError(key) from None
|
|
154
|
+
def __contains__(self, key):
|
|
155
|
+
return facade.has(key)
|
|
156
|
+
|
|
157
|
+
ns = ChainMap(_FEMOView(), vars(builtins))
|
|
158
|
+
try:
|
|
159
|
+
return eval(expr, {"__builtins__": builtins}, ns)
|
|
160
|
+
except Exception:
|
|
161
|
+
try:
|
|
162
|
+
return self.evaluate(expr, facade, strict=False)
|
|
163
|
+
except Exception:
|
|
164
|
+
raise FEMOVariableError(f"无法求值迭代器表达式: {expr!r}")
|
|
165
|
+
|
|
166
|
+
# ── 条件表达式 ────────────────────────────────────────
|
|
167
|
+
def evaluate_condition(self, cond: str, facade) -> bool:
|
|
168
|
+
"""条件求值:tokenize → 属性访问合并 → 变量替换 → in 比较规范化
|
|
169
|
+
→ 白名单 eval。(五步管线自旧 runtime 五个 def 等价迁移。)"""
|
|
170
|
+
tokens = self._tokenize_condition(cond.strip())
|
|
171
|
+
tokens = self._merge_attr_access(tokens, facade)
|
|
172
|
+
tokens = self._replace_variables(tokens, facade)
|
|
173
|
+
tokens = self._merge_dots_and_negatives(tokens)
|
|
174
|
+
tokens = self._normalize_in_comparison(tokens)
|
|
175
|
+
expr = ' '.join(tokens)
|
|
176
|
+
return eval(expr, {"__builtins__": {}}, _SAFE_BUILTINS)
|
|
177
|
+
|
|
178
|
+
def _tokenize_condition(self, expr: str) -> List[str]:
|
|
179
|
+
tokens: List[str] = []
|
|
180
|
+
i = 0
|
|
181
|
+
n = len(expr)
|
|
182
|
+
while i < n:
|
|
183
|
+
c = expr[i]
|
|
184
|
+
if c in (' ', '\t'):
|
|
185
|
+
i += 1
|
|
186
|
+
continue
|
|
187
|
+
if c in ('"', "'"):
|
|
188
|
+
quote = c
|
|
189
|
+
j = i + 1
|
|
190
|
+
while j < n and expr[j] != quote:
|
|
191
|
+
if expr[j] == '\\':
|
|
192
|
+
j += 1
|
|
193
|
+
j += 1
|
|
194
|
+
if j >= n:
|
|
195
|
+
raise FEMOVariableError(f"条件表达式中的字符串未闭合: {expr[i:]}")
|
|
196
|
+
tokens.append(expr[i:j + 1])
|
|
197
|
+
i = j + 1
|
|
198
|
+
continue
|
|
199
|
+
if c in '()[]{}':
|
|
200
|
+
tokens.append(c)
|
|
201
|
+
i += 1
|
|
202
|
+
continue
|
|
203
|
+
if c.isdigit() or (c == '-' and i + 1 < n and expr[i + 1].isdigit()
|
|
204
|
+
and (i == 0 or tokens[-1] in '([=<>!]'
|
|
205
|
+
or tokens[-1] in ('and', 'or', 'not', 'in', 'is')
|
|
206
|
+
or tokens[-1] in '([=<>!+-*/%')):
|
|
207
|
+
j = i + 1 if c == '-' else i
|
|
208
|
+
has_dot = False
|
|
209
|
+
while j < n and (expr[j].isdigit() or (expr[j] == '.' and not has_dot)):
|
|
210
|
+
if expr[j] == '.':
|
|
211
|
+
has_dot = True
|
|
212
|
+
j += 1
|
|
213
|
+
tokens.append(expr[i:j])
|
|
214
|
+
i = j
|
|
215
|
+
continue
|
|
216
|
+
two_char = expr[i:i + 2]
|
|
217
|
+
if two_char in ('==', '!=', '<=', '>=', '//', '**', '<<', '>>', '&&', '||'):
|
|
218
|
+
tokens.append(two_char)
|
|
219
|
+
i += 2
|
|
220
|
+
continue
|
|
221
|
+
if c in '+-*/%<>=!&|^~.':
|
|
222
|
+
tokens.append(c)
|
|
223
|
+
i += 1
|
|
224
|
+
continue
|
|
225
|
+
j = i
|
|
226
|
+
while j < n and (expr[j].isalnum() or expr[j] in '_@'):
|
|
227
|
+
j += 1
|
|
228
|
+
if j > i:
|
|
229
|
+
tokens.append(expr[i:j])
|
|
230
|
+
i = j
|
|
231
|
+
continue
|
|
232
|
+
raise FEMOVariableError(f"条件表达式包含无法识别的字符: {c!r}")
|
|
233
|
+
return tokens
|
|
234
|
+
|
|
235
|
+
def _merge_attr_access(self, tokens: List[str], facade) -> List[str]:
|
|
236
|
+
"""合并 actor 属性访问:A . @B 或 @B . A → 求值为字面量。"""
|
|
237
|
+
result: List[str] = []
|
|
238
|
+
i = 0
|
|
239
|
+
n = len(tokens)
|
|
240
|
+
while i < n:
|
|
241
|
+
if i + 2 < n and tokens[i + 1] == '.' and \
|
|
242
|
+
(tokens[i].startswith('@') or tokens[i + 2].startswith('@')):
|
|
243
|
+
merged = f"{tokens[i]}.{tokens[i + 2]}"
|
|
244
|
+
val = self._eval_actor_attr(merged, facade)
|
|
245
|
+
result.append(repr(val))
|
|
246
|
+
i += 3
|
|
247
|
+
continue
|
|
248
|
+
result.append(tokens[i])
|
|
249
|
+
i += 1
|
|
250
|
+
return result
|
|
251
|
+
|
|
252
|
+
def _eval_actor_attr(self, attr_expr: str, facade) -> Any:
|
|
253
|
+
parts = attr_expr.split('.', 1)
|
|
254
|
+
if len(parts) != 2:
|
|
255
|
+
raise FEMOVariableError(f"无效的属性访问: {attr_expr}")
|
|
256
|
+
left, right = parts
|
|
257
|
+
if left.startswith('@'):
|
|
258
|
+
actor_ref, attr_name = left, right
|
|
259
|
+
elif right.startswith('@'):
|
|
260
|
+
actor_ref, attr_name = right, left
|
|
261
|
+
else:
|
|
262
|
+
raise FEMOVariableError(f"属性访问中必须包含一个 @actor 引用: {attr_expr}")
|
|
263
|
+
return self.resolve_actor_attr(actor_ref, attr_name, facade)
|
|
264
|
+
|
|
265
|
+
def _replace_variables(self, tokens: List[str], facade) -> List[str]:
|
|
266
|
+
result: List[str] = []
|
|
267
|
+
for token in tokens:
|
|
268
|
+
if token in ('and', 'or', 'not', 'in', 'is', 'True', 'False', 'None'):
|
|
269
|
+
result.append(token)
|
|
270
|
+
continue
|
|
271
|
+
if token in ('true', 'TRUE'):
|
|
272
|
+
result.append('True')
|
|
273
|
+
continue
|
|
274
|
+
if token in ('false', 'FALSE'):
|
|
275
|
+
result.append('False')
|
|
276
|
+
continue
|
|
277
|
+
if (token in '()[]{}' or token in '+-*/%<>=!&|^~.'
|
|
278
|
+
or token in ('==', '!=', '<=', '>=', '//', '**', '<<', '>>', '&&', '||')
|
|
279
|
+
or token.startswith(('"', "'"))
|
|
280
|
+
or (token[0].isdigit() or (token[0] == '-' and len(token) > 1 and token[1].isdigit()))):
|
|
281
|
+
result.append(token)
|
|
282
|
+
continue
|
|
283
|
+
if token.startswith('@'):
|
|
284
|
+
if token in self._actors:
|
|
285
|
+
result.append(repr(token))
|
|
286
|
+
continue
|
|
287
|
+
if facade.has(token):
|
|
288
|
+
result.append(repr(facade.get(token)))
|
|
289
|
+
continue
|
|
290
|
+
raise FEMOVariableError(f"条件表达式中未声明的 actor 或变量: {token}")
|
|
291
|
+
if facade.has(token):
|
|
292
|
+
result.append(repr(facade.get(token)))
|
|
293
|
+
continue
|
|
294
|
+
if token in _SAFE_BUILTINS:
|
|
295
|
+
result.append(token)
|
|
296
|
+
continue
|
|
297
|
+
raise FEMOVariableError(f"条件表达式中未声明的变量: {token}")
|
|
298
|
+
return result
|
|
299
|
+
|
|
300
|
+
@staticmethod
|
|
301
|
+
def _merge_dots_and_negatives(tokens: List[str]) -> List[str]:
|
|
302
|
+
merged: List[str] = []
|
|
303
|
+
i = 0
|
|
304
|
+
while i < len(tokens):
|
|
305
|
+
tok = tokens[i]
|
|
306
|
+
if tok == '-' and i + 1 < len(tokens) and tokens[i + 1][0].isdigit():
|
|
307
|
+
merged.append('-' + tokens[i + 1])
|
|
308
|
+
i += 2
|
|
309
|
+
continue
|
|
310
|
+
if (i > 0 and tokens[i - 1].isdigit() and tok == '.'
|
|
311
|
+
and i + 1 < len(tokens) and tokens[i + 1].isdigit()):
|
|
312
|
+
prev = merged.pop()
|
|
313
|
+
merged.append(prev + '.' + tokens[i + 1])
|
|
314
|
+
i += 2
|
|
315
|
+
continue
|
|
316
|
+
merged.append(tok)
|
|
317
|
+
i += 1
|
|
318
|
+
return merged
|
|
319
|
+
|
|
320
|
+
@staticmethod
|
|
321
|
+
def _normalize_in_comparison(tokens: List[str]) -> List[str]:
|
|
322
|
+
"""处理 Python 链式比较问题:'x in y ==/!= True/False' → 正确形式。"""
|
|
323
|
+
i = 0
|
|
324
|
+
n = len(tokens)
|
|
325
|
+
result: List[str] = []
|
|
326
|
+
while i < n:
|
|
327
|
+
if i + 4 < n and tokens[i + 1] == 'in':
|
|
328
|
+
val, container = tokens[i], tokens[i + 2]
|
|
329
|
+
op, bool_val = tokens[i + 3], tokens[i + 4]
|
|
330
|
+
if op in ('==', '!=') and bool_val in ('True', 'False'):
|
|
331
|
+
inner = ['(', val, 'in', container, ')']
|
|
332
|
+
if (op == '==' and bool_val == 'True') or (op == '!=' and bool_val == 'False'):
|
|
333
|
+
result.extend(inner)
|
|
334
|
+
else:
|
|
335
|
+
result.append('not')
|
|
336
|
+
result.extend(inner)
|
|
337
|
+
i += 5
|
|
338
|
+
continue
|
|
339
|
+
result.append(tokens[i])
|
|
340
|
+
i += 1
|
|
341
|
+
return result
|
|
342
|
+
|
|
343
|
+
# ── 动态键 ────────────────────────────────────────────
|
|
344
|
+
def eval_key(self, key_str: str, facade) -> Any:
|
|
345
|
+
"""dict[key] 的 key 求值:变量 → 帧路由取值(修复旧 _eval_key 只查
|
|
346
|
+
globals 的 bug——par 循环变量作 key 现在能解析到局部值);
|
|
347
|
+
字面量数字 / 字符串直取。"""
|
|
348
|
+
t = key_str.strip().strip('"').strip("'")
|
|
349
|
+
if facade.has(t):
|
|
350
|
+
return facade.get(t)
|
|
351
|
+
try:
|
|
352
|
+
return int(t)
|
|
353
|
+
except ValueError:
|
|
354
|
+
return t
|
|
355
|
+
|
|
356
|
+
# ── actor 链与属性(委托 actor_resolver,逻辑一字不动) ──
|
|
357
|
+
def resolve_actor_ref(self, ref: str, facade) -> str:
|
|
358
|
+
"""@引用 → 真实演员名(追链最多 10 层)。"""
|
|
359
|
+
try:
|
|
360
|
+
return resolve_actor_var(facade, self._actors, ref)
|
|
361
|
+
except ValueError as e:
|
|
362
|
+
raise FEMOVariableError(str(e)) from e
|
|
363
|
+
|
|
364
|
+
def resolve_actor_attr(self, actor_ref: str, attr_name: str, facade) -> Any:
|
|
365
|
+
"""@actor.attr / attr.@actor 双向访问(保留属性优先→可见域字典)。"""
|
|
366
|
+
try:
|
|
367
|
+
return resolve_actor_attr(facade, self._actors, actor_ref, attr_name)
|
|
368
|
+
except ValueError as e:
|
|
369
|
+
raise FEMOVariableError(str(e)) from e
|
|
370
|
+
|
|
371
|
+
def _get_actor_type(self, actor_ref: str) -> Optional[str]:
|
|
372
|
+
if not isinstance(actor_ref, str) or not actor_ref.startswith('@'):
|
|
373
|
+
return None
|
|
374
|
+
adef = self._actors.get(actor_ref)
|
|
375
|
+
if adef is None:
|
|
376
|
+
return None
|
|
377
|
+
t = getattr(adef, 'type', None)
|
|
378
|
+
return t.value if t is not None else None
|
|
379
|
+
|
|
380
|
+
# ── prompt 插值 ───────────────────────────────────────
|
|
381
|
+
def interpolate_prompt(self, text: str, facade,
|
|
382
|
+
in_mappings: Optional[List[Any]] = None) -> str:
|
|
383
|
+
"""{var} 插值 + in: 显式映射先替换。
|
|
384
|
+
(迁移自 _replace_prompt_vars + _exec_ai/_exec_human 三段重复的
|
|
385
|
+
in_mappings 手工 replace;统一后 blocks 侧 showprompt 也走此——
|
|
386
|
+
修复旧 hasattr 恒 False 导致的 showprompt 不替换 bug。)"""
|
|
387
|
+
if not isinstance(text, str):
|
|
388
|
+
raise FEMOVariableError(
|
|
389
|
+
f"interpolate_prompt 需要字符串参数,收到 {type(text)}")
|
|
390
|
+
result = text
|
|
391
|
+
for im in (in_mappings or []):
|
|
392
|
+
try:
|
|
393
|
+
val = self.evaluate(im.global_expr, facade, strict=False)
|
|
394
|
+
result = result.replace('{' + im.local_name + '}', str(val))
|
|
395
|
+
except FEMOVariableError:
|
|
396
|
+
raise
|
|
397
|
+
except Exception:
|
|
398
|
+
pass # 保留旧 in_mappings 替换的宽松语义(失败留给 {var} 主路径)
|
|
399
|
+
result = re.sub(r'\{([^}]+)\}', lambda m: self._prompt_replacer(m, facade), result)
|
|
400
|
+
if result is None:
|
|
401
|
+
raise FEMOVariableError("interpolate_prompt: re.sub 返回了 None")
|
|
402
|
+
return result
|
|
403
|
+
|
|
404
|
+
def _prompt_replacer(self, m: re.Match, facade) -> str:
|
|
405
|
+
var_path = m.group(1)
|
|
406
|
+
# 1. 实体视角 @actor.attr(直接求值)
|
|
407
|
+
if re.match(r'^@\w+\.\w+(\.\w+)?$', var_path):
|
|
408
|
+
translated = self._translate_actor_attr(var_path, facade)
|
|
409
|
+
return str(translated)
|
|
410
|
+
# 2. .@ 动态键模式
|
|
411
|
+
if '.@' in var_path:
|
|
412
|
+
container, dynamic_key = self._resolve_actor_path(var_path, facade)
|
|
413
|
+
if dynamic_key:
|
|
414
|
+
val = facade.get(f"{container}[{dynamic_key}]")
|
|
415
|
+
if val is None:
|
|
416
|
+
raise FEMOVariableError(f"Prompt 动态键 {{{var_path}}} 的值为 None。")
|
|
417
|
+
return str(val)
|
|
418
|
+
# 3. @ 开头且不是静态演员 → 帧路由取值
|
|
419
|
+
if var_path.startswith('@') and var_path not in self._actors:
|
|
420
|
+
if facade.has(var_path):
|
|
421
|
+
val = facade.get(var_path)
|
|
422
|
+
if val is None:
|
|
423
|
+
raise FEMOVariableError(
|
|
424
|
+
f"Prompt 变量 {{{var_path}}} 的值为 None,请检查变量是否已赋值。")
|
|
425
|
+
return str(val)
|
|
426
|
+
raise FEMOVariableError(
|
|
427
|
+
f"Prompt 变量 {{{var_path}}} 在 actors 和 vars 中均未找到。")
|
|
428
|
+
# 4. 普通路径求值
|
|
429
|
+
try:
|
|
430
|
+
val = self.evaluate(var_path, facade, strict=False)
|
|
431
|
+
if val is None:
|
|
432
|
+
raise FEMOVariableError(
|
|
433
|
+
f"Prompt 变量 {{{var_path}}} 的值为 None,请检查变量是否已初始化。")
|
|
434
|
+
return str(val)
|
|
435
|
+
except FEMOVariableError:
|
|
436
|
+
raise
|
|
437
|
+
except Exception as e:
|
|
438
|
+
raise FEMOVariableError(f"Prompt 变量替换失败: {{{var_path}}},错误: {e}") from e
|
|
439
|
+
|
|
440
|
+
def _translate_actor_attr(self, expr: str, facade) -> str:
|
|
441
|
+
"""@actor.attr → 实际值(prompt 替换用)。多级属性不支持(旧语义)。
|
|
442
|
+
facade 必须传——属性非保留字时 actor_resolver 内部要用它查 vars 字典
|
|
443
|
+
(旧实现传 self.vm;漏传 None 会在 vm.has 处 AttributeError)。"""
|
|
444
|
+
pattern = r'(@\w+)\.(\w+)(\.\w+)?'
|
|
445
|
+
|
|
446
|
+
def replacer(m: re.Match) -> str:
|
|
447
|
+
if m.group(3):
|
|
448
|
+
raise FEMOVariableError(f"不支持多级属性访问: {m.group(0)}")
|
|
449
|
+
value = self.resolve_actor_attr(m.group(1), m.group(2), facade)
|
|
450
|
+
return str(value)
|
|
451
|
+
|
|
452
|
+
return re.sub(pattern, replacer, expr)
|
|
453
|
+
|
|
454
|
+
def _resolve_actor_path(self, path: str, facade) -> tuple:
|
|
455
|
+
"""vote_results.@voter / @voter.salary → (容器路径, 动态键)。
|
|
456
|
+
(迁移自 FEMORunner._resolve_actor_path。)"""
|
|
457
|
+
if '.@' not in path and not path.startswith('@'):
|
|
458
|
+
return path, None
|
|
459
|
+
parts = path.split('.')
|
|
460
|
+
resolved_parts = []
|
|
461
|
+
dynamic_key = None
|
|
462
|
+
for i, part in enumerate(parts):
|
|
463
|
+
if part.startswith('@'):
|
|
464
|
+
val = self.evaluate(part, facade, strict=False)
|
|
465
|
+
if val is None:
|
|
466
|
+
val = part
|
|
467
|
+
resolved_parts.append(str(val))
|
|
468
|
+
if i == len(parts) - 1:
|
|
469
|
+
dynamic_key = str(val)
|
|
470
|
+
else:
|
|
471
|
+
resolved_parts.append(part)
|
|
472
|
+
container = '.'.join(resolved_parts[:-1]) if len(resolved_parts) > 1 \
|
|
473
|
+
else resolved_parts[0]
|
|
474
|
+
return container, dynamic_key
|
|
475
|
+
|
|
476
|
+
# ── 赋值右值 ──────────────────────────────────────────
|
|
477
|
+
def eval_right_value(self, raw: str, facade) -> Any:
|
|
478
|
+
"""赋值右值:引号串去引号(含中文引号)/ 布尔 / 数字 / 字面量 /
|
|
479
|
+
变量表达式。(迁移自 FEMORunner._eval_right_value。)"""
|
|
480
|
+
raw = raw.strip()
|
|
481
|
+
if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in ('"', "'", '“', '”'):
|
|
482
|
+
return raw[1:-1]
|
|
483
|
+
if raw.lower() == 'true':
|
|
484
|
+
return True
|
|
485
|
+
if raw.lower() == 'false':
|
|
486
|
+
return False
|
|
487
|
+
try:
|
|
488
|
+
if '.' in raw:
|
|
489
|
+
return float(raw)
|
|
490
|
+
return int(raw)
|
|
491
|
+
except ValueError:
|
|
492
|
+
pass
|
|
493
|
+
if (raw.startswith('[') and raw.endswith(']')) or \
|
|
494
|
+
(raw.startswith('{') and raw.endswith('}')):
|
|
495
|
+
try:
|
|
496
|
+
return ast.literal_eval(raw)
|
|
497
|
+
except (ValueError, SyntaxError) as e:
|
|
498
|
+
raise FEMOVariableError(f"无法解析字面量 {raw!r}: {e}") from e
|
|
499
|
+
return self.evaluate(raw, facade, strict=False)
|
|
500
|
+
|
|
501
|
+
def clear_func_cache(self) -> None:
|
|
502
|
+
"""清空函数调用缓存。**接线约定(步骤 C4)**:runtime 的
|
|
503
|
+
_follow_next_edge 在每条边评估前调用——对齐旧语义
|
|
504
|
+
(self._func_cache = {}),否则条件边里的副作用函数(随机发牌、
|
|
505
|
+
读文件)会被缓存跨节点复用(狼人杀随机发牌直接失效)。"""
|
|
506
|
+
self._func_cache.clear()
|
|
507
|
+
|
|
508
|
+
# ── 内部 ──────────────────────────────────────────────
|
|
509
|
+
@staticmethod
|
|
510
|
+
def _split_items(s: str) -> List[str]:
|
|
511
|
+
items, depth, cur, in_str, qc = [], 0, [], False, None
|
|
512
|
+
for c in s:
|
|
513
|
+
if in_str:
|
|
514
|
+
cur.append(c)
|
|
515
|
+
if c == qc:
|
|
516
|
+
in_str = False
|
|
517
|
+
else:
|
|
518
|
+
if c in ('"', "'"):
|
|
519
|
+
in_str, qc = True, c
|
|
520
|
+
cur.append(c)
|
|
521
|
+
elif c in ('[', '{', '('):
|
|
522
|
+
depth += 1
|
|
523
|
+
cur.append(c)
|
|
524
|
+
elif c in (']', '}', ')'):
|
|
525
|
+
depth -= 1
|
|
526
|
+
cur.append(c)
|
|
527
|
+
elif c == ',' and depth == 0:
|
|
528
|
+
items.append(''.join(cur))
|
|
529
|
+
cur = []
|
|
530
|
+
else:
|
|
531
|
+
cur.append(c)
|
|
532
|
+
if cur:
|
|
533
|
+
items.append(''.join(cur))
|
|
534
|
+
return items
|
|
535
|
+
|
|
536
|
+
def _parse_dict_literal(self, inner: str, facade, strict: bool) -> Dict[str, Any]:
|
|
537
|
+
result: Dict[str, Any] = {}
|
|
538
|
+
for item in self._split_items(inner):
|
|
539
|
+
if ':' in item:
|
|
540
|
+
k, v = item.split(':', 1)
|
|
541
|
+
key = k.strip().strip('"').strip("'")
|
|
542
|
+
result[key] = self.evaluate(v.strip(), facade, strict=strict)
|
|
543
|
+
return result
|
|
544
|
+
|
|
545
|
+
def _call_module_func(self, func_path: str, args_str: str, facade) -> Any:
|
|
546
|
+
"""module.func(args) → 外部 Python 函数(evaluator 的函数调用分支)。
|
|
547
|
+
桥/模块缺失返回 None(旧语义);参数逐个 evaluate。"""
|
|
548
|
+
cache_key = f"{func_path}({args_str})"
|
|
549
|
+
if cache_key in self._func_cache:
|
|
550
|
+
return self._func_cache[cache_key]
|
|
551
|
+
parts = func_path.split('.', 1)
|
|
552
|
+
if len(parts) != 2:
|
|
553
|
+
return None
|
|
554
|
+
mod = self._code_modules.get(parts[0])
|
|
555
|
+
if mod is None or not hasattr(mod, parts[1]):
|
|
556
|
+
return None
|
|
557
|
+
func = getattr(mod, parts[1])
|
|
558
|
+
args = []
|
|
559
|
+
if args_str.strip():
|
|
560
|
+
for arg in args_str.split(','):
|
|
561
|
+
arg = arg.strip()
|
|
562
|
+
if not arg:
|
|
563
|
+
continue
|
|
564
|
+
args.append(self.evaluate(arg, facade, strict=False))
|
|
565
|
+
result = func(*args)
|
|
566
|
+
self._func_cache[cache_key] = result
|
|
567
|
+
return result
|