femo-plugin 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/docs/ActiveRoadmaps/Func/345/201/234/346/255/242/350/257/255/344/271/211-/351/201/227/345/274/203/346/216/245/347/273/255-/346/226/275/345/267/245/346/270/205/345/215/225.md +91 -0
  2. package/docs/ActiveRoadmaps//345/217/214user/346/226/275/345/267/245/346/270/205/345/215/225.md +326 -0
  3. 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 +616 -569
  4. package/femo2host/AGENTS.md +1 -1
  5. package/femo2host/femoGenConnector/engine-client.mjs +7 -2
  6. package/femo2host/femoGenConnector/file-dialogs.mjs +108 -2
  7. package/femo2host/femoToolcall/chronica.py +99 -19
  8. package/femo2host/femo_api.py +14 -1
  9. package/femo2host/host/actor-core.d.mts +25 -0
  10. package/femo2host/host/actor-core.mjs +72 -0
  11. package/femo2host/host/cast-core.d.mts +3 -0
  12. package/femo2host/host/cast-core.mjs +14 -0
  13. package/femo2host/host/daemon-client.mjs +59 -10
  14. package/femo2host/host/hub-render-core.d.mts +2 -0
  15. package/femo2host/host/hub-render-core.mjs +6 -2
  16. package/femo2host/host/run-state-core.d.mts +4 -0
  17. package/femo2host/host/run-state-core.mjs +4 -0
  18. package/femo2host/host/speech-core.mjs +11 -4
  19. package/femo2host/host/tools-core.d.mts +11 -0
  20. package/femo2host/host/tools-core.mjs +39 -0
  21. package/femo2host/mailbox.py +66 -20
  22. package/femo2host/projectionCenter/app.css +61 -0
  23. package/femo2host/projectionCenter/composer.mjs +69 -11
  24. package/femo2host/projectionCenter/identity.mjs +131 -0
  25. package/femo2host/projectionCenter/index.html +54 -1
  26. package/femo2host/projectionCenter/main.mjs +209 -33
  27. package/femo2host/projectionCenter/panels.mjs +108 -16
  28. package/femo2host/projectionCenter/render.mjs +813 -695
  29. package/femo2host/projectionCenter/state.mjs +30 -0
  30. package/femo2host/projectionCenter/util.mjs +28 -0
  31. package/femo2host/projection_hub.py +9917 -8422
  32. package/femo2host/python/femo_bridge.py +270 -32
  33. package/femo2host/python/femo_daemon.py +1528 -1209
  34. package/femo2host/python/mirror_window.py +237 -0
  35. package/femoBridges/ContextExample.py +113 -71
  36. package/femoCompiler/AGENTS.md +1 -0
  37. package/femoCompiler/FEMO_parser.py +2641 -2567
  38. package/femoCompiler/FEMO_runtime.py +201 -44
  39. package/femoCompiler/FEMO_scope_resolver.py +26 -12
  40. package/femoCompiler/block_collector.py +24 -27
  41. package/femoCompiler/db_utils.py +560 -503
  42. package/femoCompiler/femoAsync.py +466 -436
  43. package/femoCompiler/func_registry.py +74 -0
  44. package/femoCompiler/protocol.py +127 -127
  45. package/femoCompiler/save_dialog.py +497 -446
  46. 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 +229 -142
  47. package/femoExamples/AI/350/201/212/345/244/251/345/256/244/random_wait_time.py +91 -2
  48. package/femoExamples/LuxFiat/luxfiat-loop.femo +0 -1
  49. package/femoExamples/LuxFiat/luxfiat-simple.femo +23 -24
  50. package/femoExamples/debug/347/245/236/345/231/250/debug/347/245/236/345/231/250.femo +221 -222
  51. package/femoExamples/discussion.femo +72 -72
  52. 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-9/344/272/272/351/242/204/345/245/263/347/214/216.femo +1 -2
  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 +1 -2
  54. package/femoExamples//347/213/274/344/272/272/346/235/200//347/213/274/344/272/272/346/235/200.femo +1 -2
  55. 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 +1 -1
  56. 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 +1 -1
  57. package/femoGen/src/femoParser.jsx +14 -0
  58. package/hostAdapter/dshAdapter/host/femo-skill.ts +23 -10
  59. package/hostAdapter/dshAdapter/host/routes/projection-input.ts +3 -0
  60. package/hostAdapter/dshAdapter/lib/client.js +20 -2
  61. package/hostAdapter/dshAdapter/lib/client.js.map +2 -2
  62. package/hostAdapter/dshAdapter/lib/main.js +161 -18
  63. package/hostAdapter/dshAdapter/lib/main.js.map +3 -3
  64. package/hostAdapter/dshAdapter/package.json +1 -1
  65. package/hostAdapter/webAdapter/console/index.html +12 -4
  66. package/hostAdapter/webAdapter/extension/background.js +16 -5
  67. package/hostAdapter/webAdapter/extension/seat-agent-core.js +2 -1
  68. package/hostAdapter/webAdapter/extension/sidepanel/actors.mjs +101 -0
  69. package/hostAdapter/webAdapter/extension/sidepanel/main.mjs +81 -20
  70. package/hostAdapter/webAdapter/extension/sidepanel/reconnect.mjs +33 -0
  71. package/hostAdapter/webAdapter/extension/sidepanel/run-control.mjs +22 -11
  72. package/hostAdapter/webAdapter/extension/sidepanel/seats.mjs +6 -20
  73. package/hostAdapter/webAdapter/extension/sidepanel.html +30 -8
  74. package/hostAdapter/webAdapter/native/install-native-host.mjs +1 -0
  75. package/hostAdapter/webAdapter/native/register-core.mjs +69 -28
  76. package/hostAdapter/webAdapter/native/web-launcher.sh +37 -0
  77. package/hostAdapter/webAdapter/readme.md +51 -10
  78. package/hostAdapter/webAdapter/server/bridge.mjs +1 -1
  79. package/hostAdapter/webAdapter/server/runtime.mjs +51 -5
  80. package/hostAdapter/webAdapter/server/seats.mjs +11 -6
  81. package/hostAdapter/webAdapter/server/service.mjs +108 -15
  82. package/hostAdapter/webAdapter/shared/seats-core.mjs +31 -6
  83. package/hostAdapter/webAdapter/sites/chatglm.cn/inject.js +76 -4
  84. package/hostAdapter/webAdapter/sites/chatgpt.com/SITE.md +1 -0
  85. package/hostAdapter/webAdapter/sites/chatgpt.com/content.js +13 -4
  86. package/hostAdapter/webAdapter/sites/chatgpt.com/inject.js +40 -4
  87. package/hostAdapter/webAdapter/start-service.command +16 -0
  88. package/hostAdapter/webAdapter/tests/chatgpt-parser.test.mjs +37 -0
  89. package/hostAdapter/webAdapter/tests/runtime.test.mjs +42 -0
  90. package/hostAdapter/webAdapter/tests/seats-core.test.mjs +37 -1
  91. package/hostAdapter/webAdapter/tests/smoke-service.mjs +261 -232
  92. package/hostAdapter/zcodeAdapter/runtime/speech-collect.mjs +6 -0
  93. package/hostAdapter/zcodeAdapter/tests/unbound-actors.test.mjs +51 -0
  94. package/package.json +1 -1
  95. package//350/257/255/346/263/225/346/226/207/346/241/243.md +1222 -1202
