hit-cxf
2026-04-02 57e08ce2f0ecbac8a5efa8a3c13f0a157f0a8956
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
# -*- coding: utf-8 -*-
"""
阶段1: 编剧智能体 - 多轮LLM交互生成结构化剧本JSON
流程: Logline → 节拍表(4幕) → 分场大纲(逐幕) → JSON结构化提取(带校验重试)
"""
 
import os
import re
import json
import asyncio
import logging
import string
import random
from datetime import datetime, timezone
from typing import Any, Optional, Dict
 
from prompts.loader import load_prompt_with_fallback
 
def _get_script_prompt(name: str, lang: str = "zh") -> str:
    return load_prompt_with_fallback("script", name, lang, "zh")
 
from .base_agent import AgentInterface
 
# 导入提示词加载器
from prompts.loader import load_prompt
 
logger = logging.getLogger(__name__)
 
ACT_NAMES_ZH = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"}
ACT_NAMES_EN = {1: "Inciting Incident", 2: "Break into Two", 3: "Dark Night of the Soul", 4: "Finale"}
 
class ScriptWriterAgent(AgentInterface):
    """编剧智能体:多轮LLM交互 → 结构化剧本JSON"""
 
    def __init__(self):
        super().__init__(name="ScriptWriter")
 
    # ─── JSON 提取 ───
 
    @staticmethod
    def _extract_json_from_text(text: str) -> Optional[dict]:
        """从LLM输出中提取JSON对象"""
        text = text.strip()
        text = re.sub(r'^```(?:json)?\s*', '', text)
        text = re.sub(r'\s*```$', '', text)
        text = text.strip()
 
        try:
            return json.loads(text)
        except json.JSONDecodeError:
            pass
 
        start = text.find('{')
        end = text.rfind('}')
        if start != -1 and end != -1 and end > start:
            try:
                return json.loads(text[start:end + 1])
            except json.JSONDecodeError:
                pass
        return None
 
    @staticmethod
    def _extract_json_array_from_text(text: str) -> Optional[list]:
        """从LLM输出中提取JSON数组"""
        text = text.strip()
        # 去除 markdown 代码块标记(支持多行)
        text = re.sub(r'```(?:json)?\s*\n?', '', text)
        text = text.strip()
 
        try:
            result = json.loads(text)
            if isinstance(result, list):
                return result
            # LLM 有时返回对象而非数组,尝试包装
            if isinstance(result, dict):
                return [result]
        except json.JSONDecodeError:
            pass
 
        start = text.find('[')
        end = text.rfind(']')
        if start != -1 and end != -1 and end > start:
            try:
                result = json.loads(text[start:end + 1])
                if isinstance(result, list):
                    return result
            except json.JSONDecodeError:
                pass
 
        # 尝试匹配多个独立 JSON 对象
        objects = []
        for m in re.finditer(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', text):
            try:
                obj = json.loads(m.group())
                if isinstance(obj, dict) and 'logline' in obj:
                    objects.append(obj)
            except json.JSONDecodeError:
                continue
        if objects:
            return objects
 
        return None
 
    @staticmethod
    def _gen_id(prefix: str = "char") -> str:
        return f"{prefix}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}"
 
    # ─── 保存结果 ───
 
    def _save_result(self, json_data: dict, sid: str, is_zh: bool):
        """保存结构化剧本JSON到结果文件"""
        from config import settings
        script_dir = os.path.join(settings.RESULT_DIR, 'script')
        os.makedirs(script_dir, exist_ok=True)
 
        result_file = os.path.join(script_dir, f'script_{sid}.json')
        results = {}
        if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
            with open(result_file, 'r', encoding='utf-8') as f:
                results = json.load(f)
 
        results.setdefault(str(sid), {})['script_json'] = json_data
        with open(result_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=4, ensure_ascii=False)
 
    def _save_progress(self, sid: str, phase: str, data: dict):
        """保存剧本生成的中间进度状态到结果文件"""
        from config import settings
        script_dir = os.path.join(settings.RESULT_DIR, 'script')
        os.makedirs(script_dir, exist_ok=True)
 
        result_file = os.path.join(script_dir, f'script_{sid}.json')
        results = {}
        if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
            with open(result_file, 'r', encoding='utf-8') as f:
                results = json.load(f)
 
        # 初始化 progress 字段
        results.setdefault(str(sid), {}).setdefault('progress', {})
 
        # 保存当前阶段信息
        results[str(sid)]['progress']['current_phase'] = phase
        results[str(sid)]['progress']['updated_at'] = datetime.now(timezone.utc).isoformat()
 
        # 根据阶段保存对应的数据
        if phase == 'logline_check':
            # 创意检查结果
            results[str(sid)]['progress']['idea_analyzed'] = data.get('idea_analyzed', False)
            results[str(sid)]['progress']['logline_extracted'] = data.get('logline_summary')
        elif phase == 'logline_generation':
            # 生成的候选 logline
            results[str(sid)]['progress']['logline_options'] = data.get('logline_options', [])
        elif phase == 'logline_confirmed':
            # 用户选择的 logline
            results[str(sid)]['progress']['selected_logline'] = data.get('selected_logline')
        elif phase == 'mode_selection':
            # 用户选择的模式
            results[str(sid)]['progress']['selected_mode'] = data.get('selected_mode')
        elif phase == 'script_generation':
            # 完整剧本已生成
            results[str(sid)]['progress']['script_generated'] = True
            results[str(sid)]['progress']['title'] = data.get('title')
 
        with open(result_file, 'w', encoding='utf-8') as f:
            json.dump(results, f, indent=4, ensure_ascii=False)
 
    # ─── 核心流程 ───
 
    async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
 
        # 检查当前阶段,避免重复生成 logline
        current_phase = input_data.get("phase", "")
        selected_logline = input_data.get("selected_logline")
        selected_mode = input_data.get("selected_mode")
 
        # 如果已选择模式,直接生成剧本
        if selected_mode:
            # 如果 selected_logline 是索引(数字),需要转换为 logline 对象
            if isinstance(selected_logline, int):
                logline_options = input_data.get("logline_options", [])
                if 0 <= selected_logline < len(logline_options):
                    logline_data = logline_options[selected_logline]
                else:
                    logline_data = {}
            else:
                logline_data = selected_logline if isinstance(selected_logline, dict) else {}
 
            if selected_mode == "micro":
                return await self._phase_micro_script_gen(input_data, logline_data)
            else:
                return await self._phase_script_gen(input_data, logline_data)
 
        # 如果已选择 logline 但未选择模式,返回模式选择
        if selected_logline and current_phase == "mode_selection":
            return {
                "payload": {
                    "phase": "mode_selection",
                    "selected_logline": selected_logline,
                    "session_id": input_data.get("session_id", ""),
                },
                "requires_intervention": True,
                "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
            }
 
        # (A) 用户介入修改最终剧本
        if intervention and "modified_script" in intervention:
            modified = intervention["modified_script"]
            sid = input_data.get("session_id", "")
            if isinstance(modified, str):
                modified = self._extract_json_from_text(modified) or {}
            is_zh = any('\u4e00' <= c <= '\u9fff' for c in modified.get("title", ""))
            modified["session_id"] = sid
            self._save_result(modified, sid, is_zh)
            return {"payload": modified, "requires_intervention": False, "stage_completed": True}
 
        # (B1) 用户选择了创作模式 → 根据模式生成剧本
        if intervention and "selected_mode" in intervention:
            selected = input_data.get("selected_logline", {})
            mode = intervention["selected_mode"]
            sid = input_data.get("session_id", "")
 
            # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
            if isinstance(selected, int):
                logline_options = input_data.get("logline_options", [])
                if 0 <= selected < len(logline_options):
                    logline_data = logline_options[selected]
                else:
                    logline_data = {}
            else:
                logline_data = selected if isinstance(selected, dict) else {}
 
            # 保存进度状态
            self._save_progress(sid, "mode_selection", {
                "selected_mode": mode
            })
 
            if mode == "micro":
                return await self._phase_micro_script_gen(input_data, logline_data)
            else:
                return await self._phase_script_gen(input_data, logline_data)
 
        # (B2) 用户选择了一个 Logline → 显示模式选择
        if intervention and "selected_logline" in intervention:
            selected = intervention["selected_logline"]
            sid = input_data.get("session_id", "")
 
            # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
            if isinstance(selected, int):
                logline_options = input_data.get("logline_options", [])
                if 0 <= selected < len(logline_options):
                    logline_data = logline_options[selected]
                else:
                    logline_data = {}
            else:
                logline_data = selected if isinstance(selected, dict) else {}
 
            # 保存进度状态
            self._save_progress(sid, "logline_confirmed", {
                "selected_logline": logline_data
            })
 
            return {
                "payload": {
                    "phase": "mode_selection",
                    "selected_logline": logline_data,
                    "session_id": sid,
                },
                "requires_intervention": True,
                "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
            }
 
        # 首次运行:自动判断是直接提取 logline 还是进入扩写
        auto_mode = input_data.get("auto_mode", False)
 
        # 代理(自动)模式:跳过 Logline 选择,直接生成剧本
        if auto_mode:
            return await self._phase_direct(input_data)
 
        # 自动判断:创意足够则提取 logline,否则自动扩写生成 3 个选项
        return await self._phase_logline_check(input_data)
 
    # ─── Phase 1A: 生成 3 个 Logline 方案 ───
 
    async def _phase_logline_gen(self, input_data: Dict) -> Dict:
        idea = input_data.get("idea", "")
        sid = input_data.get("session_id", "")
        llm_model = input_data.get("llm_model", "qwen3.5-plus")
        web_search = input_data.get("web_search", False)
        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
        def run():
            from tool.llm_client import LLM
            llm = LLM()
            self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
            prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
 
            for attempt in range(3):
                self._check_cancel()
                raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
                logger.info(f"[ScriptWriter] Logline gen attempt {attempt + 1}, raw output ({len(raw)} chars): {raw[:500]}")
                options = self._extract_json_array_from_text(raw)
                if options and len(options) > 0:
                    # 确保每个选项包含必要字段
                    required = {"logline", "who", "goal", "conflict", "twist", "theme"}
                    valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
                    if valid:
                        self._report_progress("剧本生成", "Logline 方案已生成", 20)
                        return valid[:3]
 
                logger.warning(f"[ScriptWriter] Logline gen attempt {attempt + 1}: parse failed")
                if is_zh:
                    prompt = (
                        "上次输出格式不正确,请严格按要求重新输出。"
                        "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
                        + (_get_script_prompt("logline_generate", "zh")).format(idea=idea)
                    )
                else:
                    prompt = (
                        "Previous output format was incorrect. Please try again. "
                        "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
                        + (_get_script_prompt("logline_generate", "en")).format(idea=idea)
                    )
 
            raise Exception("Logline 生成失败:多次尝试均无法解析输出")
 
        loop = asyncio.get_running_loop()
        options = await loop.run_in_executor(None, run)
 
        # 保存进度状态
        self._save_progress(sid, "logline_generation", {
            "logline_options": options
        })
 
        return {
            "payload": {
                "phase": "logline_selection",
                "logline_options": options,
                "session_id": sid,
            },
            "requires_intervention": True,
            "openclaw_hint": "生成了多个情节候选(logline),需要用户选择。请展示给用户并等待用户选择。",
        }
 
    # ─── Phase 1B: 检测输入是否可提取 Logline ───
 
    async def _phase_logline_check(self, input_data: Dict) -> Dict:
        idea = input_data.get("idea", "")
        sid = input_data.get("session_id", "")
        llm_model = input_data.get("llm_model", "qwen3.5-plus")
        web_search = input_data.get("web_search", False)
        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
        def run():
            from tool.llm_client import LLM
            llm = LLM()
            self._report_progress("剧本生成", "分析创意文本...", 5)
            check_prompt = _get_script_prompt("logline_check", "zh" if is_zh else "en").format(idea=idea)
            answer = self._cancellable_query(llm, check_prompt, model=llm_model, task_id=sid, web_search=web_search).strip()
 
            if answer.lower().startswith("yes"):
                self._report_progress("剧本生成", "提取 Logline...", 10)
                extract_prompt = _get_script_prompt("logline_extract", "zh" if is_zh else "en").format(idea=idea)
                raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
                logger.info(f"[ScriptWriter] Logline extract raw ({len(raw)} chars): {raw[:500]}")
                logline_data = self._extract_json_from_text(raw)
                if logline_data and isinstance(logline_data, dict) and 'logline' in logline_data:
                    self._report_progress("剧本生成", "Logline 提取完成", 20)
                    return {"phase": "logline_confirm", "logline_summary": logline_data}
 
            return {"phase": "suggest_expand"}
 
        loop = asyncio.get_running_loop()
        result = await loop.run_in_executor(None, run)
        result["session_id"] = sid
 
        # 如果创意不够,自动进入扩写阶段,生成 3 个 logline 供选择
        if result.get("phase") == "suggest_expand":
            return await self._phase_logline_gen(input_data)
 
        # 保存进度状态
        phase = result.get("phase", "logline_check")
        self._save_progress(sid, "logline_check", {
            "idea_analyzed": phase == "logline_confirm",
            "logline_summary": result.get("logline_summary")
        })
 
        return {
            "payload": result,
            "requires_intervention": True,
            "openclaw_hint": "已提取情节概要,需要用户确认。请展示给用户并等待用户确认。",
        }
 
    # ─── Phase 2: 根据选定 Logline 生成完整剧本 ───
 
    async def _phase_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
        idea = input_data.get("idea", "")
        sid = input_data.get("session_id", "")
        style = input_data.get("style", "anime")
        llm_model = input_data.get("llm_model", "qwen3.5-plus")
        web_search = input_data.get("web_search", False)
        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
        # 用 Logline 六要素构建丰富的故事概要
        if is_zh:
            draft = (
                f"故事核心 Logline:{logline_data.get('logline', '')}\n"
                f"主角:{logline_data.get('who', '')}\n"
                f"目标:{logline_data.get('goal', '')}\n"
                f"核心障碍:{logline_data.get('conflict', '')}\n"
                f"反转:{logline_data.get('twist', '')}\n"
                f"主题:{logline_data.get('theme', '')}\n\n"
                f"原始灵感:{idea}"
            )
        else:
            draft = (
                f"Story Logline: {logline_data.get('logline', '')}\n"
                f"Protagonist: {logline_data.get('who', '')}\n"
                f"Goal: {logline_data.get('goal', '')}\n"
                f"Core Conflict: {logline_data.get('conflict', '')}\n"
                f"Twist: {logline_data.get('twist', '')}\n"
                f"Theme: {logline_data.get('theme', '')}\n\n"
                f"Original idea: {idea}"
            )
 
        def run():
            from config import settings as app_settings
            from tool.llm_client import LLM
 
            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
 
            llm = LLM()
 
            # 逐幕生成节拍表 + 分场大纲 + 结构化提取
            json_data = self._generate_script_incremental(
                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
            )
 
            # 补充元数据
            json_data.setdefault("project_id", f"proj_{sid}")
            json_data.setdefault("version", 1)
            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
            json_data["metadata"] = {
                "generation_model": llm_model,
                "generation_prompt": idea,
            }
            json_data["session_id"] = sid
            json_data["logline_data"] = logline_data
 
            self._save_result(json_data, sid, is_zh)
            # 保存进度状态
            self._save_progress(sid, "script_generation", {
                "title": json_data.get("title")
            })
            self._report_progress("剧本生成", "完成", 100)
            return json_data
 
        loop = asyncio.get_running_loop()
        script_json = await loop.run_in_executor(None, run)
 
        # 保存进度状态
        self._save_progress(sid, "script_generation", {
            "title": script_json.get("title")
        })
 
        return {
            "payload": script_json,
            "requires_intervention": False,
            "stage_completed": True,  # 明确标记阶段完成
            "openclaw_hint": "剧本生成完成。",
        }
 
    # ─── Phase 2-Micro: 微电影模式 - 根据选定 Logline 生成紧凑单幕剧本 ───
 
    async def _phase_micro_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
        idea = input_data.get("idea", "")
        sid = input_data.get("session_id", "")
        style = input_data.get("style", "anime")
        llm_model = input_data.get("llm_model", "qwen3.5-plus")
        web_search = input_data.get("web_search", False)
        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
        # 用 Logline 六要素构建故事概要
        if is_zh:
            draft = (
                f"故事核心 Logline:{logline_data.get('logline', '')}\n"
                f"主角:{logline_data.get('who', '')}\n"
                f"目标:{logline_data.get('goal', '')}\n"
                f"核心障碍:{logline_data.get('conflict', '')}\n"
                f"反转:{logline_data.get('twist', '')}\n"
                f"主题:{logline_data.get('theme', '')}\n\n"
                f"原始灵感:{idea}"
            )
        else:
            draft = (
                f"Story Logline: {logline_data.get('logline', '')}\n"
                f"Protagonist: {logline_data.get('who', '')}\n"
                f"Goal: {logline_data.get('goal', '')}\n"
                f"Core Conflict: {logline_data.get('conflict', '')}\n"
                f"Twist: {logline_data.get('twist', '')}\n"
                f"Theme: {logline_data.get('theme', '')}\n\n"
                f"Original idea: {idea}"
            )
 
        def run():
            from config import settings as app_settings
            from tool.llm_client import LLM
 
            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
 
            llm = LLM()
 
            # 微电影模式: 单幕生成
            json_data = self._generate_micro_script_incremental(
                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
            )
 
            # 补充元数据
            json_data.setdefault("project_id", f"proj_{sid}")
            json_data.setdefault("version", 1)
            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
            json_data["metadata"] = {
                "generation_model": llm_model,
                "generation_prompt": idea,
                "mode": "micro",
            }
            json_data["session_id"] = sid
            json_data["logline_data"] = logline_data
 
            self._save_result(json_data, sid, is_zh)
            # 保存进度状态
            self._save_progress(sid, "script_generation", {
                "title": json_data.get("title")
            })
            self._report_progress("剧本生成", "完成", 100)
            return json_data
 
        loop = asyncio.get_running_loop()
        script_json = await loop.run_in_executor(None, run)
 
        # 保存进度状态
        self._save_progress(sid, "script_generation", {
            "title": script_json.get("title")
        })
 
        return {
            "payload": script_json,
            "requires_intervention": False,
            "stage_completed": True,  # 明确标记阶段完成
            "openclaw_hint": "剧本生成完成。",
        }
 
    # ─── 代理模式(自动生成 Logline 并选择第一个) ───
 
    async def _phase_direct(self, input_data: Dict) -> Dict:
        """代理模式:生成 3 个 Logline → 自动选择第一个 → 生成完整剧本"""
        idea = input_data.get("idea", "")
        sid = input_data.get("session_id", "")
        style = input_data.get("style", "anime")
        llm_model = input_data.get("llm_model", "qwen3.5-plus")
        web_search = input_data.get("web_search", False)
        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
        def run():
            from config import settings as app_settings
            from tool.llm_client import LLM
 
            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
 
            llm = LLM()
 
            # Step 1: 生成 Logline 方案
            self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
            prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
 
            logline_data = None
            for attempt in range(3):
                self._check_cancel()
                raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
                logger.info(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}, raw ({len(raw)} chars): {raw[:500]}")
                options = self._extract_json_array_from_text(raw)
                if options and len(options) > 0:
                    required = {"logline", "who", "goal", "conflict", "twist", "theme"}
                    valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
                    if valid:
                        logline_data = valid[0]  # 自动选择第一个
                        logger.info(f"[ScriptWriter][auto] Auto-selected logline: {logline_data.get('logline', '')[:80]}")
                        break
 
                logger.warning(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}: parse failed")
                if is_zh:
                    prompt = (
                        "上次输出格式不正确,请严格按要求重新输出。"
                        "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
                        + _get_script_prompt("logline_generate", "zh").format(idea=idea)
                    )
                else:
                    prompt = (
                        "Previous output format was incorrect. Please try again. "
                        "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
                        + _get_script_prompt("logline_generate", "en").format(idea=idea)
                    )
 
            if logline_data is None:
                raise Exception("Logline 生成失败:多次尝试均无法解析输出")
 
            self._report_progress("剧本生成", "已自动选择 Logline,开始创作情节...", 15)
 
            # Step 2: 用 Logline 六要素构建故事概要
            if is_zh:
                draft = (
                    f"故事核心 Logline:{logline_data.get('logline', '')}\n"
                    f"主角:{logline_data.get('who', '')}\n"
                    f"目标:{logline_data.get('goal', '')}\n"
                    f"核心障碍:{logline_data.get('conflict', '')}\n"
                    f"反转:{logline_data.get('twist', '')}\n"
                    f"主题:{logline_data.get('theme', '')}\n\n"
                    f"原始灵感:{idea}"
                )
            else:
                draft = (
                    f"Story Logline: {logline_data.get('logline', '')}\n"
                    f"Protagonist: {logline_data.get('who', '')}\n"
                    f"Goal: {logline_data.get('goal', '')}\n"
                    f"Core Conflict: {logline_data.get('conflict', '')}\n"
                    f"Twist: {logline_data.get('twist', '')}\n"
                    f"Theme: {logline_data.get('theme', '')}\n\n"
                    f"Original idea: {idea}"
                )
 
            # Step 3: 逐幕生成节拍表 + 分场大纲 + 结构化提取
            json_data = self._generate_script_incremental(
                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
            )
 
            # 补充元数据
            json_data.setdefault("project_id", f"proj_{sid}")
            json_data.setdefault("version", 1)
            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
            json_data["metadata"] = {
                "generation_model": llm_model,
                "generation_prompt": idea,
            }
            json_data["session_id"] = sid
            json_data["logline_data"] = logline_data
 
            self._save_result(json_data, sid, is_zh)
            # 保存进度状态
            self._save_progress(sid, "script_generation", {
                "title": json_data.get("title")
            })
            self._report_progress("剧本生成", "完成", 100)
            return json_data
 
        loop = asyncio.get_running_loop()
        script_json = await loop.run_in_executor(None, run)
 
        # 保存进度状态
        self._save_progress(sid, "script_generation", {
            "title": script_json.get("title")
        })
 
        return {
            "payload": script_json,
            "requires_intervention": False,
            "stage_completed": True,  # 明确标记阶段完成
            "openclaw_hint": "剧本生成完成。",
        }
 
    # ─── 公共: 逐幕生成节拍表 + 分场大纲 + 结构化提取 ───
 
    def _generate_script_incremental(self, llm, draft: str, idea: str, style: str,
                                      llm_model: str, sid: str, is_zh: bool,
                                      web_search: bool = False,
                                      pct_start: int = 20) -> dict:
        """生成 Save the Cat! 节拍表 → 逐幕生成分场大纲 + 结构化提取,返回合并的 JSON"""
 
        # Step 1: 生成四幕节拍表
        self._report_progress("剧本生成", "生成节拍表...", pct_start)
        prompt = _get_script_prompt("beat_sheet", "zh" if is_zh else "en").format(draft=draft, idea=idea, style=style)
        beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
        logger.info(f"[ScriptWriter] Beat sheet generated ({len(beat_sheet)} chars)")
 
        # 发送节拍表到前端
        self._report_progress("剧本生成", "节拍表生成完成", pct_start + 5,
                              data={"beat_sheet": beat_sheet})
 
        # Step 2: 提取顶层元数据 (title, logline, genre, synopsis, mood)
        self._report_progress("剧本生成", "提取故事元信息...", pct_start + 7)
        meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(beat_sheet=beat_sheet)
        meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
        meta_data = self._extract_json_from_text(meta_raw) or {}
        logger.info(f"[ScriptWriter] Meta extracted: {list(meta_data.keys())}")
 
        # Step 3: 逐幕生成分场大纲 + 结构化提取
        act_names = ACT_NAMES_ZH if is_zh else ACT_NAMES_EN
        all_characters = []  # 累积角色
        all_settings = []    # 累积场景
        all_scenes = []      # 累积分场
        seen_char_names = set()
        seen_setting_names = set()
        scene_start = 1
 
        for act_num in range(1, 5):
            self._check_cancel()
            act_name = act_names[act_num]
 
            # --- 生成分场大纲 ---
            pct_outline = pct_start + 8 + (act_num - 1) * 15  # 28, 43, 58, 73
            progress_msg = (f"生成第{act_num}幕分场大纲({act_name})..."
                            if is_zh else f"Generating Act {act_num} outline ({act_name})...")
            self._report_progress("剧本生成", progress_msg, pct_outline)
 
            outline_prompt = _get_script_prompt("step_outline", "zh" if is_zh else "en").format(
                beat_sheet=beat_sheet,
                act_number=act_num,
                act_name=act_name,
                scene_start=scene_start,
                style=style,
            )
            outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
            logger.info(f"[ScriptWriter] Act {act_num} outline generated ({len(outline)} chars)")
 
            # --- 结构化提取本幕 JSON ---
            pct_extract = pct_outline + 8
            progress_msg = (f"提取第{act_num}幕结构化数据..."
                            if is_zh else f"Extracting Act {act_num} structured data...")
            self._report_progress("剧本生成", progress_msg, pct_extract)
 
            act_json = self._extract_act_json(
                llm, outline, act_num, scene_start, style, llm_model, sid, is_zh, web_search
            )
 
            # 累积角色(去重)
            for c in act_json.get("characters", []):
                if c.get("name") and c["name"] not in seen_char_names:
                    if not c.get("character_id"):
                        c["character_id"] = self._gen_id("char")
                    all_characters.append(c)
                    seen_char_names.add(c["name"])
 
            # 累积场景(去重)
            for s in act_json.get("settings", []):
                if s.get("name") and s["name"] not in seen_setting_names:
                    if not s.get("setting_id"):
                        s["setting_id"] = self._gen_id("set")
                    all_settings.append(s)
                    seen_setting_names.add(s["name"])
 
            # 累积分场
            act_scenes = act_json.get("scenes", [])
            all_scenes.extend(act_scenes)
 
            # 计算下一幕场次起始
            if act_scenes:
                scene_start = max(s.get("scene_number", scene_start) for s in act_scenes) + 1
 
            # 发送本幕结果到前端
            act_label = f"第{act_num}幕 - {act_name}" if is_zh else f"Act {act_num} - {act_name}"
            self._report_progress("剧本生成",
                                  f"{act_label} 完成" if is_zh else f"{act_label} done",
                                  pct_extract + 2,
                                  data={"act_complete": {
                                      "act": act_num,
                                      "act_name": act_name,
                                      "characters": act_json.get("characters", []),
                                      "settings": act_json.get("settings", []),
                                      "scenes": act_scenes,
                                  }})
 
        # Step 4: 合并最终 JSON
        # 重新编号 scene_number
        for i, sc in enumerate(all_scenes):
            sc["scene_number"] = i + 1
 
        json_data = {
            "title": meta_data.get("title", ""),
            "logline": meta_data.get("logline", ""),
            "genre": meta_data.get("genre", []),
            "target_duration": 1800,
            "synopsis": meta_data.get("synopsis", ""),
            "characters": all_characters,
            "settings": all_settings,
            "scenes": all_scenes,
            "overall_style": style,
            "mood": meta_data.get("mood", ""),
        }
 
        # Step 5: 合并相似场景和角色
        self._report_progress("剧本生成",
                              "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
                              96)
        json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
 
        return json_data
 
    # ─── 微电影模式: 单幕紧凑生成 ───
 
    def _generate_micro_script_incremental(self, llm, draft: str, idea: str, style: str,
                                            llm_model: str, sid: str, is_zh: bool,
                                            web_search: bool = False,
                                            pct_start: int = 20) -> dict:
        """微电影模式:生成紧凑单幕剧情概要 → 分场大纲 → 结构化提取,返回合并的 JSON"""
 
        # Step 1: 生成单幕剧情概要
        self._report_progress("剧本生成", "生成微电影剧情概要...", pct_start)
        prompt = _get_script_prompt("micro_beat_sheet", "zh" if is_zh else "en").format(
            draft=draft, idea=idea, style=style
        )
        beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
        logger.info(f"[ScriptWriter][micro] Beat sheet generated ({len(beat_sheet)} chars)")
 
        # 发送概要到前端
        self._report_progress("剧本生成", "剧情概要生成完成", pct_start + 10,
                              data={"beat_sheet": beat_sheet})
 
        # Step 2: 提取顶层元数据
        self._report_progress("剧本生成", "提取故事元信息...", pct_start + 15)
        meta_prompt = _get_script_prompt("micro_meta_extract", "zh" if is_zh else "en").format(
            beat_sheet=beat_sheet
        )
        meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
        meta_data = self._extract_json_from_text(meta_raw) or {}
        logger.info(f"[ScriptWriter][micro] Meta extracted: {list(meta_data.keys())}")
 
        # Step 3: 生成分场大纲
        self._check_cancel()
        self._report_progress("剧本生成",
                              "生成微电影分场大纲..." if is_zh else "Generating micro-film step outline...",
                              pct_start + 25)
 
        outline_prompt = _get_script_prompt("micro_step_outline", "zh" if is_zh else "en").format(
            beat_sheet=beat_sheet, style=style
        )
        outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
        logger.info(f"[ScriptWriter][micro] Outline generated ({len(outline)} chars)")
 
        # Step 4: 结构化 JSON 提取
        self._report_progress("剧本生成",
                              "提取结构化数据..." if is_zh else "Extracting structured data...",
                              pct_start + 45)
 
        act_json = self._extract_act_json(
            llm, outline, act_number=1, scene_start=1,
            style=style, llm_model=llm_model, sid=sid, is_zh=is_zh,
            web_search=web_search
        )
 
        characters = act_json.get("characters", [])
        settings = act_json.get("settings", [])
        scenes = act_json.get("scenes", [])
 
        # 补全 ID
        for c in characters:
            if not c.get("character_id"):
                c["character_id"] = self._gen_id("char")
        for s in settings:
            if not s.get("setting_id"):
                s["setting_id"] = self._gen_id("set")
 
        # 重新编号并去掉 act 字段(微电影不分幕)
        for i, sc in enumerate(scenes):
            sc["scene_number"] = i + 1
            sc.pop("act", None)
 
        # 发送到前端
        act_label = "微电影" if is_zh else "Micro-film"
        self._report_progress("剧本生成",
                              f"{act_label} 分场完成" if is_zh else f"{act_label} scenes done",
                              pct_start + 60,
                              data={"act_complete": {
                                  "act": 1,
                                  "act_name": act_label,
                                  "characters": characters,
                                  "settings": settings,
                                  "scenes": scenes,
                              }})
 
        # Step 5: 合并最终 JSON
        json_data = {
            "title": meta_data.get("title", ""),
            "logline": meta_data.get("logline", ""),
            "genre": meta_data.get("genre", []),
            "target_duration": 180,  # 微电影默认 3 分钟
            "synopsis": meta_data.get("synopsis", ""),
            "characters": characters,
            "settings": settings,
            "scenes": scenes,
            "overall_style": style,
            "mood": meta_data.get("mood", ""),
        }
 
        # Step 6: 合并相似场景和角色
        self._report_progress("剧本生成",
                              "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
                              pct_start + 70)
        json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
 
        return json_data
 
    # ─── 公共: 单幕结构化提取 (带校验重试) ───
 
    def _extract_act_json(self, llm, outline: str, act_number: int,
                          scene_start: int, style: str,
                          llm_model: str, sid: str, is_zh: bool,
                          web_search: bool = False) -> dict:
        """从单幕分场大纲提取结构化JSON,带校验重试"""
        extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
            act_number=act_number, scene_start=scene_start, outline=outline
        )
 
        last_error = ""
 
        for attempt in range(3):
            self._check_cancel()
            raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
            parsed = self._extract_json_from_text(raw)
 
            if parsed is None:
                last_error = "LLM输出无法解析为JSON"
                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: JSON parse failed")
                extract_prompt = (
                    ("上次输出不是合法JSON,请重新输出。" if is_zh
                     else "Previous output was not valid JSON. Please try again. ")
                    + extract_prompt
                )
                continue
 
            # 基本校验: 必须有 scenes 列表
            scenes = parsed.get("scenes")
            if not isinstance(scenes, list) or len(scenes) == 0:
                last_error = "scenes 必须是非空列表"
                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: no scenes")
                extract_prompt = (
                    (f"上次输出的JSON缺少scenes。请确保scenes是非空列表。" if is_zh
                     else "Previous JSON had no scenes. Ensure scenes is a non-empty array. ")
                    + extract_prompt
                )
                continue
 
            # 校验每个 scene 的必要字段
            valid = True
            for i, sc in enumerate(scenes):
                for key in ["scene_number", "act", "location", "characters", "plot"]:
                    if key not in sc:
                        last_error = f"scenes[{i}] 缺少字段: {key}"
                        valid = False
                        break
                if not valid:
                    break
 
            if not valid:
                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: {last_error}")
                extract_prompt = (
                    (f"上次输出的JSON存在问题: {last_error}。请修正后重新输出。" if is_zh
                     else f"Previous JSON issue: {last_error}. Please fix and retry. ")
                    + extract_prompt
                )
                continue
 
            return parsed
 
        raise Exception(f"第{act_number}幕JSON提取失败 (已重试3次): {last_error}")
 
    # ─── 公共: 场景 & 角色合并 ───
 
    def _consolidate_script(self, llm, json_data: dict,
                            llm_model: str, sid: str, is_zh: bool,
                            web_search: bool = False) -> dict:
        """审查并合并重复/相似的场景和角色"""
        characters = json_data.get("characters", [])
        settings = json_data.get("settings", [])
        scenes = json_data.get("scenes", [])
 
        if len(settings) <= 1 and len(characters) <= 1:
            return json_data
 
        # 构建简洁的列表供 LLM 审查
        settings_summary = [{"name": s["name"], "description": s.get("description", "")}
                            for s in settings]
        chars_summary = [{"name": c["name"], "description": c.get("description", "")}
                         for c in characters]
 
        prompt = _get_script_prompt("consolidate", "zh" if is_zh else "en").format(
            settings_json=json.dumps(settings_summary, ensure_ascii=False, indent=2),
            characters_json=json.dumps(chars_summary, ensure_ascii=False, indent=2),
        )
 
        self._check_cancel()
        raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
        result = self._extract_json_from_text(raw)
 
        if not result or not isinstance(result, dict):
            logger.warning("[ScriptWriter] Consolidation: failed to parse LLM response, skipping")
            return json_data
 
        setting_merges = result.get("setting_merges", {})
        char_merges = result.get("character_merges", {})
 
        if not setting_merges and not char_merges:
            logger.info("[ScriptWriter] Consolidation: nothing to merge")
            return json_data
 
        # --- 合并场景 ---
        if setting_merges:
            logger.info(f"[ScriptWriter] Merging settings: {setting_merges}")
            # 移除被合并的 settings
            merged_names = set(setting_merges.keys())
            json_data["settings"] = [s for s in settings if s["name"] not in merged_names]
 
            # 更新 scenes 中的 location 引用
            for sc in scenes:
                loc = sc.get("location", "")
                if loc in setting_merges:
                    sc["location"] = setting_merges[loc]
 
        # --- 合并角色 ---
        if char_merges:
            logger.info(f"[ScriptWriter] Merging characters: {char_merges}")
            merged_char_names = set(char_merges.keys())
            json_data["characters"] = [c for c in characters if c["name"] not in merged_char_names]
 
            # 更新 scenes 中的 characters 引用
            for sc in scenes:
                new_chars = []
                seen = set()
                for cn in sc.get("characters", []):
                    target = char_merges.get(cn, cn)
                    if target not in seen:
                        new_chars.append(target)
                        seen.add(target)
                sc["characters"] = new_chars
 
        logger.info(f"[ScriptWriter] After consolidation: "
                     f"{len(json_data['settings'])} settings, "
                     f"{len(json_data['characters'])} characters")
 
        # 验证 scenes 的 location 是否都在 settings 中
        settings_names = {s["name"] for s in json_data.get("settings", [])}
        for sc in json_data.get("scenes", []):
            loc = sc.get("location", "")
            if loc and loc not in settings_names:
                logger.error(f"[ScriptWriter] ERROR: Scene location '{loc}' not found in settings! available: {settings_names}")
 
        return json_data