femo-plugin 1.0.2 → 1.0.4
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/README.md +632 -635
- package/docs/ActiveRoadmaps/ARCHITECTURE.md +466 -0
- package/docs/ActiveRoadmaps/compiler/345/244/232job/345/220/214/350/267/221/346/224/271/351/200/240-/346/226/275/345/267/245/346/270/205/345/215/225.md +164 -0
- package/docs/ActiveRoadmaps/dshAdapter-/351/207/215/346/236/204/346/226/275/345/267/245/346/270/205/345/215/225.md +154 -0
- package/docs/ActiveRoadmaps/hub/345/224/257/344/270/200/345/214/226/350/256/276/350/256/241.md +107 -0
- package/docs/ActiveRoadmaps/webAdapter-/351/235/231/351/273/230/351/230/266/346/242/257/346/226/275/345/267/245/344/272/244/346/216/245.md +158 -0
- package/docs/ActiveRoadmaps/zcode-/346/227/240/345/255/220/344/273/243/347/220/206/345/214/226/346/226/275/345/267/245/346/270/205/345/215/225.md +166 -0
- package/docs/ActiveRoadmaps//345/274/225/346/223/216/345/270/270/351/251/273/345/214/226/347/254/2542/346/255/245/344/272/244/346/216/245.md +108 -0
- package/docs/ActiveRoadmaps//345/274/225/346/223/216/345/270/270/351/251/273/350/277/233/347/250/213/346/226/275/345/267/245/346/270/205/345/215/225.md +178 -0
- package/docs/ActiveRoadmaps//346/212/225/345/275/261/345/256/277/344/270/273/346/240/207/346/263/250/344/277/256/346/255/243/350/256/276/350/256/241.md +61 -0
- package/docs/ActiveRoadmaps//346/212/225/345/275/261/351/241/265/346/213/206/345/210/206/346/226/275/345/267/245/346/270/205/345/215/225.md +116 -0
- package/docs/ActiveRoadmaps//347/224/273/345/270/203/347/233/264/350/277/236/345/274/225/346/223/216/346/226/275/345/267/245/346/270/205/345/215/225.md +259 -0
- package/docs/README.md +38 -0
- package/docs/Specs//345/205/254/345/205/261/345/261/202/350/256/276/350/256/241/347/272/246/346/235/237.md +63 -0
- package/docs/Specs//345/256/277/344/270/273/346/216/245/345/205/245/346/270/205/345/215/225.md +137 -0
- package/docs/Specs//346/212/225/345/275/261/344/270/255/345/277/203/350/241/214/345/215/217/350/256/256.md +569 -0
- package/docs/Specs//350/267/250/345/256/277/344/270/273/345/257/271/350/257/235/346/223/215/344/275/234/346/214/207/345/215/227.md +124 -0
- package/femo2host/AGENTS.md +165 -0
- package/femo2host/femoGenConnector/SKILL.common.md +232 -0
- package/femo2host/femoGenConnector/engine-client.mjs +255 -0
- package/femo2host/femoGenConnector/femogen-canvas-state.mjs +56 -0
- package/femo2host/femoGenConnector/femogen-files.d.mts +22 -0
- package/femo2host/femoGenConnector/femogen-files.mjs +208 -0
- package/femo2host/femoGenConnector/file-dialogs.d.mts +15 -0
- package/femo2host/femoGenConnector/file-dialogs.mjs +131 -0
- package/femo2host/femoGenConnector/sse-core.d.mts +40 -0
- package/femo2host/femoGenConnector/sse-core.mjs +95 -0
- package/femo2host/femoRoot.d.mts +7 -0
- package/femo2host/femoRoot.mjs +44 -0
- package/femo2host/femoToolcall/chronica.py +159 -156
- package/femo2host/femoToolcall/femo_debugger.py +1518 -1515
- package/femo2host/femo_api.py +472 -437
- package/femo2host/femo_gen_api.jsx +90 -77
- package/femo2host/host/api-retry.d.mts +44 -0
- package/femo2host/host/api-retry.mjs +155 -0
- package/femo2host/host/cast-core.d.mts +20 -0
- package/femo2host/host/cast-core.mjs +113 -0
- package/femo2host/host/daemon-client.d.mts +63 -0
- package/femo2host/host/daemon-client.mjs +606 -0
- package/femo2host/host/debug-run-core.d.mts +121 -0
- package/femo2host/host/debug-run-core.mjs +531 -0
- package/femo2host/host/delivery-queue.d.mts +18 -0
- package/femo2host/host/delivery-queue.mjs +101 -0
- package/femo2host/host/event-core.d.mts +84 -0
- package/femo2host/host/event-core.mjs +356 -0
- package/femo2host/host/femo-relation.d.mts +22 -0
- package/femo2host/host/femo-relation.mjs +39 -0
- package/femo2host/host/hub-client.d.mts +11 -0
- package/femo2host/host/hub-client.mjs +74 -0
- package/femo2host/host/hub-feed-core.d.mts +68 -0
- package/femo2host/host/hub-feed-core.mjs +274 -0
- package/femo2host/host/hub-render-core.d.mts +43 -0
- package/femo2host/host/hub-render-core.mjs +140 -0
- package/femo2host/host/mailbox-push-core.d.mts +40 -0
- package/femo2host/host/mailbox-push-core.mjs +113 -0
- package/femo2host/host/mount-registry.mjs +110 -0
- package/femo2host/host/node-retry.d.mts +37 -0
- package/femo2host/host/node-retry.mjs +200 -0
- package/femo2host/host/notice-core.d.mts +33 -0
- package/femo2host/host/notice-core.mjs +83 -0
- package/femo2host/host/projection-core.d.mts +78 -0
- package/femo2host/host/projection-core.mjs +279 -0
- package/femo2host/host/run-control-core.d.mts +23 -0
- package/femo2host/host/run-control-core.mjs +72 -0
- package/femo2host/host/run-state-core.d.mts +59 -0
- package/femo2host/host/run-state-core.mjs +173 -0
- package/femo2host/host/session-registry.mjs +56 -0
- package/femo2host/host/skill-expand.d.mts +11 -0
- package/femo2host/host/skill-expand.mjs +51 -0
- package/femo2host/host/speech-core.d.mts +43 -0
- package/femo2host/host/speech-core.mjs +75 -0
- package/femo2host/host/state-files.d.mts +35 -0
- package/femo2host/host/state-files.mjs +267 -0
- package/femo2host/host/subagent-core.d.mts +81 -0
- package/femo2host/host/subagent-core.mjs +303 -0
- package/femo2host/host/tools-core.d.mts +72 -0
- package/femo2host/host/tools-core.mjs +684 -0
- package/femo2host/host/variable-api.d.mts +23 -0
- package/femo2host/host/variable-api.mjs +90 -0
- package/femo2host/mail_courier.py +104 -0
- package/femo2host/mailbox.py +545 -0
- package/femo2host/projectionCenter/app.css +848 -0
- package/femo2host/projectionCenter/composer.mjs +272 -0
- package/femo2host/projectionCenter/debug-panel.mjs +131 -0
- package/femo2host/projectionCenter/index.html +96 -0
- package/femo2host/projectionCenter/main.mjs +479 -0
- package/femo2host/projectionCenter/panels.mjs +280 -0
- package/femo2host/projectionCenter/render.mjs +695 -0
- package/femo2host/projectionCenter/sessions.mjs +138 -0
- package/femo2host/projectionCenter/state.mjs +105 -0
- package/femo2host/projectionCenter/theme.css +250 -0
- package/femo2host/projectionCenter/util.mjs +96 -0
- package/femo2host/projection_hub.py +8422 -0
- package/femo2host/python/femo_bridge.py +2131 -0
- package/femo2host/python/femo_daemon.py +1209 -0
- package/femo2host/python/setting.py +153 -0
- package/femoBridges/ContextExample.py +167 -42
- package/femoBridges/MemoryExample.py +33 -30
- package/femoBridges/getDir/get_dir.py +32 -18
- package/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 +1 -1
- package/femoBridges/llmBridge.py +1 -1
- package/femoBridges/llmProviders.py +39 -35
- package/femoCompiler/AGENTS.md +185 -0
- package/femoCompiler/FEMO_CLIrenderer.py +50 -30
- package/femoCompiler/FEMO_config.py +2 -1
- package/femoCompiler/FEMO_errors.py +286 -278
- package/femoCompiler/FEMO_normalizer.py +12 -7
- package/femoCompiler/FEMO_parser.py +217 -118
- package/femoCompiler/FEMO_runtime.py +491 -251
- package/femoCompiler/FEMO_scope_resolver.py +6 -3
- package/femoCompiler/actor_resolver.py +3 -3
- package/femoCompiler/block_collector.py +31 -28
- package/femoCompiler/db_utils.py +18 -0
- package/femoCompiler/femoAsync.py +436 -401
- package/femoCompiler/host_manifest.py +22 -2
- package/femoCompiler/job_manager.py +203 -61
- package/femoCompiler/protocol.py +13 -12
- package/femoCompiler/save_dialog.py +103 -59
- package/femoCompiler/task_world.py +579 -544
- package/femoCompiler/vars/checkpoint.py +3 -3
- package/femoCompiler/vars/env.py +77 -12
- package/femoCompiler/vars/evaluator.py +11 -6
- package/femoCompiler/vars/join.py +1 -1
- package/femoCompiler/vars/model.py +7 -7
- package/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +5 -5
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/AI/350/201/212/345/244/251/345/256/244-/345/270/246agent/347/211/210.femo +142 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/AI/350/201/212/345/244/251/345/256/244.femo +111 -0
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +80 -10
- package/{hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo → femoExamples/LuxFiat/luxfiat-loop.femo} +67 -38
- package/femoExamples/LuxFiat/{luxfiat.femo → luxfiat-simple.femo} +1 -15
- package/femoExamples/LuxFiat/wait.py +2 -2
- package/femoExamples/_join_wiring_tlib.py +28 -0
- package/femoExamples/discussion.femo +7 -5
- package/femoExamples/mt_test/file_a.py +5 -0
- package/femoExamples/plan-mode.femo +55 -0
- package/femoExamples//345/237/272/347/241/200/350/277/236/351/200/232/346/265/213/350/257/225.femo +38 -0
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +248 -20
- package/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils9.py +609 -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 → 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-9/344/272/272/351/242/204/345/245/263/347/214/216.femo} +308 -53
- package/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 +222 -47
- package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +4 -4
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +286 -2
- 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-/350/217/234/345/270/202/345/234/272/345/261/200.femo +95 -3
- 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 +126 -42
- package/femoGen/AGENTS.md +145 -0
- package/femoGen/document_ch.html +20 -13
- package/femoGen/document_en.html +9 -2
- package/femoGen/index.html +4 -2
- package/femoGen/intro_ch.html +28 -26
- package/femoGen/intro_en.html +9 -2
- package/femoGen/src/FemoWorAuto.jsx +1215 -257
- package/femoGen/src/actionModal.jsx +2 -2
- package/femoGen/src/bubbleOverlay.jsx +7 -5
- package/femoGen/src/canvasNodes.jsx +261 -61
- package/femoGen/src/common.jsx +94 -20
- package/femoGen/src/debugPanel.jsx +170 -43
- package/femoGen/src/engineWatch.jsx +323 -0
- package/femoGen/src/faIcons.jsx +11 -4
- package/femoGen/src/femoDiagnostics.js +1 -1
- package/femoGen/src/femoDirBrowse.jsx +430 -0
- package/femoGen/src/femoFileList.jsx +36 -6
- package/femoGen/src/femoGenerator.jsx +9 -9
- package/femoGen/src/femoParser.jsx +2276 -2255
- package/femoGen/src/femoPreview.jsx +30 -0
- package/femoGen/src/femoSaveReminder.jsx +75 -0
- package/femoGen/src/graphBuilder.jsx +2 -2
- package/femoGen/src/indentEdit.js +81 -0
- package/femoGen/src/libPanel.jsx +1 -1
- package/femoGen/src/mobileView.jsx +2871 -2796
- package/femoGen/src/projectPanel.jsx +2 -2
- package/femoGen/src/snap.js +101 -0
- package/femoGen/src/soulModal.jsx +4 -2
- package/femoGen/src/styles/font.css +13 -10
- package/femoGen/src/themes.js +297 -12
- package/femoGen/src/watchMirror.js +170 -0
- package/femoGen/vite.config.js +33 -28
- package/hostAdapter/dshAdapter/README.md +112 -68
- package/hostAdapter/dshAdapter/build.mjs +49 -6
- package/hostAdapter/dshAdapter/check-imports.mjs +85 -0
- package/hostAdapter/dshAdapter/client/client-ui/cast-button.tsx +232 -0
- package/hostAdapter/dshAdapter/client/{lineage-fork-native.jsx → client-ui/catalog-dropdown.jsx} +689 -624
- package/hostAdapter/dshAdapter/client/client-ui/chat-node.tsx +12 -9
- package/hostAdapter/dshAdapter/client/client-ui/composer-common.tsx +74 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer-permission.tsx +183 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer-ring.tsx +196 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer-run-state.tsx +134 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer-stats.tsx +163 -0
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +417 -1100
- package/hostAdapter/dshAdapter/client/client-ui/editor-page.tsx +747 -726
- package/hostAdapter/dshAdapter/client/client-ui/editor-view.tsx +89 -88
- package/hostAdapter/dshAdapter/client/client-ui/hub-constants.ts +10 -0
- package/hostAdapter/dshAdapter/client/client-ui/hub-window.tsx +545 -0
- package/hostAdapter/dshAdapter/client/client-ui/primitives-compat.ts +39 -0
- package/hostAdapter/dshAdapter/client/client-ui/proj2/frame-router.ts +17 -52
- package/hostAdapter/dshAdapter/client/client-ui/proj2/index.ts +1 -1
- package/hostAdapter/dshAdapter/client/client-ui/proj2/ledger.ts +12 -12
- package/hostAdapter/dshAdapter/client/client-ui/proj2/turn-view.tsx +8 -16
- package/hostAdapter/dshAdapter/client/client-ui/proj2/window-id.ts +8 -9
- package/hostAdapter/dshAdapter/client/client-ui/stream-store.ts +187 -550
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +4 -10
- package/hostAdapter/dshAdapter/client/client-ui/view-button.tsx +550 -572
- package/hostAdapter/dshAdapter/client/client-ui/view-state.ts +1 -1
- package/hostAdapter/dshAdapter/client/client.tsx +611 -518
- package/hostAdapter/dshAdapter/client/femo-reasoning-row.tsx +104 -103
- package/hostAdapter/dshAdapter/client/femo-tool-row.tsx +264 -0
- package/hostAdapter/dshAdapter/client/lineage-fork.jsx +55 -570
- package/hostAdapter/dshAdapter/dshPatch/DSH-0.1.2-fork/344/277/256/346/224/271/351/234/200/346/261/202.md +4 -4
- package/hostAdapter/dshAdapter/dshPatch/patch-dsh-0.1.2-alpha.1.py +1 -1
- package/{femo2host/femoToolcall → hostAdapter/dshAdapter}/femo-chat.mjs +4 -2
- package/hostAdapter/dshAdapter/host/actor-name.ts +30 -0
- package/hostAdapter/dshAdapter/host/actor-usage.ts +54 -0
- package/hostAdapter/dshAdapter/host/actors/dispatch.ts +152 -0
- package/hostAdapter/dshAdapter/host/actors/main/capture.ts +219 -0
- package/hostAdapter/dshAdapter/host/actors/main/delivery.ts +233 -0
- package/hostAdapter/dshAdapter/host/actors/main/index.ts +420 -0
- package/hostAdapter/dshAdapter/host/actors/main/notice.ts +180 -0
- package/hostAdapter/dshAdapter/host/actors/native/child-setup.ts +103 -0
- package/hostAdapter/dshAdapter/host/actors/native/index.ts +672 -0
- package/hostAdapter/dshAdapter/host/actors/native/registry.ts +55 -0
- package/hostAdapter/dshAdapter/host/actors/native/turn-watch.ts +159 -0
- package/hostAdapter/dshAdapter/host/api-retry.ts +30 -123
- package/hostAdapter/dshAdapter/host/bridge-supervisor.ts +96 -0
- package/hostAdapter/dshAdapter/host/bridge.ts +147 -224
- package/hostAdapter/dshAdapter/host/compat/dsh-session-host.ts +46 -0
- package/hostAdapter/dshAdapter/host/{list-cache.ts → compat/list-cache.ts} +1 -1
- package/hostAdapter/dshAdapter/host/compat/plugin-source.ts +41 -0
- package/hostAdapter/dshAdapter/host/config.ts +149 -124
- package/hostAdapter/dshAdapter/host/debug-run.ts +274 -793
- package/hostAdapter/dshAdapter/host/diag/debug-log.ts +44 -0
- package/hostAdapter/dshAdapter/host/{diag-feed.ts → diag/diag-feed.ts} +11 -18
- package/hostAdapter/dshAdapter/host/{host-log.ts → diag/host-log.ts} +1 -1
- package/hostAdapter/dshAdapter/host/engine-transcript.ts +2 -2
- package/hostAdapter/dshAdapter/host/events/engine-events.ts +747 -0
- package/hostAdapter/dshAdapter/host/events/mailbox-push.ts +332 -0
- package/hostAdapter/dshAdapter/host/{pre-step-gate.ts → events/pre-step-gate.ts} +26 -32
- package/hostAdapter/dshAdapter/host/femo-files.ts +6 -207
- package/hostAdapter/dshAdapter/host/femo-skill.ts +153 -0
- package/hostAdapter/dshAdapter/host/femoIdentity.ts +101 -0
- package/hostAdapter/dshAdapter/host/http.ts +10 -12
- package/hostAdapter/dshAdapter/host/hub/god-mirror.ts +307 -0
- package/hostAdapter/dshAdapter/host/hub/hub-feed.ts +129 -0
- package/hostAdapter/dshAdapter/host/hub/hub-proxy.ts +203 -0
- package/hostAdapter/dshAdapter/host/{stream-frames.ts → hub/stream-frames.ts} +36 -77
- package/hostAdapter/dshAdapter/host/index.ts +354 -638
- package/hostAdapter/dshAdapter/host/job-index.ts +36 -0
- package/hostAdapter/dshAdapter/host/main-actor.ts +24 -853
- package/hostAdapter/dshAdapter/host/main-delivery-queue.ts +5 -112
- package/hostAdapter/dshAdapter/host/node-retry.ts +22 -246
- package/hostAdapter/dshAdapter/host/persona.ts +50 -96
- package/hostAdapter/dshAdapter/host/projection/hub-anchor.ts +21 -0
- package/hostAdapter/dshAdapter/host/{projection.ts → projection/projection.ts} +112 -188
- package/hostAdapter/dshAdapter/host/{windowing-native.ts → projection/windowing-native.ts} +35 -37
- package/hostAdapter/dshAdapter/host/routes/dialogs.ts +63 -0
- package/hostAdapter/dshAdapter/host/routes/engine-gateway.ts +128 -0
- package/hostAdapter/dshAdapter/host/routes/index.ts +603 -0
- package/hostAdapter/dshAdapter/host/{projection-input.ts → routes/projection-input.ts} +255 -246
- package/hostAdapter/dshAdapter/host/routes/projection.ts +174 -0
- package/hostAdapter/dshAdapter/host/routes/run.ts +127 -0
- package/hostAdapter/dshAdapter/host/routes/script-files.ts +68 -0
- package/hostAdapter/dshAdapter/host/routes/state.ts +273 -0
- package/hostAdapter/dshAdapter/host/run-control.ts +687 -641
- package/hostAdapter/dshAdapter/host/session-roster.ts +407 -0
- package/hostAdapter/dshAdapter/host/sse.ts +27 -0
- package/hostAdapter/dshAdapter/host/state-files.ts +13 -301
- package/hostAdapter/dshAdapter/host/tool-deps.ts +299 -0
- package/hostAdapter/dshAdapter/host/tools.ts +395 -486
- package/hostAdapter/dshAdapter/host/verbs.ts +81 -0
- package/hostAdapter/dshAdapter/host.manifest.json +2 -1
- package/hostAdapter/dshAdapter/lib/client.js +9209 -6558
- package/hostAdapter/dshAdapter/lib/client.js.map +4 -4
- package/hostAdapter/dshAdapter/lib/index.js +13 -8213
- package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
- package/hostAdapter/dshAdapter/lib/main.js +10154 -0
- package/hostAdapter/dshAdapter/lib/main.js.map +7 -0
- package/hostAdapter/dshAdapter/package.json +5 -4
- package/hostAdapter/dshAdapter/pnpm-lock.yaml +606 -596
- package/hostAdapter/dshAdapter/shared/window-id.d.mts +5 -0
- package/hostAdapter/dshAdapter/shared/window-id.mjs +22 -0
- package/hostAdapter/dshAdapter/tsconfig.host-verify.json +6 -0
- package/hostAdapter/dshAdapter/tsconfig.json +1 -3
- package/hostAdapter/webAdapter/AGENTS.md +203 -0
- package/hostAdapter/webAdapter/console/index.html +760 -0
- package/hostAdapter/webAdapter/extension/background.js +738 -0
- package/hostAdapter/webAdapter/extension/bubble.js +201 -0
- package/hostAdapter/webAdapter/extension/icons/icon128.png +0 -0
- package/hostAdapter/webAdapter/extension/icons/icon16.png +0 -0
- package/hostAdapter/webAdapter/extension/icons/icon32.png +0 -0
- package/hostAdapter/webAdapter/extension/icons/icon48.png +0 -0
- package/hostAdapter/webAdapter/extension/seat-agent-core.js +791 -0
- package/hostAdapter/webAdapter/extension/sidepanel/conn.mjs +25 -0
- package/hostAdapter/webAdapter/extension/sidepanel/feeds.mjs +57 -0
- package/hostAdapter/webAdapter/extension/sidepanel/human-seat.mjs +111 -0
- package/hostAdapter/webAdapter/extension/sidepanel/main.mjs +186 -0
- package/hostAdapter/webAdapter/extension/sidepanel/run-control.mjs +183 -0
- package/hostAdapter/webAdapter/extension/sidepanel/seats.mjs +172 -0
- package/hostAdapter/webAdapter/extension/sidepanel/svclog.mjs +78 -0
- package/hostAdapter/webAdapter/extension/sidepanel.html +600 -0
- package/hostAdapter/webAdapter/manifest.json +158 -0
- package/hostAdapter/webAdapter/native/install-native-host.cmd +8 -0
- package/hostAdapter/webAdapter/native/install-native-host.mjs +27 -0
- package/hostAdapter/webAdapter/native/register-core.mjs +101 -0
- package/hostAdapter/webAdapter/native/web-launcher.cs +141 -0
- package/hostAdapter/webAdapter/native/web-launcher.mjs +160 -0
- package/hostAdapter/webAdapter/package.json +13 -0
- package/hostAdapter/webAdapter/readme.md +365 -0
- package/hostAdapter/webAdapter/server/board.mjs +42 -0
- package/hostAdapter/webAdapter/server/bridge.mjs +68 -0
- package/hostAdapter/webAdapter/server/canvas.mjs +520 -0
- package/hostAdapter/webAdapter/server/http-io.mjs +20 -0
- package/hostAdapter/webAdapter/server/keeper.mjs +114 -0
- package/hostAdapter/webAdapter/server/mailbox-push.mjs +184 -0
- package/hostAdapter/webAdapter/server/runtime.mjs +1025 -0
- package/hostAdapter/webAdapter/server/seats.mjs +239 -0
- package/hostAdapter/webAdapter/server/service.mjs +1051 -0
- package/hostAdapter/webAdapter/shared/dom.mjs +33 -0
- package/hostAdapter/webAdapter/shared/femo-logo.mjs +36 -0
- package/hostAdapter/webAdapter/shared/guard.mjs +28 -0
- package/hostAdapter/webAdapter/shared/human-seat-core.mjs +56 -0
- package/hostAdapter/webAdapter/shared/run-core.mjs +20 -0
- package/hostAdapter/webAdapter/shared/seats-core.mjs +73 -0
- package/hostAdapter/webAdapter/sites/aistudio.google.com/SITE.md +66 -0
- package/hostAdapter/webAdapter/sites/aistudio.google.com/content.js +144 -0
- package/hostAdapter/webAdapter/sites/aistudio.google.com/inject.js +240 -0
- package/hostAdapter/webAdapter/sites/aistudio.google.com/site.mjs +70 -0
- package/hostAdapter/webAdapter/sites/chat.deepseek.com/SITE.md +77 -0
- package/hostAdapter/webAdapter/sites/chat.deepseek.com/content.js +103 -0
- package/hostAdapter/webAdapter/sites/chat.deepseek.com/inject.js +181 -0
- package/hostAdapter/webAdapter/sites/chat.deepseek.com/site.mjs +73 -0
- package/hostAdapter/webAdapter/sites/chatglm.cn/SITE.md +63 -0
- package/hostAdapter/webAdapter/sites/chatglm.cn/content.js +121 -0
- package/hostAdapter/webAdapter/sites/chatglm.cn/inject.js +190 -0
- package/hostAdapter/webAdapter/sites/chatglm.cn/site.mjs +63 -0
- package/hostAdapter/webAdapter/sites/chatgpt.com/SITE.md +58 -0
- package/hostAdapter/webAdapter/sites/chatgpt.com/content.js +124 -0
- package/hostAdapter/webAdapter/sites/chatgpt.com/inject.js +404 -0
- package/hostAdapter/webAdapter/sites/chatgpt.com/site.mjs +68 -0
- package/hostAdapter/webAdapter/sites/grok.com/SITE.md +42 -0
- package/hostAdapter/webAdapter/sites/grok.com/content.js +120 -0
- package/hostAdapter/webAdapter/sites/grok.com/inject.js +259 -0
- package/hostAdapter/webAdapter/sites/grok.com/site.mjs +73 -0
- package/hostAdapter/webAdapter/sites/www.doubao.com/SITE.md +62 -0
- package/hostAdapter/webAdapter/sites/www.doubao.com/content.js +115 -0
- package/hostAdapter/webAdapter/sites/www.doubao.com/inject.js +232 -0
- package/hostAdapter/webAdapter/sites/www.doubao.com/site.mjs +62 -0
- package/hostAdapter/webAdapter/sites/www.kimi.com/SITE.md +57 -0
- package/hostAdapter/webAdapter/sites/www.kimi.com/content.js +117 -0
- package/hostAdapter/webAdapter/sites/www.kimi.com/inject.js +194 -0
- package/hostAdapter/webAdapter/sites/www.kimi.com/site.mjs +61 -0
- package/hostAdapter/webAdapter/sites/www.qianwen.com/SITE.md +43 -0
- package/hostAdapter/webAdapter/sites/www.qianwen.com/content.js +123 -0
- package/hostAdapter/webAdapter/sites/www.qianwen.com/inject.js +273 -0
- package/hostAdapter/webAdapter/sites/www.qianwen.com/site.mjs +72 -0
- package/hostAdapter/webAdapter/sites.mjs +67 -0
- package/hostAdapter/webAdapter/start-service.cmd +13 -0
- package/hostAdapter/webAdapter/tests/canvas-files.test.mjs +134 -0
- package/hostAdapter/webAdapter/tests/chatgpt-parser.test.mjs +161 -0
- package/hostAdapter/webAdapter/tests/doubao-parser.test.mjs +151 -0
- package/hostAdapter/webAdapter/tests/keeper.test.mjs +108 -0
- package/hostAdapter/webAdapter/tests/runtime.test.mjs +962 -0
- package/hostAdapter/webAdapter/tests/seats-core.test.mjs +134 -0
- package/hostAdapter/webAdapter/tests/site-boundary.test.mjs +161 -0
- package/hostAdapter/webAdapter/tests/smoke-bridge.mjs +65 -0
- package/hostAdapter/webAdapter/tests/smoke-service.mjs +232 -0
- package/hostAdapter/webAdapter/web.host.manifest.json +6 -0
- package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -23
- package/hostAdapter/zcodeAdapter/README.md +73 -61
- package/hostAdapter/zcodeAdapter/commands/femo.md +8 -9
- package/hostAdapter/zcodeAdapter/hooks/hooks.json +13 -16
- package/hostAdapter/zcodeAdapter/hooks/lib.mjs +318 -59
- package/hostAdapter/zcodeAdapter/hooks/mail-context.mjs +4 -0
- package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +4 -3
- package/hostAdapter/zcodeAdapter/hooks/turn-collect.mjs +3 -0
- package/hostAdapter/zcodeAdapter/icon.png +0 -0
- package/hostAdapter/zcodeAdapter/mcp/engine-bind.mjs +56 -0
- package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +42 -258
- package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +198 -320
- package/hostAdapter/zcodeAdapter/paths.mjs +78 -0
- package/hostAdapter/zcodeAdapter/runtime/femo-possess.mjs +356 -0
- package/hostAdapter/zcodeAdapter/runtime/femo-stream-watcher.mjs +214 -0
- package/hostAdapter/zcodeAdapter/runtime/mailbox-cli.mjs +33 -0
- package/hostAdapter/zcodeAdapter/runtime/pulled-letter.mjs +36 -0
- package/hostAdapter/zcodeAdapter/runtime/speech-collect.mjs +547 -0
- package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +52 -89
- package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +16 -6
- package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +160 -157
- package/hostAdapter/zcodeAdapter/tests/harness.mjs +91 -0
- package/hostAdapter/zcodeAdapter/tests/hooks-smoke.mjs +205 -0
- package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +34 -17
- package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +203 -107
- package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +100 -130
- package/hostAdapter/zcodeAdapter/tests/memory-store.mjs +72 -0
- package/hostAdapter/zcodeAdapter/tests/modelio-weave.test.mjs +82 -0
- package/hostAdapter/zcodeAdapter/tests/mount-state.test.mjs +150 -0
- package/hostAdapter/zcodeAdapter/tests/pulled-letter.test.mjs +77 -0
- package/hostAdapter/zcodeAdapter/tests/run-state-core.test.mjs +95 -0
- package/hostAdapter/zcodeAdapter/tests/speech-draft.mjs +163 -0
- package/hostAdapter/zcodeAdapter/tests/stream-watcher.test.mjs +154 -0
- package/hostAdapter/zcodeAdapter/tests/turn-marker.test.mjs +110 -0
- package/hostAdapter/zcodeAdapter/tests/unbound-actors.test.mjs +48 -0
- package/hostAdapter/zcodeAdapter/tests/variable-api.test.mjs +79 -0
- package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +2 -1
- package/package.json +2 -2
- package//350/257/255/346/263/225/346/226/207/346/241/243.md +1202 -1136
- package/FEMO_logo.svg +0 -55
- package/FEMO_logo_slogan.svg +0 -29
- package/_tmp/fallback/driver2.py +0 -176
- package/_tmp/fallback/events.jsonl +0 -108
- package/_tmp/fallback/gateway_ui.py +0 -325
- package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +0 -1
- package/_tmp/fallback/outbox/r1.done +0 -1
- package/_tmp/fallback/outbox/r2.done +0 -1
- package/_tmp/fallback/outbox/r3.done +0 -1
- package/_tmp/fallback/outbox/r4.done +0 -1
- package/_tmp/fallback/outbox/r5.done +0 -1
- package/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +0 -42
- package/femoGen/src/useCanvasInteraction.jsx +0 -319
- package/hostAdapter/dshAdapter/client/client-ui/femo-stream-live.tsx +0 -264
- package/hostAdapter/dshAdapter/dshPatch/MEOW_MODIFICATIONS.md +0 -3105
- package/hostAdapter/dshAdapter/host/debug-log.ts +0 -29
- package/hostAdapter/dshAdapter/host/engine-events.ts +0 -894
- package/hostAdapter/dshAdapter/host/god-mirror.ts +0 -234
- package/hostAdapter/dshAdapter/host/preset-install.ts +0 -59
- package/hostAdapter/dshAdapter/host/proj-trace.ts +0 -49
- package/hostAdapter/dshAdapter/host/routes.ts +0 -1196
- package/hostAdapter/dshAdapter/host/section-gate.ts +0 -108
- package/hostAdapter/dshAdapter/host/subagent-native.ts +0 -997
- package/hostAdapter/dshAdapter/host/subagent.ts +0 -1205
- package/hostAdapter/dshAdapter/package-lock.json +0 -500
- package/hostAdapter/dshAdapter/preset/agent.cordis.yml +0 -220
- package/hostAdapter/dshAdapter/preset/preset.yml +0 -3
- package/hostAdapter/dshAdapter/python/dev-bridge-test.py +0 -43
- package/hostAdapter/dshAdapter/python/femo_bridge.py +0 -533
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +0 -1
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +0 -3
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +0 -10
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +0 -11
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +0 -11
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +0 -23
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +0 -201
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +0 -635
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +0 -9
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +0 -4
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +0 -156
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +0 -69
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +0 -1515
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +0 -437
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +0 -77
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +0 -555
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +0 -163
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +0 -1
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +0 -56
- 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 +0 -10
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +0 -247
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +0 -308
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +0 -198
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +0 -35
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +0 -278
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +0 -163
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +0 -396
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +0 -2468
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +0 -3630
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +0 -209
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +0 -1
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +0 -86
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +0 -441
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +0 -485
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +0 -401
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +0 -68
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +0 -767
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +0 -126
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +0 -402
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +0 -544
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +0 -19
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +0 -113
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +0 -686
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +0 -567
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +0 -303
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +0 -157
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +0 -245
- 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 +0 -192
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +0 -42
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +0 -10
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +0 -29
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +0 -222
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +0 -70
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +0 -23
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +0 -29
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +0 -205
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +0 -324
- 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 +0 -331
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +0 -683
- 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 +0 -348
- 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 +0 -393
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +0 -3
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +0 -16
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +0 -59
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +0 -3
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +0 -3
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +0 -3
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +0 -43
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +0 -533
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +0 -192
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +0 -258
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +0 -429
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +0 -163
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +0 -294
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +0 -93
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +0 -26
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +0 -157
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +0 -107
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +0 -111
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +0 -107
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +0 -130
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +0 -144
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +0 -5
- 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 +0 -113
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +0 -1136
- package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +0 -3
- package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +0 -3
- package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +0 -3
- package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +0 -192
- package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +0 -163
- package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +0 -294
- package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +0 -107
- package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +0 -144
- 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 +0 -113
- package/scripts/diag-find-redblue.mjs +0 -38
- package/scripts/diag-god-log.mjs +0 -31
- package/scripts/diag-god-log2.mjs +0 -39
- package/scripts/diag-god-log3.mjs +0 -35
- package/scripts/diag-god-log4.mjs +0 -59
- package/scripts/diag-god-log4b.mjs +0 -39
- package/scripts/diag-redblue-god.mjs +0 -39
- package/scripts/diag-redblue-log.mjs +0 -37
- package/scripts/diag-redblue-span.mjs +0 -41
- package/scripts/diag-stage-1017.mjs +0 -63
- package/scripts/dump_session.py +0 -36
- package/scripts/link-workspace.ps1 +0 -51
- package/scripts/list_souls.py +0 -18
- package/scripts/probe-composer-refresh.mjs +0 -197
- package/scripts/seed_story_souls.py +0 -86
- package/scripts/sync-zcode-dist.ps1 +0 -55
- package/scripts/theme-tokenize/color-extract.txt +0 -288
- package/scripts/theme-tokenize/round1-quoted.ps1 +0 -149
- package/scripts/theme-tokenize/round2-bare.ps1 +0 -138
- package/scripts/theme-tokenize/round3-shape.ps1 +0 -110
- package/tests/_diag_r4_join.femo +0 -32
- package/tests/conftest.py +0 -95
- package/tests/diag-subagent-dir-3081.mjs +0 -101
- package/tests/femoGenerator.test.mjs +0 -3909
- package/tests/femoParser.test.mjs +0 -4813
- package/tests/femogen_notice.test.mjs +0 -109
- package/tests/femoparser_validation.test.mjs +0 -84
- package/tests/main-delivery-queue.test.mjs +0 -329
- package/tests/pre-step-gate.test.mjs +0 -282
- package/tests/read-subagent-model.mjs +0 -24
- package/tests/run-script-tests.py +0 -97
- package/tests/safe-steer.test.mjs +0 -59
- package/tests/strip_comments.test.mjs +0 -164
- package/tests/test_actor_failed.py +0 -92
- package/tests/test_compile_warnings.py +0 -99
- package/tests/test_debug_log_bus.py +0 -108
- package/tests/test_debugger_module_mode.py +0 -141
- package/tests/test_error_buckets.py +0 -117
- package/tests/test_error_dispatcher.py +0 -261
- package/tests/test_exec_ai_retry.py +0 -155
- package/tests/test_exec_human_retry.py +0 -159
- package/tests/test_file_resolve.py +0 -104
- package/tests/test_flow_events.py +0 -311
- package/tests/test_flow_ref_validation.py +0 -92
- package/tests/test_func_dict_fallback.py +0 -39
- package/tests/test_job_lifecycle.py +0 -236
- package/tests/test_job_manager.py +0 -424
- package/tests/test_mind.py +0 -99
- package/tests/test_module_call_args.py +0 -258
- package/tests/test_module_visibility.py +0 -238
- package/tests/test_notice.py +0 -143
- package/tests/test_out_whitelist.py +0 -83
- package/tests/test_par_if_dispatch.py +0 -64
- package/tests/test_par_nested_for.py +0 -78
- package/tests/test_parser.py +0 -494
- package/tests/test_pause.py +0 -102
- package/tests/test_pause_contract.py +0 -135
- package/tests/test_protocol_transcript.py +0 -158
- package/tests/test_scope_self.py +0 -202
- package/tests/test_source_validate.py +0 -113
- package/tests/test_task_world.py +0 -447
- package/tests/test_town_structure.py +0 -70
- package/tests/test_v2_checkpoint.py +0 -115
- package/tests/test_v2_env.py +0 -383
- package/tests/test_v2_evaluator.py +0 -227
- package/tests/test_v2_join.py +0 -315
- package/tests/test_v2_join_wiring.py +0 -429
- package/tests/test_v2_merge.py +0 -167
- package/tests/test_v2_model.py +0 -143
- package/tests/test_v2_resume_e2e.py +0 -472
- package/tests/test_var_decls.py +0 -271
- package/tests/verify-model-functions.mjs +0 -90
- package/tests/verify-subagent-model-3081.mjs +0 -153
- 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 +0 -395
- 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 +0 -66
- 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 +0 -475
- 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 +0 -847
- 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 +0 -654
- 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 +0 -471
- /package/hostAdapter/dshAdapter/host/{native-state.ts → compat/native-state.ts} +0 -0
- /package/hostAdapter/dshAdapter/host/{session-events.ts → compat/session-events.ts} +0 -0
|
@@ -1,3630 +0,0 @@
|
|
|
1
|
-
#femoCompiler/FEMO_runtime.py
|
|
2
|
-
"""
|
|
3
|
-
FEMO Runtime - Scripting Host Engine 运行时 v5.0(变量系统接线版)
|
|
4
|
-
负责: 流程执行, AI/human/func/assign 调度, LLM 调用, 事件
|
|
5
|
-
v5.0(2026-09-05 R2 通电,清单 v2 §8.2): 变量子系统切换到 vars/ 包
|
|
6
|
-
(TaskEnv/WorldStore/VarFacade/Evaluator)+ task_world 适配层(TaskContext/
|
|
7
|
-
assemble_world/fork_branches/join_sign_in)——VarManager/ExecutionContext
|
|
8
|
-
退役;求值四套散装通道收敛 Evaluator;fork 副本隔离/git 式合并/内建直通
|
|
9
|
-
生效。join 凑齐协调在 R3 接线(本版 join 网关维持直通现状)。
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
import importlib.util
|
|
13
|
-
import sys
|
|
14
|
-
import os
|
|
15
|
-
import types
|
|
16
|
-
import json
|
|
17
|
-
import re
|
|
18
|
-
import time
|
|
19
|
-
import threading
|
|
20
|
-
import asyncio
|
|
21
|
-
from typing import Any, Dict, List, Optional, Tuple, Set
|
|
22
|
-
from .femoAsync import AsyncEngine, CancelledError
|
|
23
|
-
# (task_pause import 已随 C3 修复退役(§5.7):TaskPauseManager/save_snapshot/
|
|
24
|
-
# restore_snapshot 不再被 runtime 引用;文件移 mytrashbin 留痕。)
|
|
25
|
-
from femoBridges.getDir.get_dir import get_FEMOroot_dir
|
|
26
|
-
from femoCompiler.FEMO_CLIrenderer import CLIRenderer, emit_step, emit_context_ready, emit_memory_ready
|
|
27
|
-
from femoCompiler.actor_resolver import resolve_actor_var, resolve_actor_attr
|
|
28
|
-
|
|
29
|
-
# ============================================================
|
|
30
|
-
# 变量子系统(2026-09-05 R2 通电)
|
|
31
|
-
# ============================================================
|
|
32
|
-
# 语言层单一定义点:FEMOVariableError 从 vars.model re-export(旧本地类退役)
|
|
33
|
-
from femoCompiler.vars.model import FEMOVariableError
|
|
34
|
-
from femoCompiler.protocol import normalize_transcript_steps
|
|
35
|
-
from femoCompiler.vars.checkpoint import dump_state, restore_state
|
|
36
|
-
from femoCompiler.vars.evaluator import Evaluator
|
|
37
|
-
from femoCompiler.task_world import (
|
|
38
|
-
TaskContext, ModuleFrame, task_ctx, current_task_ctx, set_task_ctx,
|
|
39
|
-
TaskWorld, assemble_world, fork_branches, branch_main, join_sign_in,
|
|
40
|
-
make_coordinator, GraphQuery, ChildSpec, seed_new_declarations,
|
|
41
|
-
)
|
|
42
|
-
# 同名沿用:既有读点 `ctx = _current_context.get()` 零改动(装的换 TaskContext)
|
|
43
|
-
from femoCompiler.task_world import _task_ctx as _current_context
|
|
44
|
-
|
|
45
|
-
from femoCompiler.FEMO_parser import (
|
|
46
|
-
Script, ModuleDef, ActionDef, FlowGraph, FlowNode, FlowEdge,
|
|
47
|
-
ExecutorType, OutType, ActorRef, DynamicActorRef, VarRef,
|
|
48
|
-
ActorDef, OutDef, InMapping, MethodDef, _split_module_ref,
|
|
49
|
-
)
|
|
50
|
-
from femoCompiler.FEMO_errors import (
|
|
51
|
-
ErrorCategory, FEMOActorExecutionError, FEMOConfigError, FEMOTransientError, classify_error,
|
|
52
|
-
build_dispatcher, VERDICT_FATAL, VERDICT_RETRY, VERDICT_EXHAUSTED, VERDICT_TOLERANT,
|
|
53
|
-
FEEDBACK_TARGET_AI, FEEDBACK_TARGET_HUMAN, NODE_SETTLED_EVENT,
|
|
54
|
-
)
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
class FEMOException(Exception):
|
|
58
|
-
def __init__(self, code: str, message: str):
|
|
59
|
-
self.code = code
|
|
60
|
-
self.message = message
|
|
61
|
-
super().__init__(f"[{code}] {message}")
|
|
62
|
-
|
|
63
|
-
class FEMOConcurrencyError(FEMOException):
|
|
64
|
-
def __init__(self, message: str):
|
|
65
|
-
super().__init__("FEMO-101", message)
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
class FEMORunPaused(Exception):
|
|
69
|
-
"""直连模式 AI 失败挂起(C3 修复,施工清单 v3 §5.7):节点门口断点已拍
|
|
70
|
-
(_record_checkpoint),raise 后由 run_async 的 except 分支走
|
|
71
|
-
on_state_change('suspended', 'node_pause')——替换旧 task_pause.pause()
|
|
72
|
-
的 `await event.wait()` 无超时挂死协程(C3:永挂无人 set)。
|
|
73
|
-
为什么是 suspended 不是 failed:提案 §六 C3 归宿表锚点"AI 失败走
|
|
74
|
-
on_state_change(suspended)",且保留直连模式续跑能力。
|
|
75
|
-
fork/par 分支内 raise 时会被 branch_main 的 except Exception 收进
|
|
76
|
-
_fork_errors → 转 FEMOVariableError → failed(既有分支错误上报链,
|
|
77
|
-
诚实收场;主链直连 AI 失败=suspended)。"""
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
# 赋值通道统一变量名(三处共用:extract_ai_assignments / _parse_single_assignment /
|
|
81
|
-
# _exec_assign——清单拍板 8④;含 $ 前缀[shared] / @ 前缀[actor 变量] / $@ 双前缀 /
|
|
82
|
-
# 中文变量名;保留 [] 以兼容 dict 索引路径写)
|
|
83
|
-
VAR_NAME_RE = r'[@$]*[\w\u4e00-\u9fff\[\]]+'
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
# ============================================================
|
|
87
|
-
# 工具函数
|
|
88
|
-
# ============================================================
|
|
89
|
-
|
|
90
|
-
def extract_ai_assignments(text: str) -> List[Tuple[str, str]]:
|
|
91
|
-
"""
|
|
92
|
-
从 AI 输出中提取 SET VARIABLE: <<VAR = expr>> 格式的主动赋值语句。
|
|
93
|
-
支持中英文等价符号:
|
|
94
|
-
SET VARIABLE: <<KILL = @Alice>>
|
|
95
|
-
设定变量:《KILL = @Alice》
|
|
96
|
-
SET VARIABLE: <<KILL += 1>>
|
|
97
|
-
SET VARIABLE: <<KILL = add(@Alice)>>
|
|
98
|
-
SET VARIABLE: <<$x = 1>>(shared 变量,拍板 8④)
|
|
99
|
-
"""
|
|
100
|
-
pattern = (
|
|
101
|
-
r'(?:SET\s+VARIABLE|设定变量|设置变量)'
|
|
102
|
-
r'\s*[::]\s*'
|
|
103
|
-
r'(?:<<|《|〈|《《)'
|
|
104
|
-
r'\s*(' + VAR_NAME_RE + r')\s*' # 变量名(VAR_NAME_RE:$ / @ / 中文)
|
|
105
|
-
r'([+\-]?=)\s*' # 操作符 = / += / -=
|
|
106
|
-
r'(.+?)' # 表达式
|
|
107
|
-
r'(?:>>|》|〉|》》)'
|
|
108
|
-
)
|
|
109
|
-
matches = re.findall(pattern, text)
|
|
110
|
-
result = []
|
|
111
|
-
for m in matches:
|
|
112
|
-
var_name = m[0].strip()
|
|
113
|
-
op = m[1].strip()
|
|
114
|
-
value = m[2].strip()
|
|
115
|
-
# 合并操作符和值,如 "= @Alice" 或 "+= 1"
|
|
116
|
-
expr = f"{op} {value}"
|
|
117
|
-
result.append((var_name, expr))
|
|
118
|
-
return result
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
def text_assignments_to_dict(chat_text: str) -> dict:
|
|
122
|
-
"""从人类聊天文本中提取 SET VARIABLE: <<VAR = expr>> 赋值,转为结构化
|
|
123
|
-
variables dict(与前端变量框上传的 dict 同一数据约定,供
|
|
124
|
-
_try_apply_human_variables 统一应用):
|
|
125
|
-
- 普通赋值剥掉 '= ' 前缀(应用侧会统一补回);
|
|
126
|
-
- 增量赋值保留 '+= N' / '-= N' 原样。
|
|
127
|
-
2026-09-01 新增:人类(含 @mind 分发与 CLI 模式)在聊天输入框里直接写
|
|
128
|
-
赋值语句即可生效,与 AI 节点同一套提取器;前端结构化变量框仍然保留,
|
|
129
|
-
两条通道并存,框值优先(显式 UI 输入覆盖文本解析结果)。"""
|
|
130
|
-
out: dict = {}
|
|
131
|
-
for var_name, expr in extract_ai_assignments(chat_text or ''):
|
|
132
|
-
expr = expr.strip()
|
|
133
|
-
if expr.startswith('+=') or expr.startswith('-='):
|
|
134
|
-
out[var_name] = expr
|
|
135
|
-
elif expr.startswith('='):
|
|
136
|
-
out[var_name] = expr[1:].strip()
|
|
137
|
-
else:
|
|
138
|
-
out[var_name] = expr
|
|
139
|
-
return out
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
def parse_assign_syntax(expr: str, var_name: str = ''):
|
|
143
|
-
"""
|
|
144
|
-
只支持文档规定的语法:
|
|
145
|
-
= value
|
|
146
|
-
+= N
|
|
147
|
-
-= N
|
|
148
|
-
= add(x)
|
|
149
|
-
= remove(x)
|
|
150
|
-
支持中文括号、引号。
|
|
151
|
-
"""
|
|
152
|
-
if not isinstance(expr, str):
|
|
153
|
-
raise FEMOVariableError(
|
|
154
|
-
f"parse_assign_syntax 需要字符串,但收到了 {type(expr)}: {expr!r}"
|
|
155
|
-
)
|
|
156
|
-
expr = expr.strip()
|
|
157
|
-
# 统一中文符号
|
|
158
|
-
expr = expr.replace('(', '(').replace(')', ')').replace('“', '"').replace('”', '"')
|
|
159
|
-
|
|
160
|
-
# 1. += N
|
|
161
|
-
m = re.match(r'\+\=\s*(.+)$', expr)
|
|
162
|
-
if m:
|
|
163
|
-
val_str = m.group(1).strip()
|
|
164
|
-
try:
|
|
165
|
-
return ('increment', float(val_str))
|
|
166
|
-
except ValueError:
|
|
167
|
-
raise FEMOVariableError(f"+= 右侧需要数字,得到: {val_str!r}")
|
|
168
|
-
|
|
169
|
-
# 2. -= N
|
|
170
|
-
m = re.match(r'\-\=\s*(.+)$', expr)
|
|
171
|
-
if m:
|
|
172
|
-
val_str = m.group(1).strip()
|
|
173
|
-
try:
|
|
174
|
-
return ('increment', -float(val_str))
|
|
175
|
-
except ValueError:
|
|
176
|
-
raise FEMOVariableError(f"-= 右侧需要数字,得到: {val_str!r}")
|
|
177
|
-
|
|
178
|
-
# 3. = add(...)
|
|
179
|
-
m = re.match(r'=\s*add\((.+)\)$', expr)
|
|
180
|
-
if m:
|
|
181
|
-
return ('add', m.group(1).strip())
|
|
182
|
-
|
|
183
|
-
# 4. = remove(...)
|
|
184
|
-
m = re.match(r'=\s*remove\((.+)\)$', expr)
|
|
185
|
-
if m:
|
|
186
|
-
return ('remove', m.group(1).strip())
|
|
187
|
-
|
|
188
|
-
# 5. = value
|
|
189
|
-
m = re.match(r'=\s*(.+)$', expr)
|
|
190
|
-
if m:
|
|
191
|
-
value_str = m.group(1).strip()
|
|
192
|
-
if value_str.lower() == 'true': return ('set', True)
|
|
193
|
-
if value_str.lower() == 'false': return ('set', False)
|
|
194
|
-
try:
|
|
195
|
-
if '.' in value_str: return ('set', float(value_str))
|
|
196
|
-
return ('set', int(value_str))
|
|
197
|
-
except ValueError:
|
|
198
|
-
pass
|
|
199
|
-
# 去掉可能的外围引号
|
|
200
|
-
if (value_str.startswith('"') and value_str.endswith('"')) or \
|
|
201
|
-
(value_str.startswith("'") and value_str.endswith("'")):
|
|
202
|
-
value_str = value_str[1:-1]
|
|
203
|
-
return ('set', value_str)
|
|
204
|
-
|
|
205
|
-
# 无法解析
|
|
206
|
-
raise FEMOVariableError(
|
|
207
|
-
f"无法解析赋值表达式: {expr!r}。"
|
|
208
|
-
f"支持的格式: = value, += N, -= N, = add(x), = remove(x)"
|
|
209
|
-
)
|
|
210
|
-
|
|
211
|
-
def call_python(bridge, path: str, kwargs: dict = None) -> Any:
|
|
212
|
-
"""共用的外接 Python 模块调用"""
|
|
213
|
-
kwargs = kwargs or {}
|
|
214
|
-
return bridge.call(path, **kwargs)
|
|
215
|
-
|
|
216
|
-
def _resolve_val(val, facade):
|
|
217
|
-
"""递归解析变量值,直到不是 @ 开头的变量引用(追链上限 10 层防环)。
|
|
218
|
-
静态演员引用(@Alice 在 actors 表)经 facade.get 原样返回名字本身——
|
|
219
|
-
out 变量存演员名语义不变;@变量 → 取当前值(可能再是 @引用 → 继续解)。"""
|
|
220
|
-
for _ in range(10):
|
|
221
|
-
if isinstance(val, str) and val.startswith('@') and facade.has(val):
|
|
222
|
-
val = facade.get(val)
|
|
223
|
-
else:
|
|
224
|
-
return val
|
|
225
|
-
return val
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
def process_ai_result(facade, triplets: list, out_defs: list,
|
|
229
|
-
retry_info: dict = None) -> dict:
|
|
230
|
-
"""
|
|
231
|
-
解析 AI 返回的三元组,综合决定:赋值 / 重试 / 报错 / 忽略。
|
|
232
|
-
"""
|
|
233
|
-
retry_info = retry_info or {}
|
|
234
|
-
retries_left = retry_info.get('retries_left', 0)
|
|
235
|
-
on_error = retry_info.get('on_error', 'abort')
|
|
236
|
-
|
|
237
|
-
ai_values = {}
|
|
238
|
-
for t in triplets:
|
|
239
|
-
if len(t) == 3:
|
|
240
|
-
var_name, value, _ = t
|
|
241
|
-
ai_values[var_name] = value
|
|
242
|
-
elif len(t) == 2:
|
|
243
|
-
var_name, value = t
|
|
244
|
-
ai_values[var_name] = value
|
|
245
|
-
|
|
246
|
-
assigned = {}
|
|
247
|
-
missing_required = []
|
|
248
|
-
|
|
249
|
-
for out_def in out_defs:
|
|
250
|
-
var_name = getattr(out_def, 'global_name', None) or getattr(out_def, 'var_name', '')
|
|
251
|
-
required = getattr(out_def, 'required', True)
|
|
252
|
-
default = getattr(out_def, 'default', None)
|
|
253
|
-
|
|
254
|
-
if var_name in ai_values:
|
|
255
|
-
intent = parse_assign_syntax(str(ai_values[var_name]), var_name)
|
|
256
|
-
op, val = intent
|
|
257
|
-
if op in ('set', 'add', 'remove'):
|
|
258
|
-
# @ 开头的变量引用 → 解析为最终值/实体名
|
|
259
|
-
val = _resolve_val(val, facade)
|
|
260
|
-
intent = (op, val)
|
|
261
|
-
facade.apply_intent(var_name, intent)
|
|
262
|
-
assigned[var_name] = ai_values[var_name]
|
|
263
|
-
else:
|
|
264
|
-
if required:
|
|
265
|
-
missing_required.append(var_name)
|
|
266
|
-
else:
|
|
267
|
-
if default is not None:
|
|
268
|
-
facade.apply_intent(var_name, ('set', default))
|
|
269
|
-
assigned[var_name] = default
|
|
270
|
-
|
|
271
|
-
if missing_required:
|
|
272
|
-
if retries_left > 0 and on_error in ('retry', None):
|
|
273
|
-
return {'status': 'retry', 'assigned': assigned,
|
|
274
|
-
'missing_required': missing_required,
|
|
275
|
-
'error_msg': f"必须变量缺失: {missing_required},剩余重试 {retries_left-1} 次"}
|
|
276
|
-
elif on_error == 'fallback':
|
|
277
|
-
for var_name in missing_required:
|
|
278
|
-
default = None
|
|
279
|
-
for od in out_defs:
|
|
280
|
-
od_name = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
281
|
-
if od_name == var_name:
|
|
282
|
-
default = getattr(od, 'default', None)
|
|
283
|
-
break
|
|
284
|
-
if default is not None:
|
|
285
|
-
facade.apply_intent(var_name, ('set', default))
|
|
286
|
-
assigned[var_name] = default
|
|
287
|
-
return {'status': 'ok', 'assigned': assigned,
|
|
288
|
-
'missing_required': [],
|
|
289
|
-
'error_msg': f"必须变量缺失已用默认值兜底: {missing_required}"}
|
|
290
|
-
else:
|
|
291
|
-
return {'status': 'error', 'assigned': assigned,
|
|
292
|
-
'missing_required': missing_required,
|
|
293
|
-
'error_msg': f"必须变量缺失且无重试机会: {missing_required}"}
|
|
294
|
-
|
|
295
|
-
return {'status': 'ok', 'assigned': assigned,
|
|
296
|
-
'missing_required': [], 'error_msg': None}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
def format_human_dialog(chat_text: str, variables: dict) -> str:
|
|
300
|
-
"""
|
|
301
|
-
将人类聊天文本和变量赋值拼接为存储格式。
|
|
302
|
-
|
|
303
|
-
规则:
|
|
304
|
-
- 输入以 += 或 -= 开头 → 拼 "varName += N"(标准化空格)
|
|
305
|
-
- 否则 → 拼 "varName = raw"
|
|
306
|
-
"""
|
|
307
|
-
lines = []
|
|
308
|
-
if chat_text and chat_text.strip():
|
|
309
|
-
lines.append(chat_text.strip())
|
|
310
|
-
for var_name, var_value in (variables or {}).items():
|
|
311
|
-
raw = str(var_value).strip()
|
|
312
|
-
if not raw:
|
|
313
|
-
continue
|
|
314
|
-
if raw.startswith('+=') or raw.startswith('-='):
|
|
315
|
-
op = raw[:2]
|
|
316
|
-
val = raw[2:].strip()
|
|
317
|
-
lines.append(f"SET VARIABLE : <<{var_name} {op} {val}>>")
|
|
318
|
-
else:
|
|
319
|
-
lines.append(f"SET VARIABLE : <<{var_name} = {raw}>>")
|
|
320
|
-
result = '\n'.join(lines)
|
|
321
|
-
print(f"[format_human_dialog] chat_text={chat_text!r}, variables={variables}, result={result!r}")
|
|
322
|
-
return result
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
# ============================================================
|
|
326
|
-
# PythonBridge — 动态加载 .py 并调用函数
|
|
327
|
-
# ============================================================
|
|
328
|
-
class PythonBridge:
|
|
329
|
-
"""加载外部 Python 文件,调用其中函数"""
|
|
330
|
-
|
|
331
|
-
def __init__(self, base_dir: str = ""):
|
|
332
|
-
# base_dir = 剧本文件所在目录(有剧本地址时由 host 传入);
|
|
333
|
-
# 空 = 剧本未保存(纯文本运行),此时相对路径一律报错。
|
|
334
|
-
self.base_dir = base_dir
|
|
335
|
-
self.modules: Dict[str, types.ModuleType] = {}
|
|
336
|
-
|
|
337
|
-
def load(self, alias: str, filepath: str) -> types.ModuleType:
|
|
338
|
-
"""
|
|
339
|
-
加载 .py 文件,注册为 alias。
|
|
340
|
-
地址解析规则(todo #2):
|
|
341
|
-
- 绝对路径 → 直接使用(无脑支持)
|
|
342
|
-
- 相对路径 → 相对剧本文件所在目录(base_dir)解析
|
|
343
|
-
- base_dir 为空(剧本未保存)→ 相对路径报错
|
|
344
|
-
func_code 默认位置已取消(不再回退查找)。
|
|
345
|
-
"""
|
|
346
|
-
if os.path.isabs(filepath):
|
|
347
|
-
full_path = filepath
|
|
348
|
-
elif self.base_dir:
|
|
349
|
-
full_path = os.path.join(self.base_dir, filepath)
|
|
350
|
-
else:
|
|
351
|
-
raise FileNotFoundError(
|
|
352
|
-
f"Python Bridge: 相对路径 '{filepath}' 需要剧本文件地址(剧本未保存)。"
|
|
353
|
-
f"请先「导出 .FEMO」保存剧本,或改用绝对路径。"
|
|
354
|
-
)
|
|
355
|
-
|
|
356
|
-
if not os.path.exists(full_path):
|
|
357
|
-
raise FileNotFoundError(f"Python Bridge: 文件不存在 {full_path}")
|
|
358
|
-
|
|
359
|
-
spec = importlib.util.spec_from_file_location(alias, full_path)
|
|
360
|
-
mod = importlib.util.module_from_spec(spec)
|
|
361
|
-
spec.loader.exec_module(mod)
|
|
362
|
-
self.modules[alias] = mod
|
|
363
|
-
return mod
|
|
364
|
-
|
|
365
|
-
def call(self, dotted_name: str, *args, **kwargs) -> Any:
|
|
366
|
-
"""调用 module.function 形式的函数"""
|
|
367
|
-
if '.' not in dotted_name:
|
|
368
|
-
raise ValueError(f"Python Bridge: 无效调用格式 '{dotted_name}',需要 'module.function'")
|
|
369
|
-
alias, func_name = dotted_name.split('.', 1)
|
|
370
|
-
if alias not in self.modules:
|
|
371
|
-
raise KeyError(f"Python Bridge: 模块 '{alias}' 未加载")
|
|
372
|
-
mod = self.modules[alias]
|
|
373
|
-
func = getattr(mod, func_name, None)
|
|
374
|
-
if func is None:
|
|
375
|
-
raise AttributeError(f"Python Bridge: 模块 '{alias}' 中没有函数 '{func_name}'")
|
|
376
|
-
return func(*args, **kwargs)
|
|
377
|
-
|
|
378
|
-
def has(self, dotted_name: str) -> bool:
|
|
379
|
-
"""检查函数是否存在"""
|
|
380
|
-
if '.' not in dotted_name:
|
|
381
|
-
return False
|
|
382
|
-
alias, func_name = dotted_name.split('.', 1)
|
|
383
|
-
if alias not in self.modules:
|
|
384
|
-
return False
|
|
385
|
-
return hasattr(self.modules[alias], func_name)
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
# ============================================================
|
|
392
|
-
# FEMORunner — 运行器 v4.0
|
|
393
|
-
# ============================================================
|
|
394
|
-
class FEMORunner:
|
|
395
|
-
"""执行解析后的 Script - 直接理解新格式 FlowGraph"""
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
def __init__(self, script, base_dir: str = ".", verbose: bool = True, event_callback=None,
|
|
399
|
-
user_api_key: str = None, user_api_provider: str = None,
|
|
400
|
-
user_api_url: str = None, user_api_model: str = None,
|
|
401
|
-
resume_state: dict = None,
|
|
402
|
-
runtime_callbacks: dict = None, run_tag: str = ''):
|
|
403
|
-
print("[runtime] FEMORunner.__init__ 开始")
|
|
404
|
-
self.script = script
|
|
405
|
-
# ── Job 旁挂(运行状态链路重构 §5.2,依赖倒置契约 §4.2)──
|
|
406
|
-
# Runtime 不认识 Job:四个可选回调 on_flow_start/on_checkpoint/
|
|
407
|
-
# on_state_change/on_run_end 由宿主(bridge)注入;run_tag=wait_key
|
|
408
|
-
# 世代前缀(bridge 注入 f"j{job_id}:")。两参全带缺省——CLI 裸跑/
|
|
409
|
-
# 现有构造点不传 → _rc_call 全 no-op、前缀逐字节等于现状。
|
|
410
|
-
self._rc = runtime_callbacks or {}
|
|
411
|
-
self._run_tag = run_tag
|
|
412
|
-
self.verbose = verbose
|
|
413
|
-
self.user_api_key = user_api_key
|
|
414
|
-
self.user_api_provider = user_api_provider
|
|
415
|
-
self.user_api_url = user_api_url
|
|
416
|
-
self.user_api_model = user_api_model
|
|
417
|
-
# ── 变量世界装配(2026-09-05 R2 通电:VarManager 退役)──
|
|
418
|
-
# ⚠️ assemble_world 在下方 code: 文件加载后调用(evaluator 需要
|
|
419
|
-
# code_modules 做函数调用分支;内建 getter 用实时属性无需提前)
|
|
420
|
-
self.base_dir = base_dir
|
|
421
|
-
self.bridge = PythonBridge(base_dir)
|
|
422
|
-
# 内建直通(拍板:session_id/turn_count 恒为 runner 实时值,剧本赋值报只读)
|
|
423
|
-
self._builtins_getter = (
|
|
424
|
-
lambda n: self._current_session_id if n == 'session_id' else self._current_turn_id)
|
|
425
|
-
self._task_coros: Dict[str, asyncio.Task] = {} # 两层 task 桥(清单 §1.2)
|
|
426
|
-
self._coordinators: Dict[str, Any] = {} # per join_id 协调器缓存(代次内置)
|
|
427
|
-
self._cascade = None # run 级 JoinCascade 总线(嵌套 join 级联;_coordinator_for 惰性建)
|
|
428
|
-
self._skip_frames: Set[str] = set() # 循环帧集合(D5:push add/pop discard)
|
|
429
|
-
self._current_prompt = ""
|
|
430
|
-
self._current_actor_info = {}
|
|
431
|
-
self._current_session_id = 0
|
|
432
|
-
self._current_turn_id = 0
|
|
433
|
-
# ── 事件回调(用于前后端通信) ──
|
|
434
|
-
self._event_callback = event_callback # callable(event_type, data_dict)
|
|
435
|
-
# ── 异步引擎(替代原线程池/事件机制) ──
|
|
436
|
-
self.engine = AsyncEngine()
|
|
437
|
-
# 解析全局 delay 配置并传给引擎
|
|
438
|
-
delay = script.meta.get('delay', 0)
|
|
439
|
-
if isinstance(delay, str):
|
|
440
|
-
try:
|
|
441
|
-
delay = float(delay)
|
|
442
|
-
except (ValueError, TypeError):
|
|
443
|
-
delay = 0
|
|
444
|
-
self.engine.llm_delay = delay
|
|
445
|
-
|
|
446
|
-
# (task_pause/TaskPauseManager 已随 C3 修复退役(§5.7/§5.9)——直连
|
|
447
|
-
# AI 失败改走 FEMORunPaused → suspended(node_pause),不再有挂死协程。)
|
|
448
|
-
# ── 错误三桶分发入口(2026-09-05 重构,施工清单 v4 §4①):
|
|
449
|
-
# ErrorDispatcher 只裁决与发信号;重试循环留在 runtime(裁决⑤)。
|
|
450
|
-
self.errors = build_dispatcher(self)
|
|
451
|
-
# ── 断点状态:位置 + per-task 变量世界整包,经 checkpoint 事件交宿主持久化 ──
|
|
452
|
-
# 记录的是"位置"(task_id→node id):续跑/改剧本后从该节点重放(分支直启)。
|
|
453
|
-
self.checkpoints: Dict[str, str] = {} # task_id → node_id(宿主可见性/续跑位置)
|
|
454
|
-
self._positions: Dict[str, Dict[str, Any]] = {} # task_id → {node_id, mod_stack, loop_frames}
|
|
455
|
-
self._last_vars_dump: str = "" # state 去重基线:没变化不随事件上行(事件体积)
|
|
456
|
-
# 外部注入的恢复态(断点续跑):{checkpoints, session_id, state=整包}。
|
|
457
|
-
# session_id 优先级最高——续跑=回到同一个世界(同一场次房间)接着演。
|
|
458
|
-
# ⚠️ 数据源单一性约束(接线约定 5):恢复唯一数据源=state(R4 起字段
|
|
459
|
-
# 名 state,载荷暂名 vars 的过渡期已随宿主更名结束);checkpoints 是
|
|
460
|
-
# 宿主可见性信号,恢复侧不消费它。
|
|
461
|
-
self.resume_checkpoints: Dict[str, str] = dict((resume_state or {}).get('checkpoints') or {})
|
|
462
|
-
self.resume_state: dict = resume_state or {}
|
|
463
|
-
# ── 人类输入等待机制(FastAPI 模式) ──
|
|
464
|
-
self._human_input_event = None
|
|
465
|
-
self._human_input_data = None
|
|
466
|
-
self._human_input_counter = 0 # 每次 human 节点等待时 +1,生成唯一 wait_key
|
|
467
|
-
|
|
468
|
-
self._stopped = False # 全局停止标志
|
|
469
|
-
self._main_task: Optional[asyncio.Task] = None # 主协程引用
|
|
470
|
-
self._llm_stop_event: Optional[threading.Event] = None # LLM 停止信号
|
|
471
|
-
# 发言人状态机(编号已改由 _alloc_turn 独立分配,此状态机仅剩遗留读点)
|
|
472
|
-
self.speaker = {"current": None, "last": None}
|
|
473
|
-
self._oratio_idx = 0
|
|
474
|
-
self._step_idx = 0
|
|
475
|
-
# ── turn 号分配(2026-08-28 par 丢行根治)──
|
|
476
|
-
# 旧实现由说话人状态机"推算"turn/step:par 并发分支交叉推进共享状态,
|
|
477
|
-
# 会产生撞键行(如甲思考 react (turn1,step0) 撞出题的 (turn1,step0)),
|
|
478
|
-
# 再被 get_session_context 去重静默吞掉——甲亮答上下文丢前文的根因。
|
|
479
|
-
# 现在节点开工时在锁内领取严格递增的独立 turn 号(按领取顺序定号)。
|
|
480
|
-
self._turn_lock = threading.Lock()
|
|
481
|
-
self._turn_seq = None # 本 run 已分配到的 turn 号;None=尚未首次取号
|
|
482
|
-
self._turn_seq_sid = None # 上次取号所属 session(换场时重新对齐起点)
|
|
483
|
-
|
|
484
|
-
# ── Session 和 Turn 初始化 ──
|
|
485
|
-
from femoCompiler.db_utils import init_database, get_max_session_id, get_or_create_session, get_next_turn_id, session_exists
|
|
486
|
-
init_database()
|
|
487
|
-
|
|
488
|
-
# ── 断点续跑:注入的场次身份优先级最高(宿主已校验剧本指纹未变)。
|
|
489
|
-
# 场次不存在(台账被清)→ 拒绝失忆续跑:宁可 fresh_start,不演失忆剧。
|
|
490
|
-
resume_sid = self.resume_state.get('session_id')
|
|
491
|
-
resumed_session = False
|
|
492
|
-
if resume_sid not in (None, '', 0):
|
|
493
|
-
try:
|
|
494
|
-
sid = int(resume_sid)
|
|
495
|
-
except (TypeError, ValueError):
|
|
496
|
-
raise ValueError(f"断点的 session_id 无效: {resume_sid!r}")
|
|
497
|
-
if not session_exists(sid):
|
|
498
|
-
raise ValueError(
|
|
499
|
-
f"断点指向的场次 {sid} 不存在(运行台账可能已被清空),拒绝失忆续跑;请 fresh_start 重新开演。")
|
|
500
|
-
self._current_session_id = sid
|
|
501
|
-
self._current_turn_id = get_next_turn_id(sid)
|
|
502
|
-
resumed_session = True
|
|
503
|
-
print(f"[runtime]🔁 断点续跑:复用场次 {sid}(turn {self._current_turn_id}),前情对话照常可见")
|
|
504
|
-
|
|
505
|
-
session_meta = script.meta.get('session', None)
|
|
506
|
-
if resumed_session:
|
|
507
|
-
pass # 场次已由断点注入决定,跳过 meta.session 判定
|
|
508
|
-
elif session_meta is None or str(session_meta).strip().lower() == 'new':
|
|
509
|
-
# 纯 new 或无声明:无脑新建
|
|
510
|
-
self._current_session_id = get_max_session_id() + 1
|
|
511
|
-
get_or_create_session(session_id=self._current_session_id, title=script.meta.get('name', ''))
|
|
512
|
-
self._current_turn_id = 1
|
|
513
|
-
print(f"[runtime]🆕 新建 session: {self._current_session_id}, turn: 1")
|
|
514
|
-
else:
|
|
515
|
-
session_meta_str = str(session_meta).strip()
|
|
516
|
-
# 检查是否包含斜杠,格式: 数字/new
|
|
517
|
-
if '/' in session_meta_str:
|
|
518
|
-
parts = [p.strip() for p in session_meta_str.split('/', 1)]
|
|
519
|
-
if len(parts) != 2 or parts[1].lower() != 'new':
|
|
520
|
-
print(f"[runtime]❌ meta.session 格式无效: {session_meta},期望格式: 数字/new")
|
|
521
|
-
raise ValueError(f"meta.session 格式无效: {session_meta}")
|
|
522
|
-
try:
|
|
523
|
-
declared_sid = int(parts[0])
|
|
524
|
-
except (ValueError, TypeError):
|
|
525
|
-
print(f"[runtime]❌ meta.session 格式无效: {session_meta},斜杠前必须为数字")
|
|
526
|
-
raise ValueError(f"meta.session 斜杠前必须为数字: {session_meta}")
|
|
527
|
-
# 数字/new 逻辑
|
|
528
|
-
if session_exists(declared_sid):
|
|
529
|
-
# 存在直接使用
|
|
530
|
-
self._current_session_id = declared_sid
|
|
531
|
-
self._current_turn_id = get_next_turn_id(declared_sid)
|
|
532
|
-
print(f"[runtime]📂 继续 session: {self._current_session_id}, turn: {self._current_turn_id}")
|
|
533
|
-
else:
|
|
534
|
-
# 不存在,先计算新建后的 ID
|
|
535
|
-
new_id = get_max_session_id() + 1
|
|
536
|
-
if new_id == declared_sid:
|
|
537
|
-
# 恰好匹配,新建并写入
|
|
538
|
-
get_or_create_session(session_id=declared_sid, title=script.meta.get('name', ''))
|
|
539
|
-
self._current_session_id = declared_sid
|
|
540
|
-
self._current_turn_id = 1
|
|
541
|
-
print(f"[runtime]🆕 新建 session (恰好匹配): {self._current_session_id}, turn: 1")
|
|
542
|
-
else:
|
|
543
|
-
print(f"[runtime]⚠️ 声明的 session {declared_sid} 不存在,新建后 ID 为 {new_id},不是 {declared_sid}。")
|
|
544
|
-
# 询问用户
|
|
545
|
-
try:
|
|
546
|
-
user_input = input(f"是否新建 session {new_id}?(y/N): ").strip().lower()
|
|
547
|
-
except (EOFError, KeyboardInterrupt):
|
|
548
|
-
user_input = ''
|
|
549
|
-
if user_input == 'y':
|
|
550
|
-
get_or_create_session(session_id=new_id, title=script.meta.get('name', ''))
|
|
551
|
-
self._current_session_id = new_id
|
|
552
|
-
self._current_turn_id = 1
|
|
553
|
-
print(f"[runtime]🆕 用户确认新建 session: {self._current_session_id}, turn: 1")
|
|
554
|
-
else:
|
|
555
|
-
print(f"[runtime]❌ 用户取消新建 session")
|
|
556
|
-
raise ValueError(f"Session {declared_sid} 不存在,用户拒绝新建")
|
|
557
|
-
else:
|
|
558
|
-
# 纯数字
|
|
559
|
-
try:
|
|
560
|
-
declared_sid = int(session_meta_str)
|
|
561
|
-
except (ValueError, TypeError):
|
|
562
|
-
print(f"[runtime]❌ meta.session 值无效: {session_meta}")
|
|
563
|
-
raise ValueError(f"meta.session 无效: {session_meta}")
|
|
564
|
-
if not session_exists(declared_sid):
|
|
565
|
-
print(f"[runtime]❌ 声明的 session {declared_sid} 不存在。请使用 session = new 新建,或 session = {declared_sid}/new 自动匹配。")
|
|
566
|
-
raise ValueError(f"Session {declared_sid} 不存在")
|
|
567
|
-
self._current_session_id = declared_sid
|
|
568
|
-
self._current_turn_id = get_next_turn_id(declared_sid)
|
|
569
|
-
print(f"[runtime]📂 继续 session: {self._current_session_id}, turn: {self._current_turn_id}")
|
|
570
|
-
|
|
571
|
-
# 加载 code: 区域声明的 .py 文件
|
|
572
|
-
for alias, filepath in script.code.items():
|
|
573
|
-
# 处理 file: 前缀
|
|
574
|
-
if filepath.startswith('file:"') and filepath.endswith('"'):
|
|
575
|
-
filepath = filepath[6:-1]
|
|
576
|
-
elif filepath.startswith("file:'") and filepath.endswith("'"):
|
|
577
|
-
filepath = filepath[6:-1]
|
|
578
|
-
self.bridge.load(alias, filepath)
|
|
579
|
-
|
|
580
|
-
# ── 变量世界装配(R2 通电:替代 VarManager+literal_eval 二段求值;
|
|
581
|
-
# session_id/turn_count 走内建直通不再写存储)──
|
|
582
|
-
self.world: TaskWorld = assemble_world(
|
|
583
|
-
script, builtins_getter=self._builtins_getter,
|
|
584
|
-
code_modules=self.bridge.modules)
|
|
585
|
-
self.evaluator = self.world.evaluator
|
|
586
|
-
|
|
587
|
-
# ── 断点续跑:per-task 变量世界整包恢复(新格式,清单 D8)──
|
|
588
|
-
# 恢复=原样重建(envs/world/forks/ledger/positions),随后 task_id
|
|
589
|
-
# 序号取快照最大号+1 续分配防撞号。旧合并视图平铺格式已作废
|
|
590
|
-
# (restore_state VERSION 响亮报错,按拍板 fresh 开演)。
|
|
591
|
-
rs_state = self.resume_state.get('state')
|
|
592
|
-
if isinstance(rs_state, dict) and rs_state:
|
|
593
|
-
restored = restore_state(rs_state)
|
|
594
|
-
_envs, _world, _forks, _ledger, _positions = restored
|
|
595
|
-
# 引擎侧唯一数据源=state(接线约定 5);以快照重建世界组件
|
|
596
|
-
self.world.envs = _envs
|
|
597
|
-
self.world.world = _world
|
|
598
|
-
self.world.forks = _forks
|
|
599
|
-
self.world.ledger = _ledger
|
|
600
|
-
self.evaluator = self.world.evaluator
|
|
601
|
-
# task_id 序号防撞号(清单 D8):续分配从快照最大号+1 起——恢复后
|
|
602
|
-
# fork/merge 还会分配新 task 号,不续号会与快照已有的 t1/t2… 撞号
|
|
603
|
-
# (ledger/envs 登记互相覆盖,世界状态错乱)。
|
|
604
|
-
seq_next = self.world.max_task_seq()
|
|
605
|
-
self.world.idgen.restore_from(seq_next)
|
|
606
|
-
self.resume_positions: Dict[str, Dict[str, Any]] = dict(_positions)
|
|
607
|
-
print(f"[runtime]🔁 断点续跑:恢复 per-task 世界({len(_envs)} env / "
|
|
608
|
-
f"{len(_positions)} 位置),task 序号续自 t{seq_next}")
|
|
609
|
-
# 【2026-09-06 vars 增删容差(用户拍板)】整包恢复只认快照——新剧本
|
|
610
|
-
# 新声明的变量不在恢复后的世界里,读到即"未声明"崩。按声明初值补种;
|
|
611
|
-
# 快照有而新剧本已删的成为孤儿值(无人读则无害)。都打 ⚠️——能跑,
|
|
612
|
-
# 但作者应当知情(⚠️ 补种值=声明初值,非断点时刻的中间态)。
|
|
613
|
-
# 【2026-09-07 warning 桶】汇总发 WARNING(notify_author),作者在
|
|
614
|
-
# 聊天窗/错误面板可见——原来只进 bridge 日志,作者蒙在鼓里。
|
|
615
|
-
seeded, orphaned = seed_new_declarations(self.world, script)
|
|
616
|
-
if seeded:
|
|
617
|
-
names = ', '.join(seeded)
|
|
618
|
-
print(f"[runtime] ⚠️ 断点续跑:新增变量 {names} 不在快照世界,已用声明初值补种")
|
|
619
|
-
self.errors.warn(
|
|
620
|
-
f"断点续跑:新增变量 {names} 不在快照世界,已用声明初值补种"
|
|
621
|
-
"(补种值=声明初值,非断点时刻的中间态)")
|
|
622
|
-
if orphaned:
|
|
623
|
-
names = ', '.join(orphaned)
|
|
624
|
-
print(f"[runtime] ⚠️ 断点续跑:变量 {names} 在新剧本已删除,快照残留值成为孤儿数据(无人读则无害)")
|
|
625
|
-
self.errors.warn(
|
|
626
|
-
f"断点续跑:变量 {names} 在新剧本已删除,快照残留值成为孤儿数据(无人读则无害)")
|
|
627
|
-
else:
|
|
628
|
-
self.resume_positions = {}
|
|
629
|
-
|
|
630
|
-
# 步数控制(保留)
|
|
631
|
-
self.global_step = 0
|
|
632
|
-
self.global_max_steps = 0
|
|
633
|
-
|
|
634
|
-
# ── CLI 渲染器(若未提供外部事件回调且非 FastAPI 模式) ──
|
|
635
|
-
if self._event_callback is None and self._human_input_event is None:
|
|
636
|
-
cli_renderer = CLIRenderer(verbose=self.verbose)
|
|
637
|
-
self._event_callback = cli_renderer.handle_event
|
|
638
|
-
self._cli_renderer = cli_renderer # 保存引用,供清屏命令使用
|
|
639
|
-
else:
|
|
640
|
-
self._cli_renderer = None
|
|
641
|
-
|
|
642
|
-
if self.verbose:
|
|
643
|
-
print("\n🔧 Python Bridge 已加载模块:")
|
|
644
|
-
for alias in self.bridge.modules:
|
|
645
|
-
funcs = [name for name, obj in vars(self.bridge.modules[alias]).items()
|
|
646
|
-
if callable(obj) and not name.startswith('_')]
|
|
647
|
-
print(f"[runtime]{alias}: {funcs}")
|
|
648
|
-
|
|
649
|
-
def _emit_event(self, event_type: str, data: dict = None):
|
|
650
|
-
"""向前端发送事件"""
|
|
651
|
-
if data:
|
|
652
|
-
def _sanitize(obj):
|
|
653
|
-
if isinstance(obj, dict):
|
|
654
|
-
return {k: _sanitize(v) for k, v in obj.items()}
|
|
655
|
-
elif isinstance(obj, list):
|
|
656
|
-
return [_sanitize(item) for item in obj]
|
|
657
|
-
elif isinstance(obj, (str, int, float, bool, type(None))):
|
|
658
|
-
return obj
|
|
659
|
-
else:
|
|
660
|
-
return str(obj)
|
|
661
|
-
data = _sanitize(data)
|
|
662
|
-
|
|
663
|
-
# 调试:打印所有发往前端的事件
|
|
664
|
-
#print(f"[EMIT] {event_type}: {json.dumps(data, ensure_ascii=False, default=str) if data else '{}'}")
|
|
665
|
-
|
|
666
|
-
if self._event_callback:
|
|
667
|
-
self._event_callback(event_type, data or {})
|
|
668
|
-
|
|
669
|
-
def _rc_call(self, name: str, *args) -> None:
|
|
670
|
-
"""窄回调安全调用(§4.2 依赖倒置契约):回调是旁挂,环境故障不能带崩
|
|
671
|
-
演出本体——try/except 打 log。旁挂失效最坏=Job 停在 running → 重启
|
|
672
|
-
对账判 crash,不会伪 finished。未注入该回调(缺省 None)→ no-op。"""
|
|
673
|
-
callback = self._rc.get(name)
|
|
674
|
-
if callback is None:
|
|
675
|
-
return
|
|
676
|
-
try:
|
|
677
|
-
callback(*args)
|
|
678
|
-
except Exception as exc: # noqa: BLE001 ——旁挂绝不反向炸演出
|
|
679
|
-
print(f"[runtime]⚠️ runtime callback {name!r} failed: {exc}")
|
|
680
|
-
|
|
681
|
-
def _record_checkpoint(self, ctx: TaskContext, node_id: str) -> None:
|
|
682
|
-
"""记录一个 task 当前执行到的节点位置与 per-task 变量世界整包
|
|
683
|
-
(进入节点前调用)。
|
|
684
|
-
|
|
685
|
-
存的是"位置"(task_id→node id,分支直启的恢复点);节点不存在于
|
|
686
|
-
新剧本时从头跑。[END]/[BREAK] 是终点/跳出点,永不作为续跑位置记录
|
|
687
|
-
——否则残留的 checkpoint 会让后续每次 run 都从终点"续跑"而整体跳过
|
|
688
|
-
剧本。
|
|
689
|
-
|
|
690
|
-
载荷 {checkpoints, session_id, state?}:checkpoints=task_id→node_id
|
|
691
|
-
位置映射(宿主 canResume 判据,纯透传);state=dump_state per-task
|
|
692
|
-
世界整包(仅内容变化时携带去重省流量;R4 起字段名 state,与宿主
|
|
693
|
-
宿主侧事件/开演两模块同刻更名——引擎与宿主同插件
|
|
694
|
-
同次构建部署,无跨版本窗口)。
|
|
695
|
-
⚠️ 引擎恢复侧唯一数据源=state.positions(接线约定 5)。
|
|
696
|
-
"""
|
|
697
|
-
if node_id in ('[END]', '[BREAK]'):
|
|
698
|
-
return
|
|
699
|
-
position_changed = self.checkpoints.get(ctx.task_id) != node_id
|
|
700
|
-
# 本 task 的执行栈快照(直启时 restore_stack 用);module_frames 含
|
|
701
|
-
# 每层模块的母 flow 调用节点(caller_node_id)——直启跑完模块 flow 后
|
|
702
|
-
# 逐层弹栈回母 flow 续传(恢复模型 §3.5 模块场景补全,_resume_module_unwind)。
|
|
703
|
-
mod_stack, loop_frames = ctx.facade.export_stack()
|
|
704
|
-
self._positions[ctx.task_id] = {
|
|
705
|
-
'node_id': node_id,
|
|
706
|
-
'mod_stack': list(mod_stack),
|
|
707
|
-
'module_frames': [{'name': mf.name, 'caller_node_id': mf.caller_node_id}
|
|
708
|
-
for mf in ctx.module_frames],
|
|
709
|
-
'loop_frames': list(loop_frames),
|
|
710
|
-
}
|
|
711
|
-
state = dump_state(
|
|
712
|
-
envs=self.world.envs, world=self.world.world,
|
|
713
|
-
forks=self.world.forks, ledger=self.world.ledger,
|
|
714
|
-
positions=self._positions)
|
|
715
|
-
state_dump = json.dumps(state, ensure_ascii=False, default=str, sort_keys=True)
|
|
716
|
-
state_changed = state_dump != self._last_vars_dump
|
|
717
|
-
if not position_changed and not state_changed:
|
|
718
|
-
return
|
|
719
|
-
if position_changed:
|
|
720
|
-
self.checkpoints[ctx.task_id] = node_id
|
|
721
|
-
self._last_vars_dump = state_dump
|
|
722
|
-
# D1(前端断点高亮):checkpoint_labels={task_id: 显示名}——per-task
|
|
723
|
-
# 全量查表(各 task 位置可能在不同 flow,按 _positions 的 mod_stack
|
|
724
|
-
# 逐个解析);查表失败/网关缺省退化 node_id(0-e 兜底形态)。
|
|
725
|
-
# 恢复侧仍消费 node_id,双字段并存不互扰。
|
|
726
|
-
labels: Dict[str, str] = {}
|
|
727
|
-
for tid, pos in self._positions.items():
|
|
728
|
-
node_str = str(pos.get('node_id', ''))
|
|
729
|
-
label = node_str
|
|
730
|
-
try:
|
|
731
|
-
flow_i, _extra_i = self._flow_for_stack(list(pos.get('mod_stack') or []))
|
|
732
|
-
except Exception as exc:
|
|
733
|
-
print(f"[runtime]⚠️ checkpoint_labels 查表失败(task {tid} 退化 node_id): {exc}")
|
|
734
|
-
flow_i = None
|
|
735
|
-
if flow_i is not None:
|
|
736
|
-
node_obj = flow_i.nodes.get(node_str)
|
|
737
|
-
if node_obj is not None and getattr(node_obj, 'label', ''):
|
|
738
|
-
label = node_obj.label
|
|
739
|
-
labels[tid] = label
|
|
740
|
-
payload: Dict[str, Any] = {'checkpoints': dict(self.checkpoints),
|
|
741
|
-
'checkpoint_labels': labels}
|
|
742
|
-
if self._current_session_id:
|
|
743
|
-
payload['session_id'] = self._current_session_id
|
|
744
|
-
if state_changed:
|
|
745
|
-
payload['state'] = state
|
|
746
|
-
self._emit_event('checkpoint', payload)
|
|
747
|
-
# Job 旁挂(§5.3):断点归引擎落盘(JobManager.merge_checkpoint)——
|
|
748
|
-
# 宿主不再持久化 resume 块(A3/C5 死于结构)。
|
|
749
|
-
self._rc_call('on_checkpoint', payload)
|
|
750
|
-
|
|
751
|
-
def _resume_start_for(self, task_id: str, fallback: str, flow) -> str:
|
|
752
|
-
"""续跑起点:该 task 上次记录的节点若仍在新剧本中则用之,否则从头。"""
|
|
753
|
-
if not self.resume_checkpoints:
|
|
754
|
-
return fallback
|
|
755
|
-
resumed = self.resume_checkpoints.get(task_id)
|
|
756
|
-
if resumed and resumed in flow.nodes:
|
|
757
|
-
print(f"[resume] 分支 {task_id} 从节点 {resumed} 继续")
|
|
758
|
-
return resumed
|
|
759
|
-
if resumed:
|
|
760
|
-
print(f"[resume] 分支 {task_id} 的记录节点 {resumed} 已不在新剧本,从头执行")
|
|
761
|
-
return fallback
|
|
762
|
-
|
|
763
|
-
def _resolve_module_def(self, mod_path: str):
|
|
764
|
-
"""沿模块完整路径('Outer.Inner')解析模块定义——嵌套模块 mod_path
|
|
765
|
-
栈解析(清单 D4):逐段下钻 script.modules。"""
|
|
766
|
-
mod = None
|
|
767
|
-
container = self.script.modules
|
|
768
|
-
for part in mod_path.split('.'):
|
|
769
|
-
mod = container.get(part)
|
|
770
|
-
if mod is None:
|
|
771
|
-
raise FEMOVariableError(
|
|
772
|
-
f"模块 '{mod_path}' 解析失败于段 '{part}'(未声明或路径错误)")
|
|
773
|
-
container = mod.modules
|
|
774
|
-
return mod
|
|
775
|
-
|
|
776
|
-
def _chain_actions_for(self, mod_path: str) -> Optional[dict]:
|
|
777
|
-
"""模块 flow 的 extra_actions:词法链(mod_path 逐段 祖先→自身)
|
|
778
|
-
actions 合并,自身覆盖同名(拍板 6 的 action 侧对齐——嵌套子模块
|
|
779
|
-
flow 可引用母链模块的 action)。全局 script.actions 不在此合并:
|
|
780
|
-
_execute_node_content 查不到 extra 时本就回退全局。"""
|
|
781
|
-
merged: dict = {}
|
|
782
|
-
container = self.script.modules
|
|
783
|
-
for part in (mod_path or '').split('.'):
|
|
784
|
-
mod = container.get(part)
|
|
785
|
-
if mod is None:
|
|
786
|
-
return None
|
|
787
|
-
merged.update(mod.actions or {})
|
|
788
|
-
container = mod.modules
|
|
789
|
-
return merged or None
|
|
790
|
-
|
|
791
|
-
def _flow_for_stack(self, mod_stack) -> Tuple[Any, Optional[dict]]:
|
|
792
|
-
"""直启/分支执行的目标 flow 与 extra_actions:模块栈顶决定
|
|
793
|
-
(栈顶剧本级 → mainflow;否则对应模块 flow,extra_actions 同源)。"""
|
|
794
|
-
if not mod_stack:
|
|
795
|
-
return self.script.flow, None
|
|
796
|
-
mod = self._resolve_module_def(mod_stack[-1])
|
|
797
|
-
return mod.flow, self._chain_actions_for(mod_stack[-1])
|
|
798
|
-
|
|
799
|
-
async def _resume_module_unwind(self, ctx: TaskContext) -> None:
|
|
800
|
-
"""直启恢复的模块调用链续传(恢复模型 §3.5 的模块场景补全,R4)。
|
|
801
|
-
|
|
802
|
-
分支直启按栈顶 flow(模块 flow)跑:到 [OUT]/[BREAK] 时 _execute_path
|
|
803
|
-
返回——**正常场景**母协程(fork gather 收场后)继续母 flow 的剩余执行
|
|
804
|
-
流;**直启场景**母协程不存在(root 已随 fork 终止且不直启),若不续传,
|
|
805
|
-
模块出口后 mainflow 的后续节点永远没人跑(flow_done 照发、剧本断头)。
|
|
806
|
-
|
|
807
|
-
本方法逐层弹栈:exit_module 清模块帧(宪法 1.2)→ 按快照调用链
|
|
808
|
-
(ModuleFrame.caller_node_id,_run_module push 时记录)定位母 flow 中
|
|
809
|
-
的模块调用节点 → 从其出边继续 _execute_path;嵌套模块逐层回退,直到
|
|
810
|
-
模块栈空(mainflow)或流程自然终止。已知边界(留档待议):模块调用点
|
|
811
|
-
在母 flow 的 for 循环体内时,restore_stack 重建的栈序(循环帧恒排在
|
|
812
|
-
模块帧后)与运行期真实栈序(模块帧在循环帧内)不一致,exit_module
|
|
813
|
-
的栈顶校验会 fail loud——不会静默错跑,该组合场景的恢复待单独处理。"""
|
|
814
|
-
while ctx.module_frames:
|
|
815
|
-
top = ctx.module_frames[-1]
|
|
816
|
-
mod_path = top.name
|
|
817
|
-
ctx.module_frames.pop()
|
|
818
|
-
ctx.facade.exit_module() # pop 帧 + 清模块 local(宪法 1.2)
|
|
819
|
-
parent_stack = [mf.name for mf in ctx.module_frames]
|
|
820
|
-
flow, extra = self._flow_for_stack(parent_stack)
|
|
821
|
-
caller = top.caller_node_id or ''
|
|
822
|
-
if flow is None or not caller or caller not in flow.nodes:
|
|
823
|
-
print(f"[resume]⚠️ 模块 {mod_path} 的调用点 {caller!r} 不在新剧本"
|
|
824
|
-
f"母 flow 中,续跑止于模块出口")
|
|
825
|
-
return
|
|
826
|
-
nxt = self._follow_next_edge(caller, flow)
|
|
827
|
-
if not nxt:
|
|
828
|
-
return # 调用点后无出边:流程正常终止
|
|
829
|
-
print(f"[resume]🔗 模块 {mod_path} 跑完,从调用点 {caller} 续传母 flow → {nxt}")
|
|
830
|
-
await self._execute_path(flow, nxt, stop_at=None,
|
|
831
|
-
extra_actions=extra, max_steps=0)
|
|
832
|
-
|
|
833
|
-
def _parse_single_assignment(self, text: str) -> tuple:
|
|
834
|
-
"""
|
|
835
|
-
解析单条赋值文本,返回 (变量名, 表达式)。
|
|
836
|
-
支持格式:@KILL = @Ellis, KILL = @Alice, $x = 1, SCORE += 1, TASKS = add(@Alice)
|
|
837
|
-
解析失败抛出 ValueError。
|
|
838
|
-
"""
|
|
839
|
-
# 变量名支持 @/$ 前缀(VAR_NAME_RE,拍板 8④)
|
|
840
|
-
m = re.match(r'^\s*(' + VAR_NAME_RE + r')\s*([+\-]?=)\s*(.+)$', text)
|
|
841
|
-
if not m:
|
|
842
|
-
raise ValueError(f"无法解析赋值语句: {text}")
|
|
843
|
-
var_name = m.group(1).strip()
|
|
844
|
-
op = m.group(2).strip()
|
|
845
|
-
value = m.group(3).strip()
|
|
846
|
-
expr = f"{op} {value}"
|
|
847
|
-
return var_name, expr
|
|
848
|
-
|
|
849
|
-
# ══════════════════════════════════════════════════
|
|
850
|
-
# 边遍历辅助
|
|
851
|
-
# ══════════════════════════════════════════════════
|
|
852
|
-
|
|
853
|
-
def _follow_next_edge(self, node_id: str, flow) -> Optional[str]:
|
|
854
|
-
"""条件求值 + 找下一条边,返回目标节点 ID"""
|
|
855
|
-
cond_edges = [e for e in flow.edges if e.source == node_id and e.condition]
|
|
856
|
-
default_edges = [e for e in flow.edges if e.source == node_id and not e.condition]
|
|
857
|
-
|
|
858
|
-
ctx = current_task_ctx()
|
|
859
|
-
facade = ctx.facade if ctx is not None else None
|
|
860
|
-
self.evaluator.clear_func_cache() # 接线约定 4:每条边评估前清(副作用函数不跨节点缓存)
|
|
861
|
-
for e in cond_edges:
|
|
862
|
-
result = self.evaluator.evaluate_condition(e.condition, facade)
|
|
863
|
-
print(f"[runtime] 🔍 此处有条件判断: 条件 = {e.condition},结果 = {result}")
|
|
864
|
-
if result:
|
|
865
|
-
return e.target
|
|
866
|
-
|
|
867
|
-
if default_edges:
|
|
868
|
-
return default_edges[0].target
|
|
869
|
-
|
|
870
|
-
# 【2026-09-07 warning 桶】流程在无出边处停止=按设计正常收尾的一种,
|
|
871
|
-
# 不阻断(return None → 上层正常结束),但作者应当知情。
|
|
872
|
-
print(f"[runtime]⚠️ 节点 {node_id} 没有任何符合条件的出边,流程将在此停止。")
|
|
873
|
-
self.errors.warn(f"节点 {node_id} 没有任何符合条件的出边,流程将在此停止。")
|
|
874
|
-
|
|
875
|
-
return None
|
|
876
|
-
|
|
877
|
-
def _collect_loop_body(self, gateway_id: str, flow) -> Tuple[Set[str], Optional[str], Optional[str]]:
|
|
878
|
-
"""
|
|
879
|
-
找出 for 循环体包含的节点,以及循环入口和出口。
|
|
880
|
-
返回 (body_node_ids, body_entry_id, exit_node_id)
|
|
881
|
-
"""
|
|
882
|
-
body = set()
|
|
883
|
-
queue = []
|
|
884
|
-
|
|
885
|
-
# 从 gateway 出发,所有非自环边的目标是候选入口
|
|
886
|
-
for e in flow.edges:
|
|
887
|
-
if e.source == gateway_id and e.target != gateway_id:
|
|
888
|
-
queue.append(e.target)
|
|
889
|
-
|
|
890
|
-
# BFS 收集 body 节点(不穿过 gateway)
|
|
891
|
-
visited = set()
|
|
892
|
-
while queue:
|
|
893
|
-
nid = queue.pop(0)
|
|
894
|
-
if nid in visited or nid == gateway_id:
|
|
895
|
-
continue
|
|
896
|
-
visited.add(nid)
|
|
897
|
-
body.add(nid)
|
|
898
|
-
|
|
899
|
-
for e in flow.edges:
|
|
900
|
-
if e.source == nid and e.target != gateway_id and e.target not in visited:
|
|
901
|
-
queue.append(e.target)
|
|
902
|
-
|
|
903
|
-
# body_entry: gateway 的第一条进入 body 的边
|
|
904
|
-
body_entry = None
|
|
905
|
-
for e in flow.edges:
|
|
906
|
-
if e.source == gateway_id and e.target in body:
|
|
907
|
-
body_entry = e.target
|
|
908
|
-
break
|
|
909
|
-
|
|
910
|
-
# exit_node: gateway 的边中,目标不在 body 里且不是 gateway 自身的
|
|
911
|
-
exit_node = None
|
|
912
|
-
for e in flow.edges:
|
|
913
|
-
if e.source == gateway_id and e.target != gateway_id and e.target not in body:
|
|
914
|
-
exit_node = e.target
|
|
915
|
-
break
|
|
916
|
-
|
|
917
|
-
return body, body_entry, exit_node
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
def _check_cancel(self):
|
|
923
|
-
"""检查当前协程是否被取消"""
|
|
924
|
-
self.engine.check_cancel()
|
|
925
|
-
|
|
926
|
-
def stop(self):
|
|
927
|
-
"""全局立刻停止:取消主协程,中断 LLM 流式输出。
|
|
928
|
-
v3(运行状态链路重构 §5.5):
|
|
929
|
-
- 幂等头:二次 stop / HMR dispose 不再双 flow_paused(灭 D6);
|
|
930
|
-
- _stopped 从零消费标志复活为真消费(A1 取消诚实化的判定依据:
|
|
931
|
-
run_async 取消路径据它区分 user_pause / cancelled);
|
|
932
|
-
- 时序红线(v1 裁决):**先 cancel 后 abort**——cancel 先置 _must_cancel,
|
|
933
|
-
abort_all 唤醒的协程在恢复点直接吃 CancelledError 零推进;反过来
|
|
934
|
-
(先 abort)唤醒与 cancel 之间存在同步推进窗口,协程可能拿着输入值
|
|
935
|
-
继续跑赋值/落库(僵尸推进)。"""
|
|
936
|
-
if self._stopped:
|
|
937
|
-
return # ① 幂等头(D6)
|
|
938
|
-
print("[runtime] 收到全局停止信号,正在停止所有任务...")
|
|
939
|
-
self._stopped = True # ② 真消费标志(A1 判定 + 幂等依据)
|
|
940
|
-
|
|
941
|
-
# ③ 中断正在进行的 LLM 流式请求
|
|
942
|
-
if self._llm_stop_event:
|
|
943
|
-
self._llm_stop_event.set()
|
|
944
|
-
|
|
945
|
-
# ④ 取消主协程 + 所有活动分支协程(先 cancel)。
|
|
946
|
-
# asyncio 的 cancel 不级联:fork 分支等子任务注册在
|
|
947
|
-
# engine._active_tasks,只取消 _main_task 会让分支继续跑
|
|
948
|
-
# (表现为"停止失败、狼人节点疯狂重复")。
|
|
949
|
-
# 【2026-09-07 214 事故根治】cancel 一律走 call_soon_threadsafe:
|
|
950
|
-
# stop() 从 bridge 的 stdin 派发线程调用(非循环线程),裸
|
|
951
|
-
# task.cancel() 内部经 loop.call_soon(非线程安全)调度唤醒、
|
|
952
|
-
# 不写 self-pipe——循环恰 park 在 select 时取消令牌被静默丢失,
|
|
953
|
-
# 循环从此永久空转,停止成了死信(214"停止已受理、引擎永不
|
|
954
|
-
# 收场"的机制本体)。call_soon_threadsafe 自带 self-pipe 唤醒,
|
|
955
|
-
# 回调在循环线程执行;深任务链 cancel 的同步递归发生在彼处
|
|
956
|
-
# (femo_bridge 已把 recursionlimit 提到 200k 兜底)。
|
|
957
|
-
targets = [self._main_task]
|
|
958
|
-
targets.extend(self._task_coros.values()) # 两层 task 桥双保险(值都在 engine._active_tasks)
|
|
959
|
-
active = getattr(self.engine, '_active_tasks', None)
|
|
960
|
-
if active:
|
|
961
|
-
targets.extend(active)
|
|
962
|
-
for task in targets:
|
|
963
|
-
if task is not None and not task.done():
|
|
964
|
-
try:
|
|
965
|
-
task.get_loop().call_soon_threadsafe(task.cancel)
|
|
966
|
-
except RuntimeError:
|
|
967
|
-
# 循环已关闭(run 已收尾):任务由循环退场收割,无需调度
|
|
968
|
-
pass
|
|
969
|
-
print("[runtime] 主协程与全部活动分支协程已取消")
|
|
970
|
-
|
|
971
|
-
# ⑤ 后 abort——唤醒 cancel 漏网的 executor 等待者(A2):wait_for_input
|
|
972
|
-
# 的 _aborted 恢复点让它们直接吃 CancelledError 零推进。
|
|
973
|
-
try:
|
|
974
|
-
self.engine.human_input.abort_all()
|
|
975
|
-
except Exception as exc:
|
|
976
|
-
print(f"[runtime]⚠️ human_input.abort_all failed: {exc}")
|
|
977
|
-
|
|
978
|
-
# ⑥ 发送事件通知前端(首发照发:v4 停靠清场——宿主作废在飞 main 回答/
|
|
979
|
-
# 掐断在飞子代理——全挂它上面,不发则宿主停靠托管挂满 15min)
|
|
980
|
-
self._emit_event('flow_paused', {})
|
|
981
|
-
|
|
982
|
-
async def _run_join(self, join_id: str, node, flow, extra_actions=None, max_steps=0) -> Optional[str]:
|
|
983
|
-
"""join 网关(R3 接线,清单 D3——主流程路径)。
|
|
984
|
-
|
|
985
|
-
统一走 task_world.join_sign_in:到达即签到挂起;等待集沿 join 入边
|
|
986
|
-
拓扑反溯(fork 网关对齐血统链收集孩子 / 嵌套 join 级联 / 串行直连
|
|
987
|
-
到达即过);凑齐 = LCA base + git 式三方合并(冲突保留 base + 警告,
|
|
988
|
-
拍板 7)→ merge 出**新 task**(宪法 1.1)→ 本协程变身幸运者从出口
|
|
989
|
-
继续;返回 None = 本 task 终止(迟到者/非触发者),调用方不得再跑
|
|
990
|
-
出口。join(N) 的"凑 N 即跑、余者掐尾"语义首次生效(§1.4 实锤旧
|
|
991
|
-
Runtime 里 join(数字) 从未生效)。"""
|
|
992
|
-
return await join_sign_in(self, self.world, flow, join_id, node,
|
|
993
|
-
extra_actions, max_steps)
|
|
994
|
-
|
|
995
|
-
# ══════════════════════════════════════════════════
|
|
996
|
-
# join 协调器接线(R3,清单 D3)
|
|
997
|
-
# ══════════════════════════════════════════════════
|
|
998
|
-
|
|
999
|
-
def _coordinator_for(self, join_id: str, node, flow, tw: TaskWorld):
|
|
1000
|
-
"""per join_id 协调器缓存(循环体里的 join 多轮复用靠协调器自带
|
|
1001
|
-
代次)。mode/sources 取自编译期产物:join_mode(parse_join 产出
|
|
1002
|
-
'all' 或数字字符串——数字串→int,根治旧 Runtime 数字掉 else 的死
|
|
1003
|
-
代码语义,拍板 2);sources=直连入边的来源节点集(join 列表节点,
|
|
1004
|
-
事件显示与文档对照用)。GraphQuery 沿 join 入边在**当前 flow 图内**
|
|
1005
|
-
反溯(模块边界即停);cascade 为 run 级共享总线(嵌套 join 级联)。"""
|
|
1006
|
-
coord = self._coordinators.get(join_id)
|
|
1007
|
-
if coord is None:
|
|
1008
|
-
meta = getattr(node, 'meta', None) or {}
|
|
1009
|
-
raw_mode = str(meta.get('join_mode', 'all')).strip()
|
|
1010
|
-
if raw_mode.lower() == 'all' or not raw_mode:
|
|
1011
|
-
mode = 'all'
|
|
1012
|
-
elif raw_mode.isdigit():
|
|
1013
|
-
mode = int(raw_mode)
|
|
1014
|
-
else:
|
|
1015
|
-
raise FEMOVariableError(
|
|
1016
|
-
f"join 模式 '{raw_mode}' 不合法(join(all) 或 join(N),N 为正整数)")
|
|
1017
|
-
# join 列表节点 = 直连入边的 source(parse_join 产出),去重保序
|
|
1018
|
-
sources = tuple(dict.fromkeys(
|
|
1019
|
-
e.source for e in flow.edges if e.target == join_id))
|
|
1020
|
-
if self._cascade is None:
|
|
1021
|
-
from femoCompiler.vars.join import JoinCascade
|
|
1022
|
-
self._cascade = JoinCascade()
|
|
1023
|
-
coord = make_coordinator(
|
|
1024
|
-
tw=tw, join_id=join_id, mode=mode, sources=sources,
|
|
1025
|
-
emit_event=self._emit_event,
|
|
1026
|
-
cancel_fn=self._cancel_branch_task,
|
|
1027
|
-
graph_query=GraphQuery(flow),
|
|
1028
|
-
skip_frames=self._skip_frames,
|
|
1029
|
-
cascade=self._cascade)
|
|
1030
|
-
self._coordinators[join_id] = coord
|
|
1031
|
-
return coord
|
|
1032
|
-
|
|
1033
|
-
def _cancel_branch_task(self, task_id: str) -> None:
|
|
1034
|
-
"""join(N) 凑齐时掐掉未到达分支的单链(cancel_fn 通道)。
|
|
1035
|
-
只 cancel 该 task 的协程(_task_coros 两层 task 桥),不影响其他
|
|
1036
|
-
分支/其他模块对同一 action 的调用(文档 §8.3 线程管理)。"""
|
|
1037
|
-
t = self._task_coros.get(task_id)
|
|
1038
|
-
if t is not None and not t.done():
|
|
1039
|
-
print(f"[JOIN] join 掐断分支 task {task_id}(单链立即停)")
|
|
1040
|
-
t.cancel()
|
|
1041
|
-
|
|
1042
|
-
# ══════════════════════════════════════════════════
|
|
1043
|
-
# 统一的图遍历执行器
|
|
1044
|
-
# ══════════════════════════════════════════════════
|
|
1045
|
-
|
|
1046
|
-
async def _execute_flow(self, flow, start: str = None,
|
|
1047
|
-
stop_at: Set[str] = None,
|
|
1048
|
-
extra_actions: dict = None,
|
|
1049
|
-
max_steps: int = 0) -> Optional[str]:
|
|
1050
|
-
"""
|
|
1051
|
-
统一的 DFS 式图遍历执行器。
|
|
1052
|
-
- flow: FlowGraph 对象
|
|
1053
|
-
- start: 起始节点 ID
|
|
1054
|
-
- stop_at: 遇到这些节点就停下(不执行)
|
|
1055
|
-
- extra_actions: 额外的 action 字典(模块局部 action 优先查这里)
|
|
1056
|
-
- max_steps: 最大步数 (0=不限)
|
|
1057
|
-
返回: 停在哪个节点 ID
|
|
1058
|
-
"""
|
|
1059
|
-
if not flow or not flow.nodes:
|
|
1060
|
-
return None
|
|
1061
|
-
|
|
1062
|
-
stop_at = stop_at or set()
|
|
1063
|
-
|
|
1064
|
-
# ★ 计算 start:优先参数 > flow.entry > [START] 节点 > 自动推断
|
|
1065
|
-
if start is None:
|
|
1066
|
-
start = getattr(flow, 'entry', None) or ''
|
|
1067
|
-
if not start:
|
|
1068
|
-
# 优先使用 [START] 节点(即使它有入边)
|
|
1069
|
-
if '[START]' in flow.nodes:
|
|
1070
|
-
start = '[START]'
|
|
1071
|
-
else:
|
|
1072
|
-
# 自动推断:不是任何边 target 的节点就是入口
|
|
1073
|
-
targets = {e.target for e in flow.edges}
|
|
1074
|
-
for nid in flow.nodes:
|
|
1075
|
-
if nid not in targets:
|
|
1076
|
-
start = nid
|
|
1077
|
-
break
|
|
1078
|
-
if not start:
|
|
1079
|
-
raise FEMOVariableError(
|
|
1080
|
-
"无法确定流程入口节点。请检查 mainflow 中是否定义了起始节点,"
|
|
1081
|
-
"或是否所有节点都被其他节点指向(如成环且无 [START] 节点)。"
|
|
1082
|
-
)
|
|
1083
|
-
|
|
1084
|
-
start = start or flow.entry
|
|
1085
|
-
if not start:
|
|
1086
|
-
return None
|
|
1087
|
-
|
|
1088
|
-
# 续跑:本流程从上次记录的节点继续(节点须仍存在);位置键=task_id
|
|
1089
|
-
# (分支直启恢复点,互不覆盖)。
|
|
1090
|
-
ctx = current_task_ctx()
|
|
1091
|
-
flow_key = ctx.task_id if ctx is not None else '__main__'
|
|
1092
|
-
start = self._resume_start_for(flow_key, start, flow)
|
|
1093
|
-
|
|
1094
|
-
current = start
|
|
1095
|
-
step = 0
|
|
1096
|
-
|
|
1097
|
-
# 入口 [START]:单边走第一条边;多出边 = 一次性 fork(与循环内
|
|
1098
|
-
# 语义一致,不静默丢线——之前只走第一条边会悄悄吞掉其余分支)。
|
|
1099
|
-
# fork 后主流程结束(_run_fork gather 等待所有分支完成;无限循环
|
|
1100
|
-
# 分支由 engine 跟踪,shutdown 时取消)。
|
|
1101
|
-
if current == '[START]':
|
|
1102
|
-
start_out = [e for e in flow.edges if e.source == current]
|
|
1103
|
-
if len(start_out) > 1:
|
|
1104
|
-
await self._run_fork(current, flow.nodes.get(current), flow,
|
|
1105
|
-
extra_actions or {}, max_steps)
|
|
1106
|
-
return None
|
|
1107
|
-
next_node = self._follow_next_edge(current, flow)
|
|
1108
|
-
if next_node:
|
|
1109
|
-
current = next_node
|
|
1110
|
-
else:
|
|
1111
|
-
return None
|
|
1112
|
-
|
|
1113
|
-
prev_node = '[START]' if start != '[START]' else '外部'
|
|
1114
|
-
while current:
|
|
1115
|
-
# 到达停止点
|
|
1116
|
-
if current in stop_at:
|
|
1117
|
-
return current
|
|
1118
|
-
|
|
1119
|
-
if max_steps > 0 and step >= max_steps:
|
|
1120
|
-
print(f"[runtime]⚠️ 达到最大步数 {max_steps}")
|
|
1121
|
-
return current
|
|
1122
|
-
|
|
1123
|
-
step += 1
|
|
1124
|
-
node = flow.nodes.get(current)
|
|
1125
|
-
if not node:
|
|
1126
|
-
raise FEMOVariableError(f"节点未定义: {current}")
|
|
1127
|
-
|
|
1128
|
-
# 节点位置检查点:进入节点前记录(续跑从此节点重放;键=task_id)
|
|
1129
|
-
ctx = current_task_ctx()
|
|
1130
|
-
if ctx is not None:
|
|
1131
|
-
self._record_checkpoint(ctx, current)
|
|
1132
|
-
|
|
1133
|
-
# ── 获取节点类型 ──
|
|
1134
|
-
kind = node.type if node.type else 'empty'
|
|
1135
|
-
info = node.meta
|
|
1136
|
-
# ID 覆盖
|
|
1137
|
-
if current == '[END]':
|
|
1138
|
-
kind = 'end'
|
|
1139
|
-
elif current == '[BREAK]':
|
|
1140
|
-
kind = 'break'
|
|
1141
|
-
# 网关细化
|
|
1142
|
-
if kind == 'gateway':
|
|
1143
|
-
gw = node.meta.get('gw_kind', '')
|
|
1144
|
-
if gw in ('for', 'par', 'fork', 'join'):
|
|
1145
|
-
kind = f'gateway_{gw}'
|
|
1146
|
-
# Delay 节点类型标记
|
|
1147
|
-
if node.type == 'delay' or node.meta.get('is_delay_node'):
|
|
1148
|
-
kind = 'delay'
|
|
1149
|
-
# 动作 / 模块覆盖(保持原有逻辑,但注意 module_call 优先级)
|
|
1150
|
-
if node.module_ref:
|
|
1151
|
-
kind = 'module_call'
|
|
1152
|
-
elif node.action_name:
|
|
1153
|
-
kind = 'action'
|
|
1154
|
-
|
|
1155
|
-
emit_step(self, step, prev_node, current, kind)
|
|
1156
|
-
|
|
1157
|
-
if kind == 'end':
|
|
1158
|
-
print("🏁 到达 [END]")
|
|
1159
|
-
return current
|
|
1160
|
-
if kind == 'break':
|
|
1161
|
-
print("⛔ 到达 [BREAK]")
|
|
1162
|
-
return current
|
|
1163
|
-
|
|
1164
|
-
# ── FOR / PAR 网关 ──
|
|
1165
|
-
if kind in ('gateway_for', 'gateway_par'):
|
|
1166
|
-
prev_node = current
|
|
1167
|
-
current = await self._run_for_loop(current, node, info, flow,
|
|
1168
|
-
extra_actions, max_steps)
|
|
1169
|
-
print(f"[runtime] 🔄 For/Par 返回后 current = {current}")
|
|
1170
|
-
continue
|
|
1171
|
-
|
|
1172
|
-
# ── FORK 网关(可能由 par 展开) ──
|
|
1173
|
-
if kind == 'gateway_fork':
|
|
1174
|
-
prev_node = current
|
|
1175
|
-
current = await self._run_fork(current, node, flow,
|
|
1176
|
-
extra_actions, max_steps)
|
|
1177
|
-
continue
|
|
1178
|
-
|
|
1179
|
-
# ── JOIN 网关 ──
|
|
1180
|
-
if kind == 'gateway_join':
|
|
1181
|
-
prev_node = current
|
|
1182
|
-
current = await self._run_join(current, node, flow, extra_actions=extra_actions, max_steps=max_steps)
|
|
1183
|
-
continue
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
# ── 统一执行节点内容(适用于 action / module_call / start / router 等) ──
|
|
1187
|
-
await self._execute_node_content(node, flow, extra_actions, max_steps, node_id=current)
|
|
1188
|
-
|
|
1189
|
-
# ── 走边进入下一个节点 ──
|
|
1190
|
-
out_edges = [e for e in flow.edges if e.source == current]
|
|
1191
|
-
print(f"[runtime] 📤 节点 {current} 的出边: {[(e.target, e.condition) for e in out_edges]}")
|
|
1192
|
-
if len(out_edges) > 1:
|
|
1193
|
-
# 多出边 = fork 并发语义(文档:不写 fork 直接 mermaid 多分支也并行)。
|
|
1194
|
-
# 无条件边必走、条件边评估为真才走,各分支并发执行。
|
|
1195
|
-
#
|
|
1196
|
-
# ⚠️ 已知现状(2026-09-03 拍板留痕,本次变量系统重构不解决):
|
|
1197
|
-
# 多条线【直接指向同一节点】时(mermaid 直连汇聚、无 join 语法),
|
|
1198
|
-
# 各分支会【独立执行该节点及其后续整条链】——汇聚节点之后的节点
|
|
1199
|
-
# 每个分支各跑一遍,不是"合二为一"。正确的汇合语义是显式写
|
|
1200
|
-
# join(all)(接收端签到合并、merge 出新 task)。直连汇聚的隐式
|
|
1201
|
-
# join 语义待后续版本收敛;变量侧已按显式 join 的正确语义实现
|
|
1202
|
-
# (几线合一 → world.merge → 新 Task,源 task 生命周期终止)。
|
|
1203
|
-
print(f"[runtime] 🔀 节点 {current} 有多条出边({len(out_edges)} 条),按 fork 并发执行")
|
|
1204
|
-
prev_node = current
|
|
1205
|
-
current = await self._run_fork(current, node, flow, extra_actions, max_steps)
|
|
1206
|
-
continue
|
|
1207
|
-
next_node = self._follow_next_edge(current, flow)
|
|
1208
|
-
if current == '[p]': # 特别关注 [p] 节点
|
|
1209
|
-
print(f"[runtime]🔍 [p] 节点的下一节点: {next_node}")
|
|
1210
|
-
# 【2026-09-07 二次修复】死路(无出边/条件全不成立)= 按设计正常收尾
|
|
1211
|
-
# (_follow_next_edge 的 warning 桶注释原文:"return None → 上层正常
|
|
1212
|
-
# 结束")。此处原有一个 raise 与该设计自相矛盾——分支里的死路
|
|
1213
|
-
# (_execute_path)早已优雅允许,唯独主链死路整场报错,双 walker
|
|
1214
|
-
# 双语义。现统一:死路 → _follow_next_edge 已警告一次 → 本链优雅
|
|
1215
|
-
# 停止(其他分支不受影响;唯一主链死路=整场正常结束)。
|
|
1216
|
-
prev_node = current
|
|
1217
|
-
current = next_node
|
|
1218
|
-
|
|
1219
|
-
# 协作式调度让出:assign 等快速节点不会自然挂起,不让出会
|
|
1220
|
-
# 饿死并行的其他 fork 分支(多地点常驻并行线场景)。
|
|
1221
|
-
await asyncio.sleep(0)
|
|
1222
|
-
|
|
1223
|
-
# ... 循环结束
|
|
1224
|
-
# 【2026-09-07 二次修复】此处不再发"没有可用的出边"警告:
|
|
1225
|
-
# - 真实死路(节点无出边/条件全不成立)已由 _follow_next_edge 警告
|
|
1226
|
-
# 一次并优雅停止(warning 桶,见上);
|
|
1227
|
-
# - fork/par/join 网关处母 walk 收尾是正常机制(续跑在子协程里:
|
|
1228
|
-
# fork 纯收场等子任务、join 变身由幸运者接棒)——包装协程在此
|
|
1229
|
-
# 结束不是断链。此前在此处对网关收尾告警,一局误报 6 次(作者
|
|
1230
|
-
# 被吓退),且与真正的卡死(join 环上死等,完全无声)毫无关系,
|
|
1231
|
-
# 纯属误导,整段退役。
|
|
1232
|
-
return None
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
async def _execute_node_content(self, node, flow, extra_actions: dict, max_steps: int = 0, node_id: str = ""):
|
|
1240
|
-
"""执行节点的:绑定的动作 → 绑定的模块 → extra_actions 序列"""
|
|
1241
|
-
print(f"[runtime] >>> _execute_node_content: node_id={node_id}, type={getattr(node, 'type', '?')}, is_delay={node.meta.get('is_delay_node', False)}")
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
# 记录当前节点 ID 到线程本地的上下文,避免多线程覆盖
|
|
1246
|
-
ctx = current_task_ctx()
|
|
1247
|
-
if ctx:
|
|
1248
|
-
ctx.current_node_id = node_id
|
|
1249
|
-
# 0. 处理节点 prompt(视作人类发言)
|
|
1250
|
-
if hasattr(node, 'prompt') and node.prompt:
|
|
1251
|
-
prompt_text = self.evaluator.interpolate_prompt(
|
|
1252
|
-
node.prompt, ctx.facade if ctx else None)
|
|
1253
|
-
if prompt_text:
|
|
1254
|
-
from .save_dialog import save_human_turn
|
|
1255
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
1256
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
1257
|
-
actor_info = {'user': f'femo-{femo_id}'}
|
|
1258
|
-
# 尝试获取节点绑定的 action 的 scope(2026-08-31 起空 scope=all、
|
|
1259
|
-
# self 由 _build_scope 判定,统一走 _raw_scope_for;节点无绑定
|
|
1260
|
-
# action 时保持空 → _build_scope 兜底注入 femo-id+owner)
|
|
1261
|
-
action_scope = ([], [])
|
|
1262
|
-
ad = None
|
|
1263
|
-
if node.action_name:
|
|
1264
|
-
ad = extra_actions.get(node.action_name) if extra_actions else None
|
|
1265
|
-
if not ad:
|
|
1266
|
-
ad = self.script.actions.get(node.action_name)
|
|
1267
|
-
if ad:
|
|
1268
|
-
action_scope = self._raw_scope_for(ad)
|
|
1269
|
-
turn_id, oratio_idx = self._update_speaker('node')
|
|
1270
|
-
print(f"[DEBUG node_prompt] actor_info={actor_info}, meta_owner={meta_owner}, femo_id={self.script.meta.get('id', 'unknown')}")
|
|
1271
|
-
event = save_human_turn(
|
|
1272
|
-
session_id=self._current_session_id,
|
|
1273
|
-
turn_id=turn_id,
|
|
1274
|
-
oratio_idx=oratio_idx,
|
|
1275
|
-
user_input=prompt_text,
|
|
1276
|
-
actor_info=actor_info,
|
|
1277
|
-
meta_owner=meta_owner,
|
|
1278
|
-
action_scope=action_scope,
|
|
1279
|
-
is_node_prompt=True,
|
|
1280
|
-
femo_id=self.script.meta.get('id', 'unknown'),
|
|
1281
|
-
raw_action_scope=(ad.scope if ad and ad.scope else None),
|
|
1282
|
-
)
|
|
1283
|
-
if event:
|
|
1284
|
-
event.wait()
|
|
1285
|
-
print(f"[runtime]📄 节点 prompt 已存入: turn={turn_id}, oratio={oratio_idx}")
|
|
1286
|
-
elif self.speaker["current"] == 'ai':
|
|
1287
|
-
# 节点无 prompt 但当前为 AI 状态,step_idx 递增(作为内部步骤)
|
|
1288
|
-
self._step_idx += 1
|
|
1289
|
-
|
|
1290
|
-
# 1. 执行节点绑定的动作
|
|
1291
|
-
if node.action_name:
|
|
1292
|
-
ad = extra_actions.get(node.action_name) if extra_actions else None
|
|
1293
|
-
if not ad:
|
|
1294
|
-
ad = self.script.actions.get(node.action_name)
|
|
1295
|
-
if ad:
|
|
1296
|
-
print(f"[runtime]⚡ 节点动作: {node.action_name}")
|
|
1297
|
-
# 保存当前节点名,供 AI 暂停时使用
|
|
1298
|
-
self._current_node_id = node.node_id if hasattr(node, 'node_id') else ''
|
|
1299
|
-
await self._exec_action_def(ad)
|
|
1300
|
-
else:
|
|
1301
|
-
# 【2026-09-07 warning 桶】动作未定义=节点空过(不阻断流程),
|
|
1302
|
-
# 但剧情线大概率缺了一环——作者应当知情。
|
|
1303
|
-
print(f"[runtime]⚠️ 动作未定义: {node.action_name}")
|
|
1304
|
-
self.errors.warn(
|
|
1305
|
-
f"动作未定义: {node.action_name}(节点 {node_id} 空过,流程继续)",
|
|
1306
|
-
node_id=str(node_id))
|
|
1307
|
-
|
|
1308
|
-
# 2. 执行节点绑定的模块
|
|
1309
|
-
if node.module_ref:
|
|
1310
|
-
print(f"[runtime]📦 节点模块: &{node.module_ref}, caller_node_id={node_id!r}")
|
|
1311
|
-
await self._run_module(node.module_ref, caller_node_id=node_id)
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
# ══════════════════════════════════════════════════
|
|
1315
|
-
# FOR 循环执行
|
|
1316
|
-
# ══════════════════════════════════════════════════
|
|
1317
|
-
|
|
1318
|
-
async def _run_for_loop(self, gateway_id: str, node, info: dict,
|
|
1319
|
-
flow, extra_actions: dict, max_steps: int) -> Optional[str]:
|
|
1320
|
-
"""执行 for 循环(串行),返回循环后的下一个节点 ID。
|
|
1321
|
-
R2:循环变量写入循环帧(D5——生命周期=循环,join 收口 skip 豁免);
|
|
1322
|
-
迭代器/条件求值走 Evaluator;range 兼容对齐 par(旧 for 缺此兼容导致
|
|
1323
|
-
for i in range(1,100) 空转——行为变化清单 §5)。"""
|
|
1324
|
-
var_name = info.get('var_name', '')
|
|
1325
|
-
iterable_expr = info.get('iterable', '')
|
|
1326
|
-
ctx = current_task_ctx()
|
|
1327
|
-
if ctx is None:
|
|
1328
|
-
raise FEMOVariableError("for 循环执行需要 TaskContext(协程未绑执行上下文)")
|
|
1329
|
-
facade = ctx.facade
|
|
1330
|
-
iterable = self.evaluator.evaluate_iterable(iterable_expr, facade)
|
|
1331
|
-
if isinstance(iterable, range):
|
|
1332
|
-
iterable = list(iterable)
|
|
1333
|
-
if not isinstance(iterable, (list, tuple)):
|
|
1334
|
-
# 【2026-09-07 warning 桶】迭代器不是列表=循环体零执行直接穿出
|
|
1335
|
-
# (不阻断),多半是变量没按列表声明/赋值——作者应当知情。
|
|
1336
|
-
print(f"[runtime]⚠️ 迭代器 '{iterable_expr}' 不是列表: {iterable}")
|
|
1337
|
-
self.errors.warn(
|
|
1338
|
-
f"for 迭代器 '{iterable_expr}' 不是列表(实际 {type(iterable).__name__}),"
|
|
1339
|
-
"循环体零执行直接穿出",
|
|
1340
|
-
node_id=str(gateway_id))
|
|
1341
|
-
iterable = []
|
|
1342
|
-
|
|
1343
|
-
all_out_edges = [e for e in flow.edges if e.source == gateway_id]
|
|
1344
|
-
has_conditional = any(e.condition for e in all_out_edges)
|
|
1345
|
-
loop_entries = []
|
|
1346
|
-
exit_edge = None
|
|
1347
|
-
if has_conditional:
|
|
1348
|
-
for e in all_out_edges:
|
|
1349
|
-
if e.condition:
|
|
1350
|
-
loop_entries.append(e)
|
|
1351
|
-
else:
|
|
1352
|
-
if exit_edge is not None:
|
|
1353
|
-
raise ValueError(
|
|
1354
|
-
f"For 循环节点 {gateway_id} 存在多条出口边: {exit_edge.target} 和 {e.target}"
|
|
1355
|
-
)
|
|
1356
|
-
exit_edge = e
|
|
1357
|
-
else:
|
|
1358
|
-
# 无条件边:第一条循环体入口、(若有)第二条循环出口——解析器保证
|
|
1359
|
-
# 注册顺序(for 块体内链先、块后出口行后)
|
|
1360
|
-
if len(all_out_edges) > 2:
|
|
1361
|
-
raise ValueError(
|
|
1362
|
-
f"For 循环节点 {gateway_id} 存在多条无条件出边 "
|
|
1363
|
-
f"({[e.target for e in all_out_edges]}):至多一条循环体入口 + 一条出口。"
|
|
1364
|
-
)
|
|
1365
|
-
loop_entries.append(all_out_edges[0])
|
|
1366
|
-
if len(all_out_edges) == 2:
|
|
1367
|
-
exit_edge = all_out_edges[1]
|
|
1368
|
-
if not loop_entries:
|
|
1369
|
-
raise ValueError(
|
|
1370
|
-
f"For 循环节点 {gateway_id} 没有任何循环体入口边。"
|
|
1371
|
-
f"请检查 flow 中 for 循环的写法,确保循环体内部有节点。"
|
|
1372
|
-
)
|
|
1373
|
-
|
|
1374
|
-
# 循环体内节点到其后继节点的边映射(不经过回边)
|
|
1375
|
-
edge_map = {}
|
|
1376
|
-
for e in flow.edges:
|
|
1377
|
-
if e.source != gateway_id:
|
|
1378
|
-
edge_map.setdefault(e.source, []).append(e)
|
|
1379
|
-
|
|
1380
|
-
# 循环帧(D5):push/收口 pop 放 finally(break/return/异常都平衡);
|
|
1381
|
-
# _skip_frames 以引用同步给 join 协调器(拍板 1:循环帧豁免 merge)
|
|
1382
|
-
facade.push_loop_frame(gateway_id)
|
|
1383
|
-
self._skip_frames.add(gateway_id)
|
|
1384
|
-
if not len(iterable):
|
|
1385
|
-
# 【2026-09-06 探针】空迭代=循环体零执行直接穿出——恢复场景下
|
|
1386
|
-
# 迭代器变量若未被快照正确恢复,就会表现为"秒跑完"。
|
|
1387
|
-
print(f"[resume-diag] ⚠️ for '{iterable_expr}' 求值为空——循环体零执行直接穿出")
|
|
1388
|
-
try:
|
|
1389
|
-
for i, item in enumerate(iterable):
|
|
1390
|
-
if var_name:
|
|
1391
|
-
facade.set_loop_var(gateway_id, var_name, item)
|
|
1392
|
-
ctx.current_loop_var = var_name
|
|
1393
|
-
print(f"[runtime]🔄 For: {var_name} = {item} ({i+1}/{len(iterable)})")
|
|
1394
|
-
|
|
1395
|
-
# 重新评估条件,找到匹配的入口边
|
|
1396
|
-
target_node = None
|
|
1397
|
-
for e in loop_entries:
|
|
1398
|
-
if not e.condition or self.evaluator.evaluate_condition(e.condition, facade):
|
|
1399
|
-
target_node = e.target
|
|
1400
|
-
break
|
|
1401
|
-
if target_node is None:
|
|
1402
|
-
print(f"[runtime]⏭️ For: 无匹配条件,跳过本轮")
|
|
1403
|
-
continue
|
|
1404
|
-
|
|
1405
|
-
current = target_node
|
|
1406
|
-
while current and current != gateway_id:
|
|
1407
|
-
# 分层步数检查(模块帧栈顶逐层计数;无模块帧→全局步数)
|
|
1408
|
-
if ctx.module_frames:
|
|
1409
|
-
mf = ctx.module_frames[-1]
|
|
1410
|
-
if mf.max_steps > 0 and mf.step >= mf.max_steps:
|
|
1411
|
-
print(f"[runtime]⚠️ 模块 '{mf.name}' 达到最大步数 {mf.max_steps}")
|
|
1412
|
-
break
|
|
1413
|
-
mf.step += 1
|
|
1414
|
-
else:
|
|
1415
|
-
if self.global_max_steps > 0 and self.global_step >= self.global_max_steps:
|
|
1416
|
-
print(f"[runtime]⚠️ 主流程达到最大步数 {self.global_max_steps}")
|
|
1417
|
-
break
|
|
1418
|
-
self.global_step += 1
|
|
1419
|
-
|
|
1420
|
-
node_obj = flow.nodes.get(current)
|
|
1421
|
-
if node_obj:
|
|
1422
|
-
await self._execute_node_content(node_obj, flow, extra_actions, 0, node_id=current)
|
|
1423
|
-
|
|
1424
|
-
# 找下一个节点:有回边立即结束本轮循环体
|
|
1425
|
-
next_candidates = []
|
|
1426
|
-
has_back_edge = False
|
|
1427
|
-
for e in edge_map.get(current, []):
|
|
1428
|
-
if e.target == gateway_id:
|
|
1429
|
-
has_back_edge = True
|
|
1430
|
-
else:
|
|
1431
|
-
next_candidates.append(e)
|
|
1432
|
-
if has_back_edge:
|
|
1433
|
-
break
|
|
1434
|
-
if not next_candidates:
|
|
1435
|
-
break
|
|
1436
|
-
|
|
1437
|
-
next_target = None
|
|
1438
|
-
for e in next_candidates:
|
|
1439
|
-
if e.condition and self.evaluator.evaluate_condition(e.condition, facade):
|
|
1440
|
-
next_target = e.target
|
|
1441
|
-
break
|
|
1442
|
-
if next_target is None:
|
|
1443
|
-
next_target = next_candidates[0].target
|
|
1444
|
-
current = next_target
|
|
1445
|
-
finally:
|
|
1446
|
-
facade.pop_loop_frame(gateway_id)
|
|
1447
|
-
self._skip_frames.discard(gateway_id)
|
|
1448
|
-
|
|
1449
|
-
print(f"[runtime]🔄 For: 迭代完毕,退出")
|
|
1450
|
-
if exit_edge:
|
|
1451
|
-
print(f"[runtime] For 返回出口节点: {exit_edge.target}")
|
|
1452
|
-
return exit_edge.target
|
|
1453
|
-
if loop_entries:
|
|
1454
|
-
# 无显式出口行:从入口顺藤摸瓜找到不在循环体内的下一个节点(原逻辑)
|
|
1455
|
-
visited = set()
|
|
1456
|
-
queue = [loop_entries[0].target]
|
|
1457
|
-
while queue:
|
|
1458
|
-
cur = queue.pop(0)
|
|
1459
|
-
if cur in visited:
|
|
1460
|
-
continue
|
|
1461
|
-
visited.add(cur)
|
|
1462
|
-
if cur == gateway_id:
|
|
1463
|
-
continue
|
|
1464
|
-
for e in flow.edges:
|
|
1465
|
-
if e.source == cur and e.target != gateway_id:
|
|
1466
|
-
queue.append(e.target)
|
|
1467
|
-
for e in flow.edges:
|
|
1468
|
-
if e.source in [le.target for le in loop_entries] and e.target != gateway_id:
|
|
1469
|
-
has_back = any(be.source == e.target and be.target == gateway_id for be in flow.edges)
|
|
1470
|
-
if not has_back:
|
|
1471
|
-
print(f"[runtime] For 返回顺藤摸瓜节点: {e.target}")
|
|
1472
|
-
return e.target
|
|
1473
|
-
print(f"[runtime] For 无出口,返回 None")
|
|
1474
|
-
return None
|
|
1475
|
-
|
|
1476
|
-
async def _execute_path(self, flow, start: str,
|
|
1477
|
-
stop_at: Set[str] = None,
|
|
1478
|
-
extra_actions: dict = None,
|
|
1479
|
-
max_steps: int = 0):
|
|
1480
|
-
current = start
|
|
1481
|
-
|
|
1482
|
-
while current and current not in (stop_at or set()):
|
|
1483
|
-
ctx = current_task_ctx() # 每轮重取(join 变身后指向新 task)
|
|
1484
|
-
# ── 分层步数检查(模块帧栈顶逐层计数;无模块帧→全局步数)──
|
|
1485
|
-
if ctx is not None and ctx.module_frames:
|
|
1486
|
-
mf = ctx.module_frames[-1]
|
|
1487
|
-
if mf.max_steps > 0 and mf.step >= mf.max_steps:
|
|
1488
|
-
print(f"[runtime]⚠️ 模块 '{mf.name}' 达到最大步数 {mf.max_steps}")
|
|
1489
|
-
break
|
|
1490
|
-
mf.step += 1
|
|
1491
|
-
else:
|
|
1492
|
-
if self.global_max_steps > 0 and self.global_step >= self.global_max_steps:
|
|
1493
|
-
print(f"[runtime]⚠️ 主流程达到最大步数 {self.global_max_steps}")
|
|
1494
|
-
break
|
|
1495
|
-
self.global_step += 1
|
|
1496
|
-
|
|
1497
|
-
node = flow.nodes.get(current)
|
|
1498
|
-
if not node:
|
|
1499
|
-
# 【2026-09-06 探针】静默中断点:恢复位置/后继在新图中不存在时
|
|
1500
|
-
# 原来直接 break——路径无声蒸发,是"秒跑完"假象的高危源头。
|
|
1501
|
-
print(f"[resume-diag] ⚠️ 节点 {current!r} 不在当前 flow 中——路径中断(检查断点位置/连线是否失效)")
|
|
1502
|
-
break
|
|
1503
|
-
|
|
1504
|
-
# 节点位置检查点:进入节点前记录(键=task_id,分支直启恢复点)
|
|
1505
|
-
if ctx is not None:
|
|
1506
|
-
self._record_checkpoint(ctx, current)
|
|
1507
|
-
|
|
1508
|
-
# ── 获取节点类型 ──
|
|
1509
|
-
kind = node.type if node.type else 'empty'
|
|
1510
|
-
info = node.meta
|
|
1511
|
-
if current == '[END]':
|
|
1512
|
-
kind = 'end'
|
|
1513
|
-
elif current == '[BREAK]':
|
|
1514
|
-
kind = 'break'
|
|
1515
|
-
if kind == 'gateway':
|
|
1516
|
-
gw = node.meta.get('gw_kind', '')
|
|
1517
|
-
if gw in ('for', 'par', 'fork', 'join'):
|
|
1518
|
-
kind = f'gateway_{gw}'
|
|
1519
|
-
# Delay 节点类型标记
|
|
1520
|
-
if node.type == 'delay' or node.meta.get('is_delay_node'):
|
|
1521
|
-
kind = 'delay'
|
|
1522
|
-
if node.module_ref:
|
|
1523
|
-
kind = 'module_call'
|
|
1524
|
-
elif node.action_name:
|
|
1525
|
-
kind = 'action'
|
|
1526
|
-
|
|
1527
|
-
if kind == 'end' or kind == 'break':
|
|
1528
|
-
return
|
|
1529
|
-
|
|
1530
|
-
if kind in ('gateway_for', 'gateway_par'):
|
|
1531
|
-
current = await self._run_for_loop(current, node, info, flow,
|
|
1532
|
-
extra_actions, max_steps)
|
|
1533
|
-
continue
|
|
1534
|
-
|
|
1535
|
-
if kind == 'gateway_fork':
|
|
1536
|
-
current = await self._run_fork(current, node, flow, extra_actions, max_steps)
|
|
1537
|
-
continue
|
|
1538
|
-
|
|
1539
|
-
if kind == 'gateway_join':
|
|
1540
|
-
# R3 接线(清单 D3):分支路径到达 join 不再"直接穿过"
|
|
1541
|
-
# (§1.4 实锤旧语义)——统一走 join_sign_in 签到等待;
|
|
1542
|
-
# 返回 None = 本 task 终止(迟到者/非触发者),退出本链。
|
|
1543
|
-
current = await join_sign_in(self, self.world, flow, current,
|
|
1544
|
-
node, extra_actions, max_steps)
|
|
1545
|
-
continue
|
|
1546
|
-
|
|
1547
|
-
# 统一执行节点内容
|
|
1548
|
-
#print(f"[runtime]_execute_path 正在执行节点: {current}, 类型: {kind}, 动作: {getattr(node, 'action_name', '')}, 模块: {getattr(node, 'module_ref', '')}")
|
|
1549
|
-
await self._execute_node_content(node, flow, extra_actions, max_steps, node_id=current)
|
|
1550
|
-
|
|
1551
|
-
current = self._follow_next_edge(current, flow)
|
|
1552
|
-
|
|
1553
|
-
# 协作式调度让出:分支(fork/par)内快速节点循环时让出事件循环,
|
|
1554
|
-
# 避免独占并饿死其他并行分支(多地点常驻并行线场景)。
|
|
1555
|
-
await asyncio.sleep(0)
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
# ══════════════════════════════════════════════════
|
|
1559
|
-
# FORK 执行
|
|
1560
|
-
# ══════════════════════════════════════════════════
|
|
1561
|
-
|
|
1562
|
-
async def _run_fork(self, gateway_id: str, node, flow,
|
|
1563
|
-
extra_actions: dict, max_steps: int = 0) -> Optional[str]:
|
|
1564
|
-
"""fork 执行器(par 合流,清单 D2 三步曲——委托 task_world.fork_branches)。
|
|
1565
|
-
母 task 终止(变量上已不存在),N 个子 task 值副本各跑各的;gather 纯
|
|
1566
|
-
收场等全死(**必须保留**:不 gather 则 run_async finally 的
|
|
1567
|
-
engine.shutdown() 会杀掉未完分支);join 不接(fork/join 解耦——
|
|
1568
|
-
分支自己跑到 join 网关签到,R3 接协调器)。"""
|
|
1569
|
-
print(f"[FORK] ========== 进入 fork 网关 {gateway_id} ==========")
|
|
1570
|
-
ctx = current_task_ctx()
|
|
1571
|
-
if ctx is None:
|
|
1572
|
-
raise FEMOVariableError("fork 执行需要 TaskContext(协程未绑执行上下文)")
|
|
1573
|
-
is_par = bool(node.meta.get('is_par_fork'))
|
|
1574
|
-
child_specs: List[ChildSpec] = []
|
|
1575
|
-
if is_par:
|
|
1576
|
-
# par 展开:每迭代一分支(range 兼容),循环帧=本 par 网关。
|
|
1577
|
-
# ⚠️ par 出边【不在母上下文过滤】——出边条件含循环变量
|
|
1578
|
-
# (如 if (@speaker.type=="ai")),母上下文里 par_var 未写入;
|
|
1579
|
-
# 入口选择移交分支协程(ChildSpec.select_from_gateway,
|
|
1580
|
-
# branch_main 在循环帧写入后于分支上下文求值——旧 par_branch 同语义)
|
|
1581
|
-
var_name = node.meta.get('par_var', '')
|
|
1582
|
-
iterable = self.evaluator.evaluate_iterable(
|
|
1583
|
-
node.meta.get('par_iterable', ''), ctx.facade)
|
|
1584
|
-
if isinstance(iterable, range):
|
|
1585
|
-
iterable = list(iterable)
|
|
1586
|
-
if not isinstance(iterable, (list, tuple)):
|
|
1587
|
-
raise FEMOVariableError(
|
|
1588
|
-
f"par 迭代器 '{node.meta.get('par_iterable', '')}' 不是列表: {iterable!r}")
|
|
1589
|
-
for item in iterable:
|
|
1590
|
-
child_specs.append(ChildSpec(
|
|
1591
|
-
select_from_gateway=gateway_id, loop_gw=gateway_id,
|
|
1592
|
-
loop_var=var_name, loop_value=item))
|
|
1593
|
-
print(f"[FORK] par 展开 {len(child_specs)} 分支(var={var_name})")
|
|
1594
|
-
else:
|
|
1595
|
-
# 普通 fork:条件边过滤(母上下文求值——出边条件不含分支变量)
|
|
1596
|
-
branch_entries = []
|
|
1597
|
-
for e in flow.edges:
|
|
1598
|
-
if e.source != gateway_id:
|
|
1599
|
-
continue
|
|
1600
|
-
if e.condition:
|
|
1601
|
-
cond_result = self.evaluator.evaluate_condition(e.condition, ctx.facade)
|
|
1602
|
-
print(f"[FORK] 边 {e.source} -> {e.target} 条件: {e.condition} 结果: {cond_result}")
|
|
1603
|
-
if not cond_result:
|
|
1604
|
-
continue
|
|
1605
|
-
else:
|
|
1606
|
-
print(f"[FORK] 边 {e.source} -> {e.target} 无条件")
|
|
1607
|
-
branch_entries.append(e.target)
|
|
1608
|
-
for target in branch_entries:
|
|
1609
|
-
child_specs.append(ChildSpec(start_node=target))
|
|
1610
|
-
print(f"[FORK] 活跃分支入口: {branch_entries}")
|
|
1611
|
-
if not child_specs:
|
|
1612
|
-
# 零活跃分支:仍 register 空事件(接线约定 3,防 join(all) 死等)
|
|
1613
|
-
print("[FORK] 没有活跃分支(register 空事件防 join 死等)")
|
|
1614
|
-
tasks = fork_branches(self, self.world, ctx, flow, gateway_id,
|
|
1615
|
-
child_specs, extra_actions, max_steps)
|
|
1616
|
-
if is_par:
|
|
1617
|
-
# par 循环帧豁免(拍板 1,D5 的 par 侧):par 循环帧由
|
|
1618
|
-
# fork_branches 构造期直接放入子 env(不走 push_loop_frame),
|
|
1619
|
-
# _skip_frames 在此登记——分支到 join 签到凑齐时 merge 豁免本帧
|
|
1620
|
-
# (循环变量各分支不同值,不制造 conflict 噪音);gather 收场
|
|
1621
|
-
# 后移除(帧生命周期=分支存续期,与 for 循环帧 push/pop 对称)。
|
|
1622
|
-
self._skip_frames.add(gateway_id)
|
|
1623
|
-
print(f"[FORK] 等待 {len(tasks)} 分支全部完成(纯收场,不连接 join)")
|
|
1624
|
-
try:
|
|
1625
|
-
await asyncio.gather(*tasks, return_exceptions=True)
|
|
1626
|
-
finally:
|
|
1627
|
-
if is_par:
|
|
1628
|
-
self._skip_frames.discard(gateway_id)
|
|
1629
|
-
# 编译器原则:分支有错必须上报,不能静默 flow_done(branch_main 已收集)
|
|
1630
|
-
if self._fork_errors:
|
|
1631
|
-
detail = "; ".join(f"[{name}] {err}" for name, err in self._fork_errors)
|
|
1632
|
-
self._fork_errors = []
|
|
1633
|
-
raise FEMOVariableError(f"fork 分支执行失败: {detail}")
|
|
1634
|
-
return None
|
|
1635
|
-
|
|
1636
|
-
# ══════════════════════════════════════════════════
|
|
1637
|
-
# Actor 类型查询
|
|
1638
|
-
# ══════════════════════════════════════════════════
|
|
1639
|
-
|
|
1640
|
-
def _get_actor_type(self, actor_ref: str) -> Optional[str]:
|
|
1641
|
-
"""根据 @xxx 引用查找 actor 类型,返回 'ai'/'human' 或 None"""
|
|
1642
|
-
if not isinstance(actor_ref, str) or not actor_ref.startswith('@'):
|
|
1643
|
-
return None
|
|
1644
|
-
name = actor_ref
|
|
1645
|
-
if name in self.script.actors:
|
|
1646
|
-
return self.script.actors[name].type.value
|
|
1647
|
-
return None
|
|
1648
|
-
|
|
1649
|
-
# ══════════════════════════════════════════════════
|
|
1650
|
-
# 模块执行 — 使用 _execute_flow
|
|
1651
|
-
# ══════════════════════════════════════════════════
|
|
1652
|
-
|
|
1653
|
-
async def _run_module(self, mod_name: str, caller_node_id: str = "", args: list = None, max_steps: int = 0):
|
|
1654
|
-
"""执行子流程 Module(清单 D4:模块帧,不是 task——两维度正交的
|
|
1655
|
-
运行期落地;嵌套 mod_path 沿定义链由内向外解析(兄弟互调可见,词法,
|
|
1656
|
-
拍板 6 同构);模块参数调用点 args 入帧,无 args 回退同名可见[拍板
|
|
1657
|
-
8③])。"""
|
|
1658
|
-
ctx = current_task_ctx()
|
|
1659
|
-
if ctx is None:
|
|
1660
|
-
raise FEMOVariableError(f"模块 '{mod_name}' 执行需要 TaskContext(协程未绑执行上下文)")
|
|
1661
|
-
facade = ctx.facade
|
|
1662
|
-
|
|
1663
|
-
# ── 嵌套模块 mod_path 解析(正确性关键:帧键与 ScopeTable owner 一致)──
|
|
1664
|
-
raw = (mod_name or '').strip()
|
|
1665
|
-
# 拆参与编译期共用 parser 的 _split_module_ref(单一事实源):模块名
|
|
1666
|
-
# 允许点路径,'Outer.Inner(x)' → ('Outer.Inner', 'x')——此前运行时
|
|
1667
|
-
# 自带 \w+ 拆参正则不认 '.',点路径带参会整串被当模块名查找而炸。
|
|
1668
|
-
clean_name, args_str = _split_module_ref(raw)
|
|
1669
|
-
mod_def = None
|
|
1670
|
-
mod_path = clean_name
|
|
1671
|
-
if ctx.module_frames and '.' not in clean_name:
|
|
1672
|
-
# 嵌套引用沿定义链由内向外解析(词法,拍板 6 的模块名侧):自己
|
|
1673
|
-
# 的孩子 → 母层的孩子(=兄弟互调)→ … → 顶层。命中层的完整点
|
|
1674
|
-
# 路径作 mod_path——帧键/ScopeTable owner/词法链 action 合并全部
|
|
1675
|
-
# 只依赖它,checkpoint 续跑天然一致。内外同名时内层(更近祖先)
|
|
1676
|
-
# 胜出,与既有「子模块遮蔽顶层同名」行为一致。
|
|
1677
|
-
segs = ctx.module_frames[-1].name.split('.')
|
|
1678
|
-
for depth in range(len(segs), 0, -1):
|
|
1679
|
-
anc_path = '.'.join(segs[:depth])
|
|
1680
|
-
anc = self._resolve_module_def(anc_path)
|
|
1681
|
-
sub = (anc.modules or {}).get(clean_name)
|
|
1682
|
-
if sub is not None:
|
|
1683
|
-
mod_def = sub
|
|
1684
|
-
mod_path = f"{anc_path}.{clean_name}"
|
|
1685
|
-
break
|
|
1686
|
-
if mod_def is None:
|
|
1687
|
-
mod_def = self.script.modules.get(clean_name)
|
|
1688
|
-
if mod_def is None and '.' in clean_name:
|
|
1689
|
-
# 顶层点路径('Outer.Inner'):主流程直引嵌套模块 / 调试器模块
|
|
1690
|
-
# 单测 wrapper 的进场通道(2026-09-12)——沿路径逐段下钻。帧键
|
|
1691
|
-
# 与 ScopeTable owner 同为完整点路径,module_initials/enter_module
|
|
1692
|
-
# 天然一致。
|
|
1693
|
-
mod_def = self._resolve_module_def(clean_name)
|
|
1694
|
-
if mod_def is None:
|
|
1695
|
-
# 编译期 validate_flow_refs 已拦截未声明的 module_ref——运行期
|
|
1696
|
-
# 再遇即流程装配不一致。原 print+return 会静默假跑:流程照常走完
|
|
1697
|
-
# 报 completed,模块一个节点都没执行(2026-09-12 收掉)。
|
|
1698
|
-
raise FEMOVariableError(
|
|
1699
|
-
f"模块 '{mod_name}' 未定义(运行期解析失败;编译期校验应已拦截,"
|
|
1700
|
-
f"此处出现即流程装配不一致,请检查 module_ref 拼写/模块是否已声明)")
|
|
1701
|
-
mod_meta = getattr(mod_def, 'meta', None) or {}
|
|
1702
|
-
mod_max_steps = mod_meta.get('max_steps', 0)
|
|
1703
|
-
|
|
1704
|
-
# ── 模块参数通道(拍板 8③):调用点 args 按位置对应形参求值入帧;
|
|
1705
|
-
# 无 args 的形参回退同名可见(旧"全局同名巧合"的兼容收编)──
|
|
1706
|
-
# ⚠️ R4 补(清单 §4.1 原文:initials = 调用点 args 求值结果 +
|
|
1707
|
-
# table.module_initials(mod_path)):模块 vars: 声明的 local 初值必须
|
|
1708
|
-
# 一并入帧——R2 接线时漏了 module_initials,模块帧为空,模块内读写
|
|
1709
|
-
# 声明变量报"已声明但当前 task 中无值"(分支静默死亡、checkpoint 停
|
|
1710
|
-
# 在原节点的实锤场景=tests/test_v2_resume_e2e.py 模块内 assign)。
|
|
1711
|
-
# args 显式传参覆盖同名初值;不声明局部变量的模块 module_initials={}
|
|
1712
|
-
# → 零变化。
|
|
1713
|
-
call_initials: Dict[str, Any] = dict(self.world.table.module_initials(mod_path))
|
|
1714
|
-
params = list(getattr(mod_def, 'params', []) or [])
|
|
1715
|
-
if args_str and args_str.strip():
|
|
1716
|
-
act_args = [a.strip() for a in Evaluator._split_items(args_str) if a.strip()]
|
|
1717
|
-
if len(act_args) > len(params):
|
|
1718
|
-
raise FEMOVariableError(
|
|
1719
|
-
f"模块 {mod_path} 调用实参数量({len(act_args)})超过形参数量({len(params)})")
|
|
1720
|
-
for pname, aexpr in zip(params, act_args):
|
|
1721
|
-
call_initials[pname] = self.evaluator.evaluate(aexpr, facade, strict=False)
|
|
1722
|
-
for p in params:
|
|
1723
|
-
if p not in call_initials and facade.has(p):
|
|
1724
|
-
call_initials[p] = facade.get(p)
|
|
1725
|
-
|
|
1726
|
-
# ★ 前端信号:进入模块
|
|
1727
|
-
print(f"[runtime]📡 >>> 发送 module_enter: module_name={mod_path!r}, caller_node={caller_node_id!r}")
|
|
1728
|
-
self._emit_event('module_enter', {'module_name': mod_path, 'caller_node': caller_node_id})
|
|
1729
|
-
facade.enter_module(mod_path, call_initials) # push 帧(模块 local+参数;$ 初值防御性跳过)
|
|
1730
|
-
ctx.module_frames.append(ModuleFrame(name=mod_path, step=0,
|
|
1731
|
-
max_steps=mod_max_steps,
|
|
1732
|
-
caller_node_id=caller_node_id))
|
|
1733
|
-
try:
|
|
1734
|
-
print(f"[runtime]📦 进入子流程: &{mod_path}")
|
|
1735
|
-
if mod_def.flow:
|
|
1736
|
-
extra_actions = self._chain_actions_for(mod_path)
|
|
1737
|
-
final_node = await self._execute_flow(mod_def.flow,
|
|
1738
|
-
stop_at={'[OUT]'},
|
|
1739
|
-
extra_actions=extra_actions)
|
|
1740
|
-
if final_node is not None and final_node not in ('[OUT]', '[BREAK]'):
|
|
1741
|
-
raise FEMOVariableError(
|
|
1742
|
-
f"模块 {mod_path} 异常终止于节点 {final_node},预期应到达 [OUT] 或 [BREAK]。")
|
|
1743
|
-
print(f"[runtime]📦 退出子流程: &{mod_path}")
|
|
1744
|
-
finally:
|
|
1745
|
-
ctx.module_frames.pop()
|
|
1746
|
-
facade.exit_module() # pop + 清帧:模块 local 出模块即清(宪法 1.2)
|
|
1747
|
-
# ★ 前端信号:退出模块
|
|
1748
|
-
print(f"[runtime]📡 <<< 发送 module_exit: module_name={mod_path!r}")
|
|
1749
|
-
self._emit_event('module_exit', {'module_name': mod_path})
|
|
1750
|
-
|
|
1751
|
-
# ══════════════════════════════════════════════════
|
|
1752
|
-
# Action 执行调度
|
|
1753
|
-
# ══════════════════════════════════════════════════
|
|
1754
|
-
|
|
1755
|
-
def exec_action(self, action_name: str, local_vars: dict = None) -> Any:
|
|
1756
|
-
"""执行一个 action(从全局 actions 查找)"""
|
|
1757
|
-
ad = self.script.actions.get(action_name)
|
|
1758
|
-
if ad is None:
|
|
1759
|
-
raise KeyError(f"Action '{action_name}' 未找到")
|
|
1760
|
-
return self._exec_action_def(ad)
|
|
1761
|
-
|
|
1762
|
-
async def _exec_action_def(self, ad) -> Any:
|
|
1763
|
-
"""执行已找到的 action 定义,统一调度"""
|
|
1764
|
-
etype = str(ad.executor_type).split('.')[-1].lower() if ad.executor_type else ''
|
|
1765
|
-
eparam = ad.executor_param or ''
|
|
1766
|
-
|
|
1767
|
-
print(f"[runtime]{'='*40}")
|
|
1768
|
-
print(f"[runtime]⚡ 执行 action (@{etype}({eparam}))")
|
|
1769
|
-
print(f"[runtime]{'='*40}")
|
|
1770
|
-
|
|
1771
|
-
if etype == 'func': return await self._exec_func(ad, eparam)
|
|
1772
|
-
elif etype == 'assign': return self._exec_assign(ad) # assign 是同步的,暂不 await
|
|
1773
|
-
elif etype == 'ai': return await self._exec_ai(ad, eparam)
|
|
1774
|
-
elif etype == 'human': return await self._exec_human(ad, eparam)
|
|
1775
|
-
elif etype == 'mind': return await self._exec_mind(ad, eparam)
|
|
1776
|
-
elif etype == 'notice': return await self._exec_notice(ad, eparam)
|
|
1777
|
-
else:
|
|
1778
|
-
print(f"[runtime]⚠️ 未支持的执行类型: @{etype}")
|
|
1779
|
-
return None
|
|
1780
|
-
|
|
1781
|
-
# ══════════════════════════════════════════════════
|
|
1782
|
-
# @func 处理
|
|
1783
|
-
# ══════════════════════════════════════════════════
|
|
1784
|
-
|
|
1785
|
-
async def _exec_func(self, ad, eparam: str) -> Any:
|
|
1786
|
-
import inspect
|
|
1787
|
-
# ── 发送 node_start 事件 ──
|
|
1788
|
-
self._emit_event('node_start', {
|
|
1789
|
-
'node_name': self._get_current_node_id(),
|
|
1790
|
-
'node_type': 'func',
|
|
1791
|
-
})
|
|
1792
|
-
print(f"[DEBUG _exec_func] 发送 node_start 事件:{ad.name}")
|
|
1793
|
-
kwargs = {}
|
|
1794
|
-
#print(f"[runtime]_exec_func: action={ad.name}, in_mappings={[(im.local_name, im.global_expr) for im in ad.in_mappings]}")
|
|
1795
|
-
ctx = current_task_ctx()
|
|
1796
|
-
facade = ctx.facade if ctx is not None else None
|
|
1797
|
-
if ad.in_mappings:
|
|
1798
|
-
for im in ad.in_mappings:
|
|
1799
|
-
# 统一走 Evaluator(路径/动态键/@引用全收敛,清单 D7)
|
|
1800
|
-
val = self.evaluator.evaluate(im.global_expr, facade, strict=False)
|
|
1801
|
-
print(f"[runtime]📥 in: {im.local_name} = {val!r}")
|
|
1802
|
-
kwargs[im.local_name] = val
|
|
1803
|
-
else:
|
|
1804
|
-
# 自动推断:Python 函数参数名 == 剧本变量名(文档 §21:参数名与 vars
|
|
1805
|
-
# 变量名一致)。不给任何剧本做硬编码别名兜底(2026-09-02 拍板删除);
|
|
1806
|
-
# 无对应变量且有默认值 → 用默认值;无默认值 → 响亮报错(原为 print
|
|
1807
|
-
# 警告后继续、下游 TypeError,现统一 fail loud)。
|
|
1808
|
-
parts = eparam.split('.', 1)
|
|
1809
|
-
if len(parts) == 2:
|
|
1810
|
-
mod_name, func_name = parts
|
|
1811
|
-
mod = self.bridge.modules.get(mod_name)
|
|
1812
|
-
if mod and hasattr(mod, func_name):
|
|
1813
|
-
func = getattr(mod, func_name)
|
|
1814
|
-
sig = inspect.signature(func)
|
|
1815
|
-
for param_name, param in sig.parameters.items():
|
|
1816
|
-
if param_name in ('self', 'cls'): continue
|
|
1817
|
-
if facade.has(param_name):
|
|
1818
|
-
val = facade.get(param_name)
|
|
1819
|
-
kwargs[param_name] = val
|
|
1820
|
-
print(f"[runtime]📥 in(auto): {param_name} = {val!r}")
|
|
1821
|
-
elif param.default is not inspect.Parameter.empty:
|
|
1822
|
-
pass
|
|
1823
|
-
else:
|
|
1824
|
-
raise FEMOVariableError(
|
|
1825
|
-
f"in(auto): 参数 '{param_name}' 无对应变量且无默认值。"
|
|
1826
|
-
f"请在 action 的 in: 中显式映射,或将 Python 参数名对齐 vars: 声明。"
|
|
1827
|
-
)
|
|
1828
|
-
|
|
1829
|
-
print(f"[runtime]📞 调用 {eparam}(**kwargs)")
|
|
1830
|
-
try:
|
|
1831
|
-
result = await self.engine.run_in_thread(self.bridge.call, eparam, **kwargs)
|
|
1832
|
-
print(f"[runtime]✅ 函数 {eparam} 执行成功,返回值: {result!r}")
|
|
1833
|
-
except Exception as e:
|
|
1834
|
-
self._emit_event('flow_error', {'error': str(e)})
|
|
1835
|
-
print(f"[runtime]❌ 函数 {eparam} 执行失败: {e}")
|
|
1836
|
-
raise
|
|
1837
|
-
|
|
1838
|
-
# Out 写回
|
|
1839
|
-
if ad.outs and result is not None:
|
|
1840
|
-
self._apply_outs(ad, result)
|
|
1841
|
-
|
|
1842
|
-
# ── 发送 func 结果事件 ──
|
|
1843
|
-
func_output = {}
|
|
1844
|
-
for od in ad.outs:
|
|
1845
|
-
var_name = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
1846
|
-
if var_name:
|
|
1847
|
-
try:
|
|
1848
|
-
func_output[var_name] = facade.get(var_name)
|
|
1849
|
-
except Exception:
|
|
1850
|
-
pass
|
|
1851
|
-
self._emit_event('func_result', {
|
|
1852
|
-
'node_name': self._get_current_node_id(),
|
|
1853
|
-
'input': kwargs,
|
|
1854
|
-
'output': func_output if func_output else repr(result),
|
|
1855
|
-
})
|
|
1856
|
-
print(f"[DEBUG _exec_func] 发送 func_result 事件:{ad.name}, output={func_output}")
|
|
1857
|
-
|
|
1858
|
-
return result
|
|
1859
|
-
|
|
1860
|
-
# ══════════════════════════════════════════════════
|
|
1861
|
-
# @assign 处理
|
|
1862
|
-
# ══════════════════════════════════════════════════
|
|
1863
|
-
def _exec_assign(self, ad) -> Any:
|
|
1864
|
-
print(f"[runtime]📝 Assign Action: {ad.name}")
|
|
1865
|
-
# ── 发送 node_start 事件 ──
|
|
1866
|
-
self._emit_event('node_start', {
|
|
1867
|
-
'node_name': self._get_current_node_id(),
|
|
1868
|
-
'node_type': 'assign',
|
|
1869
|
-
})
|
|
1870
|
-
ctx = current_task_ctx()
|
|
1871
|
-
facade = ctx.facade if ctx is not None else None
|
|
1872
|
-
assign_input = {} # 每条赋值实际喂入的值(RHS 求值结果/增量/add-remove 项)——气泡 In 面板用
|
|
1873
|
-
for i, od in enumerate(ad.outs):
|
|
1874
|
-
print(f"[runtime][DEBUG ASSIGN] out[{i}]: var_name={od.var_name!r}")
|
|
1875
|
-
for od in ad.outs:
|
|
1876
|
-
expr = od.var_name
|
|
1877
|
-
print(f"[runtime][DEBUG ASSIGN] 处理表达式: {expr!r}")
|
|
1878
|
-
|
|
1879
|
-
# 匹配: path = value / path += N / path -= N / path = add(x) / path = remove(x)
|
|
1880
|
-
# (VAR_NAME_RE:含 $ shared / @ actor 变量 / 中文——拍板 8④)
|
|
1881
|
-
m = re.match(r'^(' + VAR_NAME_RE + r')\s*([+\-]?=)\s*(.+)$', expr)
|
|
1882
|
-
if not m:
|
|
1883
|
-
raise FEMOVariableError(
|
|
1884
|
-
f"@assign 无法解析表达式: {expr!r}。"
|
|
1885
|
-
f"请使用 'var = value', 'var += N', 'var -= N' 等格式。"
|
|
1886
|
-
)
|
|
1887
|
-
path = m.group(1)
|
|
1888
|
-
op_str = m.group(2) # '=', '+=', '-='
|
|
1889
|
-
right_raw = m.group(3).strip()
|
|
1890
|
-
|
|
1891
|
-
# 检查变量是否声明
|
|
1892
|
-
if facade is None or not facade.has(path):
|
|
1893
|
-
raise FEMOVariableError(
|
|
1894
|
-
f"@assign 错误:变量 '{path}' 未声明。"
|
|
1895
|
-
f"所有变量必须在 vars: 中预先声明。"
|
|
1896
|
-
)
|
|
1897
|
-
|
|
1898
|
-
# 解析右侧值:引号字符串去引号,数字直接转,其他当作变量求值(Evaluator)
|
|
1899
|
-
right_val = self.evaluator.eval_right_value(right_raw, facade)
|
|
1900
|
-
|
|
1901
|
-
# 根据运算符构造 intent 并执行
|
|
1902
|
-
if op_str == '+=':
|
|
1903
|
-
if not isinstance(right_val, (int, float)):
|
|
1904
|
-
raise FEMOVariableError(f"@assign += 右侧需要数字,得到: {right_val!r}")
|
|
1905
|
-
intent = ('increment', right_val)
|
|
1906
|
-
elif op_str == '-=':
|
|
1907
|
-
if not isinstance(right_val, (int, float)):
|
|
1908
|
-
raise FEMOVariableError(f"@assign -= 右侧需要数字,得到: {right_val!r}")
|
|
1909
|
-
intent = ('increment', -right_val)
|
|
1910
|
-
elif op_str == '=':
|
|
1911
|
-
# 检查是否是 add() / remove() 形式
|
|
1912
|
-
add_m = re.match(r'^add\((.+)\)$', right_raw)
|
|
1913
|
-
if add_m:
|
|
1914
|
-
item = self.evaluator.eval_right_value(add_m.group(1).strip(), facade)
|
|
1915
|
-
intent = ('add', item)
|
|
1916
|
-
else:
|
|
1917
|
-
rem_m = re.match(r'^remove\((.+)\)$', right_raw)
|
|
1918
|
-
if rem_m:
|
|
1919
|
-
item = self.evaluator.eval_right_value(rem_m.group(1).strip(), facade)
|
|
1920
|
-
intent = ('remove', item)
|
|
1921
|
-
else:
|
|
1922
|
-
intent = ('set', right_val)
|
|
1923
|
-
else:
|
|
1924
|
-
raise FEMOVariableError(f"@assign 不支持的运算符: {op_str!r}")
|
|
1925
|
-
|
|
1926
|
-
assign_input[path] = intent[1]
|
|
1927
|
-
|
|
1928
|
-
try:
|
|
1929
|
-
facade.apply_intent(path, intent)
|
|
1930
|
-
except Exception as e:
|
|
1931
|
-
raise FEMOVariableError(f"@assign 执行失败:{path} <- {right_val!r},错误: {e}")
|
|
1932
|
-
|
|
1933
|
-
print(f"[runtime][DEBUG ASSIGN] 赋值后 {path} = {facade.get(path)}")
|
|
1934
|
-
|
|
1935
|
-
# ── 发送 assign 结果事件 ──
|
|
1936
|
-
assign_output = {}
|
|
1937
|
-
for od in ad.outs:
|
|
1938
|
-
expr = od.var_name
|
|
1939
|
-
m = re.match(r'^(' + VAR_NAME_RE + r')\s*[+\-]?=\s*(.+)$', expr)
|
|
1940
|
-
if m:
|
|
1941
|
-
var_path = m.group(1)
|
|
1942
|
-
try:
|
|
1943
|
-
assign_output[var_path] = facade.get(var_path)
|
|
1944
|
-
except Exception:
|
|
1945
|
-
pass
|
|
1946
|
-
self._emit_event('assign_result', {
|
|
1947
|
-
'node_name': self._get_current_node_id(),
|
|
1948
|
-
'input': assign_input,
|
|
1949
|
-
'output': assign_output,
|
|
1950
|
-
})
|
|
1951
|
-
|
|
1952
|
-
return None
|
|
1953
|
-
|
|
1954
|
-
async def handle_error(self, error: Exception, node_id: str = '') -> ErrorCategory:
|
|
1955
|
-
"""统一错误处理入口(薄壳,2026-09-05 重构——裁决下沉 ErrorDispatcher)。
|
|
1956
|
-
|
|
1957
|
-
全库零调用点(v4 §3.4 实锤),保留签名/返回类型兼容既有约定;
|
|
1958
|
-
行为=dispatch 归桶发信号(FATAL→notify_author / AGENT→node_retry)
|
|
1959
|
-
后映射回 ErrorCategory。执行者输出类错误(AI 赋值违规)不走这里——
|
|
1960
|
-
它们由 _exec_ai/_exec_human 直接调 self.errors.dispatch(errors 通道)。"""
|
|
1961
|
-
verdict = self.errors.dispatch(error, node_id)
|
|
1962
|
-
return {
|
|
1963
|
-
VERDICT_FATAL: ErrorCategory.FATAL,
|
|
1964
|
-
VERDICT_RETRY: ErrorCategory.AGENT,
|
|
1965
|
-
VERDICT_EXHAUSTED: ErrorCategory.AGENT,
|
|
1966
|
-
VERDICT_TOLERANT: ErrorCategory.TOLERANT,
|
|
1967
|
-
}[verdict]
|
|
1968
|
-
|
|
1969
|
-
# ═══ R2/R3 施工补丁(2026-09-04):_invoke_ai_llm 从「FEMO_runtime - 重构前副本.py」
|
|
1970
|
-
# ═══ 2451-2559 原样搬回——R2 换变量子系统时此方法随旧代码脱落,但 _exec_ai 1942 行
|
|
1971
|
-
# ═══ 调用点仍在(施工中间态),AI 节点会 AttributeError。依赖核查:_resolve_ai_source/
|
|
1972
|
-
# ═══ _resolve_actor_def/_resolve_ai_model/_emit_event/_llm_stop_event/engine.* 均在,
|
|
1973
|
-
# ═══ _host_ai_backend 由 femo_bridge.py 注入,与本文件无关。actor_thinking 传递
|
|
1974
|
-
# ═══ 随方法恢复(宿主侧重连三层优先级的第一层重新接通)。
|
|
1975
|
-
async def _invoke_ai_llm(self, blocks: dict, ad, eparam: str, actor_info: dict, scope_info: list,
|
|
1976
|
-
_current_node_id: str, ai_name: str = '', wait_key: str = '',
|
|
1977
|
-
emit_request: bool = True) -> str:
|
|
1978
|
-
"""调用一次 LLM(宿主子代理后端 or 直连),返回最终回复文本。
|
|
1979
|
-
AI 输出容错重试的每一轮都走这里。
|
|
1980
|
-
ai_name:执行者演员名(_exec_ai 三级解析结果),随 ai_request 传给
|
|
1981
|
-
宿主——每个请求自带身份(2026-08-28 Par 并发修复):par 循环体各分支
|
|
1982
|
-
node id 相同而演员不同,宿主旧取法(按 node_id 键控的共享映射)会被
|
|
1983
|
-
后到分支覆盖,speaker 行写上另一分支的演员名。
|
|
1984
|
-
wait_key/emit_request(2026-09-05 重构,施工清单 v4 §4⑤):宿主后端分支
|
|
1985
|
-
专用——wait_key 由 _exec_ai 循环外一次生成,全部重试轮共用(宿主
|
|
1986
|
-
steer 后经同一 wait_key 回传);emit_request=False 的重试轮不重发
|
|
1987
|
-
ai_request(重发会 spawn 新子代理,steer 链路断裂)。缺省时旧行为
|
|
1988
|
-
自生成 wait_key 并照常发 ai_request(兼容缺省调用方)。直连分支无视
|
|
1989
|
-
两参,逐字不动。"""
|
|
1990
|
-
def stream_cb(token):
|
|
1991
|
-
self._emit_event('ai_token', {
|
|
1992
|
-
'node_name': _current_node_id,
|
|
1993
|
-
'token': token
|
|
1994
|
-
})
|
|
1995
|
-
|
|
1996
|
-
# 创建停止信号并保存引用
|
|
1997
|
-
self._llm_stop_event = threading.Event()
|
|
1998
|
-
|
|
1999
|
-
# ★ 按 provider 限流,防止 429
|
|
2000
|
-
provider = self._resolve_ai_source(ad, eparam)
|
|
2001
|
-
await self.engine.throttle_llm(provider)
|
|
2002
|
-
|
|
2003
|
-
# ── 宿主子代理后端(宿主提供 LLM 执行;引擎无 LLM 直连)──
|
|
2004
|
-
if getattr(self, '_host_ai_backend', False):
|
|
2005
|
-
# wait_key:_exec_ai 循环外一次生成全轮共用(v4 §4⑤);缺省时旧行为自生成。
|
|
2006
|
-
if wait_key:
|
|
2007
|
-
host_wait_key = wait_key
|
|
2008
|
-
else:
|
|
2009
|
-
# 缺省兜底生成点同样带 run_tag 世代前缀(§5.6 三处同改)
|
|
2010
|
-
host_wait_key = f"{self._run_tag}ai_{_current_node_id}_{getattr(self, '_ai_request_counter', 0)}"
|
|
2011
|
-
self._ai_request_counter = getattr(self, '_ai_request_counter', 0) + 1
|
|
2012
|
-
# 角色级工具开关:actor 声明 tools: true/false 时带上布尔值,
|
|
2013
|
-
# tools: [..] 列表作为白名单;均未声明时 actor_tools=None,
|
|
2014
|
-
# 由宿主按其默认决定(缺省应恢复"可用工具")。
|
|
2015
|
-
actor_tools: Optional[bool] = None
|
|
2016
|
-
actor_tool_list: List[str] = []
|
|
2017
|
-
actor_thinking = ''
|
|
2018
|
-
adef = self._resolve_actor_def(ad, eparam)
|
|
2019
|
-
actor_source = ''
|
|
2020
|
-
if adef is not None:
|
|
2021
|
-
actor_tools = getattr(adef, 'tools_enabled', None)
|
|
2022
|
-
actor_tool_list = list(getattr(adef, 'tools', None) or [])
|
|
2023
|
-
actor_source = str(getattr(adef, 'source', None) or '').strip()
|
|
2024
|
-
# actor 的 thinking 档位(None=剧本未声明 → 宿主剥离继承 effort,
|
|
2025
|
-
# 落到部署默认档位;声明了就按写的走,宿主注入对应 effort)
|
|
2026
|
-
actor_thinking = str(getattr(adef, 'thinking', None) or '').strip()
|
|
2027
|
-
if emit_request:
|
|
2028
|
-
self._emit_event('ai_request', {
|
|
2029
|
-
'wait_key': host_wait_key,
|
|
2030
|
-
'node_name': _current_node_id,
|
|
2031
|
-
'ai_name': ai_name or '',
|
|
2032
|
-
'blocks': blocks,
|
|
2033
|
-
'actor_info': actor_info,
|
|
2034
|
-
# source:剧本 actor 声明的模型(裸 id 或 provider/model),宿主据此选模型
|
|
2035
|
-
'source': actor_source,
|
|
2036
|
-
'scope': str(ad.scope) if getattr(ad, 'scope', None) else '',
|
|
2037
|
-
'scope_info': scope_info,
|
|
2038
|
-
'actor_tools': actor_tools,
|
|
2039
|
-
'actor_tool_list': actor_tool_list,
|
|
2040
|
-
'actor_thinking': actor_thinking,
|
|
2041
|
-
})
|
|
2042
|
-
# 分身调试(2026-08-31 首演空台词事故取证):引擎侧视角落文件
|
|
2043
|
-
try:
|
|
2044
|
-
import os as _os
|
|
2045
|
-
import datetime as _dt
|
|
2046
|
-
with open(_os.path.join('user_data', 'debug-main-actor.log'), 'a', encoding='utf-8') as _f:
|
|
2047
|
-
_f.write(f"[{_dt.datetime.now().isoformat()}] [引擎] ai_request 已发出: node={_current_node_id} source={actor_source!r} wait_key={host_wait_key}\n")
|
|
2048
|
-
except Exception:
|
|
2049
|
-
pass
|
|
2050
|
-
host_result = await self.engine.human_input.wait_for_input(host_wait_key, timeout=3600)
|
|
2051
|
-
if isinstance(host_result, dict) and host_result.get('__actor_failed__'):
|
|
2052
|
-
# 宿主执行体最终失败(B5 执行失败信号):执行者已不在场——不打回
|
|
2053
|
-
# (node_retry 无接收者=挂等)、不重等同一 wait_key(无人应答)。
|
|
2054
|
-
# 上抛专用异常,由 _exec_ai 按「沉默收场」裁决(见 except 分支)。
|
|
2055
|
-
raise FEMOActorExecutionError(
|
|
2056
|
-
str(host_result.get('kind') or ''),
|
|
2057
|
-
str(host_result.get('detail') or ''))
|
|
2058
|
-
# 分身调试:等待返回的原始结果(截断 200 字)
|
|
2059
|
-
try:
|
|
2060
|
-
import os as _os
|
|
2061
|
-
import datetime as _dt
|
|
2062
|
-
with open(_os.path.join('user_data', 'debug-main-actor.log'), 'a', encoding='utf-8') as _f:
|
|
2063
|
-
_f.write(f"[{_dt.datetime.now().isoformat()}] [引擎] wait 返回: {str(host_result)[:200]}\n")
|
|
2064
|
-
except Exception:
|
|
2065
|
-
pass
|
|
2066
|
-
# host 负责:启动子 agent、组装完整轨迹(思考链[仅工具轮]+回复+工具结果)。
|
|
2067
|
-
# 引擎在这里只取最终回复(用于继续流程/事件),轨迹全文走 save_ai_turn 落库。
|
|
2068
|
-
if isinstance(host_result, dict):
|
|
2069
|
-
# 转写分离(2026-08-29):宿主按 TranscriptStep 契约回传结构化
|
|
2070
|
-
# 转写(生料契约见 femoCompiler/protocol.py——tool_calls/
|
|
2071
|
-
# tool_results 结构化,[TOOL CALL #N] 模板由引擎在这里套用),
|
|
2072
|
-
# 引擎逐 step 落库——cot/tool_call/tool_result 各归各位,
|
|
2073
|
-
# response 只存该轮发言。旧 payload(成品字符串)兼容透传。
|
|
2074
|
-
self._host_steps = normalize_transcript_steps(host_result.get('steps'))
|
|
2075
|
-
if not self._host_steps and host_result.get('trajectory'):
|
|
2076
|
-
# 兜底:旧宿主 payload 无 steps 时把整段轨迹当单行(历史形态)
|
|
2077
|
-
self._host_steps = [{'step': 0, 'cot': '', 'reply': host_result.get('trajectory') or '',
|
|
2078
|
-
'toolCall': '', 'toolResult': ''}]
|
|
2079
|
-
# 待办⑨:宿主回传的实际响应模型(provider/model),落库用;
|
|
2080
|
-
# main 节点在 save_ai_finish 处固定 'main',不吃此值。
|
|
2081
|
-
self._host_model_id = str(host_result.get('model_id') or '')
|
|
2082
|
-
return host_result.get('output') or ''
|
|
2083
|
-
else:
|
|
2084
|
-
self._host_steps = []
|
|
2085
|
-
self._host_model_id = ''
|
|
2086
|
-
return host_result or ''
|
|
2087
|
-
else:
|
|
2088
|
-
# 直连模式(无宿主):函数级 import 保持局部作用域,勿上移
|
|
2089
|
-
_adef_direct = self._resolve_actor_def(ad, eparam)
|
|
2090
|
-
if _adef_direct is not None and str(getattr(_adef_direct, 'source', None) or '').strip() == 'main':
|
|
2091
|
-
raise FEMOConfigError(
|
|
2092
|
-
"source:main 需要宿主代答(主模型分身调用),直连模式不支持。"
|
|
2093
|
-
)
|
|
2094
|
-
from femoBridges.llmBridge import call_ai_with_blocks
|
|
2095
|
-
return await self.engine.run_in_thread(
|
|
2096
|
-
call_ai_with_blocks,
|
|
2097
|
-
blocks,
|
|
2098
|
-
stream_callback=stream_cb,
|
|
2099
|
-
stop_event=self._llm_stop_event,
|
|
2100
|
-
user_api_key=getattr(self, 'user_api_key', None),
|
|
2101
|
-
user_api_provider=getattr(self, 'user_api_provider', None),
|
|
2102
|
-
user_api_url=getattr(self, 'user_api_url', None),
|
|
2103
|
-
# 直连模式:source 声明了模型则覆盖配置默认模型
|
|
2104
|
-
model=self._resolve_ai_model(ad, eparam),
|
|
2105
|
-
)
|
|
2106
|
-
|
|
2107
|
-
def _extract_ai_assignments(self, llm_output: str, out_whitelist: Optional[set] = None) -> tuple:
|
|
2108
|
-
"""提取 AI 输出中的 SET VARIABLE 赋值。
|
|
2109
|
-
返回 (SET_VARIABLE 列表, assign_errors 列表):
|
|
2110
|
-
- 解析/赋值失败(未声明变量、不在 out 白名单等)→ assign_errors(触发重试)
|
|
2111
|
-
- 格式类失败 → SET_VARIABLE(宽容路径,交给 resolve/丢弃)
|
|
2112
|
-
out_whitelist:本节点 out 声明的变量名集合;非 None 时 AI 只能赋值其中
|
|
2113
|
-
的变量(防幻觉乱赋值),其余报 FEMOVariableError 走重试。"""
|
|
2114
|
-
all_matches = re.findall(
|
|
2115
|
-
r'(?:SET\s+VARIABLE|设定变量)\s*[::]\s*(?:<<|《|〈|《《)\s*(.+?)(?:>>|》|〉|》》)',
|
|
2116
|
-
llm_output
|
|
2117
|
-
)
|
|
2118
|
-
SET_VARIABLE = []
|
|
2119
|
-
assign_errors = []
|
|
2120
|
-
ctx = current_task_ctx()
|
|
2121
|
-
facade = ctx.facade if ctx is not None else None
|
|
2122
|
-
for match in all_matches:
|
|
2123
|
-
try:
|
|
2124
|
-
var_name, expr = self._parse_single_assignment(match.strip())
|
|
2125
|
-
# out 白名单:AI 只能赋值本节点 out 声明的变量(防幻觉乱赋值)。
|
|
2126
|
-
if out_whitelist is not None and var_name not in out_whitelist:
|
|
2127
|
-
raise FEMOVariableError(
|
|
2128
|
-
f"变量 '{var_name}' 不在本节点的 out 声明范围内(out 只声明了: "
|
|
2129
|
-
f"{', '.join(sorted(out_whitelist)) if out_whitelist else '无'})。"
|
|
2130
|
-
f"AI 只能赋值 out 中声明的变量。"
|
|
2131
|
-
)
|
|
2132
|
-
intent = parse_assign_syntax(expr, var_name)
|
|
2133
|
-
op, val = intent
|
|
2134
|
-
if op in ('set', 'add', 'remove') and isinstance(val, str):
|
|
2135
|
-
val = self.evaluator.evaluate(val, facade, strict=False)
|
|
2136
|
-
intent = (op, val)
|
|
2137
|
-
facade.apply_intent(var_name, intent)
|
|
2138
|
-
print(f"[runtime]📤 AI赋值: {var_name} {intent}")
|
|
2139
|
-
except FEMOVariableError as e:
|
|
2140
|
-
print(f"[runtime]⚠️ AI 赋值变量错误: {match!r}, error={e}")
|
|
2141
|
-
assign_errors.append(str(e))
|
|
2142
|
-
except Exception as e:
|
|
2143
|
-
print(f"[runtime]解析失败详情: match={match!r}, error={e}")
|
|
2144
|
-
SET_VARIABLE.append(match.strip())
|
|
2145
|
-
return SET_VARIABLE, assign_errors
|
|
2146
|
-
|
|
2147
|
-
async def _exec_ai(self, ad, eparam: str) -> Any:
|
|
2148
|
-
self._check_cancel()
|
|
2149
|
-
if not eparam and not ad.as_actor:
|
|
2150
|
-
print(f"[runtime]🤖 AI Action(无身份信息,将调用裸 AI)")
|
|
2151
|
-
else:
|
|
2152
|
-
print(f"[runtime]🤖 AI Action")
|
|
2153
|
-
|
|
2154
|
-
ctx = current_task_ctx()
|
|
2155
|
-
facade = ctx.facade if ctx is not None else None
|
|
2156
|
-
prompt = self.evaluator.interpolate_prompt(
|
|
2157
|
-
str(ad.prompt or ""), facade, in_mappings=ad.in_mappings)
|
|
2158
|
-
if prompt is None:
|
|
2159
|
-
raise FEMOVariableError(f"AI Action '{ad.name}' 的 prompt 替换后变为 None,请检查 prompt 中的变量引用是否正确。")
|
|
2160
|
-
if not isinstance(prompt, str):
|
|
2161
|
-
prompt = str(prompt)
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
# ── 发送 node_start 事件(必须在任何可能阻塞的操作之前)──
|
|
2165
|
-
# scope: self 保留字段在 _scope_info_for 内展开为[发言人演员名]。
|
|
2166
|
-
scope_info = self._scope_info_for(ad, eparam)
|
|
2167
|
-
self._emit_event('node_start', {
|
|
2168
|
-
'node_name': self._get_current_node_id(),
|
|
2169
|
-
'node_type': 'ai',
|
|
2170
|
-
'prompt': prompt,
|
|
2171
|
-
'scope': scope_info,
|
|
2172
|
-
})
|
|
2173
|
-
|
|
2174
|
-
if ad.interrupt: print(f"[runtime]🔔 Interrupt: {ad.interrupt}")
|
|
2175
|
-
for od in ad.outs:
|
|
2176
|
-
var_name = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
2177
|
-
print(f"[runtime]📤 out: {var_name}")
|
|
2178
|
-
|
|
2179
|
-
# ── 收集 blocks 并调用 LLM ──
|
|
2180
|
-
# 注意:此处不得 import llmBridge/llmProviders——其模块顶层 import requests,
|
|
2181
|
-
# 而宿主后端模式下系统 Python 无第三方依赖(纯标准库原则)。真正的 LLM
|
|
2182
|
-
# 调用在 _invoke_ai_llm 内按 _host_ai_backend 分支延迟 import(2026-08-21
|
|
2183
|
-
# 修复:原无条件死 import 使宿主后端模式 AI 节点必炸 No module named 'requests')。
|
|
2184
|
-
from femoCompiler.block_collector import collect_blocks
|
|
2185
|
-
from femoBridges.ContextExample import MODE_FULL
|
|
2186
|
-
|
|
2187
|
-
self._current_prompt = prompt
|
|
2188
|
-
# 直接传原始参数,让 _get_actor_info 上下文感知解析
|
|
2189
|
-
actor_info = self._get_actor_info(ad, eparam)
|
|
2190
|
-
turn_id_alloc = self._alloc_turn() # 本节点独立 turn 号(par 并发安全)
|
|
2191
|
-
|
|
2192
|
-
blocks = collect_blocks(
|
|
2193
|
-
action=ad,
|
|
2194
|
-
meta=self.script.meta,
|
|
2195
|
-
actors_def=self.script.actors,
|
|
2196
|
-
var_manager=facade,
|
|
2197
|
-
evaluator=self.evaluator,
|
|
2198
|
-
code_modules=self.bridge.modules,
|
|
2199
|
-
memory_defs=self.script.memories,
|
|
2200
|
-
context_defs=self.script.contexts,
|
|
2201
|
-
session_id=self._current_session_id,
|
|
2202
|
-
turn_id=turn_id_alloc,
|
|
2203
|
-
actor_info=actor_info,
|
|
2204
|
-
runner=self,
|
|
2205
|
-
base_dir=self.base_dir,
|
|
2206
|
-
# 默认上下文拼接模式:DSH 宿主后端由 femo_bridge 钉
|
|
2207
|
-
# first_full_then_incremental;直连等未钉的调用方=full(原行为)。
|
|
2208
|
-
# 剧本显式声明的自定义 context 方法不受影响(block_collector 分派)。
|
|
2209
|
-
context_mode=getattr(self, '_context_mode', MODE_FULL),
|
|
2210
|
-
)
|
|
2211
|
-
|
|
2212
|
-
# ---- 存储 prompt 到 dialog ----
|
|
2213
|
-
from .save_dialog import save_human_turn
|
|
2214
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
2215
|
-
raw_scope = self._raw_scope_for(ad)
|
|
2216
|
-
|
|
2217
|
-
prompt_actor_info = {}
|
|
2218
|
-
if ad.as_actor and ad.as_actor in self.script.actors:
|
|
2219
|
-
as_def = self.script.actors[ad.as_actor]
|
|
2220
|
-
if as_def.type.value == 'human':
|
|
2221
|
-
prompt_actor_info['user'] = str(as_def.source)
|
|
2222
|
-
if 'user' not in prompt_actor_info and meta_owner:
|
|
2223
|
-
prompt_actor_info['user'] = str(meta_owner[0])
|
|
2224
|
-
|
|
2225
|
-
# 本节点所有行共用 alloc 的 turn 号;oratio 按行内序(prompt=0, showprompt=1)
|
|
2226
|
-
turn_id, oratio_idx = turn_id_alloc, 0
|
|
2227
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
2228
|
-
event = save_human_turn(
|
|
2229
|
-
session_id=self._current_session_id,
|
|
2230
|
-
turn_id=turn_id,
|
|
2231
|
-
oratio_idx=oratio_idx,
|
|
2232
|
-
user_input=prompt,
|
|
2233
|
-
actor_info=prompt_actor_info,
|
|
2234
|
-
meta_owner=meta_owner,
|
|
2235
|
-
action_scope=raw_scope,
|
|
2236
|
-
is_node_prompt=True,
|
|
2237
|
-
femo_id=femo_id,
|
|
2238
|
-
prompt_type='prompt',
|
|
2239
|
-
raw_action_scope=ad.scope,
|
|
2240
|
-
)
|
|
2241
|
-
if event:
|
|
2242
|
-
await self.engine.run_in_thread(event.wait)
|
|
2243
|
-
|
|
2244
|
-
# showprompt 渲染提前、落库推迟(2026-08-29 合写):show 行改与发言行
|
|
2245
|
-
# 同事务落库——要不然都有要不然都没有。prompt 行(幕后指令)保持节点
|
|
2246
|
-
# 开始落库:它是"节点启动过"的痕迹,且不属于对话流。
|
|
2247
|
-
showprompt_text = ''
|
|
2248
|
-
if ad.showprompt:
|
|
2249
|
-
showprompt_text = self.evaluator.interpolate_prompt(
|
|
2250
|
-
str(ad.showprompt), facade, in_mappings=ad.in_mappings)
|
|
2251
|
-
print(f"[runtime]💬 AI prompt 已存入 dialog: turn={turn_id}, oratio={oratio_idx}")
|
|
2252
|
-
|
|
2253
|
-
# ── 发送上下文就绪事件 ──
|
|
2254
|
-
# 演员显示名双名制(2026-09-11 拍板,2026-09-12 三修定稿):@戏中名(括号名)
|
|
2255
|
-
# ——@保留、不去重。括号名:有 soul id=Soul name;无 soul 时仅 model id
|
|
2256
|
-
# 为 main 的伪 soul 显示 'main',其余不加括号。投影窗 speaker 标签/气泡
|
|
2257
|
-
# 浮层/直播帧全以此名为键,此处一处组装三端生效。原三级兜底
|
|
2258
|
-
# (soul 块正则 → @演员名 → "AI")原样保留在后面。
|
|
2259
|
-
ai_name = None
|
|
2260
|
-
soul_display = ''
|
|
2261
|
-
soul_id_str = str((actor_info or {}).get('soul', '') or '')
|
|
2262
|
-
if soul_id_str:
|
|
2263
|
-
try:
|
|
2264
|
-
from femoCompiler.db_utils import get_soul_by_id
|
|
2265
|
-
soul_info = get_soul_by_id(soul_id_str)
|
|
2266
|
-
if soul_info:
|
|
2267
|
-
soul_display = str(soul_info.get('soul_name', '') or '').strip()
|
|
2268
|
-
except Exception:
|
|
2269
|
-
pass
|
|
2270
|
-
if not soul_display and soul_id_str == 'main':
|
|
2271
|
-
# source:main 裸天使伪 soul:无角色卡,括号名=model id 'main'
|
|
2272
|
-
# (2026-09-12 拍板:"如果是main就显示main";普通无 soul AI
|
|
2273
|
-
# 不加括号,走后面的 @名兜底)
|
|
2274
|
-
soul_display = 'main'
|
|
2275
|
-
role_display = str(self._resolve_actor_name(eparam) or '').strip()
|
|
2276
|
-
if role_display and not role_display.startswith('@'):
|
|
2277
|
-
role_display = f'@{role_display}'
|
|
2278
|
-
if soul_display and role_display:
|
|
2279
|
-
ai_name = f"{role_display}({soul_display})"
|
|
2280
|
-
elif soul_display:
|
|
2281
|
-
ai_name = soul_display
|
|
2282
|
-
if not ai_name:
|
|
2283
|
-
soul_block = blocks.get('soul', '')
|
|
2284
|
-
match = re.search(r'名字[::]\s*(\S+)', soul_block)
|
|
2285
|
-
if match:
|
|
2286
|
-
ai_name = match.group(1)
|
|
2287
|
-
if not ai_name:
|
|
2288
|
-
# 宿主后端模式兜底(2026-08-24):无 soul 的 actor 用执行者名本身,
|
|
2289
|
-
# 别落到裸 "AI"——宿主投影窗的 speaker 行/角色窗 id/流式直播门控全以
|
|
2290
|
-
# 此名为键,"AI" 会让角色窗永远对不上号(actor_info 空老 bug 的收尾)。
|
|
2291
|
-
resolved_actor = self._resolve_actor_name(eparam)
|
|
2292
|
-
if resolved_actor:
|
|
2293
|
-
ai_name = resolved_actor if str(resolved_actor).startswith('@') else f'@{resolved_actor}'
|
|
2294
|
-
if not ai_name:
|
|
2295
|
-
ai_name = "AI"
|
|
2296
|
-
|
|
2297
|
-
showprompt_for_frontend = None
|
|
2298
|
-
if hasattr(ad, 'showprompt') and ad.showprompt:
|
|
2299
|
-
showprompt_for_frontend = self.evaluator.interpolate_prompt(
|
|
2300
|
-
str(ad.showprompt), facade)
|
|
2301
|
-
|
|
2302
|
-
self._emit_event('context_ready', {
|
|
2303
|
-
'node_name': self._get_current_node_id(),
|
|
2304
|
-
'context': blocks.get('context', ''),
|
|
2305
|
-
'showprompt': showprompt_for_frontend,
|
|
2306
|
-
'ai_name': ai_name,
|
|
2307
|
-
})
|
|
2308
|
-
|
|
2309
|
-
# 提前捕获当前节点 ID,供线程池回调使用
|
|
2310
|
-
_current_node_id = self._get_current_node_id()
|
|
2311
|
-
|
|
2312
|
-
# ── 重试轮共用 wait_key(2026-09-05 重构,施工清单 v4 §4.③(a)):
|
|
2313
|
-
# 循环外一次生成——宿主停靠托管锚点、多轮 wait_for_input 配对键、
|
|
2314
|
-
# dispatcher 计数键三者同锚。counter 只拼字符串,宿主纯透传。──
|
|
2315
|
-
self._ai_request_counter = getattr(self, '_ai_request_counter', 0) + 1
|
|
2316
|
-
# run_tag 世代前缀(§5.6):跨 Job 键永不重合——旧 run 的滞留信(宿主
|
|
2317
|
-
# 晚到投递)带着旧前缀,新 run 的 wait_for_input 用新前缀查询永远
|
|
2318
|
-
# pop 不到;run_tag=''(CLI 裸跑/现状构造点)时逐字节等于旧形态。
|
|
2319
|
-
node_wait_key = f"{self._run_tag}ai_{_current_node_id}_{self._ai_request_counter}"
|
|
2320
|
-
|
|
2321
|
-
# ── AI 输出容错:赋值失败(未声明变量等)→ 错误反馈 → 重新调用本节点 ──
|
|
2322
|
-
# 上限 = max_retries + 1(未设置默认 2 次重试);格式类失败进 SET_VARIABLE 宽容处理
|
|
2323
|
-
max_tries = max(1, (getattr(ad, 'max_retries', None) or 2) + 1)
|
|
2324
|
-
# dispatcher 的剧本反馈上限(按现状规则取值;显式 0 的 falsy bug 本期不修,裁决①)
|
|
2325
|
-
retries_max = max_tries - 1
|
|
2326
|
-
SET_VARIABLE = []
|
|
2327
|
-
assign_errors = []
|
|
2328
|
-
# 节点退出原因(node_settled 用):ok=校验通过 / gave_up=反馈超限按结束
|
|
2329
|
-
settled_outcome = 'ok'
|
|
2330
|
-
# out 白名单(防 AI 幻觉乱赋值):本节点 out 声明的变量名集合。
|
|
2331
|
-
out_whitelist = {
|
|
2332
|
-
getattr(od, 'var_name', '') for od in (ad.outs or [])
|
|
2333
|
-
if getattr(od, 'var_name', '')
|
|
2334
|
-
}
|
|
2335
|
-
for _attempt in range(max_tries):
|
|
2336
|
-
try:
|
|
2337
|
-
llm_output = await self._invoke_ai_llm(
|
|
2338
|
-
blocks, ad, eparam, actor_info, scope_info, _current_node_id, ai_name or '',
|
|
2339
|
-
wait_key=node_wait_key, emit_request=(_attempt == 0))
|
|
2340
|
-
# ↑ emit_request=False 的重试轮【不重发 ai_request】——宿主 steer
|
|
2341
|
-
# 后经同一 wait_key 回传,重发会 spawn 新子代理,steer 链路断裂。
|
|
2342
|
-
except FEMOTransientError as e:
|
|
2343
|
-
# LLM 临时失败(限流/超时/网络)→ AGENT 桶:feedback 后重跑本节点
|
|
2344
|
-
if _attempt >= max_tries - 1:
|
|
2345
|
-
print(f"[runtime]⚠️ LLM 临时失败重试用尽: {e}")
|
|
2346
|
-
llm_output = None
|
|
2347
|
-
break
|
|
2348
|
-
feedback = f'- LLM 调用临时失败(限流/超时/网络):{e}'
|
|
2349
|
-
# 重试反馈不再注入 blocks['basic_safety'](2026-09-05 猫猫拍板
|
|
2350
|
-
# 删除:错误提示不该出现在子代理 prompt 的系统头段;后续将改为
|
|
2351
|
-
# 节点内部 react 轮次的工具结果注入)。重试调度与 ai_retry 通知
|
|
2352
|
-
# 保持原样。
|
|
2353
|
-
self._emit_event('ai_retry', {
|
|
2354
|
-
'node_name': _current_node_id,
|
|
2355
|
-
'attempt': _attempt + 1,
|
|
2356
|
-
'errors': [feedback],
|
|
2357
|
-
})
|
|
2358
|
-
continue
|
|
2359
|
-
except FEMOActorExecutionError as e:
|
|
2360
|
-
# 宿主执行体最终失败(B5):执行者已不在场——node_retry 无接收者、
|
|
2361
|
-
# 同一 wait_key 重等无人应答。裁决=通知作者 + llm_output=None 走
|
|
2362
|
-
# runtime 既有暂停分支(分支在节点挂起、断点保留,续跑=换新执行
|
|
2363
|
-
# 体重演该节点)——即 FEMOTransientError「重试用尽走暂停分支」的
|
|
2364
|
-
# 同款语义;宿主不再伪装空台词让引擎错误体系失明。
|
|
2365
|
-
print(f"[runtime]⚠️ 执行体失败,本场挂起(可续跑): {e}")
|
|
2366
|
-
self._emit_event('notify_author', {
|
|
2367
|
-
'node_name': _current_node_id,
|
|
2368
|
-
'ai_name': ai_name or '',
|
|
2369
|
-
'severity': 'agent_giveup',
|
|
2370
|
-
'message': (f"节点 {_current_node_id}({ai_name or ''})的执行体失败"
|
|
2371
|
-
f"({e.kind}):{e.detail}——本场已挂起存档,可点「继续」重演该节点。"),
|
|
2372
|
-
})
|
|
2373
|
-
settled_outcome = 'failed'
|
|
2374
|
-
llm_output = None
|
|
2375
|
-
self._host_steps = []
|
|
2376
|
-
break
|
|
2377
|
-
except FEMOConfigError as e:
|
|
2378
|
-
# LLM 配置错误(无 key/模型/URL)→ FATAL 桶:先发 notify_author(fatal)
|
|
2379
|
-
# 信号(v4 §4.③(d),宪法要求发信号;宿主对 fatal 仅 log 防双份——
|
|
2380
|
-
# 实际作者投递由紧随的 flow_error 三通道承担),再原样 raise——
|
|
2381
|
-
# 传播到 bridge worker 统一收尾(flow_error + 全停)。
|
|
2382
|
-
print(f"[runtime]💥 LLM 配置错误(FATAL): {e}")
|
|
2383
|
-
self.errors.dispatch(e, _current_node_id, bucket=ErrorCategory.FATAL,
|
|
2384
|
-
ai_name=ai_name or '', target=FEEDBACK_TARGET_AI)
|
|
2385
|
-
raise
|
|
2386
|
-
SET_VARIABLE, assign_errors = self._extract_ai_assignments(llm_output, out_whitelist)
|
|
2387
|
-
if not assign_errors:
|
|
2388
|
-
settled_outcome = 'ok'
|
|
2389
|
-
break
|
|
2390
|
-
# 赋值错误 → ErrorDispatcher 单次裁决与发信号(重试循环留在 runtime,
|
|
2391
|
-
# 裁决⑤):未超限=node_retry 信号(宿主 steer 执行者续跑)+ continue;
|
|
2392
|
-
# 超限=notify_author 信号 + break(最后轮 output 宽容继续,现状语义)。
|
|
2393
|
-
verdict = self.errors.dispatch(
|
|
2394
|
-
None, _current_node_id, errors=assign_errors, wait_key=node_wait_key,
|
|
2395
|
-
ai_name=ai_name or '', max_retries=retries_max, attempt=_attempt + 1,
|
|
2396
|
-
target=FEEDBACK_TARGET_AI)
|
|
2397
|
-
if verdict == VERDICT_EXHAUSTED:
|
|
2398
|
-
settled_outcome = 'gave_up'
|
|
2399
|
-
break
|
|
2400
|
-
# VERDICT_RETRY → continue(宿主 steer 中;下一轮静默等同一 wait_key)
|
|
2401
|
-
print(f"[runtime]🔁 AI 赋值失败,重试({_attempt + 1}/{max_tries - 1}): {assign_errors}")
|
|
2402
|
-
|
|
2403
|
-
#if llm_output:
|
|
2404
|
-
# print(f"[runtime]🤖 AI 回复:\n{llm_output}")
|
|
2405
|
-
|
|
2406
|
-
# 存储 AI 发言(2026-08-29 转写分离):宿主侧按子会话 step 组装结构化
|
|
2407
|
-
# 转写,引擎逐 step 落库——cot/tool_call/tool_result 各归各位,response
|
|
2408
|
-
# 只存该轮发言,上游思考不再随 response 泄漏进下游上下文。
|
|
2409
|
-
# 兜底:无 steps(直连模式/旧 payload)→ 单行保存,与旧行为对齐(防半行)。
|
|
2410
|
-
host_steps = getattr(self, '_host_steps', None) or []
|
|
2411
|
-
if not host_steps and llm_output:
|
|
2412
|
-
host_steps = [{'step': 0, 'cot': '', 'reply': llm_output,
|
|
2413
|
-
'toolCall': '', 'toolResult': ''}]
|
|
2414
|
-
from .save_dialog import save_ai_finish
|
|
2415
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
2416
|
-
raw_scope = self._raw_scope_for(ad)
|
|
2417
|
-
|
|
2418
|
-
# 收尾合写(2026-08-29):showprompt 行 + 全部 react step 行同一事务——
|
|
2419
|
-
# show 行从节点开始推迟到此刻,与发言同 commit,消灭「有 show 没发言」半行。
|
|
2420
|
-
_adef_save = self._resolve_actor_def(ad, eparam)
|
|
2421
|
-
_a_source = str(getattr(_adef_save, 'source', None) or '').strip() if _adef_save is not None else ''
|
|
2422
|
-
event = save_ai_finish(
|
|
2423
|
-
session_id=self._current_session_id,
|
|
2424
|
-
turn_id=turn_id_alloc,
|
|
2425
|
-
showprompt=showprompt_text or None,
|
|
2426
|
-
steps=host_steps,
|
|
2427
|
-
actor_info=actor_info,
|
|
2428
|
-
meta_owner=meta_owner,
|
|
2429
|
-
action_scope=raw_scope,
|
|
2430
|
-
femo_id=femo_id,
|
|
2431
|
-
raw_action_scope=getattr(ad, 'scope', None),
|
|
2432
|
-
# 待办⑨:model_id 落值——source:main 节点固定 'main'(渠道标记);
|
|
2433
|
-
# 普通节点取宿主回传的实际响应模型(provider/model),取不到保持空串。
|
|
2434
|
-
model_id='main' if _a_source == 'main' else (getattr(self, '_host_model_id', '') or ''),
|
|
2435
|
-
)
|
|
2436
|
-
if event:
|
|
2437
|
-
await self.engine.run_in_thread(event.wait)
|
|
2438
|
-
print(f"[runtime]🔢 turn → {turn_id_alloc}, 转写合写落库(show + {len(host_steps)} steps)")
|
|
2439
|
-
|
|
2440
|
-
# ── 发送 ai_done 事件 ──
|
|
2441
|
-
self._emit_event('ai_done', {
|
|
2442
|
-
'node_name': self._get_current_node_id(),
|
|
2443
|
-
'output': llm_output or '',
|
|
2444
|
-
})
|
|
2445
|
-
|
|
2446
|
-
# ── 节点审结信号(2026-09-05 重构,施工清单 v4 §4.③(e))──────
|
|
2447
|
-
# 宿主停靠经纪人据此放行停靠者(ai/human 同发;wait_key 键控 par 分支
|
|
2448
|
-
# 隔离——ai_done payload 无 wait_key,按 node_name 匹配会在 par 场景串台)。
|
|
2449
|
-
# gave_up = 反馈超限按结束(最后轮 output 已宽容落盘);failed = 执行体
|
|
2450
|
-
# 最终失败(B5 actor_failed 信号——无台词可落盘,作者已经 notify_author 通道知情)。
|
|
2451
|
-
self._emit_event(NODE_SETTLED_EVENT, {
|
|
2452
|
-
'node_name': _current_node_id,
|
|
2453
|
-
'wait_key': node_wait_key,
|
|
2454
|
-
'outcome': settled_outcome,
|
|
2455
|
-
})
|
|
2456
|
-
|
|
2457
|
-
# 失败处理
|
|
2458
|
-
if llm_output is None:
|
|
2459
|
-
if ad.interrupt == 'HUMAN':
|
|
2460
|
-
print(f"[runtime]🔔 等待人类输入...")
|
|
2461
|
-
# 在线程池中执行 input,避免阻塞事件循环
|
|
2462
|
-
try:
|
|
2463
|
-
user_input = await self.engine.run_in_thread(input, " ✏️ > ")
|
|
2464
|
-
user_input = user_input.strip() if user_input else ""
|
|
2465
|
-
except (EOFError, KeyboardInterrupt):
|
|
2466
|
-
user_input = ""
|
|
2467
|
-
if user_input:
|
|
2468
|
-
print(f"[runtime]📝 人类输入: {user_input}")
|
|
2469
|
-
if ad.outs:
|
|
2470
|
-
for od in ad.outs:
|
|
2471
|
-
var_name = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
2472
|
-
if var_name:
|
|
2473
|
-
facade.apply_intent(var_name, ('set', user_input))
|
|
2474
|
-
print(f"[runtime]📤 out: {var_name} = {user_input!r}")
|
|
2475
|
-
return user_input
|
|
2476
|
-
return None
|
|
2477
|
-
else:
|
|
2478
|
-
# 直连 AI 失败挂起(C3 修复,§5.7):节点门口断点已拍(全量
|
|
2479
|
-
# 快照,宿主后端/直连同款)→ raise FEMORunPaused → run_async 走
|
|
2480
|
-
# suspended(node_pause) 可续跑。替换旧 task_pause.pause() 的
|
|
2481
|
-
# `await event.wait()` 无超时挂死协程(C3:永挂无人 set)。
|
|
2482
|
-
# 发 flow_paused 不发 flow_error:宿主把 flow_error 当 failed
|
|
2483
|
-
# 终态处理(全场掐断+steer"运行出错");挂起时在飞子代理确实
|
|
2484
|
-
# 该收、停靠确实该放行——flow_paused 的宿主分支恰好就是这套
|
|
2485
|
-
# 清场,一处信号两用(前端显示"已暂停"文案,README §十四.4 备注)。
|
|
2486
|
-
cur = current_task_ctx()
|
|
2487
|
-
node_name = cur.current_node_id if cur else ''
|
|
2488
|
-
print(f"[runtime]⚠️ AI 调用失败(返回 None),变量已保存,分支在节点 {node_name} 挂起(可续跑)…")
|
|
2489
|
-
self._emit_event('flow_paused', {
|
|
2490
|
-
'reason': 'node_pause',
|
|
2491
|
-
'node_name': node_name,
|
|
2492
|
-
'error': f'AI 调用失败,分支在节点 "{node_name}" 暂停,变量已保存',
|
|
2493
|
-
})
|
|
2494
|
-
raise FEMORunPaused(f'AI 调用失败,分支在节点 "{node_name}" 暂停,变量已保存')
|
|
2495
|
-
|
|
2496
|
-
if llm_output == "":
|
|
2497
|
-
print(f"[runtime]🤖 AI 选择了沉默,无输出,流程继续。")
|
|
2498
|
-
|
|
2499
|
-
if SET_VARIABLE:
|
|
2500
|
-
print(f"[runtime]⚠️ 解析失败的赋值已存入 SET_VARIABLE 列表: {SET_VARIABLE}")
|
|
2501
|
-
|
|
2502
|
-
if hasattr(ad, 'resolve') and ad.resolve:
|
|
2503
|
-
resolve_args = getattr(ad, 'resolve_args', [])
|
|
2504
|
-
if resolve_args:
|
|
2505
|
-
resolve_kwargs = {}
|
|
2506
|
-
for arg_name in resolve_args:
|
|
2507
|
-
if arg_name == 'SET_VARIABLE':
|
|
2508
|
-
resolve_kwargs['SET_VARIABLE'] = SET_VARIABLE
|
|
2509
|
-
elif facade is not None and facade.has(arg_name):
|
|
2510
|
-
resolve_kwargs[arg_name] = facade.get(arg_name)
|
|
2511
|
-
elif hasattr(ad, 'in_mappings'):
|
|
2512
|
-
found = False
|
|
2513
|
-
for im in ad.in_mappings:
|
|
2514
|
-
if im.local_name == arg_name:
|
|
2515
|
-
try:
|
|
2516
|
-
resolve_kwargs[arg_name] = self.evaluator.evaluate(im.global_expr, facade, strict=False)
|
|
2517
|
-
found = True
|
|
2518
|
-
except KeyError:
|
|
2519
|
-
pass
|
|
2520
|
-
break
|
|
2521
|
-
if not found:
|
|
2522
|
-
raise FEMOVariableError(
|
|
2523
|
-
f"resolve 参数 '{arg_name}' 在全局变量和 in: 声明中均未找到。"
|
|
2524
|
-
)
|
|
2525
|
-
else:
|
|
2526
|
-
raise FEMOVariableError(
|
|
2527
|
-
f"resolve 参数 '{arg_name}' 在全局变量中未找到。"
|
|
2528
|
-
)
|
|
2529
|
-
else:
|
|
2530
|
-
resolve_kwargs = {
|
|
2531
|
-
'prompt': prompt,
|
|
2532
|
-
'llm_output': llm_output,
|
|
2533
|
-
}
|
|
2534
|
-
if SET_VARIABLE:
|
|
2535
|
-
resolve_kwargs['SET_VARIABLE'] = SET_VARIABLE
|
|
2536
|
-
if hasattr(ad, 'in_mappings'):
|
|
2537
|
-
for im in ad.in_mappings:
|
|
2538
|
-
try:
|
|
2539
|
-
resolve_kwargs[im.local_name] = self.evaluator.evaluate(im.global_expr, facade, strict=False)
|
|
2540
|
-
except KeyError:
|
|
2541
|
-
pass
|
|
2542
|
-
|
|
2543
|
-
result = call_python(self.bridge, ad.resolve, resolve_kwargs)
|
|
2544
|
-
triplets = result if isinstance(result, list) else []
|
|
2545
|
-
retry_info = {
|
|
2546
|
-
'retries_left': getattr(ad, 'max_retries', 0) or 0,
|
|
2547
|
-
'on_error': getattr(ad, 'fallback', 'abort'),
|
|
2548
|
-
}
|
|
2549
|
-
return process_ai_result(facade, triplets, ad.outs, retry_info)
|
|
2550
|
-
else:
|
|
2551
|
-
return {'status': 'ok', 'assigned_pairs': []}
|
|
2552
|
-
|
|
2553
|
-
# ══════════════════════════════════════════════════
|
|
2554
|
-
# @human 桩
|
|
2555
|
-
# ══════════════════════════════════════════════════
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
_human_input_lock = None
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
def _update_speaker(self, new_speaker: str):
|
|
2562
|
-
"""
|
|
2563
|
-
更新发言者状态,返回 (turn_id, idx)
|
|
2564
|
-
- new_speaker: 'human', 'node', 或 'ai'
|
|
2565
|
-
- 返回 tuple: (turn_id, idx) 其中 idx 是 oratio_idx 或 step_idx
|
|
2566
|
-
"""
|
|
2567
|
-
last = self.speaker["current"]
|
|
2568
|
-
self.speaker["last"] = last
|
|
2569
|
-
self.speaker["current"] = new_speaker
|
|
2570
|
-
|
|
2571
|
-
if last == 'ai' and new_speaker in ('human', 'node'):
|
|
2572
|
-
# AI → 人类/节点:turn++
|
|
2573
|
-
self._current_turn_id += 1
|
|
2574
|
-
self._oratio_idx = 0
|
|
2575
|
-
self._step_idx = 0
|
|
2576
|
-
# turn_count 内建直通(读实时值,无存储写点)
|
|
2577
|
-
elif new_speaker == 'ai':
|
|
2578
|
-
if last in ('human', 'node', None):
|
|
2579
|
-
self._step_idx = 0
|
|
2580
|
-
else:
|
|
2581
|
-
self._step_idx += 1
|
|
2582
|
-
# turn 不变
|
|
2583
|
-
else: # new_speaker 是 'human' 或 'node'
|
|
2584
|
-
if last in ('human', 'node'):
|
|
2585
|
-
self._oratio_idx += 1
|
|
2586
|
-
else: # last is None or 'ai'
|
|
2587
|
-
self._oratio_idx = 0
|
|
2588
|
-
# turn 不变
|
|
2589
|
-
|
|
2590
|
-
if new_speaker == 'ai':
|
|
2591
|
-
return self._current_turn_id, self._step_idx
|
|
2592
|
-
else:
|
|
2593
|
-
return self._current_turn_id, self._oratio_idx
|
|
2594
|
-
|
|
2595
|
-
def _alloc_turn(self) -> int:
|
|
2596
|
-
"""分配下一个 turn 号(2026-08-28 par 丢行根治,引擎级锁)。
|
|
2597
|
-
par/fork 并发分支在锁内排队领取严格递增的独立 turn 号——每个节点实例
|
|
2598
|
-
按领取顺序获得唯一身份,任何两行都不可能再撞 (turn, step) 键。
|
|
2599
|
-
取号所属 session 变化时(新开场 / 断点续跑换场)按该 session 的
|
|
2600
|
-
get_next_turn_id 起点重新对齐,续跑场次自然接续旧 turn 序列。
|
|
2601
|
-
注意:取号后本节点的所有行(prompt/showprompt/react)必须共用这个号,
|
|
2602
|
-
用 oratio/step 区分行,不得再改读共享状态机。"""
|
|
2603
|
-
with self._turn_lock:
|
|
2604
|
-
sid = self._current_session_id
|
|
2605
|
-
if getattr(self, '_turn_seq_sid', None) != sid or self._turn_seq is None:
|
|
2606
|
-
# 新 session(或本 run 首次取号):从"该 session 下一个空位"起算
|
|
2607
|
-
self._turn_seq_sid = sid
|
|
2608
|
-
self._turn_seq = self._current_turn_id - 1
|
|
2609
|
-
self._turn_seq += 1
|
|
2610
|
-
self._current_turn_id = self._turn_seq
|
|
2611
|
-
return self._current_turn_id
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
def _try_apply_human_variables(self, variables: dict, out_defs: list,
|
|
2615
|
-
facade=None) -> Optional[str]:
|
|
2616
|
-
"""尝试应用人类输入的变量赋值;成功返回 None,失败返回错误信息(str)。
|
|
2617
|
-
容错原则:human 输入不稳定可重试,但未声明变量必须报错(不静默忽略)。
|
|
2618
|
-
支持动态字典键 out(damage_report.@hero → dict[实际角色])。"""
|
|
2619
|
-
if not variables:
|
|
2620
|
-
return None
|
|
2621
|
-
|
|
2622
|
-
def display_name(od):
|
|
2623
|
-
base = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
2624
|
-
dk = getattr(od, 'dynamic_key', None)
|
|
2625
|
-
return f"{base}.{dk}" if dk else base
|
|
2626
|
-
|
|
2627
|
-
by_display = {display_name(od): od for od in (out_defs or [])}
|
|
2628
|
-
declared_display = set(by_display)
|
|
2629
|
-
|
|
2630
|
-
for var_key, var_value in variables.items():
|
|
2631
|
-
raw = str(var_value).strip()
|
|
2632
|
-
if not raw:
|
|
2633
|
-
print(f"[runtime]⏭️ 变量 '{var_key}' 值为空,跳过")
|
|
2634
|
-
continue
|
|
2635
|
-
if var_key not in declared_display:
|
|
2636
|
-
return (f"变量 '{var_key}' 未声明(该节点 out 只声明了: "
|
|
2637
|
-
f"{', '.join(sorted(declared_display)) or '无'})。"
|
|
2638
|
-
f"所有变量必须在 vars: 中预先声明。")
|
|
2639
|
-
od = by_display[var_key]
|
|
2640
|
-
try:
|
|
2641
|
-
# 构造表达式:+=/-= 前缀直接用(标准化空格),否则加 "= " 前缀
|
|
2642
|
-
if raw.startswith('+=') or raw.startswith('-='):
|
|
2643
|
-
expr = raw[:2] + ' ' + raw[2:].strip()
|
|
2644
|
-
else:
|
|
2645
|
-
expr = '= ' + raw
|
|
2646
|
-
op, val = parse_assign_syntax(expr, getattr(od, 'var_name', var_key))
|
|
2647
|
-
# 对 set/add/remove 的字符串值,用 Evaluator 解析变量引用(如 @Alice)
|
|
2648
|
-
if op in ('set', 'add', 'remove') and isinstance(val, str):
|
|
2649
|
-
resolved = self.evaluator.evaluate(val, facade, strict=False)
|
|
2650
|
-
val = resolved
|
|
2651
|
-
if getattr(od, 'dynamic_key', None):
|
|
2652
|
-
# 动态字典键:dict.@actor(@actor 解析为实际角色实体)
|
|
2653
|
-
self._set_out_var(od, val)
|
|
2654
|
-
print(f"[runtime]📤 前端动态键赋值完成: {display_name(od)} = {val!r}")
|
|
2655
|
-
else:
|
|
2656
|
-
facade.apply_intent(od.var_name, (op, val))
|
|
2657
|
-
print(f"[runtime]📤 前端变量赋值完成: {od.var_name} {op} {val!r}, 当前值={facade.get(od.var_name)!r}")
|
|
2658
|
-
except FEMOVariableError as e:
|
|
2659
|
-
return str(e)
|
|
2660
|
-
except Exception as e:
|
|
2661
|
-
return f"变量 '{var_key}' 赋值失败: {e}"
|
|
2662
|
-
return None
|
|
2663
|
-
|
|
2664
|
-
async def _exec_human(self, ad, eparam: str) -> Any:
|
|
2665
|
-
# 人类动作现在支持异步等待,不再阻塞事件循环
|
|
2666
|
-
print(f"[runtime]👤 Human Action")
|
|
2667
|
-
human_scope_info = self._scope_info_for(ad, eparam)
|
|
2668
|
-
self._emit_event('node_start', {
|
|
2669
|
-
'node_name': self._get_current_node_id(),
|
|
2670
|
-
'node_type': 'human',
|
|
2671
|
-
'scope': human_scope_info,
|
|
2672
|
-
})
|
|
2673
|
-
|
|
2674
|
-
try:
|
|
2675
|
-
ctx = current_task_ctx()
|
|
2676
|
-
facade = ctx.facade if ctx is not None else None
|
|
2677
|
-
prompt = self.evaluator.interpolate_prompt(
|
|
2678
|
-
str(ad.prompt or ""), facade, in_mappings=ad.in_mappings)
|
|
2679
|
-
|
|
2680
|
-
# ── 收集 context 和 memory(与 AI 节点相同)──
|
|
2681
|
-
from femoCompiler.block_collector import collect_blocks
|
|
2682
|
-
actor_info = self._get_actor_info(ad, eparam)
|
|
2683
|
-
print(f"[DEBUG _exec_human] 刚获取的 actor_info (准备给人类发言用): {actor_info}")
|
|
2684
|
-
turn_id_alloc = self._alloc_turn() # 本节点独立 turn 号(par 并发安全)
|
|
2685
|
-
# oratio 分配(2026-08-29 合写):0=节点 prompt、1=showprompt(渲染提前、
|
|
2686
|
-
# 与玩家输入同事务落库)、2+=玩家输入;无 showprompt 的节点输入从 1 起
|
|
2687
|
-
human_oratio = 2 if getattr(ad, 'showprompt', None) else 1
|
|
2688
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
2689
|
-
blocks = collect_blocks(
|
|
2690
|
-
action=ad,
|
|
2691
|
-
meta=self.script.meta,
|
|
2692
|
-
actors_def=self.script.actors,
|
|
2693
|
-
var_manager=facade,
|
|
2694
|
-
evaluator=self.evaluator,
|
|
2695
|
-
code_modules=self.bridge.modules,
|
|
2696
|
-
memory_defs=None,
|
|
2697
|
-
context_defs=self.script.contexts,
|
|
2698
|
-
session_id=self._current_session_id,
|
|
2699
|
-
turn_id=turn_id_alloc,
|
|
2700
|
-
actor_info=actor_info,
|
|
2701
|
-
runner=self,
|
|
2702
|
-
base_dir=self.base_dir,
|
|
2703
|
-
)
|
|
2704
|
-
context_text = blocks.get('context', '')
|
|
2705
|
-
memory_text = blocks.get('memory', '')
|
|
2706
|
-
|
|
2707
|
-
scope_info = self._scope_info_for(ad, eparam)
|
|
2708
|
-
# 【2026-09-08 角色窗按钮修复】人类节点等待 scope 必含执行者本人:
|
|
2709
|
-
# 宿主把 human_wait 的 scope 冻结为等待快照(waitingHuman.waitScope),
|
|
2710
|
-
# 角色窗按钮按「快照含本窗角色」点亮。执行者是唯一确定要输入的人——
|
|
2711
|
-
# 无论剧本 scope 怎么写(如仅 [@上帝]),都必须在快照里,否则轮到
|
|
2712
|
-
# 执行者发言时其角色窗永远不亮。node_start 的 scope 不加此保证:
|
|
2713
|
-
# 宿主侧 par 并发下同名节点的 node_start 会互相覆盖(最后到达者胜),
|
|
2714
|
-
# 本字段在事件发出时刻现场冻结,才是角色窗判定的权威源。
|
|
2715
|
-
_human_executor = self._resolve_actor_name(eparam)
|
|
2716
|
-
if _human_executor:
|
|
2717
|
-
_human_tag = _human_executor if str(_human_executor).startswith('@') else f'@{_human_executor}'
|
|
2718
|
-
if _human_tag not in scope_info:
|
|
2719
|
-
scope_info = sorted(set(scope_info) | {_human_tag})
|
|
2720
|
-
# 构建 out_vars 列表(变量名完整显示,dynamic_key 拼成 dict.@actor)
|
|
2721
|
-
out_vars = []
|
|
2722
|
-
if ad.outs:
|
|
2723
|
-
for od in ad.outs:
|
|
2724
|
-
var_name = getattr(od, 'global_name', None) or getattr(od, 'var_name', '')
|
|
2725
|
-
dk = getattr(od, 'dynamic_key', None)
|
|
2726
|
-
if var_name:
|
|
2727
|
-
out_vars.append(f"{var_name}.{dk}" if dk else var_name)
|
|
2728
|
-
print(f"[runtime]📋 human_wait out_vars: {out_vars}")
|
|
2729
|
-
|
|
2730
|
-
# ── 生成唯一 wait_key,用于精确路由人类输入(run_tag 世代前缀 §5.6)──
|
|
2731
|
-
self._human_input_counter += 1
|
|
2732
|
-
node_id = self._get_current_node_id()
|
|
2733
|
-
wait_key = f"{self._run_tag}human_{node_id}_{self._human_input_counter}"
|
|
2734
|
-
print(f"[runtime]🔑 human_wait 分配专属频道: wait_key={wait_key}")
|
|
2735
|
-
|
|
2736
|
-
self._emit_event('human_wait', {
|
|
2737
|
-
'node_name': node_id,
|
|
2738
|
-
'wait_key': wait_key,
|
|
2739
|
-
'prompt': prompt,
|
|
2740
|
-
'scope': scope_info,
|
|
2741
|
-
'context': context_text,
|
|
2742
|
-
'memory': memory_text,
|
|
2743
|
-
'out_vars': out_vars,
|
|
2744
|
-
})
|
|
2745
|
-
|
|
2746
|
-
if prompt:
|
|
2747
|
-
print(f"[runtime]📝 {prompt}")
|
|
2748
|
-
from .save_dialog import save_human_turn
|
|
2749
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
2750
|
-
raw_scope = self._raw_scope_for(ad)
|
|
2751
|
-
|
|
2752
|
-
h_actor_info = self._get_actor_info(ad, eparam)
|
|
2753
|
-
if 'user' not in h_actor_info:
|
|
2754
|
-
owners = self.script.meta.get('owner', [])
|
|
2755
|
-
if owners:
|
|
2756
|
-
h_actor_info['user'] = str(owners[0])
|
|
2757
|
-
|
|
2758
|
-
turn_id, oratio_idx = turn_id_alloc, 0
|
|
2759
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
2760
|
-
event = save_human_turn(
|
|
2761
|
-
session_id=self._current_session_id,
|
|
2762
|
-
turn_id=turn_id,
|
|
2763
|
-
oratio_idx=oratio_idx,
|
|
2764
|
-
user_input=prompt,
|
|
2765
|
-
actor_info=h_actor_info,
|
|
2766
|
-
meta_owner=meta_owner,
|
|
2767
|
-
action_scope=raw_scope,
|
|
2768
|
-
is_node_prompt=True,
|
|
2769
|
-
femo_id=femo_id,
|
|
2770
|
-
raw_action_scope=ad.scope,
|
|
2771
|
-
)
|
|
2772
|
-
if event:
|
|
2773
|
-
await self.engine.run_in_thread(event.wait)
|
|
2774
|
-
print(f"[runtime]💬 Human prompt 已存入 dialog: turn={turn_id}, oratio={oratio_idx}")
|
|
2775
|
-
|
|
2776
|
-
# showprompt 渲染提前、落库推迟(2026-08-29 合写):human 节点的 show
|
|
2777
|
-
# 行此前从未落库(老缺口),现在与玩家输入行同事务落库——要不然都有
|
|
2778
|
-
# 要不然都没有;输入为空(如超时放行)时只落 show 行 = 超时留痕。
|
|
2779
|
-
show_text = ''
|
|
2780
|
-
if getattr(ad, 'showprompt', None):
|
|
2781
|
-
show_text = self.evaluator.interpolate_prompt(
|
|
2782
|
-
str(ad.showprompt), facade, in_mappings=ad.in_mappings)
|
|
2783
|
-
|
|
2784
|
-
# ── 获取人类输入:FastAPI 模式 or CLI 模式 ──
|
|
2785
|
-
chat_text = ''
|
|
2786
|
-
variables = {}
|
|
2787
|
-
retry_hint = ''
|
|
2788
|
-
|
|
2789
|
-
# 人类输入容错:赋值失败 → 带错误信息重新等待输入(不中断流程)
|
|
2790
|
-
if self._human_input_event is not None:
|
|
2791
|
-
# wait_key 在上面改动3中已计算,此处直接使用
|
|
2792
|
-
if 'wait_key' not in locals():
|
|
2793
|
-
self._human_input_counter += 1
|
|
2794
|
-
node_id = self._get_current_node_id()
|
|
2795
|
-
wait_key = f"{self._run_tag}human_{node_id}_{self._human_input_counter}"
|
|
2796
|
-
print(f"[runtime]⏳ 等待前端人类输入... 频道: {wait_key}"
|
|
2797
|
-
+ (f"(上次被拒: {retry_hint})" if retry_hint else ""))
|
|
2798
|
-
raw_input = await self.engine.human_input.wait_for_input(wait_key, timeout=3600)
|
|
2799
|
-
print(f"[runtime]📥 收到前端输入: type={type(raw_input).__name__}")
|
|
2800
|
-
print(f"[runtime]📥 raw_input = {raw_input}")
|
|
2801
|
-
# 新前端传 dict,CLI 模式传 str
|
|
2802
|
-
if isinstance(raw_input, dict):
|
|
2803
|
-
chat_text = raw_input.get('chat_text', '')
|
|
2804
|
-
variables = raw_input.get('variables', {})
|
|
2805
|
-
print(f"[runtime]📥 结构化输入: chat_text={chat_text!r}, variables={variables}")
|
|
2806
|
-
else:
|
|
2807
|
-
chat_text = str(raw_input) if raw_input else ''
|
|
2808
|
-
print(f"[runtime]📥 兼容旧格式(纯字符串): chat_text={chat_text!r}")
|
|
2809
|
-
else:
|
|
2810
|
-
# CLI 模式:将多行读取封装为同步函数,放到线程池执行
|
|
2811
|
-
print("(输入内容,按回车换行,输入空行或 /end 结束)")
|
|
2812
|
-
print("(命令:/godview 上帝视角 | /@角色名 切换视角)")
|
|
2813
|
-
|
|
2814
|
-
# 同步读取函数,保留原有特殊命令处理
|
|
2815
|
-
def _sync_read_multiline():
|
|
2816
|
-
lines = []
|
|
2817
|
-
while True:
|
|
2818
|
-
try:
|
|
2819
|
-
sys.stdout.flush()
|
|
2820
|
-
line = sys.stdin.readline()
|
|
2821
|
-
if not line:
|
|
2822
|
-
break
|
|
2823
|
-
line = line.rstrip('\n')
|
|
2824
|
-
if line == '' or line.strip().lower() == '/end':
|
|
2825
|
-
break
|
|
2826
|
-
# ── 特殊命令处理 ──
|
|
2827
|
-
if line.startswith('/'):
|
|
2828
|
-
cmd = line[1:].strip()
|
|
2829
|
-
if cmd == 'godview':
|
|
2830
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
2831
|
-
_actor_info = {'user': str(meta_owner[0])} if meta_owner else {}
|
|
2832
|
-
_blocks = collect_blocks(
|
|
2833
|
-
action=ad,
|
|
2834
|
-
meta=self.script.meta,
|
|
2835
|
-
actors_def=self.script.actors,
|
|
2836
|
-
var_manager=facade,
|
|
2837
|
-
evaluator=self.evaluator,
|
|
2838
|
-
code_modules=self.bridge.modules,
|
|
2839
|
-
memory_defs=None,
|
|
2840
|
-
context_defs=self.script.contexts,
|
|
2841
|
-
session_id=self._current_session_id,
|
|
2842
|
-
turn_id=self._current_turn_id,
|
|
2843
|
-
actor_info=_actor_info,
|
|
2844
|
-
runner=self,
|
|
2845
|
-
base_dir=self.base_dir,
|
|
2846
|
-
)
|
|
2847
|
-
if self._cli_renderer:
|
|
2848
|
-
self._cli_renderer.clear_and_show_context(
|
|
2849
|
-
"上帝视角(owner)",
|
|
2850
|
-
_blocks.get('context', '(暂无对话记录)')
|
|
2851
|
-
)
|
|
2852
|
-
elif cmd.startswith('@'):
|
|
2853
|
-
_actor_info = self._get_actor_info(ad, cmd)
|
|
2854
|
-
self._current_actor_info = _actor_info
|
|
2855
|
-
_blocks = collect_blocks(
|
|
2856
|
-
action=ad,
|
|
2857
|
-
meta=self.script.meta,
|
|
2858
|
-
actors_def=self.script.actors,
|
|
2859
|
-
var_manager=facade,
|
|
2860
|
-
evaluator=self.evaluator,
|
|
2861
|
-
code_modules=self.bridge.modules,
|
|
2862
|
-
memory_defs=None,
|
|
2863
|
-
context_defs=self.script.contexts,
|
|
2864
|
-
session_id=self._current_session_id,
|
|
2865
|
-
turn_id=self._current_turn_id,
|
|
2866
|
-
actor_info=_actor_info,
|
|
2867
|
-
runner=self,
|
|
2868
|
-
base_dir=self.base_dir,
|
|
2869
|
-
)
|
|
2870
|
-
name = cmd.lstrip('@')
|
|
2871
|
-
if self._cli_renderer:
|
|
2872
|
-
self._cli_renderer.clear_and_show_context(
|
|
2873
|
-
f"{name} 的视角",
|
|
2874
|
-
_blocks.get('context', '(暂无对话记录)')
|
|
2875
|
-
)
|
|
2876
|
-
else:
|
|
2877
|
-
print(f"⚠️ 未知命令: /{cmd}")
|
|
2878
|
-
continue
|
|
2879
|
-
lines.append(line)
|
|
2880
|
-
except (EOFError, KeyboardInterrupt):
|
|
2881
|
-
break
|
|
2882
|
-
except Exception as e:
|
|
2883
|
-
print(f"[runtime]\n⚠️ 读取输入时出错: {e},跳过本次输入")
|
|
2884
|
-
break
|
|
2885
|
-
return '\n'.join(lines)
|
|
2886
|
-
|
|
2887
|
-
raw_cli = await self.engine.run_in_thread(_sync_read_multiline)
|
|
2888
|
-
chat_text = raw_cli if raw_cli else ''
|
|
2889
|
-
# CLI 模式下 variables 保持空(CLI 不支持结构化输入)
|
|
2890
|
-
|
|
2891
|
-
# ── 变量赋值:以 ad.outs 为准,复用 parse_assign_syntax ──
|
|
2892
|
-
print(f"[runtime]📋 该节点 out 声明: "
|
|
2893
|
-
f"{[(getattr(od, 'var_name', ''), getattr(od, 'dynamic_key', None)) for od in (ad.outs or [])]}")
|
|
2894
|
-
|
|
2895
|
-
# 人类输入容错循环(2026-09-05 重构,施工清单 v4 §4.⑥,裁决④⑥):
|
|
2896
|
-
# human 与 ai 全节点统一走 ErrorDispatcher 三桶——赋值失败 →
|
|
2897
|
-
# node_retry(target='human') 信号(宿主 human 租约=投影窗 ⚠️ 提醒;
|
|
2898
|
-
# femoGen 画布同事件重开输入框)→ 既有"重等输入"分支原样(人类重输
|
|
2899
|
-
# =重试,引擎侧零新增机制)。反馈超限(P7 默认同 max_retries 上限)
|
|
2900
|
-
# → notify_author + 超时放行同款收尾 → move on。
|
|
2901
|
-
human_retries_max = max(1, (getattr(ad, 'max_retries', None) or 2) + 1) - 1
|
|
2902
|
-
human_settled_outcome = 'ok'
|
|
2903
|
-
human_actor_name = self._resolve_actor_name(eparam)
|
|
2904
|
-
while True:
|
|
2905
|
-
# ── 文本赋值(2026-09-01):聊天框里的 SET VARIABLE: <<...>> 与 AI
|
|
2906
|
-
# 同一套提取器解析;前端结构化变量框的值优先覆盖(显式 UI 输入)。──
|
|
2907
|
-
merged_vars = text_assignments_to_dict(chat_text)
|
|
2908
|
-
merged_vars.update(variables or {})
|
|
2909
|
-
assign_err = self._try_apply_human_variables(merged_vars, ad.outs, facade=facade)
|
|
2910
|
-
if assign_err is None:
|
|
2911
|
-
break
|
|
2912
|
-
retry_hint = assign_err
|
|
2913
|
-
verdict = self.errors.dispatch(
|
|
2914
|
-
None, node_id, errors=[assign_err], wait_key=wait_key,
|
|
2915
|
-
ai_name=human_actor_name, max_retries=human_retries_max,
|
|
2916
|
-
target=FEEDBACK_TARGET_HUMAN)
|
|
2917
|
-
if verdict == VERDICT_EXHAUSTED:
|
|
2918
|
-
human_settled_outcome = 'gave_up'
|
|
2919
|
-
# 超时放行同款收尾:清掉最后一次非法输入——台账只落 show 行
|
|
2920
|
-
# 留痕(超时留痕语义),非法赋值文本不进 dialog(防污染下游上下文)。
|
|
2921
|
-
chat_text = ''
|
|
2922
|
-
variables = {}
|
|
2923
|
-
break
|
|
2924
|
-
# VERDICT_RETRY:宿主 human 租约已把提醒显示到投影窗(⚠️);
|
|
2925
|
-
# femoGen 画布同事件重开输入框。既有"重等输入"分支原样——
|
|
2926
|
-
# 人类重输=重试,引擎侧零新增机制。
|
|
2927
|
-
print(f"[runtime]⚠️ 人类输入被拒绝: {assign_err},请重新输入")
|
|
2928
|
-
# 重新等输入
|
|
2929
|
-
if self._human_input_event is not None:
|
|
2930
|
-
print(f"[runtime]⏳ 重新等待前端人类输入... 频道: {wait_key}")
|
|
2931
|
-
raw_input = await self.engine.human_input.wait_for_input(wait_key, timeout=3600)
|
|
2932
|
-
if isinstance(raw_input, dict):
|
|
2933
|
-
chat_text = raw_input.get('chat_text', '')
|
|
2934
|
-
variables = raw_input.get('variables', {})
|
|
2935
|
-
else:
|
|
2936
|
-
chat_text = str(raw_input) if raw_input else ''
|
|
2937
|
-
variables = {}
|
|
2938
|
-
else:
|
|
2939
|
-
# CLI 模式:单行重试输入
|
|
2940
|
-
cli_line = await self.engine.run_in_thread(
|
|
2941
|
-
lambda: sys.stdin.readline().rstrip('\n'))
|
|
2942
|
-
chat_text = cli_line
|
|
2943
|
-
variables = {}
|
|
2944
|
-
|
|
2945
|
-
# ── 拼接存储文本(runtime 立即拼接,save_dialog 无脑存) ──
|
|
2946
|
-
dialog_text = format_human_dialog(chat_text, variables)
|
|
2947
|
-
print(f"[runtime]📝 拼接后的存储文本: {dialog_text!r}")
|
|
2948
|
-
|
|
2949
|
-
# ── 保存人类发言(2026-08-29 合写):show 行与输入行同一事务——
|
|
2950
|
-
# 要么都有要不然都没有;输入为空(如超时放行)时只落 show 行=留痕。
|
|
2951
|
-
if dialog_text or show_text:
|
|
2952
|
-
from .save_dialog import save_human_finish
|
|
2953
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
2954
|
-
raw_scope = self._raw_scope_for(ad)
|
|
2955
|
-
|
|
2956
|
-
actor_info_save = self._get_actor_info(ad, eparam)
|
|
2957
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
2958
|
-
event = save_human_finish(
|
|
2959
|
-
session_id=self._current_session_id,
|
|
2960
|
-
turn_id=turn_id_alloc,
|
|
2961
|
-
showprompt=show_text or None,
|
|
2962
|
-
user_input=dialog_text,
|
|
2963
|
-
input_oratio=human_oratio,
|
|
2964
|
-
actor_info=actor_info_save,
|
|
2965
|
-
meta_owner=meta_owner,
|
|
2966
|
-
action_scope=raw_scope,
|
|
2967
|
-
femo_id=femo_id,
|
|
2968
|
-
raw_action_scope=ad.scope,
|
|
2969
|
-
)
|
|
2970
|
-
if event:
|
|
2971
|
-
await self.engine.run_in_thread(event.wait)
|
|
2972
|
-
print(f"[runtime]🔢 turn → {turn_id_alloc}, human 收尾合写落库(show + input oratio {human_oratio})")
|
|
2973
|
-
|
|
2974
|
-
self._emit_event('human_done', {
|
|
2975
|
-
'node_name': self._get_current_node_id(),
|
|
2976
|
-
'input': chat_text,
|
|
2977
|
-
})
|
|
2978
|
-
|
|
2979
|
-
# ── 节点审结信号(2026-09-05 重构,施工清单 v4 §4.③(g))──────
|
|
2980
|
-
# human 的停靠托管同样靠 node_settled 解除(ai/human 同构)。
|
|
2981
|
-
# gave_up = 反馈超限按结束(空输入只落 show 行=超时留痕同款)。
|
|
2982
|
-
self._emit_event(NODE_SETTLED_EVENT, {
|
|
2983
|
-
'node_name': node_id,
|
|
2984
|
-
'wait_key': wait_key,
|
|
2985
|
-
'outcome': human_settled_outcome,
|
|
2986
|
-
})
|
|
2987
|
-
|
|
2988
|
-
return chat_text
|
|
2989
|
-
|
|
2990
|
-
except Exception as e:
|
|
2991
|
-
print(f"[runtime]\n❌ 人类动作执行异常: {type(e).__name__}: {e}")
|
|
2992
|
-
import traceback
|
|
2993
|
-
traceback.print_exc()
|
|
2994
|
-
raise
|
|
2995
|
-
|
|
2996
|
-
# ══════════════════════════════════════════════════
|
|
2997
|
-
# @notice 处理(公告节点:只注入一条 prompt 进 dialog,无回答者)
|
|
2998
|
-
# ══════════════════════════════════════════════════
|
|
2999
|
-
|
|
3000
|
-
async def _exec_notice(self, ad, eparam: str) -> Any:
|
|
3001
|
-
"""notice 节点:把 prompt(变量替换后)按节点 scope 落一条 dialog 行,
|
|
3002
|
-
无 LLM、无等待、无 blocks/memory/context、无重试、无 react_steps 行。
|
|
3003
|
-
|
|
3004
|
-
落库走 femoshow-<femo_id> 通道(showprompt 通道):ContextExample /
|
|
3005
|
-
MemoryExample / chronica 的行判别都认这个前缀——后续 scope 内角色提
|
|
3006
|
-
上下文时以「[节点提醒]」读到本条(femo- 前缀的幕后指令行会被拼装
|
|
3007
|
-
跳过,读不到,所以不能照抄 AI/human 节点的 prompt 落库方式)。
|
|
3008
|
-
scope: self 语义 = 仅 meta.owner 可见(notice 无发言者,_build_scope
|
|
3009
|
-
按原始字符串注入 owner);事件侧 scope 由 §守卫置空(无发言者可展开)。
|
|
3010
|
-
收尾发 notice_done(仿 func_result / assign_result 的瞬时节点完成
|
|
3011
|
-
事件)——不发则画布呼吸灯卡「运行中」直到 flow_done。"""
|
|
3012
|
-
self._check_cancel()
|
|
3013
|
-
ctx = current_task_ctx()
|
|
3014
|
-
facade = ctx.facade if ctx is not None else None
|
|
3015
|
-
|
|
3016
|
-
# 1) prompt 变量替换(与 _exec_ai 同款:{var} / in: 映射同语义)
|
|
3017
|
-
prompt = self.evaluator.interpolate_prompt(
|
|
3018
|
-
str(ad.prompt or ""), facade, in_mappings=ad.in_mappings)
|
|
3019
|
-
if prompt is None or not str(prompt).strip():
|
|
3020
|
-
raise FEMOVariableError(f"notice Action '{ad.name}' 的 prompt 为空。")
|
|
3021
|
-
prompt = str(prompt)
|
|
3022
|
-
|
|
3023
|
-
# 2) 事件①:node_start(画布按 node_type='notice' 记账,scope 供投影)
|
|
3024
|
-
scope_info = self._scope_info_for(ad, eparam)
|
|
3025
|
-
self._emit_event('node_start', {
|
|
3026
|
-
'node_name': self._get_current_node_id(),
|
|
3027
|
-
'node_type': 'notice',
|
|
3028
|
-
'prompt': prompt,
|
|
3029
|
-
'scope': scope_info,
|
|
3030
|
-
})
|
|
3031
|
-
|
|
3032
|
-
# 3) 落库:一条 femoshow-<femo_id> 行(showprompt 通道),await 落库
|
|
3033
|
-
# 确认再放行——防止紧随其后的下游节点提上下文时读不到本行
|
|
3034
|
-
# (与 _exec_ai 的 prompt 落库同款等待)。
|
|
3035
|
-
turn_id = self._alloc_turn()
|
|
3036
|
-
meta_owner = self.script.meta.get('owner', [])
|
|
3037
|
-
raw_scope = self._raw_scope_for(ad)
|
|
3038
|
-
femo_id = self.script.meta.get('id', 'unknown')
|
|
3039
|
-
from .save_dialog import save_human_turn
|
|
3040
|
-
event = save_human_turn(
|
|
3041
|
-
session_id=self._current_session_id,
|
|
3042
|
-
turn_id=turn_id,
|
|
3043
|
-
oratio_idx=1, # show 行惯例(AI 的 showprompt 也是 1)
|
|
3044
|
-
user_input=prompt,
|
|
3045
|
-
actor_info={}, # 幕后行无发言者;owner 由 _build_scope 注入
|
|
3046
|
-
meta_owner=meta_owner,
|
|
3047
|
-
action_scope=raw_scope,
|
|
3048
|
-
is_node_prompt=True,
|
|
3049
|
-
femo_id=femo_id,
|
|
3050
|
-
prompt_type='showprompt', # femoshow- 前缀 = 后续可读的关键
|
|
3051
|
-
raw_action_scope=ad.scope,
|
|
3052
|
-
)
|
|
3053
|
-
if event:
|
|
3054
|
-
await self.engine.run_in_thread(event.wait)
|
|
3055
|
-
print(f"[runtime]📢 notice '{ad.name}' 已落库: turn={turn_id}")
|
|
3056
|
-
|
|
3057
|
-
# 4) 事件②:notice_done(无 wait_key/租约,不发 node_settled)
|
|
3058
|
-
self._emit_event('notice_done', {
|
|
3059
|
-
'node_name': self._get_current_node_id(),
|
|
3060
|
-
'text': prompt,
|
|
3061
|
-
})
|
|
3062
|
-
return None
|
|
3063
|
-
|
|
3064
|
-
# ══════════════════════════════════════════════════
|
|
3065
|
-
# @mind 处理(运行时按执行者类型分发)
|
|
3066
|
-
# ══════════════════════════════════════════════════
|
|
3067
|
-
|
|
3068
|
-
async def _exec_mind(self, ad, eparam: str) -> Any:
|
|
3069
|
-
"""mind 节点:运行时按实际执行者类型分发到 AI 或 human 路径。
|
|
3070
|
-
|
|
3071
|
-
执行者可能是变量(@mind(@speaker)),由剧本在运行中赋值——每轮
|
|
3072
|
-
可能是人类也可能是 AI,编译期无法预判。因此 @mind 保持原样解析,
|
|
3073
|
-
每轮进入节点时重新解析执行者(_resolve_actor_name 读当前变量值),
|
|
3074
|
-
然后整体委托给 _exec_ai 或 _exec_human(事件、等待、赋值、重试等
|
|
3075
|
-
行为完全复用现有路径,node_type 事件也自动正确)。
|
|
3076
|
-
"""
|
|
3077
|
-
print(f"[runtime]🧠 Mind Action: {ad.name}")
|
|
3078
|
-
if not eparam:
|
|
3079
|
-
raise ValueError(
|
|
3080
|
-
f"Mind Action '{ad.name}' 缺少执行者参数。期望: action {ad.name} @mind(@角色或变量):"
|
|
3081
|
-
)
|
|
3082
|
-
actor_name = self._resolve_actor_name(eparam)
|
|
3083
|
-
if actor_name not in self.script.actors:
|
|
3084
|
-
raise ValueError(
|
|
3085
|
-
f"Mind Action '{ad.name}' 的执行者 '{eparam}' 解析为 '{actor_name}',"
|
|
3086
|
-
f"但 actors 中不存在该角色,无法确定执行者类型(ai/human)。"
|
|
3087
|
-
)
|
|
3088
|
-
atype = self.script.actors[actor_name].type.value
|
|
3089
|
-
print(f"[runtime]🧠 mind 分发: {actor_name} 是 {atype} 执行者 → "
|
|
3090
|
-
f"走 {'AI' if atype == 'ai' else 'human' if atype == 'human' else atype} 路径")
|
|
3091
|
-
if atype == 'ai':
|
|
3092
|
-
return await self._exec_ai(ad, eparam)
|
|
3093
|
-
if atype == 'human':
|
|
3094
|
-
return await self._exec_human(ad, eparam)
|
|
3095
|
-
raise ValueError(
|
|
3096
|
-
f"Mind Action '{ad.name}' 的执行者 '{actor_name}' 类型为 '{atype}',"
|
|
3097
|
-
f"mind 仅支持 ai/human 执行者(blueprint 蓝图角色尚未实现)。"
|
|
3098
|
-
)
|
|
3099
|
-
|
|
3100
|
-
# ══════════════════════════════════════════════════
|
|
3101
|
-
# Out 写回
|
|
3102
|
-
# ══════════════════════════════════════════════════
|
|
3103
|
-
|
|
3104
|
-
def _apply_outs(self, ad, result: Any, local_vars: dict = None):
|
|
3105
|
-
if not ad.outs: return
|
|
3106
|
-
#print(f"[runtime]_apply_outs: result={result!r}, outs={[(o.var_name, getattr(o, 'dynamic_key', None)) for o in ad.outs]}")
|
|
3107
|
-
outs = ad.outs
|
|
3108
|
-
if isinstance(result, tuple):
|
|
3109
|
-
if len(result) != len(outs):
|
|
3110
|
-
raise FEMOVariableError(
|
|
3111
|
-
f"@func 返回值不匹配:out 声明了 {len(outs)} 个变量,但函数返回了 {len(result)} 个值。"
|
|
3112
|
-
)
|
|
3113
|
-
for i, od in enumerate(outs):
|
|
3114
|
-
self._set_out_var(od, result[i])
|
|
3115
|
-
elif isinstance(result, dict):
|
|
3116
|
-
# 检查 out 声明的变量和返回 dict 的 key 是否一一对应
|
|
3117
|
-
out_names = [self._extract_var_name(od.var_name) for od in outs]
|
|
3118
|
-
result_keys = list(result.keys())
|
|
3119
|
-
missing_in_result = [n for n in out_names if n not in result_keys]
|
|
3120
|
-
extra_in_result = [k for k in result_keys if k not in out_names]
|
|
3121
|
-
if missing_in_result and len(outs) == 1:
|
|
3122
|
-
# 单 out + 返回 dict 与 out 名完全不匹配:
|
|
3123
|
-
# 宽容回退——函数返回的字典整体作为单值赋给唯一 out
|
|
3124
|
-
# (如 enemy_phase 返回 hp 字典给 out: hp)
|
|
3125
|
-
self._set_out_var(outs[0], result)
|
|
3126
|
-
return
|
|
3127
|
-
if missing_in_result:
|
|
3128
|
-
raise FEMOVariableError(
|
|
3129
|
-
f"@func 返回值不匹配:out 声明的变量 {missing_in_result} 在函数返回字典中不存在。"
|
|
3130
|
-
)
|
|
3131
|
-
if extra_in_result:
|
|
3132
|
-
raise FEMOVariableError(
|
|
3133
|
-
f"@func 返回值不匹配:函数返回字典中的 key {extra_in_result} 未在 out 中声明。"
|
|
3134
|
-
)
|
|
3135
|
-
for od in outs:
|
|
3136
|
-
var_name = self._extract_var_name(od.var_name)
|
|
3137
|
-
self._set_out_var(od, result[var_name])
|
|
3138
|
-
else:
|
|
3139
|
-
if len(outs) == 1:
|
|
3140
|
-
self._set_out_var(outs[0], result)
|
|
3141
|
-
else:
|
|
3142
|
-
raise FEMOVariableError(
|
|
3143
|
-
f"@func 返回值不匹配:out 声明了 {len(outs)} 个变量,但函数返回了单值。"
|
|
3144
|
-
)
|
|
3145
|
-
|
|
3146
|
-
|
|
3147
|
-
|
|
3148
|
-
|
|
3149
|
-
def _set_out_var(self, od, value: Any):
|
|
3150
|
-
"""out 写回(统一走 facade.set 路径写:纯变量名/dict.@actor/dict[idx]
|
|
3151
|
-
全支持;动态键经 Evaluator.eval_key 完整帧路由)。"""
|
|
3152
|
-
ctx = current_task_ctx()
|
|
3153
|
-
facade = ctx.facade if ctx is not None else None
|
|
3154
|
-
if facade is None:
|
|
3155
|
-
raise FEMOVariableError("out 写回需要 TaskContext(协程未绑执行上下文)")
|
|
3156
|
-
expr = od.var_name
|
|
3157
|
-
dynamic_key = getattr(od, 'dynamic_key', None)
|
|
3158
|
-
if dynamic_key:
|
|
3159
|
-
resolved_key = self.evaluator.eval_key(dynamic_key, facade)
|
|
3160
|
-
if not isinstance(resolved_key, str):
|
|
3161
|
-
raise FEMOVariableError(f"动态键 {dynamic_key} 求值后不是字符串: {resolved_key!r}")
|
|
3162
|
-
path = f"{expr}[{resolved_key}]"
|
|
3163
|
-
facade.set(path, value)
|
|
3164
|
-
print(f"[runtime]📤 out (dict): {path} = {value!r}")
|
|
3165
|
-
return
|
|
3166
|
-
|
|
3167
|
-
if '.@' in expr:
|
|
3168
|
-
container, dyn_key = self.evaluator._resolve_actor_path(expr, facade)
|
|
3169
|
-
if not dyn_key:
|
|
3170
|
-
raise FEMOVariableError(f"无法解析动态键路径: {expr!r}")
|
|
3171
|
-
|
|
3172
|
-
container_val = facade.get(container)
|
|
3173
|
-
if container_val is not None and not isinstance(container_val, dict):
|
|
3174
|
-
raise FEMOVariableError(
|
|
3175
|
-
f"无法写入 {container}[{dyn_key}]:变量 '{container}' 的类型是 {type(container_val).__name__},"
|
|
3176
|
-
f"但此处需要字典类型。请在 vars: 中将其初始值设为 '{{}}' 而非字符串。"
|
|
3177
|
-
)
|
|
3178
|
-
path = f"{container}[{dyn_key}]"
|
|
3179
|
-
facade.set(path, value)
|
|
3180
|
-
print(f"[runtime]📤 out (dict): {path} = {value!r}")
|
|
3181
|
-
return
|
|
3182
|
-
|
|
3183
|
-
facade.set(expr, value)
|
|
3184
|
-
print(f"[runtime]📤 out: {expr} = {value!r}")
|
|
3185
|
-
|
|
3186
|
-
def _extract_var_name(self, expr: str) -> str:
|
|
3187
|
-
m = re.match(r'^(@?[A-Za-z_\u4e00-\u9fff][\w\u4e00-\u9fff]*)', expr)
|
|
3188
|
-
return m.group(1) if m else expr
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
def _get_current_node_id(self) -> str:
|
|
3192
|
-
"""获取当前线程所在的流图节点 ID,线程安全"""
|
|
3193
|
-
ctx = _current_context.get()
|
|
3194
|
-
return ctx.current_node_id if ctx else ""
|
|
3195
|
-
|
|
3196
|
-
# ══════════════════════════════════════════════════
|
|
3197
|
-
# 主流程执行
|
|
3198
|
-
# ══════════════════════════════════════════════════
|
|
3199
|
-
|
|
3200
|
-
def run(self, max_steps: int = None):
|
|
3201
|
-
"""同步入口(仅用于命令行等无事件循环的场景)"""
|
|
3202
|
-
if self.engine.is_event_loop_running():
|
|
3203
|
-
raise RuntimeError(
|
|
3204
|
-
"FEMORunner.run() 不能在已有事件循环中调用。请使用 'await runner.run_async()'。"
|
|
3205
|
-
)
|
|
3206
|
-
self.engine.run_async_until_complete(self.run_async(max_steps))
|
|
3207
|
-
|
|
3208
|
-
async def run_async(self, max_steps: int = None):
|
|
3209
|
-
"""执行主流程(异步)"""
|
|
3210
|
-
# 重启 SaveQueue,避免上轮任务残留的停止状态
|
|
3211
|
-
from femoCompiler.save_dialog import save_queue
|
|
3212
|
-
save_queue.restart()
|
|
3213
|
-
|
|
3214
|
-
# 每次 run 重置 fork 分支错误收集(编译器原则:分支报错必须上报,不静默)
|
|
3215
|
-
self._fork_errors = []
|
|
3216
|
-
# 本次 run 终态判定(A1 取消诚实化,§5.4):取消/FEMORunPaused 路径置位,
|
|
3217
|
-
# flow_done 仅正常完成路径发出(取消路径不发——§八.12)。
|
|
3218
|
-
self._run_terminated = False
|
|
3219
|
-
# 每次 run 重置错误分发计数(wait_key 键控的 node_retry 次数,v4 §4②)
|
|
3220
|
-
self.errors.reset()
|
|
3221
|
-
|
|
3222
|
-
if max_steps is None:
|
|
3223
|
-
global_meta = getattr(self.script, 'meta', None) or {}
|
|
3224
|
-
max_steps = global_meta.get('max_steps', 0)
|
|
3225
|
-
|
|
3226
|
-
flow = self.script.flow
|
|
3227
|
-
if not flow:
|
|
3228
|
-
print("⚠️ 没有 flow 定义")
|
|
3229
|
-
return
|
|
3230
|
-
|
|
3231
|
-
self.global_max_steps = max_steps
|
|
3232
|
-
self.global_step = 0
|
|
3233
|
-
|
|
3234
|
-
flow_start_payload = {
|
|
3235
|
-
'entry': flow.entry,
|
|
3236
|
-
'max_steps': self.global_max_steps,
|
|
3237
|
-
# 引擎场次身份:宿主据此维护「其会话 ↔ femo 场次」的一对多账本
|
|
3238
|
-
'session_id': self._current_session_id,
|
|
3239
|
-
# 剧本全部角色(视角切换菜单用)
|
|
3240
|
-
'actors': list(self.script.actors.keys()),
|
|
3241
|
-
# 剧本 main 演员(source:main)名单:宿主主窗口回答制的流水可见性
|
|
3242
|
-
# 判定用——main 演员是编译期静态声明,必须开跑即登记(靠 ai_request
|
|
3243
|
-
# 运行时登记会漏掉首个 main 节点之前的发言,1005 场实测教训)
|
|
3244
|
-
'main_actors': [
|
|
3245
|
-
aname for aname, adef in self.script.actors.items()
|
|
3246
|
-
if str(getattr(adef, 'source', None) or '').strip() == 'main'
|
|
3247
|
-
],
|
|
3248
|
-
# 剧本名(宿主剧终日记标题用)
|
|
3249
|
-
'name': str(global_meta.get('name', '') or ''),
|
|
3250
|
-
}
|
|
3251
|
-
self._emit_event('flow_start', flow_start_payload)
|
|
3252
|
-
# Job 旁挂(§4.2 契约):JobManager 借此 mark_session 回填挂靠场次。
|
|
3253
|
-
self._rc_call('on_flow_start', {'session_id': self._current_session_id,
|
|
3254
|
-
'name': flow_start_payload.get('name', '')})
|
|
3255
|
-
|
|
3256
|
-
try:
|
|
3257
|
-
print("\n🚀 开始执行 Flow")
|
|
3258
|
-
print(f"[runtime] Entry: {flow.entry}")
|
|
3259
|
-
print(f"[DEBUG] flow.nodes count={len(flow.nodes)}, flow.edges count={len(flow.edges)}")
|
|
3260
|
-
print("[DEBUG] 进入 _execute_flow")
|
|
3261
|
-
self._main_task = asyncio.current_task()
|
|
3262
|
-
try:
|
|
3263
|
-
if self.resume_positions:
|
|
3264
|
-
# ── 分支直启(清单 D8):不为 root 起协程(root 多半已 fork
|
|
3265
|
-
# 终止),对 positions 中每个存活 task 起独立分支协程,从记录
|
|
3266
|
-
# node_id 重跑;join 签到后暂停的场景恢复后重新 sign_in
|
|
3267
|
-
# (merge 幂等)。该跑哪个 flow 由模块栈顶决定。
|
|
3268
|
-
direct_tasks = []
|
|
3269
|
-
print(f"[resume-diag] resume_positions keys={list(self.resume_positions.keys())}")
|
|
3270
|
-
for tid, pos in self.resume_positions.items():
|
|
3271
|
-
env = self.world.envs.get(tid)
|
|
3272
|
-
ledger_alive = self.world.ledger.alive(tid)
|
|
3273
|
-
try:
|
|
3274
|
-
flow_i, extra_i = self._flow_for_stack(list(pos.get('mod_stack') or []))
|
|
3275
|
-
flow_err = ''
|
|
3276
|
-
except Exception as exc:
|
|
3277
|
-
flow_i = extra_i = None
|
|
3278
|
-
flow_err = str(exc)
|
|
3279
|
-
start_node = pos.get('node_id')
|
|
3280
|
-
node_in_flow = bool(flow_i is not None and flow_i.nodes.get(start_node))
|
|
3281
|
-
# 【2026-09-06 探针】直启每个决策点全部照亮——静默跳过
|
|
3282
|
-
# (env 缺失/ledger 非存活/flow 缺失/起点不在图中)任何
|
|
3283
|
-
# 一个发生,恢复就会变成"秒跑完"假象。
|
|
3284
|
-
print(f"[resume-diag] task={tid} env={'有' if env is not None else '无'} "
|
|
3285
|
-
f"ledger_alive={ledger_alive} 起点={start_node} "
|
|
3286
|
-
f"mod_stack={list(pos.get('mod_stack') or [])} "
|
|
3287
|
-
f"flow_resolved={flow_i is not None}"
|
|
3288
|
-
f"{' exc=' + flow_err if flow_err else ''} 起点在图中={node_in_flow}")
|
|
3289
|
-
if env is None or not ledger_alive:
|
|
3290
|
-
print(f"[resume-diag] ⏭️ task {tid} 跳过直启(env 缺失或 ledger 非存活——恢复世界不认这个 task)")
|
|
3291
|
-
continue
|
|
3292
|
-
if flow_i is None:
|
|
3293
|
-
print(f"[resume-diag] ⚠️ task {tid} 的模块栈顶 flow 缺失,跳过直启")
|
|
3294
|
-
continue
|
|
3295
|
-
if not node_in_flow:
|
|
3296
|
-
print(f"[resume-diag] ⚠️ task {tid} 起点 {start_node} 不在目标 flow 中(合成网关编号变动/节点被删——断点位置失效)")
|
|
3297
|
-
t = self.engine.create_task(branch_main(
|
|
3298
|
-
self, self.world, tid, env, pos['node_id'], flow_i,
|
|
3299
|
-
extra_i, 0,
|
|
3300
|
-
stack=(tuple(pos.get('mod_stack') or []),
|
|
3301
|
-
tuple(pos.get('loop_frames') or [])),
|
|
3302
|
-
resume_callers=pos.get('module_frames') or []))
|
|
3303
|
-
direct_tasks.append(t)
|
|
3304
|
-
if direct_tasks:
|
|
3305
|
-
print(f"[runtime]🔁 分支直启:{len(direct_tasks)} 个 task 从断点重放")
|
|
3306
|
-
await asyncio.gather(*direct_tasks, return_exceptions=True)
|
|
3307
|
-
else:
|
|
3308
|
-
print("[resume-diag] ⚠️⚠️ 直启协程为零——没有任何 task 被重启,流程将立即收场(这就是'秒跑完'的直接原因)")
|
|
3309
|
-
if self._fork_errors:
|
|
3310
|
-
detail = "; ".join(f"[{n}] {e}" for n, e in self._fork_errors)
|
|
3311
|
-
self._fork_errors = []
|
|
3312
|
-
raise FEMOVariableError(f"直启分支执行失败: {detail}")
|
|
3313
|
-
else:
|
|
3314
|
-
# 全新开演:root task 't0' 绑执行上下文跑主流程
|
|
3315
|
-
root_env = self.world.envs.get('t0')
|
|
3316
|
-
root_facade = self.world.new_facade(root_env)
|
|
3317
|
-
root_ctx = TaskContext(task_id='t0', facade=root_facade)
|
|
3318
|
-
with task_ctx(root_ctx):
|
|
3319
|
-
await self._execute_flow(flow)
|
|
3320
|
-
except asyncio.CancelledError:
|
|
3321
|
-
# A1 取消诚实化(§5.4):取消路径不再吞掉后照发 flow_done——
|
|
3322
|
-
# 置终态判定位 + 旁挂挂起落盘。reason 区分用户停止/外部取消。
|
|
3323
|
-
print("[runtime] 主协程被取消,流程终止")
|
|
3324
|
-
self._run_terminated = True
|
|
3325
|
-
self._rc_call('on_state_change', 'suspended',
|
|
3326
|
-
'user_pause' if self._stopped else 'cancelled')
|
|
3327
|
-
except FEMORunPaused:
|
|
3328
|
-
# C3(§5.7):直连模式 AI 失败挂起——节点门口断点已拍,
|
|
3329
|
-
# 走 suspended(node_pause) 可续跑(替换旧 task_pause 挂死)。
|
|
3330
|
-
self._run_terminated = True
|
|
3331
|
-
self._rc_call('on_state_change', 'suspended', 'node_pause')
|
|
3332
|
-
finally:
|
|
3333
|
-
self._main_task = None
|
|
3334
|
-
|
|
3335
|
-
print("[DEBUG] 退出 _execute_flow")
|
|
3336
|
-
|
|
3337
|
-
# 取消路径也要 wait_empty(v1 吸收论证):stop 时 save_dialog 队列
|
|
3338
|
-
# 可能有未落库发言,跳过=丢台词(批次 1 实锤);D2 修复后 10s 超时
|
|
3339
|
-
# 真实生效防卡(§5.8)。
|
|
3340
|
-
from femoCompiler.save_dialog import save_queue
|
|
3341
|
-
await self.engine.run_in_thread(
|
|
3342
|
-
save_queue.wait_empty,
|
|
3343
|
-
10
|
|
3344
|
-
)
|
|
3345
|
-
|
|
3346
|
-
if not self._run_terminated:
|
|
3347
|
-
# 仅正常完成发 flow_done(A1 核心:取消路径不发——被取消的戏
|
|
3348
|
-
# 走 suspended,宿主 FSM 对"suspended 后迟到 flow_done"的拒绝
|
|
3349
|
-
# 是第二道防线,两道都要)。
|
|
3350
|
-
self._emit_event('flow_done', {})
|
|
3351
|
-
self._rc_call('on_run_end', 'finished')
|
|
3352
|
-
|
|
3353
|
-
finally:
|
|
3354
|
-
print("[runtime]🧹 开始清理 Runtime 状态")
|
|
3355
|
-
|
|
3356
|
-
# 关闭引擎,释放线程池和进程池
|
|
3357
|
-
try:
|
|
3358
|
-
await self.engine.shutdown()
|
|
3359
|
-
except Exception as e:
|
|
3360
|
-
print(f"[runtime] 引擎关闭异常: {e}")
|
|
3361
|
-
|
|
3362
|
-
self.global_step = 0
|
|
3363
|
-
self.global_max_steps = 0
|
|
3364
|
-
|
|
3365
|
-
self.evaluator.clear_func_cache()
|
|
3366
|
-
self._task_coros = {}
|
|
3367
|
-
self._coordinators = {}
|
|
3368
|
-
self._cascade = None # run 级 JoinCascade 总线随 run 重建(嵌套 join 级联)
|
|
3369
|
-
self._skip_frames = set()
|
|
3370
|
-
self._positions = {}
|
|
3371
|
-
|
|
3372
|
-
self._current_prompt = ""
|
|
3373
|
-
self._current_actor_info = {}
|
|
3374
|
-
|
|
3375
|
-
self.speaker = {
|
|
3376
|
-
"current": None,
|
|
3377
|
-
"last": None
|
|
3378
|
-
}
|
|
3379
|
-
|
|
3380
|
-
self._step_idx = 0
|
|
3381
|
-
self._oratio_idx = 0
|
|
3382
|
-
|
|
3383
|
-
self._human_input_data = None
|
|
3384
|
-
|
|
3385
|
-
print("[runtime]✅ Runtime 状态已重置")
|
|
3386
|
-
|
|
3387
|
-
# ══════════════════════════════════════════════════
|
|
3388
|
-
# 条件求值
|
|
3389
|
-
# ══════════════════════════════════════════════════
|
|
3390
|
-
|
|
3391
|
-
def _resolve_special_param(self, param_name: str) -> Any:
|
|
3392
|
-
"""
|
|
3393
|
-
解析预留字段参数。
|
|
3394
|
-
prompt → 当前 action 的 prompt 文本
|
|
3395
|
-
@actor → actor_info 字典
|
|
3396
|
-
session/session_id → session ID
|
|
3397
|
-
turn/turn_id → turn ID
|
|
3398
|
-
"""
|
|
3399
|
-
if param_name in ('prompt',):
|
|
3400
|
-
return self._current_prompt or ""
|
|
3401
|
-
if param_name in ('@actor',):
|
|
3402
|
-
return self._current_actor_info or {}
|
|
3403
|
-
if param_name in ('session', 'session_id'):
|
|
3404
|
-
return self._current_session_id or 0
|
|
3405
|
-
if param_name in ('turn', 'turn_id'):
|
|
3406
|
-
return self._current_turn_id or 0
|
|
3407
|
-
return None
|
|
3408
|
-
|
|
3409
|
-
|
|
3410
|
-
def _resolve_actor_name(self, executor_param: str) -> str:
|
|
3411
|
-
"""把执行者参数解析为真实 actor 名。
|
|
3412
|
-
|
|
3413
|
-
支持动态变量多层引用(例如 @speaker → @voter → @Cat),
|
|
3414
|
-
读当前变量值(局部优先于全局由 vm.get 决定)。
|
|
3415
|
-
"""
|
|
3416
|
-
actor_name = executor_param
|
|
3417
|
-
ctx = current_task_ctx()
|
|
3418
|
-
facade = ctx.facade if ctx is not None else None
|
|
3419
|
-
while actor_name.startswith('@') and actor_name not in self.script.actors:
|
|
3420
|
-
if facade is None or not facade.has(actor_name):
|
|
3421
|
-
break
|
|
3422
|
-
resolved = facade.get(actor_name)
|
|
3423
|
-
if not resolved or not isinstance(resolved, str) or not resolved.startswith('@'):
|
|
3424
|
-
break
|
|
3425
|
-
actor_name = resolved
|
|
3426
|
-
print(f"[DEBUG _resolve_actor_name] 二次解析: actor_name={actor_name!r}")
|
|
3427
|
-
return actor_name
|
|
3428
|
-
|
|
3429
|
-
def _scope_info_for(self, ad, eparam: str) -> list:
|
|
3430
|
-
"""节点投影 scope 列表(node_start/human_wait 事件 + ai_request payload 用)。
|
|
3431
|
-
|
|
3432
|
-
2026-08-31 猫猫拍板的 scope 默认语义:
|
|
3433
|
-
- 不写 scope / scope: 留空 = all(全员可见)——与显示层 2026-08-22 起的
|
|
3434
|
-
「空=未限定广播」语义对齐,消除 DB/显示两层分裂;
|
|
3435
|
-
- scope: self 保留字段 → [发言人演员名]:只有他自己的角色窗收到该节点
|
|
3436
|
-
的投影(god/stage 全量窗天然可见,owner 走 god 窗);其他角色窗/其他
|
|
3437
|
-
角色视角不可见。DB 侧的 self 语义由 save_dialog._build_scope 按原始
|
|
3438
|
-
字符串独立判定(注入发言者自己+meta.owner),与本函数解耦;
|
|
3439
|
-
- 其余 scope 表达式原样走 scope_str_to_actor_list。
|
|
3440
|
-
"""
|
|
3441
|
-
raw = getattr(ad, 'scope', None)
|
|
3442
|
-
raw = str(raw).strip() if raw else ''
|
|
3443
|
-
if not raw:
|
|
3444
|
-
raw = 'all'
|
|
3445
|
-
if raw.lower() == 'self':
|
|
3446
|
-
resolved = str(self._resolve_actor_name(eparam))
|
|
3447
|
-
if not resolved:
|
|
3448
|
-
# 无发言者(@notice 恒空;裸 @ai 也可能空):事件 scope 置空,
|
|
3449
|
-
# 别产出 ['@'] 垃圾。DB 侧仍由 _build_scope 按原始字符串注入
|
|
3450
|
-
# 发言者/owner(notice 即仅 meta.owner 可见)。
|
|
3451
|
-
return []
|
|
3452
|
-
return [resolved if resolved.startswith('@') else f'@{resolved}']
|
|
3453
|
-
from .FEMO_scope_resolver import scope_str_to_actor_list
|
|
3454
|
-
ctx = current_task_ctx()
|
|
3455
|
-
facade = ctx.facade if ctx is not None else None
|
|
3456
|
-
return scope_str_to_actor_list(raw, self.script.actors, facade)
|
|
3457
|
-
|
|
3458
|
-
def _raw_scope_for(self, ad) -> tuple:
|
|
3459
|
-
"""DB 落库用的 (user_scope, soul_scope) 解析(save_* 各调用点共用)。
|
|
3460
|
-
|
|
3461
|
-
2026-08-31 猫猫拍板:不写 scope / scope: 留空 = all(展开全部 actors,
|
|
3462
|
-
发言者+owner 天然包含在内);scope: self 保留字段不在此解析('self'
|
|
3463
|
-
不是合法 scope 表达式),返回空元组、连同原始字符串(调用点透传
|
|
3464
|
-
raw_action_scope)交由 save_dialog._build_scope 判定注入发言者+owner;
|
|
3465
|
-
其余表达式走 resolve_scope。节点 prompt/showprompt(femo-<id> 幕后指令
|
|
3466
|
-
行)跟随同一语义(猫猫拍板:节点 prompt/showprompt/AI/人类输出都跟随
|
|
3467
|
-
节点 scope 落库);节点无绑定 action 时由调用点保持空 → _build_scope
|
|
3468
|
-
兜底注入 femo-id+owner。
|
|
3469
|
-
"""
|
|
3470
|
-
from .FEMO_scope_resolver import resolve_scope
|
|
3471
|
-
raw = getattr(ad, 'scope', None)
|
|
3472
|
-
text = str(raw).strip() if raw else ''
|
|
3473
|
-
if text and text.lower() == 'self':
|
|
3474
|
-
return ([], [])
|
|
3475
|
-
ctx = current_task_ctx()
|
|
3476
|
-
facade = ctx.facade if ctx is not None else None
|
|
3477
|
-
return resolve_scope(text if text else 'all', self.script.actors, facade)
|
|
3478
|
-
|
|
3479
|
-
def _get_actor_info(self, action, executor_param: str) -> dict:
|
|
3480
|
-
"""解析当前 action 的 actor 信息"""
|
|
3481
|
-
info = {}
|
|
3482
|
-
actor_name = self._resolve_actor_name(executor_param)
|
|
3483
|
-
# 如果 executor_param 是动态变量,但解析后的 actor_name 是静态 actor,则视为静态
|
|
3484
|
-
if executor_param.startswith('@') and executor_param not in self.script.actors:
|
|
3485
|
-
if actor_name not in self.script.actors:
|
|
3486
|
-
# 只有解析后仍然不是静态 actor 时,才检查循环变量一致性
|
|
3487
|
-
ctx = _current_context.get()
|
|
3488
|
-
if ctx and ctx.current_loop_var is not None:
|
|
3489
|
-
if executor_param != ctx.current_loop_var:
|
|
3490
|
-
raise ValueError(
|
|
3491
|
-
f"变量名不一致:for 循环使用 {ctx.current_loop_var},"
|
|
3492
|
-
f"但 action 定义使用 {executor_param}。请统一变量名。"
|
|
3493
|
-
)
|
|
3494
|
-
|
|
3495
|
-
if actor_name in self.script.actors:
|
|
3496
|
-
adef = self.script.actors[actor_name]
|
|
3497
|
-
adef_type = getattr(adef, 'type', None)
|
|
3498
|
-
atype = adef_type.value if adef_type else ''
|
|
3499
|
-
#print(f"[DEBUG _get_actor_info] 匹配到 actor: {actor_name}, type={atype}, soul={getattr(adef, 'soul', None)!r}, source={getattr(adef, 'source', None)!r}")
|
|
3500
|
-
#print(f"[runtime]found adef: {adef}")
|
|
3501
|
-
#print(f"[runtime]adef.__dict__: {adef.__dict__}")
|
|
3502
|
-
|
|
3503
|
-
#print(f"[runtime]atype: {repr(atype)}")
|
|
3504
|
-
if atype == 'ai':
|
|
3505
|
-
soul_id = getattr(adef, 'soul', None)
|
|
3506
|
-
if soul_id is not None:
|
|
3507
|
-
info['soul'] = str(soul_id)
|
|
3508
|
-
elif str(getattr(adef, 'source', None) or '').strip() == 'main':
|
|
3509
|
-
# source:main 裸演员:伪 soul "main" 作为身份键(可见性/落库一致)
|
|
3510
|
-
info['soul'] = 'main'
|
|
3511
|
-
elif atype == 'human':
|
|
3512
|
-
source = getattr(adef, 'source', None)
|
|
3513
|
-
if source is not None:
|
|
3514
|
-
info['user'] = str(source)
|
|
3515
|
-
soul_id = getattr(adef, 'soul', None)
|
|
3516
|
-
if soul_id is not None:
|
|
3517
|
-
info['soul'] = str(soul_id)
|
|
3518
|
-
# 若 source 缺失,从 meta.owner 回退
|
|
3519
|
-
if 'user' not in info:
|
|
3520
|
-
owners = self.script.meta.get('owner', [])
|
|
3521
|
-
if owners:
|
|
3522
|
-
info['user'] = str(owners[0])
|
|
3523
|
-
else:
|
|
3524
|
-
print(f"[runtime]actor_name NOT FOUND in actors!")
|
|
3525
|
-
# 处理 human as(@soul)
|
|
3526
|
-
if hasattr(action, 'as_actor') and action.as_actor:
|
|
3527
|
-
as_name = action.as_actor
|
|
3528
|
-
if as_name in self.script.actors:
|
|
3529
|
-
soul_id = getattr(self.script.actors[as_name], 'soul', None)
|
|
3530
|
-
if soul_id is not None:
|
|
3531
|
-
info['soul'] = str(soul_id)
|
|
3532
|
-
# 收集动态属性(拍板 8⑥ 词法口径):facade.visible_view() 给出当前
|
|
3533
|
-
# 词法可见的全集(帧栈 shadowing 合并+shared)——遍历其中字典,提取
|
|
3534
|
-
# 以 actor_name 为键的条目(模块外节点收不到模块内局部字典)。
|
|
3535
|
-
ctx = current_task_ctx()
|
|
3536
|
-
if ctx is not None:
|
|
3537
|
-
for var_name, var_value in ctx.facade.visible_view().items():
|
|
3538
|
-
if isinstance(var_value, dict) and actor_name in var_value:
|
|
3539
|
-
if var_name not in info:
|
|
3540
|
-
info[var_name] = var_value[actor_name]
|
|
3541
|
-
print(f"[DEBUG _get_actor_info] 最终 actor_info = {info}")
|
|
3542
|
-
return info
|
|
3543
|
-
|
|
3544
|
-
def _resolve_actor_def(self, action, executor_param: str):
|
|
3545
|
-
"""解析动作执行者对应的演员定义。
|
|
3546
|
-
|
|
3547
|
-
支持动态变量 @xxx 解析(执行者每轮可能是变量赋值的演员名),
|
|
3548
|
-
非静态演员时回退 as_actor;找不到返回 None。
|
|
3549
|
-
"""
|
|
3550
|
-
actor_name = executor_param
|
|
3551
|
-
# 支持动态变量 @xxx 解析
|
|
3552
|
-
ctx = current_task_ctx()
|
|
3553
|
-
facade = ctx.facade if ctx is not None else None
|
|
3554
|
-
while actor_name.startswith('@') and actor_name not in self.script.actors:
|
|
3555
|
-
if facade is None or not facade.has(actor_name):
|
|
3556
|
-
break
|
|
3557
|
-
resolved = facade.get(actor_name)
|
|
3558
|
-
if not resolved or not isinstance(resolved, str) or not resolved.startswith('@'):
|
|
3559
|
-
break
|
|
3560
|
-
actor_name = resolved
|
|
3561
|
-
|
|
3562
|
-
# 如果仍然不是静态演员,尝试 as_actor
|
|
3563
|
-
if not actor_name or actor_name not in self.script.actors:
|
|
3564
|
-
if hasattr(action, 'as_actor') and action.as_actor:
|
|
3565
|
-
actor_name = action.as_actor
|
|
3566
|
-
|
|
3567
|
-
if actor_name in self.script.actors:
|
|
3568
|
-
return self.script.actors[actor_name]
|
|
3569
|
-
return None
|
|
3570
|
-
|
|
3571
|
-
def _resolve_ai_source(self, action, executor_param: str) -> str:
|
|
3572
|
-
"""
|
|
3573
|
-
解析当前 AI 动作实际调用的 API provider 标识(限流分桶用)。
|
|
3574
|
-
source 含 '/' 时取 provider 部分;裸 id / 无 source 回退用户自设 provider。
|
|
3575
|
-
返回 provider 字符串,如 "deepseek";若无法确定则返回 "unknown"。
|
|
3576
|
-
"""
|
|
3577
|
-
adef = self._resolve_actor_def(action, executor_param)
|
|
3578
|
-
if adef is not None:
|
|
3579
|
-
source = getattr(adef, 'source', None)
|
|
3580
|
-
if source:
|
|
3581
|
-
s = str(source)
|
|
3582
|
-
if '/' in s:
|
|
3583
|
-
return s.split('/', 1)[0]
|
|
3584
|
-
|
|
3585
|
-
# 回退:使用用户自设的 API provider
|
|
3586
|
-
if self.user_api_provider:
|
|
3587
|
-
return str(self.user_api_provider)
|
|
3588
|
-
|
|
3589
|
-
# 兜底
|
|
3590
|
-
return "unknown"
|
|
3591
|
-
|
|
3592
|
-
def _resolve_ai_model(self, action, executor_param: str) -> str:
|
|
3593
|
-
"""
|
|
3594
|
-
直连模式:source 声明的模型覆盖配置默认模型。
|
|
3595
|
-
裸 id 原样使用;provider/model 取 '/' 后模型部分;无 source 用 user_api_model。
|
|
3596
|
-
"""
|
|
3597
|
-
adef = self._resolve_actor_def(action, executor_param)
|
|
3598
|
-
if adef is not None:
|
|
3599
|
-
source = getattr(adef, 'source', None)
|
|
3600
|
-
if source:
|
|
3601
|
-
s = str(source)
|
|
3602
|
-
if '/' in s:
|
|
3603
|
-
return s.split('/', 1)[1]
|
|
3604
|
-
return s
|
|
3605
|
-
return str(getattr(self, 'user_api_model', None) or '')
|
|
3606
|
-
|
|
3607
|
-
# ============================================================
|
|
3608
|
-
# 便捷入口
|
|
3609
|
-
# ============================================================
|
|
3610
|
-
def run_script(script, base_dir: str = ".", max_steps: int = 100, event_callback=None):
|
|
3611
|
-
"""同步快捷入口(仅用于无事件循环的场景)"""
|
|
3612
|
-
import asyncio
|
|
3613
|
-
return asyncio.run(run_script_async(script, base_dir, max_steps, event_callback))
|
|
3614
|
-
|
|
3615
|
-
async def run_script_async(script, base_dir: str = ".", max_steps: int = 100, event_callback=None):
|
|
3616
|
-
"""异步快捷入口(用于 FastAPI 等异步环境)"""
|
|
3617
|
-
runner = FEMORunner(script, base_dir=base_dir, verbose=True, event_callback=event_callback)
|
|
3618
|
-
try:
|
|
3619
|
-
await runner.run_async(max_steps=max_steps)
|
|
3620
|
-
except FEMOVariableError as e:
|
|
3621
|
-
print(f"[runtime]\n❌ 变量错误: {e}")
|
|
3622
|
-
if event_callback:
|
|
3623
|
-
event_callback('flow_error', {'error': str(e)})
|
|
3624
|
-
# 不再 sys.exit,因为是在服务器里
|
|
3625
|
-
except Exception as e:
|
|
3626
|
-
print(f"[runtime]\n❌ 运行错误: {e}")
|
|
3627
|
-
if event_callback:
|
|
3628
|
-
event_callback('flow_error', {'error': str(e)})
|
|
3629
|
-
raise
|
|
3630
|
-
return runner
|