@@ -1,446 +1,497 @@
1
- #femoCompiler/save_dialog.py
2
- """
3
- SaveDialog.py — 对话存储模块
4
- ===============================
5
- 负责将人类发言和 AI 发言存入数据库,
6
- 自动处理 scope 注入、去重、turn 和 step_idx 管理。
7
- """
8
-
9
- #from db_utils import insert_dialog_record, insert_ai_record
10
- import threading
11
- import queue
12
- import json
13
- import time
14
-
15
- def _build_scope(action_scope, actor_info, meta_owner, raw_action_scope=None):
16
- """
17
- 构建最终的 user_scope 和 soul_scope。
18
- 自动注入发言者自己和 meta.owner,去重,删除 0。
19
-
20
- raw_action_scope: action 的原始 scope 字符串(未解析)。仅用于 scope: self
21
- 保留字段判定(2026-08-31 猫猫拍板):显式写了 self → 走下面同一条"注入发言
22
- 者自己+meta.owner"路径。判定基于原始字符串、独立于 action_scope 是否为空——
23
- 空 scope 的语义之后要改,self 的语义不能绑在"空"上面(self≠空,self=显式
24
- 只给自己+owner)。不传(None)时行为与旧版完全一致。
25
- """
26
- if raw_action_scope is not None and str(raw_action_scope).strip().lower() == 'self':
27
- action_scope = ([], [])
28
- user_scope = [str(x) for x in action_scope[0]] if action_scope else []
29
- soul_scope = [str(x) for x in action_scope[1]] if action_scope else []
30
-
31
- # 注入发言者自己(字符串)
32
- if 'user' in actor_info:
33
- uid = str(actor_info['user'])
34
- if uid not in user_scope:
35
- user_scope.append(uid)
36
- if 'soul' in actor_info and actor_info['soul'] is not None:
37
- sid = str(actor_info['soul'])
38
- if sid not in soul_scope:
39
- soul_scope.append(sid)
40
-
41
- # 注入 meta.owner(保持字符串)
42
- for uid in (meta_owner or []):
43
- uid_str = str(uid)
44
- if uid_str not in user_scope:
45
- user_scope.append(uid_str)
46
-
47
- # 删除无效值(空字符串、'0' 等)
48
- user_scope = [x for x in user_scope if x and x != '0']
49
- soul_scope = [x for x in soul_scope if x and x != '0']
50
-
51
- # 去重排序
52
- user_scope = sorted(set(user_scope))
53
- soul_scope = sorted(set(soul_scope))
54
-
55
- return user_scope, soul_scope
56
-
57
-
58
- def _do_insert_dialog(session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
59
- user_scope, soul_scope, work_mode="chat", **kwargs):
60
- from femoCompiler.db_utils import _get_conn
61
- conn = _get_conn()
62
- try:
63
- final_user_id_json = json.dumps(user_id) if isinstance(user_id, list) else (user_id or '[]')
64
- # 下行只为了调试打印,不要删除
65
- #print(f"[DEBUG _do_insert_dialog] final user_id={user_id!r}, json={json.dumps(user_id) if isinstance(user_id, list) else (user_id or '[]')}"),
66
- conn.execute("""
67
- INSERT INTO dialog
68
- (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
69
- user_scope, soul_scope, work_mode, timestamp)
70
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
71
- """, (
72
- session_id, turn_id, oratio_idx,
73
- user_prompt,
74
- json.dumps([str(x) for x in user_id]) if isinstance(user_id, list) else (str(user_id) if user_id else '[]'),
75
- soul_id or '',
76
- json.dumps([str(x) for x in (user_scope or [])]),
77
- json.dumps([str(x) for x in (soul_scope or [])]),
78
- work_mode,
79
- int(time.time()),
80
- ))
81
- conn.commit()
82
- finally:
83
- conn.close()
84
-
85
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ _do_insert_ai:唯一调用方是 _process_item 的 'ai' 分支,
86
- # 而该分支唯一的入队口 enqueue_ai 的唯一调用方 save_ai_turn 已于 2026-09-18 整体注释停用
87
- # (转写分离 2026-08-29 后由合写取代)——整条传递性死亡(双窗口交叉扫描+逐项复核)。
88
- # 无报错数日后整段删除(含本注)。
89
- # def _do_insert_ai(session_id, turn_id, step_idx, response, soul_id,
90
- # user_scope, soul_scope, model_id="", cot="", tool_call="", tool_result="", **kwargs):
91
- # from femoCompiler.db_utils import _get_conn
92
- # conn = _get_conn()
93
- # try:
94
- # conn.execute("""
95
- # INSERT INTO react_steps
96
- # (session_id, turn_id, step_idx, timestamp, response, soul_id,
97
- # user_scope, soul_scope, cot, model_id, tool_call, tool_result)
98
- # VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
99
- # """, (
100
- # session_id, turn_id, step_idx,
101
- # int(time.time()),
102
- # response,
103
- # soul_id or '',
104
- # json.dumps([str(x) for x in (user_scope or [])]),
105
- # json.dumps([str(x) for x in (soul_scope or [])]),
106
- # cot, model_id,
107
- # tool_call, tool_result,
108
- # ))
109
- # conn.commit()
110
- # finally:
111
- # conn.close()
112
- # ━━━ 观察期退役段结束:_do_insert_ai ━━━
113
-
114
-
115
-
116
-
117
- def save_human_turn(session_id, turn_id, oratio_idx, user_input, actor_info, meta_owner,
118
- action_scope=None, is_node_prompt=False, femo_id: str = '', prompt_type='prompt',
119
- raw_action_scope=None):
120
- """
121
- 将人类发言或节点 prompt 入队(后台线程写入数据库)
122
- """
123
- user_scope, soul_scope = _build_scope(action_scope, actor_info, meta_owner, raw_action_scope)
124
- # 构建 user_id 列表
125
- if is_node_prompt and femo_id:
126
- if prompt_type == 'showprompt':
127
- user_id_list = [f'femoshow-{femo_id}']
128
- else:
129
- user_id_list = [f'femo-{femo_id}']
130
- #print(f"[DEBUG save_human_turn] node mode, user_id_list={user_id_list}")
131
- else:
132
- raw_user = actor_info.get('user')
133
- user_id_list = [str(raw_user)] if raw_user else []
134
- #print(f"[DEBUG save_human_turn] normal mode, raw_user={raw_user!r}, user_id_list={user_id_list}")
135
- soul_id = str(actor_info['soul']) if actor_info.get('soul') and not is_node_prompt else ''
136
-
137
-
138
- event = save_queue.enqueue_human(
139
- session_id=session_id,
140
- turn_id=turn_id,
141
- oratio_idx=oratio_idx,
142
- user_prompt=user_input,
143
- user_id=user_id_list,
144
- soul_id=soul_id,
145
- user_scope=user_scope,
146
- soul_scope=soul_scope,
147
- )
148
- print(f"[SaveDialog] 💬 节点/人类发言已入队: session={session_id}, turn={turn_id}, oratio={oratio_idx}")
149
- return event
150
-
151
-
152
- # ── 已停用(2026-09-18):save_ai_turn 是转写分离(2026-08-29)之前的单行写法,
153
- # 全仓已无调用点——AI 节点现在一律走下面的 save_ai_finish 收尾合写(showprompt
154
- # 行 + 全部 react step 同一事务)。先注释保留、多跑几天无异常再删。
155
- # 注:SaveQueue.enqueue_ai 也只剩它一个调用方,同样待观察。
156
- #
157
- # def save_ai_turn(session_id, turn_id, step_idx, response, actor_info, meta_owner,
158
- # model_id="", thinking="", action_scope=None, raw_action_scope=None):
159
- # """
160
- # 将 AI 发言入队(后台线程写入数据库)
161
- # """
162
- # user_scope, soul_scope = _build_scope(action_scope, actor_info, meta_owner, raw_action_scope)
163
- # soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
164
- #
165
- # event = save_queue.enqueue_ai(
166
- # session_id=session_id,
167
- # turn_id=turn_id,
168
- # step_idx=step_idx,
169
- # response=response,
170
- # soul_id=soul_id,
171
- # model_id=model_id,
172
- # cot=thinking,
173
- # user_scope=user_scope,
174
- # soul_scope=soul_scope,
175
- # )
176
- # print(f"[SaveDialog] 🤖 AI 发言已入队: session={session_id}, turn={turn_id}, step={step_idx}")
177
- # return event
178
-
179
-
180
- def _do_insert_group(session_id, entries):
181
- """单事务多行写入(2026-08-29 合写):entries 里全部行一次 commit——
182
- 要么全有要么全无,消灭「有 show 没发言」的半行。异常 rollback 后 raise
183
- (不吞错)。entries 元素按 kind 区分:
184
- dialog_show → dialog 表 showprompt 行(femoshow-*)
185
- node_prompt → dialog 表 节点 prompt 行(femo-*;2026-09-27 收卷一拍:随
186
- 发言同事务落库,不再于节点开始时提前落)
187
- human_input → dialog 表 玩家输入行
188
- ai_step → react_steps 表 一轮转写(cot/tool_call/tool_result 各归各位)
189
- """
190
- from femoCompiler.db_utils import _get_conn
191
- conn = _get_conn()
192
- try:
193
- for e in entries:
194
- kind = e['kind']
195
- ts = int(time.time())
196
- if kind == 'dialog_show':
197
- conn.execute("""INSERT INTO dialog
198
- (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
199
- user_scope, soul_scope, work_mode, timestamp)
200
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
201
- (session_id, e['turn_id'], e['oratio_idx'], e['text'],
202
- json.dumps([f"femoshow-{e['femo_id']}"]), '',
203
- json.dumps([str(x) for x in (e['user_scope'] or [])]),
204
- json.dumps([str(x) for x in (e['soul_scope'] or [])]),
205
- 'chat', ts))
206
- elif kind == 'human_input':
207
- conn.execute("""INSERT INTO dialog
208
- (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
209
- user_scope, soul_scope, work_mode, timestamp)
210
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
211
- (session_id, e['turn_id'], e['oratio_idx'], e['text'],
212
- json.dumps([str(e['user_id'])]) if e['user_id'] else '[]',
213
- e['soul_id'] or '',
214
- json.dumps([str(x) for x in (e['user_scope'] or [])]),
215
- json.dumps([str(x) for x in (e['soul_scope'] or [])]),
216
- 'chat', ts))
217
- elif kind == 'node_prompt':
218
- conn.execute("""INSERT INTO dialog
219
- (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
220
- user_scope, soul_scope, work_mode, timestamp)
221
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
222
- (session_id, e['turn_id'], e['oratio_idx'], e['text'],
223
- json.dumps([f"femo-{e['femo_id']}"]), '',
224
- json.dumps([str(x) for x in (e['user_scope'] or [])]),
225
- json.dumps([str(x) for x in (e['soul_scope'] or [])]),
226
- 'chat', ts))
227
- elif kind == 'ai_step':
228
- conn.execute("""INSERT INTO react_steps
229
- (session_id, turn_id, step_idx, timestamp, response, soul_id,
230
- user_scope, soul_scope, cot, model_id, tool_call, tool_result)
231
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
232
- (session_id, e['turn_id'], e['step_idx'], ts, e['response'],
233
- e['soul_id'] or '',
234
- json.dumps([str(x) for x in (e['user_scope'] or [])]),
235
- json.dumps([str(x) for x in (e['soul_scope'] or [])]),
236
- e.get('cot', ''), e.get('model_id', ''),
237
- e.get('tool_call', ''), e.get('tool_result', '')))
238
- else:
239
- raise ValueError(f"未知合写行类型: {kind}")
240
- conn.commit()
241
- except Exception:
242
- conn.rollback()
243
- raise
244
- finally:
245
- conn.close()
246
-
247
-
248
- def save_ai_finish(session_id, turn_id, showprompt, steps, actor_info, meta_owner,
249
- action_scope=None, femo_id="unknown", model_id="", raw_action_scope=None,
250
- node_prompt=None):
251
- """AI 节点收尾合写(2026-08-29 转写分离配套;2026-09-27 收卷一拍):prompt、
252
- showprompt 与全部 react step 行同一事务落库——要不然都有,要不然都没有,
253
- 消灭半行。turn 号由调用方在收卷时刻现取(永远新鲜):并行分支在等待 LLM 的
254
- 几十秒里会把开跑时的占位号推前,迟到的发言落旧号会被增量窗口
255
- (turn > 交付游标)永久过滤(job 2613 实证)。
256
-
257
- showprompt: 渲染后的 showprompt 文本(None/空 = 无 showprompt 的节点);
258
- steps: [{step, cot, reply, toolCall, toolResult}](转写分离结构),
259
- 空 steps 回退为单空 react 行(与旧行为对齐)。
260
- node_prompt: 渲染后的节点 prompt 文本(None/空 = 无 prompt)——收卷一拍随
261
- 发言落库,不再于节点开始时提前落。
262
- model_id: 模型标识(可空,落库 react_steps.model_id 列)。"""
263
- user_scope, soul_scope = _build_scope(action_scope, actor_info, meta_owner, raw_action_scope)
264
- soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
265
- entries = []
266
- if node_prompt:
267
- entries.append({'kind': 'node_prompt', 'turn_id': turn_id, 'oratio_idx': 0,
268
- 'text': node_prompt, 'femo_id': femo_id,
269
- 'user_scope': user_scope, 'soul_scope': soul_scope})
270
- if showprompt:
271
- entries.append({'kind': 'dialog_show', 'turn_id': turn_id, 'oratio_idx': 1,
272
- 'text': showprompt, 'femo_id': femo_id,
273
- 'user_scope': user_scope, 'soul_scope': soul_scope})
274
- if not steps:
275
- steps = [{'step': 0, 'cot': '', 'reply': '', 'toolCall': '', 'toolResult': ''}]
276
- for idx, s in enumerate(steps):
277
- if not isinstance(s, dict):
278
- s = {'reply': str(s)}
279
- entries.append({'kind': 'ai_step', 'turn_id': turn_id,
280
- 'step_idx': int(s.get('step', idx) or idx),
281
- 'response': str(s.get('reply', '') or ''),
282
- 'soul_id': soul_id, 'model_id': model_id,
283
- 'cot': str(s.get('cot', '') or ''),
284
- 'tool_call': str(s.get('toolCall', '') or ''),
285
- 'tool_result': str(s.get('toolResult', '') or ''),
286
- 'user_scope': user_scope, 'soul_scope': soul_scope})
287
- print(f"[SaveDialog] 🤖 AI 收尾合写已入队: session={session_id}, turn={turn_id}, rows={len(entries)}")
288
- return save_queue.enqueue_group(session_id=session_id, entries=entries)
289
-
290
-
291
- def save_human_finish(session_id, turn_id, showprompt, user_input, input_oratio,
292
- actor_info, meta_owner, action_scope=None, femo_id="unknown",
293
- raw_action_scope=None, node_prompt=None):
294
- """human 节点收尾合写(2026-08-29;2026-09-27 收卷一拍):prompt、showprompt
295
- 与玩家输入行同一事务落库,turn 号由调用方在收卷时刻现取(永远新鲜)——
296
- 并行分支推号后,迟到的人类发言落旧号会被增量窗口永久过滤(job 2613 实证)。
297
- 输入为空(如超时放行)时仍落 prompt 行(node_prompt)——「超时留痕」语义随
298
- 行搬家:台账上留得住"这个节点等过人"。"""
299
- user_scope, soul_scope = _build_scope(action_scope, actor_info, meta_owner, raw_action_scope)
300
- raw_user = actor_info.get('user')
301
- soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
302
- entries = []
303
- if node_prompt:
304
- entries.append({'kind': 'node_prompt', 'turn_id': turn_id, 'oratio_idx': 0,
305
- 'text': node_prompt, 'femo_id': femo_id,
306
- 'user_scope': user_scope, 'soul_scope': soul_scope})
307
- if showprompt:
308
- entries.append({'kind': 'dialog_show', 'turn_id': turn_id, 'oratio_idx': 1,
309
- 'text': showprompt, 'femo_id': femo_id,
310
- 'user_scope': user_scope, 'soul_scope': soul_scope})
311
- if user_input:
312
- entries.append({'kind': 'human_input', 'turn_id': turn_id,
313
- 'oratio_idx': input_oratio, 'text': user_input,
314
- 'user_id': str(raw_user) if raw_user else '', 'soul_id': soul_id,
315
- 'user_scope': user_scope, 'soul_scope': soul_scope})
316
- print(f"[SaveDialog] 💬 human 收尾合写已入队: session={session_id}, turn={turn_id}, rows={len(entries)}")
317
- if not entries:
318
- return None
319
- return save_queue.enqueue_group(session_id=session_id, entries=entries)
320
-
321
-
322
- class SaveQueue:
323
- def __init__(self):
324
- self._queue = queue.Queue()
325
- self._running = True
326
- self._worker = threading.Thread(target=self._worker_loop, daemon=True)
327
- self._worker.start()
328
-
329
- def _worker_loop(self):
330
- """不死循环:工作线程崩溃后自动重启"""
331
- while self._running:
332
- try:
333
- self._run()
334
- except Exception as e:
335
- import traceback
336
- traceback.print_exc()
337
- #print(f"[SaveQueue] 工作线程异常退出,3 秒后重启: {e}")
338
- time.sleep(3)
339
-
340
- def _enqueue_with_event(self, typ, kwargs):
341
- """入队一个任务,返回一个 threading.Event,任务处理完成后会 set"""
342
- event = threading.Event()
343
- self._queue.put((typ, kwargs, event))
344
- return event
345
-
346
- def _run(self):
347
- print("[SaveQueue] 后台线程已启动")
348
- while True:
349
- try:
350
- item = self._queue.get(timeout=0.1)
351
-
352
- if item is None:
353
- # 毒丸修复(2026-08-24):哨兵必须 task_done 归账。否则
354
- # Queue 的 unfinished 计数永远 ≥1,同进程第二轮 run 的
355
- # wait_empty 卡死在 queue.join() → flow_done 永不发出
356
- # → 宿主 running 永远 true(「时灵时不灵」+ 新会话被
357
- # 「已有FEMO脚本在运行中」拒绝的共同根因)。
358
- self._queue.task_done()
359
- break
360
- if len(item) == 2:
361
- typ, kwargs = item
362
- event = threading.Event()
363
-
364
- else:
365
- typ, kwargs, event = item
366
-
367
- try:
368
- self._process_item((typ, kwargs))
369
- except Exception as e:
370
- print(f"[SaveQueue] 处理失败: {e}")
371
- finally:
372
- event.set()
373
-
374
- self._queue.task_done()
375
- except queue.Empty:
376
- if not self._running:
377
- break
378
- continue
379
- except Exception as e:
380
- print(f"[SaveQueue] 运行错误: {e}")
381
- import traceback
382
- traceback.print_exc()
383
-
384
- def _process_item(self, item):
385
- """实际写入数据库,item 是 (type, kwargs)"""
386
- typ, kwargs = item
387
- try:
388
- if typ == 'human':
389
- _do_insert_dialog(**kwargs)
390
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ 'ai' 分支随 _do_insert_ai/enqueue_ai 一并退役
391
- # (唯一入队口 save_ai_turn 已于 2026-09-18 注释停用,此处永不可达)。
392
- # elif typ == 'ai':
393
- # _do_insert_ai(**kwargs)
394
- # ━━━ 观察期退役段结束:'ai' 分支 ━━━
395
- elif typ == 'group':
396
- _do_insert_group(**kwargs)
397
- except Exception as e:
398
- import traceback
399
- traceback.print_exc()
400
- print(f"[SaveQueue] ❌ 写入失败: {e}")
401
-
402
- def enqueue_human(self, **kwargs):
403
- event = self._enqueue_with_event('human', kwargs)
404
- #print(f"[SaveQueue] enqueue_human: 任务已入队, event={event}")
405
- return event
406
-
407
- # ━━━ 已退役·观察期(2026-09-26 起)━━━ enqueue_ai:唯一调用方 save_ai_turn 已于 2026-09-18
408
- # 整体注释停用(转写分离后由 enqueue_group 合写取代),全仓再无调用(双窗口交叉扫描+逐项复核)。
409
- # 无报错数日后整段删除(含本注)。
410
- # def enqueue_ai(self, **kwargs):
411
- # event = self._enqueue_with_event('ai', kwargs)
412
- # #print(f"[SaveQueue] enqueue_ai: 任务已入队, event={event}")
413
- # return event
414
- # ━━━ 观察期退役段结束:enqueue_ai ━━━
415
-
416
- def enqueue_group(self, **kwargs):
417
- """合写入队(2026-08-29):多行同一事务,event 在整组 commit 后 set"""
418
- return self._enqueue_with_event('group', kwargs)
419
-
420
- def wait_empty(self, timeout=None):
421
- """等待队列清空后停止后台线程。
422
-
423
- D2 修复(运行状态链路重构 §5.8):原实现 `self._queue.join()` 无超时且
424
- timeout 参数被无视(只喂给了 _worker.join)——队列卡住时收尾挂死
425
- (取消路径必经此处,不修则"worker 秒退"承诺打折)。改为轮询
426
- unfinished_tasks(0.2s sleep,至 timeout 或清零):正常清零路径返回
427
- 语义不变(调用点未用返回值);run_async 取消路径传的 10 从此真实生效
428
- (timeout=None 保持现语义等清零)。"""
429
- deadline = None if timeout is None else time.monotonic() + timeout
430
- while self._queue.unfinished_tasks > 0:
431
- if deadline is not None and time.monotonic() >= deadline:
432
- break
433
- time.sleep(0.2)
434
- self._running = False
435
- self._queue.put(None) # 发送停止信号
436
- self._worker.join(timeout=timeout)
437
- #print("[SaveDialog] 所有数据已写入,后台线程已停止")
438
-
439
- def restart(self):
440
- """重新启动后台线程(用于连续运行多个任务)"""
441
- if not self._running:
442
- self._running = True
443
- self._worker = threading.Thread(target=self._worker_loop, daemon=True)
444
- self._worker.start()
445
-
446
- save_queue = SaveQueue()
1
+ #femoCompiler/save_dialog.py
2
+ """
3
+ SaveDialog.py — 对话存储模块
4
+ ===============================
5
+ 负责将人类发言和 AI 发言存入数据库,
6
+ 自动处理 scope 注入、去重、turn 和 step_idx 管理。
7
+ """
8
+
9
+ #from db_utils import insert_dialog_record, insert_ai_record
10
+ import threading
11
+ import queue
12
+ import json
13
+ import time
14
+
15
+ def _build_scope(action_scope, actor_info, job_users, raw_action_scope=None):
16
+ """
17
+ 构建最终的 user_scope、soul_scope 和 actor_scope。
18
+
19
+ user_scope(2026-10-11 双user 刀B 定稿口径):**参与权**——哪个人类用户
20
+ 拥有或参与了这段记录。每一行都抄当前 Job 登记的全部人类 user(job_users,
21
+ 运行时登记账直抄),不再注入 meta.owner(剧本不写 user,owner 已退役)。
22
+ 戏内可见性归 actor_scope 和 soul_scope,不归它。
23
+
24
+ actor_scope(2026-10-11 双user 刀A):scope 表达式展开出的 @actor 名单,
25
+ 存法与 soul_scope 同构——剧本 scope 写了谁就存谁;发言者自己恒注入(自己
26
+ 说的话自己永远可见);scope: self → actor_scope 只写发言者自己(作者拍板
27
+ 「actor scope 和 soul scope 里面,就写他自己就好了」)。
28
+
29
+ raw_action_scope: action 的原始 scope 字符串(未解析)。仅用于 scope: self
30
+ 保留字段判定(2026-08-31 猫猫拍板):显式写了 self → 走下面同一条"注入发言
31
+ 者自己"路径。判定基于原始字符串、独立于 action_scope 是否为空。
32
+ 不传(None)时行为与旧版完全一致。
33
+ """
34
+ if raw_action_scope is not None and str(raw_action_scope).strip().lower() == 'self':
35
+ action_scope = ([], [], [])
36
+ user_scope = [str(x) for x in action_scope[0]] if action_scope else []
37
+ soul_scope = [str(x) for x in action_scope[1]] if action_scope else []
38
+ actor_scope = [str(x) for x in action_scope[2]] if action_scope else []
39
+
40
+ # user_scope=全场登记 user(参与权,2026-10-11 拍板:所有行都抄)
41
+ for uid in (job_users or []):
42
+ uid_str = str(uid)
43
+ if uid_str and uid_str not in user_scope:
44
+ user_scope.append(uid_str)
45
+
46
+ # 注入发言者自己(字符串)
47
+ if 'user' in actor_info:
48
+ uid = str(actor_info['user'])
49
+ if uid not in user_scope:
50
+ user_scope.append(uid)
51
+ if 'soul' in actor_info and actor_info['soul'] is not None:
52
+ sid = str(actor_info['soul'])
53
+ if sid not in soul_scope:
54
+ soul_scope.append(sid)
55
+ if actor_info.get('actor'):
56
+ # @ 纪律:声明表正身原样照抄,不摘也不加。
57
+ actor_tag = str(actor_info['actor'])
58
+ if actor_tag not in actor_scope:
59
+ actor_scope.append(actor_tag)
60
+
61
+ # 删除无效值(空字符串、'0' 等)
62
+ user_scope = [x for x in user_scope if x and x != '0']
63
+ soul_scope = [x for x in soul_scope if x and x != '0']
64
+ actor_scope = [x for x in actor_scope if x and x != '0']
65
+
66
+ # 去重排序
67
+ user_scope = sorted(set(user_scope))
68
+ soul_scope = sorted(set(soul_scope))
69
+ actor_scope = sorted(set(actor_scope))
70
+
71
+ return user_scope, soul_scope, actor_scope
72
+
73
+
74
+ def _do_insert_dialog(session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
75
+ user_scope, soul_scope, actor: str = '', work_mode="chat",
76
+ actor_scope=None, **kwargs):
77
+ from femoCompiler.db_utils import _get_conn
78
+ conn = _get_conn()
79
+ try:
80
+ final_user_id_json = json.dumps(user_id) if isinstance(user_id, list) else (user_id or '[]')
81
+ # 下行只为了调试打印,不要删除
82
+ #print(f"[DEBUG _do_insert_dialog] final user_id={user_id!r}, json={json.dumps(user_id) if isinstance(user_id, list) else (user_id or '[]')}"),
83
+ conn.execute("""
84
+ INSERT INTO dialog
85
+ (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
86
+ actor, user_scope, soul_scope, actor_scope, work_mode, timestamp)
87
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
88
+ """, (
89
+ session_id, turn_id, oratio_idx,
90
+ user_prompt,
91
+ json.dumps([str(x) for x in user_id]) if isinstance(user_id, list) else (str(user_id) if user_id else '[]'),
92
+ soul_id or '',
93
+ str(actor or ''),
94
+ json.dumps([str(x) for x in (user_scope or [])]),
95
+ json.dumps([str(x) for x in (soul_scope or [])]),
96
+ json.dumps([str(x) for x in (actor_scope or [])]),
97
+ work_mode,
98
+ int(time.time()),
99
+ ))
100
+ conn.commit()
101
+ finally:
102
+ conn.close()
103
+
104
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ _do_insert_ai:唯一调用方是 _process_item 的 'ai' 分支,
105
+ # 而该分支唯一的入队口 enqueue_ai 的唯一调用方 save_ai_turn 已于 2026-09-18 整体注释停用
106
+ # (转写分离 2026-08-29 后由合写取代)——整条传递性死亡(双窗口交叉扫描+逐项复核)。
107
+ # 无报错数日后整段删除(含本注)。
108
+ # def _do_insert_ai(session_id, turn_id, step_idx, response, soul_id,
109
+ # user_scope, soul_scope, model_id="", cot="", tool_call="", tool_result="", **kwargs):
110
+ # from femoCompiler.db_utils import _get_conn
111
+ # conn = _get_conn()
112
+ # try:
113
+ # conn.execute("""
114
+ # INSERT INTO react_steps
115
+ # (session_id, turn_id, step_idx, timestamp, response, soul_id,
116
+ # user_scope, soul_scope, cot, model_id, tool_call, tool_result)
117
+ # VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
118
+ # """, (
119
+ # session_id, turn_id, step_idx,
120
+ # int(time.time()),
121
+ # response,
122
+ # soul_id or '',
123
+ # json.dumps([str(x) for x in (user_scope or [])]),
124
+ # json.dumps([str(x) for x in (soul_scope or [])]),
125
+ # cot, model_id,
126
+ # tool_call, tool_result,
127
+ # ))
128
+ # conn.commit()
129
+ # finally:
130
+ # conn.close()
131
+ # ━━━ 观察期退役段结束:_do_insert_ai ━━━
132
+
133
+
134
+
135
+
136
+ def save_human_turn(session_id, turn_id, oratio_idx, user_input, actor_info, job_users,
137
+ action_scope=None, is_node_prompt=False, femo_id: str = '', prompt_type='prompt',
138
+ raw_action_scope=None):
139
+ """
140
+ 将人类发言或节点 prompt 入队(后台线程写入数据库)。
141
+
142
+ actor 列(2026-10-10 双人类落库加固):本口只落幕后行——节点 prompt 与
143
+ notice(is_node_prompt=True 两种调用,全仓仅此两处),幕后行的发言者
144
+ 统一记 'femo'(用户拍板),由本函数内强制、调用方传不传都一样——
145
+ 单一事实源防漂移。真执行者发言走 save_human_finish(带 actor 参数)。"""
146
+ user_scope, soul_scope, actor_scope = _build_scope(action_scope, actor_info, job_users, raw_action_scope)
147
+ # 构建 user_id 列表
148
+ if is_node_prompt and femo_id:
149
+ if prompt_type == 'showprompt':
150
+ user_id_list = [f'femoshow-{femo_id}']
151
+ else:
152
+ user_id_list = [f'femo-{femo_id}']
153
+ #print(f"[DEBUG save_human_turn] node mode, user_id_list={user_id_list}")
154
+ else:
155
+ raw_user = actor_info.get('user')
156
+ user_id_list = [str(raw_user)] if raw_user else []
157
+ #print(f"[DEBUG save_human_turn] normal mode, raw_user={raw_user!r}, user_id_list={user_id_list}")
158
+ soul_id = str(actor_info['soul']) if actor_info.get('soul') and not is_node_prompt else ''
159
+ actor = 'femo' if is_node_prompt else ''
160
+
161
+
162
+ event = save_queue.enqueue_human(
163
+ session_id=session_id,
164
+ turn_id=turn_id,
165
+ oratio_idx=oratio_idx,
166
+ user_prompt=user_input,
167
+ user_id=user_id_list,
168
+ soul_id=soul_id,
169
+ actor=actor,
170
+ user_scope=user_scope,
171
+ soul_scope=soul_scope,
172
+ actor_scope=actor_scope,
173
+ )
174
+ print(f"[SaveDialog] 💬 节点/人类发言已入队: session={session_id}, turn={turn_id}, oratio={oratio_idx}")
175
+ return event
176
+
177
+
178
+ # ── 已停用(2026-09-18):save_ai_turn 是转写分离(2026-08-29)之前的单行写法,
179
+ # 全仓已无调用点——AI 节点现在一律走下面的 save_ai_finish 收尾合写(showprompt
180
+ # 行 + 全部 react step 同一事务)。先注释保留、多跑几天无异常再删。
181
+ # 注:SaveQueue.enqueue_ai 也只剩它一个调用方,同样待观察。
182
+ #
183
+ # def save_ai_turn(session_id, turn_id, step_idx, response, actor_info, meta_owner,
184
+ # model_id="", thinking="", action_scope=None, raw_action_scope=None):
185
+ # """
186
+ # 将 AI 发言入队(后台线程写入数据库)
187
+ # """
188
+ # user_scope, soul_scope = _build_scope(action_scope, actor_info, meta_owner, raw_action_scope)
189
+ # soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
190
+ #
191
+ # event = save_queue.enqueue_ai(
192
+ # session_id=session_id,
193
+ # turn_id=turn_id,
194
+ # step_idx=step_idx,
195
+ # response=response,
196
+ # soul_id=soul_id,
197
+ # model_id=model_id,
198
+ # cot=thinking,
199
+ # user_scope=user_scope,
200
+ # soul_scope=soul_scope,
201
+ # )
202
+ # print(f"[SaveDialog] 🤖 AI 发言已入队: session={session_id}, turn={turn_id}, step={step_idx}")
203
+ # return event
204
+
205
+
206
+ def _do_insert_group(session_id, entries):
207
+ """单事务多行写入(2026-08-29 合写):entries 里全部行一次 commit——
208
+ 要么全有要么全无,消灭「有 show 没发言」的半行。异常 rollback 后 raise
209
+ (不吞错)。entries 元素按 kind 区分:
210
+ dialog_show → dialog 表 showprompt 行(femoshow-*)
211
+ node_prompt → dialog 表 节点 prompt 行(femo-*;2026-09-27 收卷一拍:随
212
+ 发言同事务落库,不再于节点开始时提前落)
213
+ human_input → dialog 表 玩家输入行
214
+ ai_step → react_steps 表 一轮转写(cot/tool_call/tool_result 各归各位)
215
+ """
216
+ from femoCompiler.db_utils import _get_conn
217
+ conn = _get_conn()
218
+ try:
219
+ for e in entries:
220
+ kind = e['kind']
221
+ ts = int(time.time())
222
+ if kind == 'dialog_show':
223
+ conn.execute("""INSERT INTO dialog
224
+ (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
225
+ actor, user_scope, soul_scope, actor_scope, work_mode, timestamp)
226
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
227
+ (session_id, e['turn_id'], e['oratio_idx'], e['text'],
228
+ json.dumps([f"femoshow-{e['femo_id']}"]), '',
229
+ e.get('actor', ''),
230
+ json.dumps([str(x) for x in (e['user_scope'] or [])]),
231
+ json.dumps([str(x) for x in (e['soul_scope'] or [])]),
232
+ json.dumps([str(x) for x in (e['actor_scope'] or [])]),
233
+ 'chat', ts))
234
+ elif kind == 'human_input':
235
+ conn.execute("""INSERT INTO dialog
236
+ (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
237
+ actor, user_scope, soul_scope, actor_scope, work_mode, timestamp)
238
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
239
+ (session_id, e['turn_id'], e['oratio_idx'], e['text'],
240
+ json.dumps([str(e['user_id'])]) if e['user_id'] else '[]',
241
+ e['soul_id'] or '',
242
+ e.get('actor', ''),
243
+ json.dumps([str(x) for x in (e['user_scope'] or [])]),
244
+ json.dumps([str(x) for x in (e['soul_scope'] or [])]),
245
+ json.dumps([str(x) for x in (e['actor_scope'] or [])]),
246
+ 'chat', ts))
247
+ elif kind == 'node_prompt':
248
+ conn.execute("""INSERT INTO dialog
249
+ (session_id, turn_id, oratio_idx, user_prompt, user_id, soul_id,
250
+ actor, user_scope, soul_scope, actor_scope, work_mode, timestamp)
251
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
252
+ (session_id, e['turn_id'], e['oratio_idx'], e['text'],
253
+ json.dumps([f"femo-{e['femo_id']}"]), '',
254
+ e.get('actor', ''),
255
+ json.dumps([str(x) for x in (e['user_scope'] or [])]),
256
+ json.dumps([str(x) for x in (e['soul_scope'] or [])]),
257
+ json.dumps([str(x) for x in (e['actor_scope'] or [])]),
258
+ 'chat', ts))
259
+ elif kind == 'ai_step':
260
+ conn.execute("""INSERT INTO react_steps
261
+ (session_id, turn_id, step_idx, timestamp, response, soul_id,
262
+ actor, user_scope, soul_scope, actor_scope, cot, model_id, tool_call, tool_result)
263
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
264
+ (session_id, e['turn_id'], e['step_idx'], ts, e['response'],
265
+ e['soul_id'] or '',
266
+ e.get('actor', ''),
267
+ json.dumps([str(x) for x in (e['user_scope'] or [])]),
268
+ json.dumps([str(x) for x in (e['soul_scope'] or [])]),
269
+ json.dumps([str(x) for x in (e['actor_scope'] or [])]),
270
+ e.get('cot', ''), e.get('model_id', ''),
271
+ e.get('tool_call', ''), e.get('tool_result', '')))
272
+ else:
273
+ raise ValueError(f"未知合写行类型: {kind}")
274
+ conn.commit()
275
+ except Exception:
276
+ conn.rollback()
277
+ raise
278
+ finally:
279
+ conn.close()
280
+
281
+
282
+ def save_ai_finish(session_id, turn_id, showprompt, steps, actor_info, job_users,
283
+ action_scope=None, femo_id="unknown", model_id="", raw_action_scope=None,
284
+ node_prompt=None, actor=''):
285
+ """AI 节点收尾合写(2026-08-29 转写分离配套;2026-09-27 收卷一拍):prompt、
286
+ showprompt 与全部 react step 行同一事务落库——要不然都有,要不然都没有,
287
+ 消灭半行。turn 号由调用方在收卷时刻现取(永远新鲜):并行分支在等待 LLM 的
288
+ 几十秒里会把开跑时的占位号推前,迟到的发言落旧号会被增量窗口
289
+ (turn > 交付游标)永久过滤(job 2613 实证)。
290
+
291
+ showprompt: 渲染后的 showprompt 文本(None/空 = 无 showprompt 的节点);
292
+ steps: [{step, cot, reply, toolCall, toolResult}](转写分离结构),
293
+ 空 steps 回退为单空 react 行(与旧行为对齐)。
294
+ node_prompt: 渲染后的节点 prompt 文本(None/空 = 无 prompt)——收卷一拍随
295
+ 发言落库,不再于节点开始时提前落。
296
+ model_id: 模型标识(可空,落库 react_steps.model_id 列)。
297
+ actor: 执行者角色名(2026-10-10,带 @ 或空;只落**发言行**——用户拍板:
298
+ AI 台词记执行者,随同的 prompt/show 行是脚本幕后/旁白、actor 记 'femo';
299
+ 缺省空=老调用方/无执行者极简形态)。"""
300
+ user_scope, soul_scope, actor_scope = _build_scope(action_scope, actor_info, job_users, raw_action_scope)
301
+ soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
302
+ entries = []
303
+ if node_prompt:
304
+ entries.append({'kind': 'node_prompt', 'turn_id': turn_id, 'oratio_idx': 0,
305
+ 'text': node_prompt, 'femo_id': femo_id,
306
+ 'actor': 'femo',
307
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
308
+ 'actor_scope': actor_scope})
309
+ if showprompt:
310
+ entries.append({'kind': 'dialog_show', 'turn_id': turn_id, 'oratio_idx': 1,
311
+ 'text': showprompt, 'femo_id': femo_id,
312
+ 'actor': 'femo',
313
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
314
+ 'actor_scope': actor_scope})
315
+ if not steps:
316
+ steps = [{'step': 0, 'cot': '', 'reply': '', 'toolCall': '', 'toolResult': ''}]
317
+ for idx, s in enumerate(steps):
318
+ if not isinstance(s, dict):
319
+ s = {'reply': str(s)}
320
+ entries.append({'kind': 'ai_step', 'turn_id': turn_id,
321
+ 'step_idx': int(s.get('step', idx) or idx),
322
+ 'response': str(s.get('reply', '') or ''),
323
+ 'soul_id': soul_id, 'model_id': model_id, 'actor': actor,
324
+ 'cot': str(s.get('cot', '') or ''),
325
+ 'tool_call': str(s.get('toolCall', '') or ''),
326
+ 'tool_result': str(s.get('toolResult', '') or ''),
327
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
328
+ 'actor_scope': actor_scope})
329
+ print(f"[SaveDialog] 🤖 AI 收尾合写已入队: session={session_id}, turn={turn_id}, rows={len(entries)}")
330
+ return save_queue.enqueue_group(session_id=session_id, entries=entries)
331
+
332
+
333
+ def save_human_finish(session_id, turn_id, showprompt, user_input, input_oratio,
334
+ actor_info, job_users, action_scope=None, femo_id="unknown",
335
+ raw_action_scope=None, node_prompt=None, actor=''):
336
+ """human 节点收尾合写(2026-08-29;2026-09-27 收卷一拍):prompt、showprompt
337
+ 与玩家输入行同一事务落库,turn 号由调用方在收卷时刻现取(永远新鲜)——
338
+ 并行分支推号后,迟到的人类发言落旧号会被增量窗口永久过滤(job 2613 实证)。
339
+ 输入为空(如超时放行)时仍落 prompt 行(node_prompt)——「超时留痕」语义随
340
+ 行搬家:台账上留得住"这个节点等过人"。
341
+ actor: 执行者角色名(2026-10-10,带 @ 或空;只落**输入行**——用户拍板:
342
+ 人类台词记执行者,随同的 prompt/show 行是脚本幕后/旁白、actor 记 'femo';
343
+ 缺省空=极简剧本无 actor)。"""
344
+ user_scope, soul_scope, actor_scope = _build_scope(action_scope, actor_info, job_users, raw_action_scope)
345
+ raw_user = actor_info.get('user')
346
+ soul_id = str(actor_info['soul']) if actor_info.get('soul') else ''
347
+ entries = []
348
+ if node_prompt:
349
+ entries.append({'kind': 'node_prompt', 'turn_id': turn_id, 'oratio_idx': 0,
350
+ 'text': node_prompt, 'femo_id': femo_id,
351
+ 'actor': 'femo',
352
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
353
+ 'actor_scope': actor_scope})
354
+ if showprompt:
355
+ entries.append({'kind': 'dialog_show', 'turn_id': turn_id, 'oratio_idx': 1,
356
+ 'text': showprompt, 'femo_id': femo_id,
357
+ 'actor': 'femo',
358
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
359
+ 'actor_scope': actor_scope})
360
+ if user_input:
361
+ entries.append({'kind': 'human_input', 'turn_id': turn_id,
362
+ 'oratio_idx': input_oratio, 'text': user_input,
363
+ 'user_id': str(raw_user) if raw_user else '', 'soul_id': soul_id,
364
+ 'actor': actor,
365
+ 'user_scope': user_scope, 'soul_scope': soul_scope,
366
+ 'actor_scope': actor_scope})
367
+ print(f"[SaveDialog] 💬 human 收尾合写已入队: session={session_id}, turn={turn_id}, rows={len(entries)}")
368
+ if not entries:
369
+ return None
370
+ return save_queue.enqueue_group(session_id=session_id, entries=entries)
371
+
372
+
373
+ class SaveQueue:
374
+ def __init__(self):
375
+ self._queue = queue.Queue()
376
+ self._running = True
377
+ self._worker = threading.Thread(target=self._worker_loop, daemon=True)
378
+ self._worker.start()
379
+
380
+ def _worker_loop(self):
381
+ """不死循环:工作线程崩溃后自动重启"""
382
+ while self._running:
383
+ try:
384
+ self._run()
385
+ except Exception as e:
386
+ import traceback
387
+ traceback.print_exc()
388
+ #print(f"[SaveQueue] 工作线程异常退出,3 秒后重启: {e}")
389
+ time.sleep(3)
390
+
391
+ def _enqueue_with_event(self, typ, kwargs):
392
+ """入队一个任务,返回一个 threading.Event,任务处理完成后会 set"""
393
+ event = threading.Event()
394
+ self._queue.put((typ, kwargs, event))
395
+ return event
396
+
397
+ def _run(self):
398
+ print("[SaveQueue] 后台线程已启动")
399
+ while True:
400
+ try:
401
+ item = self._queue.get(timeout=0.1)
402
+
403
+ if item is None:
404
+ # 毒丸修复(2026-08-24):哨兵必须 task_done 归账。否则
405
+ # Queue 的 unfinished 计数永远 ≥1,同进程第二轮 run 的
406
+ # wait_empty 卡死在 queue.join() → flow_done 永不发出
407
+ # → 宿主 running 永远 true(「时灵时不灵」+ 新会话被
408
+ # 「已有FEMO脚本在运行中」拒绝的共同根因)。
409
+ self._queue.task_done()
410
+ break
411
+ if len(item) == 2:
412
+ typ, kwargs = item
413
+ event = threading.Event()
414
+
415
+ else:
416
+ typ, kwargs, event = item
417
+
418
+ try:
419
+ self._process_item((typ, kwargs))
420
+ except Exception as e:
421
+ print(f"[SaveQueue] 处理失败: {e}")
422
+ finally:
423
+ event.set()
424
+
425
+ self._queue.task_done()
426
+ except queue.Empty:
427
+ if not self._running:
428
+ break
429
+ continue
430
+ except Exception as e:
431
+ print(f"[SaveQueue] 运行错误: {e}")
432
+ import traceback
433
+ traceback.print_exc()
434
+
435
+ def _process_item(self, item):
436
+ """实际写入数据库,item 是 (type, kwargs)"""
437
+ typ, kwargs = item
438
+ try:
439
+ if typ == 'human':
440
+ _do_insert_dialog(**kwargs)
441
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ 'ai' 分支随 _do_insert_ai/enqueue_ai 一并退役
442
+ # (唯一入队口 save_ai_turn 已于 2026-09-18 注释停用,此处永不可达)。
443
+ # elif typ == 'ai':
444
+ # _do_insert_ai(**kwargs)
445
+ # ━━━ 观察期退役段结束:'ai' 分支 ━━━
446
+ elif typ == 'group':
447
+ _do_insert_group(**kwargs)
448
+ except Exception as e:
449
+ import traceback
450
+ traceback.print_exc()
451
+ print(f"[SaveQueue] ❌ 写入失败: {e}")
452
+
453
+ def enqueue_human(self, **kwargs):
454
+ event = self._enqueue_with_event('human', kwargs)
455
+ #print(f"[SaveQueue] enqueue_human: 任务已入队, event={event}")
456
+ return event
457
+
458
+ # ━━━ 已退役·观察期(2026-09-26 起)━━━ enqueue_ai:唯一调用方 save_ai_turn 已于 2026-09-18
459
+ # 整体注释停用(转写分离后由 enqueue_group 合写取代),全仓再无调用(双窗口交叉扫描+逐项复核)。
460
+ # 无报错数日后整段删除(含本注)。
461
+ # def enqueue_ai(self, **kwargs):
462
+ # event = self._enqueue_with_event('ai', kwargs)
463
+ # #print(f"[SaveQueue] enqueue_ai: 任务已入队, event={event}")
464
+ # return event
465
+ # ━━━ 观察期退役段结束:enqueue_ai ━━━
466
+
467
+ def enqueue_group(self, **kwargs):
468
+ """合写入队(2026-08-29):多行同一事务,event 在整组 commit 后 set"""
469
+ return self._enqueue_with_event('group', kwargs)
470
+
471
+ def wait_empty(self, timeout=None):
472
+ """等待队列清空后停止后台线程。
473
+
474
+ D2 修复(运行状态链路重构 §5.8):原实现 `self._queue.join()` 无超时且
475
+ timeout 参数被无视(只喂给了 _worker.join)——队列卡住时收尾挂死
476
+ (取消路径必经此处,不修则"worker 秒退"承诺打折)。改为轮询
477
+ unfinished_tasks(0.2s sleep,至 timeout 或清零):正常清零路径返回
478
+ 语义不变(调用点未用返回值);run_async 取消路径传的 10 从此真实生效
479
+ (timeout=None 保持现语义等清零)。"""
480
+ deadline = None if timeout is None else time.monotonic() + timeout
481
+ while self._queue.unfinished_tasks > 0:
482
+ if deadline is not None and time.monotonic() >= deadline:
483
+ break
484
+ time.sleep(0.2)
485
+ self._running = False
486
+ self._queue.put(None) # 发送停止信号
487
+ self._worker.join(timeout=timeout)
488
+ #print("[SaveDialog] 所有数据已写入,后台线程已停止")
489
+
490
+ def restart(self):
491
+ """重新启动后台线程(用于连续运行多个任务)"""
492
+ if not self._running:
493
+ self._running = True
494
+ self._worker = threading.Thread(target=self._worker_loop, daemon=True)
495
+ self._worker.start()
496
+
497
+ save_queue = SaveQueue()