femo-plugin 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/FEMO_logo.svg +55 -0
- package/FEMO_logo_slogan.svg +29 -0
- package/_tmp/fallback/driver2.py +176 -0
- package/_tmp/fallback/events.jsonl +108 -0
- package/_tmp/fallback/gateway_ui.py +325 -0
- package/_tmp/fallback/outbox/j1553_human_[/347/234/213/347/211/214]_1.done +1 -0
- package/_tmp/fallback/outbox/r1.done +1 -0
- package/_tmp/fallback/outbox/r2.done +1 -0
- package/_tmp/fallback/outbox/r3.done +1 -0
- package/_tmp/fallback/outbox/r4.done +1 -0
- package/_tmp/fallback/outbox/r5.done +1 -0
- package/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +3 -2
- package/hostAdapter/dshAdapter/client/client-ui/composer.tsx +112 -9
- package/hostAdapter/dshAdapter/client/client-ui/styles.ts +17 -0
- package/hostAdapter/dshAdapter/client/fa-icons.tsx +3 -0
- package/hostAdapter/dshAdapter/host/engine-events.ts +4 -1
- package/hostAdapter/dshAdapter/host/index.ts +5 -0
- package/hostAdapter/dshAdapter/host/preset-install.ts +59 -0
- package/hostAdapter/dshAdapter/host/projection-input.ts +14 -6
- package/hostAdapter/dshAdapter/lib/client.js +124 -5
- package/hostAdapter/dshAdapter/lib/client.js.map +3 -3
- package/hostAdapter/dshAdapter/lib/index.js +58 -18
- package/hostAdapter/dshAdapter/lib/index.js.map +4 -4
- package/hostAdapter/dshAdapter/package.json +1 -5
- package/hostAdapter/dshAdapter/preset/agent.cordis.yml +220 -0
- package/hostAdapter/dshAdapter/preset/preset.yml +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/gateway.port +1 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_52a9_624b.jsonl +3 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-a-_40_6211.jsonl +10 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-god.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.tmp/femo/host-history/proj-mirror/femo-main-stage.jsonl +11 -0
- package/hostAdapter/zcodeAdapter/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/README.md +61 -0
- package/hostAdapter/zcodeAdapter/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/.zcode-plugin/plugin.json +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/LICENSE +201 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/README.md +635 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/commands/femo.md +9 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/__init__.py +4 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/chronica.py +156 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo-chat.mjs +69 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femoToolcall/femo_debugger.py +1515 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_api.py +437 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femo2host/femo_gen_api.jsx +77 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/ContextExample.py +555 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/MemoryExample.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir/get_dir.py +56 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/getDir//344/275/240/345/217/257/344/273/245/350/256/276/345/256/232/344/273/273/346/204/217/346/226/207/344/273/266/345/244/271/344/270/272/347/224/250/346/210/267/346/225/260/346/215/256/346/226/207/344/273/266/345/244/271.txt +10 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmBridge.py +247 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoBridges/llmProviders.py +308 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_CLIrenderer.py +198 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_config.py +35 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_errors.py +278 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_interpreter.py +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_normalizer.py +396 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_parser.py +2468 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_runtime.py +3630 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/FEMO_scope_resolver.py +209 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/__init__.py +1 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/actor_resolver.py +86 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/block_collector.py +441 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/db_utils.py +485 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/femoAsync.py +401 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/host_manifest.py +68 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/job_manager.py +767 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/protocol.py +126 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/save_dialog.py +402 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/task_world.py +544 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/__init__.py +19 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/checkpoint.py +113 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/env.py +686 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/evaluator.py +567 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/join.py +303 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/merge.py +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoCompiler/vars/model.py +245 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/345/211/252/350/247/206/351/242/221/AI/345/211/252/350/247/206/351/242/221.femo +192 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/group-chat.femo +42 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +10 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/luxfiat.femo +38 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/LuxFiat/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +222 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/discussion.femo +70 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples/goal-mode.femo +23 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//345/270/270/347/224/250/345/267/245/345/205/267python/wait.py +29 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils.py +205 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200/werewolf_utils2.py +324 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200-/350/255/246/351/225/277/347/211/210.femo +544 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +331 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225/undercover_utils.py +683 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225-/350/217/234/345/270/202/345/234/272/345/261/200.femo +348 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/femoExamples//350/260/201/346/230/257/345/215/247/345/272/225//350/260/201/346/230/257/345/215/247/345/272/225.femo +393 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/dev-bridge-test.py +43 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/hostAdapter/dshAdapter/python/femo_bridge.py +533 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist/zcode.host.manifest.json +5 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
- package/hostAdapter/zcodeAdapter/femo-zcode-dist//350/257/255/346/263/225/346/226/207/346/241/243.md +1136 -0
- package/hostAdapter/zcodeAdapter/hooks/after-tool.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/hooks.json +16 -0
- package/hostAdapter/zcodeAdapter/hooks/lib.mjs +59 -0
- package/hostAdapter/zcodeAdapter/hooks/prompt-state.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/session-start.mjs +3 -0
- package/hostAdapter/zcodeAdapter/hooks/stop-intent.mjs +3 -0
- package/hostAdapter/zcodeAdapter/mcp/bridge-manager.mjs +192 -0
- package/hostAdapter/zcodeAdapter/mcp/event-router.mjs +258 -0
- package/hostAdapter/zcodeAdapter/mcp/femo-server.mjs +429 -0
- package/hostAdapter/zcodeAdapter/mcp/gateway.mjs +163 -0
- package/hostAdapter/zcodeAdapter/mcp/projection-writer.mjs +294 -0
- package/hostAdapter/zcodeAdapter/skills/femo/SKILL.md +93 -0
- package/hostAdapter/zcodeAdapter/tests/bridge-smoke.mjs +26 -0
- package/hostAdapter/zcodeAdapter/tests/event-router.test.mjs +157 -0
- package/hostAdapter/zcodeAdapter/tests/gateway-smoke.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/integration-human.mjs +111 -0
- package/hostAdapter/zcodeAdapter/tests/main-actor.mjs +107 -0
- package/hostAdapter/zcodeAdapter/tests/mcp-smoke.mjs +130 -0
- package/hostAdapter/zcodeAdapter/tests/projection-writer.test.mjs +144 -0
- package/hostAdapter/zcodeAdapter/zcode.host.manifest.json +5 -0
- package/hostAdapter/zcodeAdapter//346/212/225/345/275/261/347/252/227/351/207/215/350/256/276/350/256/241-/350/256/250/350/256/272/347/250/277.md +113 -0
- package/package.json +1 -1
- package/scripts/diag-find-redblue.mjs +38 -0
- package/scripts/diag-god-log.mjs +31 -0
- package/scripts/diag-god-log2.mjs +39 -0
- package/scripts/diag-god-log3.mjs +35 -0
- package/scripts/diag-god-log4.mjs +59 -0
- package/scripts/diag-god-log4b.mjs +39 -0
- package/scripts/diag-redblue-god.mjs +39 -0
- package/scripts/diag-redblue-log.mjs +37 -0
- package/scripts/diag-redblue-span.mjs +41 -0
- package/scripts/diag-stage-1017.mjs +63 -0
- package/scripts/dump_session.py +36 -0
- package/scripts/link-workspace.ps1 +51 -0
- package/scripts/list_souls.py +18 -0
- package/scripts/probe-composer-refresh.mjs +197 -0
- package/scripts/seed_story_souls.py +86 -0
- package/scripts/sync-zcode-dist.ps1 +55 -0
- package/scripts/theme-tokenize/color-extract.txt +288 -0
- package/scripts/theme-tokenize/round1-quoted.ps1 +149 -0
- package/scripts/theme-tokenize/round2-bare.ps1 +138 -0
- package/scripts/theme-tokenize/round3-shape.ps1 +110 -0
- package/tests/_diag_r4_join.femo +32 -0
- package/tests/conftest.py +95 -0
- package/tests/diag-subagent-dir-3081.mjs +101 -0
- package/tests/femoGenerator.test.mjs +3909 -0
- package/tests/femoParser.test.mjs +4813 -0
- package/tests/femogen_notice.test.mjs +109 -0
- package/tests/femoparser_validation.test.mjs +84 -0
- package/tests/main-delivery-queue.test.mjs +329 -0
- package/tests/pre-step-gate.test.mjs +282 -0
- package/tests/read-subagent-model.mjs +24 -0
- package/tests/run-script-tests.py +97 -0
- package/tests/safe-steer.test.mjs +59 -0
- package/tests/strip_comments.test.mjs +164 -0
- package/tests/test_actor_failed.py +92 -0
- package/tests/test_compile_warnings.py +99 -0
- package/tests/test_debug_log_bus.py +108 -0
- package/tests/test_debugger_module_mode.py +141 -0
- package/tests/test_error_buckets.py +117 -0
- package/tests/test_error_dispatcher.py +261 -0
- package/tests/test_exec_ai_retry.py +155 -0
- package/tests/test_exec_human_retry.py +159 -0
- package/tests/test_file_resolve.py +104 -0
- package/tests/test_flow_events.py +311 -0
- package/tests/test_flow_ref_validation.py +92 -0
- package/tests/test_func_dict_fallback.py +39 -0
- package/tests/test_job_lifecycle.py +236 -0
- package/tests/test_job_manager.py +424 -0
- package/tests/test_mind.py +99 -0
- package/tests/test_module_call_args.py +258 -0
- package/tests/test_module_visibility.py +238 -0
- package/tests/test_notice.py +143 -0
- package/tests/test_out_whitelist.py +83 -0
- package/tests/test_par_if_dispatch.py +64 -0
- package/tests/test_par_nested_for.py +78 -0
- package/tests/test_parser.py +494 -0
- package/tests/test_pause.py +102 -0
- package/tests/test_pause_contract.py +135 -0
- package/tests/test_protocol_transcript.py +158 -0
- package/tests/test_scope_self.py +202 -0
- package/tests/test_source_validate.py +113 -0
- package/tests/test_task_world.py +447 -0
- package/tests/test_town_structure.py +70 -0
- package/tests/test_v2_checkpoint.py +115 -0
- package/tests/test_v2_env.py +383 -0
- package/tests/test_v2_evaluator.py +227 -0
- package/tests/test_v2_join.py +315 -0
- package/tests/test_v2_join_wiring.py +429 -0
- package/tests/test_v2_merge.py +167 -0
- package/tests/test_v2_model.py +143 -0
- package/tests/test_v2_resume_e2e.py +472 -0
- package/tests/test_var_decls.py +271 -0
- package/tests/verify-model-functions.mjs +90 -0
- package/tests/verify-subagent-model-3081.mjs +153 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225/node-notice-/346/226/275/345/267/245/346/270/205/345/215/225.md +395 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//344/270/244/344/270/252/345/276/205/350/247/243/345/206/263/347/232/204/351/227/256/351/242/230.MD +66 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//345/201/234/346/255/242/351/223/276/344/277/256/345/244/215-/346/226/275/345/267/245/346/270/205/345/215/225.md +475 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//345/217/230/351/207/217/344/270/216task/347/263/273/347/273/237/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225-v2.md +847 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//350/277/220/350/241/214/347/212/266/346/200/201/351/223/276/350/267/257/351/207/215/346/236/204-/346/226/275/345/267/245/346/270/205/345/215/225v4.md +654 -0
- package//346/226/275/345/267/245/346/270/205/345/215/225//351/224/231/350/257/257/346/263/250/345/205/245/347/273/255/350/201/212-/346/226/275/345/267/245/346/270/205/345/215/225.md +471 -0
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""
|
|
2
|
+
bridges/ContextExample.py — 默认上下文提取实现
|
|
3
|
+
===============================================
|
|
4
|
+
从数据库提取当前 session 的对话上下文,排除当前 prompt。
|
|
5
|
+
代码原则:所有代码不许写try静默兜底不报错,有错必须报错。
|
|
6
|
+
|
|
7
|
+
上下文拼接三种模式(2026-09-11 增量上下文立项):
|
|
8
|
+
full — 本条之前所有可见内容(原有行为)
|
|
9
|
+
incremental — 本演员上次发言→本次发言之间的可见内容;
|
|
10
|
+
查库定起点(react_steps 按 soul_id 取 MAX(turn_id)),
|
|
11
|
+
无既往发言=「之间」为开场到现在=等价全量
|
|
12
|
+
first_full_then_incremental — 首轮全量、之后增量(查库语义下与 incremental
|
|
13
|
+
同体;独立成 def 作为 harness 侧稳定接口名)
|
|
14
|
+
路由入口 build_session_context(session, actor_info, mode)。
|
|
15
|
+
harness 接口决定 mode(DSH 宿主后端钉 first_full_then_incremental),
|
|
16
|
+
剧本无感;直连模式等不钉的调用方吃默认 full。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
import os
|
|
22
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
23
|
+
|
|
24
|
+
from femoCompiler.db_utils import _get_conn
|
|
25
|
+
from femoCompiler.FEMO_scope_resolver import parse_scope_field, ids_match_scope
|
|
26
|
+
from typing import List, Optional, Dict, Any
|
|
27
|
+
|
|
28
|
+
# ── 上下文可见性开关(2026-08-29 转写分离配套)────────────────────────
|
|
29
|
+
# 拼接上下文时各类内容的可见性:self=发言者本人(行 soul_id == 提问者),
|
|
30
|
+
# other=同房间其他角色。改这里的 0/1 即全局生效,无需动拼装逻辑。
|
|
31
|
+
# 配套:react_steps 按 step 分行存储(cot/tool_call/tool_result 各归各位),
|
|
32
|
+
# 上游节点的思考不再混在 response 里泄漏给下游。
|
|
33
|
+
VISIBILITY = {
|
|
34
|
+
"self": {"cot": 1, "response": 1, "tool": 1},
|
|
35
|
+
"other": {"cot": 0, "response": 1, "tool": 0},
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
# ── 拼接模式常量(harness 接口按此钉 runner._context_mode)──────────────
|
|
39
|
+
MODE_FULL = 'full'
|
|
40
|
+
MODE_INCREMENTAL = 'incremental'
|
|
41
|
+
MODE_FIRST_FULL_THEN_INCREMENTAL = 'first_full_then_incremental'
|
|
42
|
+
_KNOWN_MODES = (MODE_FULL, MODE_INCREMENTAL, MODE_FIRST_FULL_THEN_INCREMENTAL)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ── 演员双名制显示(2026-09-11 拍板,2026-09-12 三修定稿)────────────────
|
|
46
|
+
# 上下文里每个发言行显示「@戏中名(括号名)」:戏中名=@演员名(@ 保留,
|
|
47
|
+
# 不去重——@Eve(Eve)照写)。括号名按发言行身份取(2026-09-12 拍板):
|
|
48
|
+
# 行带 soul_id → Soul name(角色卡 soul_name)
|
|
49
|
+
# 无 soul_id 的人类发言 → user id 对应的 user name(查无此人退 uid 原样)
|
|
50
|
+
# 无 soul_id 的 AI 发言 → model id,仅 source:main(伪 soul 'main')显示
|
|
51
|
+
# 'main';其余无 soul AI 行无法认领,维持 "AI" 兜底
|
|
52
|
+
# 台账行只存 soul_id/user_id,戏中名必须由调用方把剧本 actors 定义穿线进来;
|
|
53
|
+
# 缺席(旧调用方/自定义 context)=空映射,渲染退回单名(原行为)。
|
|
54
|
+
def _actor_role_maps(actors_def) -> tuple:
|
|
55
|
+
"""从剧本 actors 定义提取「戏中名」映射(@ 保留)。
|
|
56
|
+
|
|
57
|
+
返回 (ai_soul_map, human_user_map, human_soul_map):
|
|
58
|
+
ai_soul_map soul_id → @戏中名(AI 演员,行按 soul_id 认领);
|
|
59
|
+
source:main 裸演员额外记 'main' 键(伪 soul,行上
|
|
60
|
+
soul_id='main');
|
|
61
|
+
human_user_map source(user_id) → @戏中名(人类演员,行按 user_id 认领);
|
|
62
|
+
human_soul_map soul_id → @戏中名(人类演员兜底——无 source 回退 owner 的
|
|
63
|
+
行 user_id 是真实 uid,与戏中名对不上号,只能按行上的
|
|
64
|
+
soul_id 认亲,如 `human @玩家 = soul:human` 的玩家行)。
|
|
65
|
+
同键多演员取先声明者。"""
|
|
66
|
+
ai_soul, human_user, human_soul = {}, {}, {}
|
|
67
|
+
if not actors_def:
|
|
68
|
+
return ai_soul, human_user, human_soul
|
|
69
|
+
for actor_name, adef in actors_def.items():
|
|
70
|
+
role = str(actor_name).strip()
|
|
71
|
+
if not role:
|
|
72
|
+
continue
|
|
73
|
+
if not role.startswith('@'):
|
|
74
|
+
role = f'@{role}'
|
|
75
|
+
atype = getattr(adef, 'type', None)
|
|
76
|
+
atype = getattr(atype, 'value', atype)
|
|
77
|
+
soul = getattr(adef, 'soul', None)
|
|
78
|
+
source = getattr(adef, 'source', None)
|
|
79
|
+
if atype == 'ai':
|
|
80
|
+
if soul is not None:
|
|
81
|
+
ai_soul.setdefault(str(soul), role)
|
|
82
|
+
if str(source or '').strip() == 'main':
|
|
83
|
+
ai_soul.setdefault('main', role)
|
|
84
|
+
elif atype == 'human':
|
|
85
|
+
if source is not None:
|
|
86
|
+
human_user.setdefault(str(source), role)
|
|
87
|
+
if soul is not None:
|
|
88
|
+
human_soul.setdefault(str(soul), role)
|
|
89
|
+
return ai_soul, human_user, human_soul
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _dual_name(role: str, display: str) -> str:
|
|
93
|
+
"""双名拼装:`@戏中名(Soul name)`;缺一退单名(不去重,2026-09-11
|
|
94
|
+
二次拍板——同名双写 @Eve(Eve)正是用户要的结构统一)。"""
|
|
95
|
+
display = str(display or '').strip()
|
|
96
|
+
role = str(role or '').strip()
|
|
97
|
+
if role and display:
|
|
98
|
+
return f"{role}({display})"
|
|
99
|
+
return display or role
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _get_records_visible_to(
|
|
103
|
+
user_ids: List[str] = None,
|
|
104
|
+
soul_ids: List[str] = None,
|
|
105
|
+
session_id: int = None,
|
|
106
|
+
include_ai: bool = True,
|
|
107
|
+
max_turns: int = 20,
|
|
108
|
+
offset: int = 0,
|
|
109
|
+
after_turn: Optional[int] = None,
|
|
110
|
+
) -> List[Dict[str, Any]]:
|
|
111
|
+
"""获取指定 user 或 soul 可见的对话记录(仅当前 session)。
|
|
112
|
+
|
|
113
|
+
after_turn:只取 turn_id > after_turn 的行(增量窗口;None=不过滤)。
|
|
114
|
+
"""
|
|
115
|
+
user_ids = user_ids or []
|
|
116
|
+
soul_ids = soul_ids or []
|
|
117
|
+
conn = _get_conn()
|
|
118
|
+
results = []
|
|
119
|
+
|
|
120
|
+
query = """
|
|
121
|
+
SELECT session_id, turn_id, oratio_idx, user_prompt AS content,
|
|
122
|
+
timestamp, user_id, soul_id, user_scope, soul_scope,
|
|
123
|
+
'human' AS source
|
|
124
|
+
FROM dialog
|
|
125
|
+
"""
|
|
126
|
+
conditions = []
|
|
127
|
+
params = []
|
|
128
|
+
|
|
129
|
+
if session_id is not None:
|
|
130
|
+
conditions.append("session_id = ?")
|
|
131
|
+
params.append(session_id)
|
|
132
|
+
|
|
133
|
+
if conditions:
|
|
134
|
+
query += " WHERE " + " AND ".join(conditions)
|
|
135
|
+
query += " ORDER BY session_id, turn_id, oratio_idx DESC"
|
|
136
|
+
|
|
137
|
+
cursor = conn.execute(query, params)
|
|
138
|
+
for row in cursor:
|
|
139
|
+
user_scope = parse_scope_field(row["user_scope"] or "[]")
|
|
140
|
+
soul_scope = parse_scope_field(row["soul_scope"] or "[]")
|
|
141
|
+
# 无 user 无 soul(裸 actor):不过滤——本 session 全部记录可见
|
|
142
|
+
# (无角色设定 = 无隔离;有 user/soul 时行为不变)。
|
|
143
|
+
no_filter = not user_ids and not soul_ids
|
|
144
|
+
match_user = user_ids and ids_match_scope(user_scope, user_ids)
|
|
145
|
+
match_soul = soul_ids and ids_match_scope(soul_scope, soul_ids)
|
|
146
|
+
print(f"[ctx-dbg] dialog turn={row['turn_id']} src={row['source']} "
|
|
147
|
+
f"u_scope={user_scope} s_scope={soul_scope} "
|
|
148
|
+
f"ask_u={user_ids} ask_s={soul_ids} no_filter={no_filter} "
|
|
149
|
+
f"match_user={match_user} match_soul={match_soul}")
|
|
150
|
+
if no_filter or match_user or match_soul:
|
|
151
|
+
results.append(dict(row))
|
|
152
|
+
|
|
153
|
+
if include_ai:
|
|
154
|
+
query2 = """
|
|
155
|
+
SELECT session_id, turn_id, step_idx, response AS content,
|
|
156
|
+
timestamp, soul_id, user_scope, soul_scope,
|
|
157
|
+
cot, tool_call, tool_result,
|
|
158
|
+
'ai' AS source
|
|
159
|
+
FROM react_steps
|
|
160
|
+
"""
|
|
161
|
+
if conditions:
|
|
162
|
+
query2 += " WHERE " + " AND ".join(conditions)
|
|
163
|
+
query2 += " ORDER BY session_id, turn_id, step_idx DESC"
|
|
164
|
+
|
|
165
|
+
cursor2 = conn.execute(query2, params)
|
|
166
|
+
for row in cursor2:
|
|
167
|
+
user_scope = parse_scope_field(row["user_scope"] or "[]")
|
|
168
|
+
soul_scope = parse_scope_field(row["soul_scope"] or "[]")
|
|
169
|
+
no_filter = not user_ids and not soul_ids
|
|
170
|
+
match_user = user_ids and ids_match_scope(user_scope, user_ids)
|
|
171
|
+
match_soul = soul_ids and ids_match_scope(soul_scope, soul_ids)
|
|
172
|
+
print(f"[ctx-dbg] react turn={row['turn_id']} src={row['source']} "
|
|
173
|
+
f"u_scope={user_scope} s_scope={soul_scope} "
|
|
174
|
+
f"ask_u={user_ids} ask_s={soul_ids} no_filter={no_filter} "
|
|
175
|
+
f"match_user={match_user} match_soul={match_soul}")
|
|
176
|
+
if no_filter or match_user or match_soul:
|
|
177
|
+
results.append(dict(row))
|
|
178
|
+
|
|
179
|
+
conn.close()
|
|
180
|
+
|
|
181
|
+
# 增量窗口:只保留「上次发言」之后的行(dialog/react 同一 turn 域)
|
|
182
|
+
if after_turn is not None:
|
|
183
|
+
results = [r for r in results if (r.get("turn_id", 0) or 0) > after_turn]
|
|
184
|
+
|
|
185
|
+
# 按时间戳或 turn_id + idx 降序排列(最近的在前)
|
|
186
|
+
results.sort(key=lambda r: (
|
|
187
|
+
r.get("turn_id", 0),
|
|
188
|
+
r.get("oratio_idx", 0) if r.get("source") == "human" else r.get("step_idx", 0)
|
|
189
|
+
), reverse=True)
|
|
190
|
+
# 去重(2026-08-28 加固):键加入 soul_id + user_id——不同角色/不同行种类的
|
|
191
|
+
# 同号行不再互吃(旧键曾把出题与甲思考的 react 行 (turn1,step0) 判为重复,
|
|
192
|
+
# 静默吞掉甲思考,导致甲亮答上下文丢前文)。撞键时不再静默丢行:全部保留
|
|
193
|
+
# 并高声告警——历史台账存在旧竞态写入的同键行,硬报错会炸老场次回放,故
|
|
194
|
+
# 选择"全保留+告警";新引擎 turn 号由 _alloc_turn 独占分配,正常不会再撞。
|
|
195
|
+
seen = set()
|
|
196
|
+
unique = []
|
|
197
|
+
for r in results:
|
|
198
|
+
key = (r["session_id"], r["turn_id"],
|
|
199
|
+
r.get("oratio_idx", -1) if r["source"] == "human" else r.get("step_idx", -1),
|
|
200
|
+
r["source"], str(r.get("soul_id") or ""), str(r.get("user_id") or ""))
|
|
201
|
+
if key in seen:
|
|
202
|
+
print(f"[ctx-dbg] ⚠️ 台账同键重复行(保留不丢): key={key} "
|
|
203
|
+
f"content={str(r.get('content', ''))[:60]!r}")
|
|
204
|
+
else:
|
|
205
|
+
seen.add(key)
|
|
206
|
+
unique.append(r)
|
|
207
|
+
# 截断到 max_turns
|
|
208
|
+
return unique
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _actor_scope_ids(actor_info: dict) -> tuple:
|
|
212
|
+
"""从 actor_info 提取 (user_ids, soul_ids) 提问者身份(原 findThisSession 内联逻辑)"""
|
|
213
|
+
user_ids = []
|
|
214
|
+
soul_ids = []
|
|
215
|
+
info = actor_info or {}
|
|
216
|
+
if "user" in info:
|
|
217
|
+
user_ids.append(str(info["user"]))
|
|
218
|
+
if "soul" in info:
|
|
219
|
+
soul_ids.append(str(info["soul"]))
|
|
220
|
+
return user_ids, soul_ids
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _last_speech_turn(session_id: int, soul_id: str) -> Optional[int]:
|
|
224
|
+
"""查库:该 soul 在本 session 的最后一次 AI 发言所在 turn(无发言→None)。
|
|
225
|
+
|
|
226
|
+
增量模式的唯一起点事实源——不经参数、不查内存,谁拼增量谁查询。
|
|
227
|
+
注意:裸演员 soul_id 落库为 '',共享命名空间(另案处理)。"""
|
|
228
|
+
conn = _get_conn()
|
|
229
|
+
try:
|
|
230
|
+
row = conn.execute(
|
|
231
|
+
"SELECT MAX(turn_id) AS t FROM react_steps WHERE session_id = ? AND soul_id = ?",
|
|
232
|
+
(session_id, str(soul_id or '')),
|
|
233
|
+
).fetchone()
|
|
234
|
+
t = row["t"] if row else None
|
|
235
|
+
return int(t) if t is not None else None
|
|
236
|
+
finally:
|
|
237
|
+
conn.close()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _render_context(records: List[Dict[str, Any]], soul_ids: List[str],
|
|
241
|
+
actors_def: Optional[dict] = None,
|
|
242
|
+
as_json: bool = False) -> str:
|
|
243
|
+
"""把可见记录行渲染成上下文(原 get_session_context 后半段)。
|
|
244
|
+
|
|
245
|
+
scope 过滤已由 _get_records_visible_to 完成;这里负责名字解析、react 行
|
|
246
|
+
按 (turn_id, soul_id) 分组、VISIBILITY 拼装(cot/tool 剥离在此)、排序。
|
|
247
|
+
|
|
248
|
+
as_json=False(缺省):文本形态——「[名字]:\\n内容」按序拼接(原行为)。
|
|
249
|
+
名字走双名制「@戏中名(Soul name)」(不去重),actors_def 缺席时退回
|
|
250
|
+
单名(原行为)。
|
|
251
|
+
|
|
252
|
+
as_json=True:结构化形态——发言条目列表的 JSON 串(ensure_ascii=False)。
|
|
253
|
+
每条 {"soul_id", "soul_name", "steps": [...]};steps = 该发言的逐轮轨迹:
|
|
254
|
+
- dialog 行(旁白/提醒/人类输入)天然单轮 → steps 只有一个
|
|
255
|
+
{"response": 内容};
|
|
256
|
+
- AI 发言按 react 轮逐轮展开,每轮 {"cot"?, "tool_call"?, "tool_result"?,
|
|
257
|
+
"response"?}——键是否存在 = VISIBILITY 常量裁决(别人的轮次根本不
|
|
258
|
+
带 cot/tool 键),键在 = 允许显示且非空。
|
|
259
|
+
消费口径:台词 = 最后一个非空 response;要全轨迹展示直接遍历 steps。
|
|
260
|
+
节点提醒行(femoshow-*)另带条目级 "showprompt": true。"""
|
|
261
|
+
if not records:
|
|
262
|
+
return "[]" if as_json else ""
|
|
263
|
+
|
|
264
|
+
# 排序主键(2026-08-29 换 turn 主序):turn_id 在 _alloc_turn 后=节点因果
|
|
265
|
+
# 序,par 慢分支的发言按自己节拍归位(910 实证),不再被墙钟完成时间打乱;
|
|
266
|
+
# 节点内按 timestamp、idx 兜底(兼管 legacy 撞号行)。react 行按
|
|
267
|
+
# (turn_id, soul_id) 分组、step_idx 升序拼轮,可见性由文件顶部 VISIBILITY
|
|
268
|
+
# 控制:自己=cot/response/tool 全量,别人=只拼 response(tool 可开关)。
|
|
269
|
+
# legacy 全量转写行(cot/tool 列为空)按 response 原样渲染,不做正则剥除。
|
|
270
|
+
from femoCompiler.db_utils import get_soul_by_id, get_user_by_id
|
|
271
|
+
import json
|
|
272
|
+
name_cache = {}
|
|
273
|
+
ai_soul_map, human_user_map, human_soul_map = _actor_role_maps(actors_def)
|
|
274
|
+
|
|
275
|
+
def _parse_first_id(raw):
|
|
276
|
+
"""从可能是 JSON 数组的字段中提取第一个 ID 字符串"""
|
|
277
|
+
if not raw:
|
|
278
|
+
return ""
|
|
279
|
+
if isinstance(raw, list):
|
|
280
|
+
return str(raw[0]) if raw else ""
|
|
281
|
+
if isinstance(raw, str):
|
|
282
|
+
# 尝试 JSON 解析
|
|
283
|
+
s = raw.strip()
|
|
284
|
+
if s.startswith('[') and s.endswith(']'):
|
|
285
|
+
try:
|
|
286
|
+
arr = json.loads(s)
|
|
287
|
+
if isinstance(arr, list) and arr:
|
|
288
|
+
return str(arr[0])
|
|
289
|
+
except Exception:
|
|
290
|
+
pass
|
|
291
|
+
return s
|
|
292
|
+
return str(raw)
|
|
293
|
+
|
|
294
|
+
def get_name(record):
|
|
295
|
+
source = record.get("source")
|
|
296
|
+
if source == "human":
|
|
297
|
+
uid = _parse_first_id(record.get("user_id"))
|
|
298
|
+
row_soul = _parse_first_id(record.get("soul_id", ""))
|
|
299
|
+
# 戏中名:先按行 user_id 认领(source 落库行),再按行 soul_id 兜底
|
|
300
|
+
# (无 source 回退 owner 的行)——人类演员自己的行两种键都可能带。
|
|
301
|
+
role = (human_user_map.get(uid) if uid else None) \
|
|
302
|
+
or (human_soul_map.get(row_soul) if row_soul else None)
|
|
303
|
+
if not uid and not row_soul:
|
|
304
|
+
return _dual_name(role, "用户")
|
|
305
|
+
if uid and uid.startswith('femoshow-'):
|
|
306
|
+
return "[节点提醒]"
|
|
307
|
+
if uid and uid.startswith('femo-'):
|
|
308
|
+
return None
|
|
309
|
+
# 括号名(2026-09-12 拍板):行带 soul_id → Soul name;无 soul_id
|
|
310
|
+
# → user id 对应的 user name(查无此人退 uid 原样)
|
|
311
|
+
if row_soul:
|
|
312
|
+
if row_soul not in name_cache:
|
|
313
|
+
soul = get_soul_by_id(row_soul)
|
|
314
|
+
name_cache[row_soul] = soul.get("soul_name", row_soul) if soul else row_soul
|
|
315
|
+
return _dual_name(role, name_cache[row_soul])
|
|
316
|
+
if uid not in name_cache:
|
|
317
|
+
user = get_user_by_id(uid)
|
|
318
|
+
name_cache[uid] = user.get("user_name", uid) if user else uid
|
|
319
|
+
return _dual_name(role, name_cache[uid])
|
|
320
|
+
else: # ai
|
|
321
|
+
sid = _parse_first_id(record.get("soul_id"))
|
|
322
|
+
if not sid:
|
|
323
|
+
# 裸演员行(无 soul 无 source:main,落库 soul_id=''):无键可认领,
|
|
324
|
+
# 维持 "AI" 兜底
|
|
325
|
+
return "AI"
|
|
326
|
+
if sid == 'main':
|
|
327
|
+
# source:main 裸天使伪 soul(无角色卡):括号名=model id 'main'
|
|
328
|
+
# (2026-09-12 拍板:"如果是main就显示main");戏中名按 actors_def
|
|
329
|
+
# 的 source:main 声明认领。投影窗 speaker 行走宿主 ai_name,不受此影响
|
|
330
|
+
return _dual_name(ai_soul_map.get('main'), "main")
|
|
331
|
+
if sid not in name_cache:
|
|
332
|
+
soul = get_soul_by_id(sid)
|
|
333
|
+
name_cache[sid] = soul.get("soul_name", sid) if soul else sid
|
|
334
|
+
return _dual_name(ai_soul_map.get(sid), name_cache[sid])
|
|
335
|
+
|
|
336
|
+
def _is_self(row):
|
|
337
|
+
row_soul = str(row.get("soul_id") or "")
|
|
338
|
+
return bool(soul_ids) and row_soul in {str(s) for s in soul_ids}
|
|
339
|
+
|
|
340
|
+
# react 行按 (turn_id, soul_id) 分组成一个发言块;dialog 行(旁白/提醒/
|
|
341
|
+
# 人类输入)保持逐行。items 元素=(turn_id, timestamp, idx, seq, entry, rounds):
|
|
342
|
+
# entry 是结构化发言条目(soul_id/soul_name/response[+cot/tool_results]),
|
|
343
|
+
# rounds 仅 AI 发言块带(每轮一条拼好的文本,文本形态用)。
|
|
344
|
+
ai_groups = {}
|
|
345
|
+
items = []
|
|
346
|
+
seq = 0
|
|
347
|
+
for r in records:
|
|
348
|
+
name = get_name(r)
|
|
349
|
+
if name is None:
|
|
350
|
+
continue
|
|
351
|
+
ts = r.get("timestamp", 0) or 0
|
|
352
|
+
turn = r.get("turn_id", 0) or 0
|
|
353
|
+
if r.get("source") == "ai":
|
|
354
|
+
key = (turn, str(r.get("soul_id") or ""))
|
|
355
|
+
g = ai_groups.setdefault(key, {"rows": [], "ts": ts, "name": name, "self": _is_self(r)})
|
|
356
|
+
g["rows"].append(r)
|
|
357
|
+
g["ts"] = min(g["ts"], ts)
|
|
358
|
+
else:
|
|
359
|
+
entry = {
|
|
360
|
+
"soul_id": str(r.get("soul_id") or ""),
|
|
361
|
+
"soul_name": name,
|
|
362
|
+
# 统一条目形状(2026-09-13 v2):一切发言都是 steps——dialog 行
|
|
363
|
+
# (旁白/提醒/人类输入)天然单轮,AI 行见下方逐 react 轮展开。
|
|
364
|
+
"steps": [{"response": r.get("content", "")}],
|
|
365
|
+
}
|
|
366
|
+
# femoshow-* 行 = 节点提醒(showprompt 的落库形态)——文本形态渲染成
|
|
367
|
+
# [节点提醒] 前缀(get_name 已返回),JSON 形态加标记位供消费方识别。
|
|
368
|
+
if str(r.get("user_id") or "").startswith("femoshow-"):
|
|
369
|
+
entry["showprompt"] = True
|
|
370
|
+
items.append((turn, ts, r.get("oratio_idx", 0) or 0, seq, entry, None))
|
|
371
|
+
seq += 1
|
|
372
|
+
for key in sorted(ai_groups.keys()):
|
|
373
|
+
g = ai_groups[key]
|
|
374
|
+
vis = VISIBILITY.get("self" if g["self"] else "other", VISIBILITY["other"])
|
|
375
|
+
rounds = []
|
|
376
|
+
steps = []
|
|
377
|
+
for row in sorted(g["rows"], key=lambda x: (x.get("step_idx", 0) or 0)):
|
|
378
|
+
parts = []
|
|
379
|
+
step = {}
|
|
380
|
+
cot_s = str(row.get("cot") or "").strip()
|
|
381
|
+
tool_result = str(row.get("tool_result") or "").strip()
|
|
382
|
+
tool_call = str(row.get("tool_call") or "").strip()
|
|
383
|
+
# 注意:SELECT 里 response AS content——ai 行的发言在 content 键,
|
|
384
|
+
# 读 response 键会永远拿到空(915 场实测:Eve 谜面整块消失)。
|
|
385
|
+
resp_text = str(row.get("content") or row.get("response") or "").strip()
|
|
386
|
+
# 可见性语义(2026-09-13 v2):VISIBILITY 决定「键是否存在」——
|
|
387
|
+
# 别人的轮次根本不带 cot/tool 键;键在 = 允许显示且非空。
|
|
388
|
+
# 每行一个 step(react 轮),逐轮全量保留,消费方自行取舍
|
|
389
|
+
# (现状:台词 = 最后一个非空 response;将来要全轨迹展示直接遍历)。
|
|
390
|
+
if vis.get("cot") and cot_s:
|
|
391
|
+
parts.append(f"[思考] {cot_s}")
|
|
392
|
+
step["cot"] = cot_s
|
|
393
|
+
if vis.get("tool"):
|
|
394
|
+
if tool_result:
|
|
395
|
+
parts.append(tool_result)
|
|
396
|
+
step["tool_result"] = tool_result
|
|
397
|
+
elif tool_call:
|
|
398
|
+
parts.append(f"[工具调用] {tool_call}")
|
|
399
|
+
if tool_call:
|
|
400
|
+
# 轨迹完整性(2026-09-13 v2):call 与 result 都独立留键——
|
|
401
|
+
# 文本形态保持 result 优先的旧排版,JSON 不丢调用原文。
|
|
402
|
+
step.setdefault("tool_call", tool_call)
|
|
403
|
+
if vis.get("response") and resp_text:
|
|
404
|
+
parts.append(resp_text)
|
|
405
|
+
step["response"] = resp_text
|
|
406
|
+
if parts:
|
|
407
|
+
rounds.append("\n".join(parts))
|
|
408
|
+
if step:
|
|
409
|
+
steps.append(step)
|
|
410
|
+
if not rounds:
|
|
411
|
+
continue
|
|
412
|
+
entry = {"soul_id": key[1], "soul_name": g["name"], "steps": steps}
|
|
413
|
+
# idx 取大数:同一 turn 内 react 块永远排在 prompt/show/人类输入之后
|
|
414
|
+
items.append((key[0], g["ts"], 10 ** 9, seq, entry, rounds))
|
|
415
|
+
seq += 1
|
|
416
|
+
items.sort(key=lambda it: (it[0], it[1], it[2], it[3]))
|
|
417
|
+
if as_json:
|
|
418
|
+
return json.dumps([it[4] for it in items], ensure_ascii=False)
|
|
419
|
+
lines = []
|
|
420
|
+
for _, _, _, _, entry, rounds in items:
|
|
421
|
+
if rounds is None:
|
|
422
|
+
lines.append(f"[{entry['soul_name']}]:\n{entry['steps'][0]['response']}")
|
|
423
|
+
else:
|
|
424
|
+
lines.append(f"[{entry['soul_name']}]:\n" + "\n\n".join(rounds))
|
|
425
|
+
return "\n\n".join(lines)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
# ═══ 三种拼接模式(只写拼接过程,工具全走上面的公共函数)════════════════
|
|
429
|
+
|
|
430
|
+
def _fetch_visible(session_id: int, actor_info: dict, mode: str):
|
|
431
|
+
"""按模式取本演员可见记录(full/incremental/JSON 形态共用的取数口)。
|
|
432
|
+
|
|
433
|
+
full=从头全量;incremental/FFTI=上次本人发言之后(查库定起点,无既往
|
|
434
|
+
发言=从头)。返回 (records, soul_ids)。"""
|
|
435
|
+
user_ids, soul_ids = _actor_scope_ids(actor_info)
|
|
436
|
+
after_turn = None
|
|
437
|
+
if mode in (MODE_INCREMENTAL, MODE_FIRST_FULL_THEN_INCREMENTAL):
|
|
438
|
+
ask_soul = soul_ids[0] if soul_ids else ''
|
|
439
|
+
after_turn = _last_speech_turn(session_id, ask_soul)
|
|
440
|
+
records = _get_records_visible_to(
|
|
441
|
+
user_ids=user_ids if user_ids else None,
|
|
442
|
+
soul_ids=soul_ids if soul_ids else None,
|
|
443
|
+
session_id=session_id,
|
|
444
|
+
include_ai=True,
|
|
445
|
+
max_turns=999999, # 足够大的数,取所有记录
|
|
446
|
+
)
|
|
447
|
+
return records, soul_ids
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def full(session_id: int, actor_info: dict, actors_def: dict = None) -> str:
|
|
451
|
+
"""全量:本条之前所有可见内容(原有行为)。"""
|
|
452
|
+
records, soul_ids = _fetch_visible(session_id, actor_info, MODE_FULL)
|
|
453
|
+
print(f"[ctx-dbg] session={session_id} full 模式检索到 {len(records)} 条可见记录 "
|
|
454
|
+
f"(ask_u={actor_info.get('user') if actor_info else None}, ask_s={soul_ids})")
|
|
455
|
+
return _render_context(records, soul_ids, actors_def)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def incremental(session_id: int, actor_info: dict, actors_def: dict = None) -> str:
|
|
459
|
+
"""增量:本演员上次发言→本次发言之间的可见内容(AI 人类 showprompt)。
|
|
460
|
+
|
|
461
|
+
起点查库定(react_steps 按 soul_id 取 MAX(turn_id));无既往发言时
|
|
462
|
+
「之间」= 开场到现在 = 等价全量。AI 发言不带 cot/tool(VISIBILITY)。"""
|
|
463
|
+
records, soul_ids = _fetch_visible(session_id, actor_info, MODE_INCREMENTAL)
|
|
464
|
+
ask_soul = soul_ids[0] if soul_ids else ''
|
|
465
|
+
if not records:
|
|
466
|
+
print(f"[ctx-dbg] session={session_id} incremental(soul={ask_soul!r})无可见记录 → 空串")
|
|
467
|
+
return ""
|
|
468
|
+
print(f"[ctx-dbg] session={session_id} incremental(soul={ask_soul!r})"
|
|
469
|
+
f"检索到 {len(records)} 条可见记录")
|
|
470
|
+
return _render_context(records, soul_ids, actors_def)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def first_full_then_incremental(session_id: int, actor_info: dict,
|
|
474
|
+
actors_def: dict = None) -> str:
|
|
475
|
+
"""首轮全量、之后增量(DSH harness 接口钉死的模式)。
|
|
476
|
+
|
|
477
|
+
查库语义下与 incremental 同体(无既往发言时 incremental 本身就退化为
|
|
478
|
+
全量);独立成 def 保持 harness 接口名稳定,将来语义分化只改这里。"""
|
|
479
|
+
return incremental(session_id, actor_info, actors_def)
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def build_session_context(session_id: int, actor_info: dict,
|
|
483
|
+
mode: str = MODE_FULL,
|
|
484
|
+
actors_def: dict = None) -> str:
|
|
485
|
+
"""上下文拼接路由入口:按 mode 分发到三种拼接方案。
|
|
486
|
+
|
|
487
|
+
mode 由调用方(harness 接口/直连)传入;未知 mode 硬报错。
|
|
488
|
+
actors_def 可选(剧本 actors 定义,双名制显示用)——block_collector
|
|
489
|
+
默认路由传入;不传=单名渲染(原行为),自定义 context 老调用方零感知。"""
|
|
490
|
+
if mode == MODE_FULL:
|
|
491
|
+
return full(session_id, actor_info, actors_def)
|
|
492
|
+
if mode == MODE_INCREMENTAL:
|
|
493
|
+
return incremental(session_id, actor_info, actors_def)
|
|
494
|
+
if mode == MODE_FIRST_FULL_THEN_INCREMENTAL:
|
|
495
|
+
return first_full_then_incremental(session_id, actor_info, actors_def)
|
|
496
|
+
raise ValueError(
|
|
497
|
+
f"未知 context mode: {mode!r}(可用:{', '.join(_KNOWN_MODES)})")
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def resolve_context_mode(session_id: int, actor_info: dict, mode: str) -> str:
|
|
501
|
+
"""FFTI 落地裁决:该演员查库无既往发言 = 本拍按 full(首次),否则
|
|
502
|
+
incremental。其余 mode 原样返回。block_collector 用它决定 system 层
|
|
503
|
+
blocks(basic_safety/basic_output/soul/user_info)是否随包——首次全量
|
|
504
|
+
带 system 层,之后增量只带增量面(2026-09-13 上下文 JSON 化配套)。"""
|
|
505
|
+
if mode != MODE_FIRST_FULL_THEN_INCREMENTAL:
|
|
506
|
+
return mode
|
|
507
|
+
_, soul_ids = _actor_scope_ids(actor_info or {})
|
|
508
|
+
ask_soul = soul_ids[0] if soul_ids else ''
|
|
509
|
+
return MODE_FULL if _last_speech_turn(session_id, ask_soul) is None else MODE_INCREMENTAL
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def build_session_context_json(session_id: int, actor_info: dict,
|
|
513
|
+
mode: str = MODE_FULL,
|
|
514
|
+
actors_def: dict = None) -> str:
|
|
515
|
+
"""build_session_context 的 JSON 形态(2026-09-13 上下文 JSON 化):
|
|
516
|
+
返回发言条目列表的 JSON 串,每条 {"soul_id", "soul_name", "steps": [...]}
|
|
517
|
+
——steps 为逐轮轨迹(dialog 行单轮;AI 行按 react 轮展开,每轮 cot /
|
|
518
|
+
tool_call / tool_result / response 按键存在性表达 VISIBILITY)。
|
|
519
|
+
mode 语义与 build_session_context 完全一致;未知 mode 同样硬报错。"""
|
|
520
|
+
if mode not in _KNOWN_MODES:
|
|
521
|
+
raise ValueError(
|
|
522
|
+
f"未知 context mode: {mode!r}(可用:{', '.join(_KNOWN_MODES)})")
|
|
523
|
+
records, soul_ids = _fetch_visible(session_id, actor_info, mode)
|
|
524
|
+
return _render_context(records, soul_ids, actors_def, as_json=True)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
# ═══ 兼容薄壳(老调用方零感知)══════════════════════════════════════════
|
|
528
|
+
|
|
529
|
+
def get_session_context(
|
|
530
|
+
session_id: int,
|
|
531
|
+
user_ids: List[str] = None,
|
|
532
|
+
soul_ids: List[str] = None,
|
|
533
|
+
actors_def: dict = None,
|
|
534
|
+
) -> str:
|
|
535
|
+
"""获取当前 session 的完整对话上下文(兼容壳 = full 模式的 collect+render)"""
|
|
536
|
+
records = _get_records_visible_to(
|
|
537
|
+
user_ids=user_ids,
|
|
538
|
+
soul_ids=soul_ids,
|
|
539
|
+
session_id=session_id,
|
|
540
|
+
include_ai=True,
|
|
541
|
+
max_turns=999999, # 足够大的数,取所有记录
|
|
542
|
+
)
|
|
543
|
+
print(f"[ctx-dbg] session={session_id} 检索到 {len(records)} 条可见记录 "
|
|
544
|
+
f"(ask_u={user_ids}, ask_s={soul_ids})")
|
|
545
|
+
return _render_context(records, soul_ids or [], actors_def)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def findThisSession(
|
|
549
|
+
session: int,
|
|
550
|
+
actor_info: dict,
|
|
551
|
+
actors_def: dict = None,
|
|
552
|
+
) -> str:
|
|
553
|
+
"""默认 context 提取入口(兼容壳 = full 模式)"""
|
|
554
|
+
context = build_session_context(session, actor_info, MODE_FULL, actors_def)
|
|
555
|
+
return context
|