@lingjingai/scriptctl 0.63.18 → 0.63.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -1
- package/changes/0.63.19.md +6 -0
- package/changes/0.63.20.md +20 -0
- package/dist/bin.js +1 -1
- package/dist/chunk-OYTWFCNO.js +983 -0
- package/dist/cli.d.ts +18 -3
- package/dist/cli.js +1 -1
- package/dist/review-agent.js +37 -36
- package/package.json +25 -21
- package/skills/scriptctl/SKILL.md +4 -2
- package/skills/scriptctl/references/ingest-workflow.md +19 -3
- package/dist/chunk-YOCQDDQC.js +0 -823
package/dist/chunk-YOCQDDQC.js
DELETED
|
@@ -1,823 +0,0 @@
|
|
|
1
|
-
import{Command as w5,CommanderError as _5}from"commander";import*as fa from"node:crypto";import*as Po from"node:fs";import*as Ai from"node:path";import*as Oe from"node:fs";import*as ht from"node:path";var Ur=class{workspace;constructor(t){this.workspace=t}get sourceText(){return ht.join(this.workspace,"source.txt")}get directDir(){return ht.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return ht.join(this.directDir,"script.initial.json")}get validation(){return ht.join(this.directDir,"validation.json")}get runState(){return ht.join(this.directDir,"run_state.json")}get episodeResultsDir(){return ht.join(this.directDir,"episode_results")}get batchResultsDir(){return ht.join(this.directDir,"batch_results")}outputScript(t){return ht.join(t,"script.json")}};function lh(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var ua=class{exists(t){return Oe.existsSync(t)}readText(t){return Oe.readFileSync(t,"utf-8")}writeText(t,n){Oe.mkdirSync(ht.dirname(t),{recursive:!0}),Oe.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Oe.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
|
|
2
|
-
`)}list(t,n="*"){if(!Oe.existsSync(t))return[];let o=lh(n),i=Oe.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(ht.join(t,s));return r.sort(),r}delete(t){Oe.existsSync(t)&&Oe.unlinkSync(t)}deleteTree(t){Oe.existsSync(t)&&Oe.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Oe.mkdirSync(ht.dirname(n),{recursive:!0}),Oe.copyFileSync(t,n)}},Tr=new ua;var J=0,G=64,b=66,fe=70,Ln=78,kp=30;var O5=Ai.join("draft","scriptctl","direct"),uh=Ai.join("workspace","script.json");var bp=["\u4E0A\u53E4\u65F6\u4EE3","\u53E4\u4EE3\u5386\u53F2","\u53E4\u98CE\u67B6\u7A7A","\u8FD1\u4EE3\u6C11\u56FD","\u73B0\u4EE3","\u6B27\u6D32\u4E2D\u4E16\u7EAA","\u8D5B\u535A\u670B\u514B","\u661F\u9645\u65F6\u4EE3","\u897F\u5E7B\u67B6\u7A7A"],Op=new Set(["actor","location","prop"]);var v5=`scriptctl parse \u8F93\u5165 = \u4E00\u4E2A md \u5DE5\u4F5C\u533A\u76EE\u5F55\u3002\u6587\u4EF6\u6309\u804C\u8D23\u5206\u5F00\uFF0C\u4E92\u4E0D\u6DF7\u5199\uFF1A
|
|
3
|
-
|
|
4
|
-
ep_001.md, ep_002.md, ... \u6B63\u6587\uFF08\u6BCF\u96C6\u4E00\u4E2A\uFF0C\u53EA\u653E\u5267\u672C\u672C\u8EAB\uFF09
|
|
5
|
-
\u4EBA\u7269.md \u5168\u5267\u552F\u4E00\u4E00\u4EFD\u89D2\u8272\u767B\u8BB0\uFF08\u6240\u6709 worker \u5171\u540C\u5F80\u91CC\u52A0\uFF09
|
|
6
|
-
\u573A\u666F.md \u5168\u5267\u552F\u4E00\u4E00\u4EFD\u5730\u70B9\u767B\u8BB0
|
|
7
|
-
\u9053\u5177.md \u5168\u5267\u552F\u4E00\u4E00\u4EFD\u9053\u5177\u767B\u8BB0
|
|
8
|
-
\u53D1\u58F0\u6E90.md \u5168\u5267\u552F\u4E00\u4E00\u4EFD\u975E\u4EBA\u7269\u53D1\u58F0\u6E90\u767B\u8BB0
|
|
9
|
-
\u6897\u6982.md \uFF08\u53EF\u9009\uFF09\u6574\u90E8\u5168\u6587\u6897\u6982
|
|
10
|
-
|
|
11
|
-
\u{1F534} \u94C1\u5F8B\uFF1A\u6B63\u6587 md \u53EA\u7BA1\u6B63\u6587\uFF0C\u7EDD\u4E0D\u5728\u6B63\u6587\u91CC\u767B\u8BB0/\u8F93\u51FA\u4EFB\u4F55\u8D44\u4EA7\u3002\u8D44\u4EA7\u4E00\u5F8B\u767B\u8BB0\u5230\u4E0A\u9762\u5BF9\u5E94
|
|
12
|
-
\u7684 \u4EBA\u7269/\u573A\u666F/\u9053\u5177/\u53D1\u58F0\u6E90 md \u91CC\u3002\u6B63\u6587\u91CC\u53EA\u201C\u5F15\u7528\u201D\u540D\u5B57\u4E0E\u5DF2\u767B\u8BB0\u72B6\u6001\uFF0C\u4E0D\u5199\u63CF\u8FF0\u3002
|
|
13
|
-
\u{1F534} \u8D44\u4EA7\u5C31\u8FD9 4 \u4EFD\uFF0C\u5168\u5267\u5171\u7528\u3001\u5927\u5BB6\u4E00\u8D77\u52A0\uFF1B\u540C\u540D\u53EA\u767B\u4E00\u6B21\uFF0C\u91CD\u590D\u65E0\u59A8\uFF08parse / \u5408\u5E76\u9636\u6BB5\u53BB\u91CD\uFF09\u3002
|
|
14
|
-
\u{1F7E1} \u53EA\u6709\u6B63\u6587\u3001\u8FD8\u6CA1\u5199\u8D44\u4EA7 md\uFF1F\u5148\u8DD1 \`scriptctl parse <dir> --extract-assets\`\uFF1A\u5B83\u4ECE\u6B63\u6587\u91CC
|
|
15
|
-
\u5F15\u7528\u5230\u7684\u8D44\u4EA7\u540D\u51FA\u53D1\uFF0C\u7528 LLM \u8865\u51FA\u63CF\u8FF0 / \u4E16\u754C\u89C2 / \u4E3B\u89D2\uFF0C\u5199\u56DE\u4E0A\u9762\u8FD9\u51E0\u4EFD\u8D44\u4EA7 md \u4F9B\u4F60\u590D\u6838\uFF1B
|
|
16
|
-
\u590D\u6838\u5FAE\u8C03\u540E\u518D\u8DD1 \`scriptctl parse <dir>\`\uFF08\u7EAF\u786E\u5B9A\u6027\uFF09\u88C5\u914D script.json\u3002
|
|
17
|
-
|
|
18
|
-
==================== 1. \u6B63\u6587 md\uFF08\u6BCF\u96C6\u4E00\u4E2A\uFF0Cep_<NNN>.md\uFF09 ====================
|
|
19
|
-
# <\u672C\u96C6\u6807\u9898> \u2190 \u7B2C\u4E00\u884C\uFF0C\u975E\u300C\u5267\u672C/\u6897\u6982\u300D\u7684\u9876\u7EA7\u6807\u9898\u5373\u672C\u96C6\u6807\u9898\uFF1B\u7F3A\u7701\u65F6 parse \u4ECE\u6B63\u6587\u751F\u6210\u77ED\u6807\u9898
|
|
20
|
-
|
|
21
|
-
## \u6897\u6982
|
|
22
|
-
<\u672C\u96C6\u4E00\u6BB5\u8BDD\u6897\u6982\uFF0C\u7EAF\u6587\u672C\uFF0C\u53EF\u591A\u884C>
|
|
23
|
-
|
|
24
|
-
# \u5267\u672C
|
|
25
|
-
|
|
26
|
-
## \u573A\u666F 1
|
|
27
|
-
- \u65F6\u7A7A: <\u5185|\u5916> <\u65E5|\u591C>
|
|
28
|
-
- \u5730\u70B9: <\u5730\u70B9\u540D>[\u573A\u666F\u72B6\u6001] \u2190 \u53EA\u5199\u540D\u5B57\uFF0C\u5F15\u7528 \u573A\u666F.md \u91CC\u767B\u8BB0\u7684\u5730\u70B9/\u72B6\u6001
|
|
29
|
-
- \u89D2\u8272: <\u89D2\u82721>, <\u89D2\u82722>(\u72B6\u6001), <\u89D2\u82723> \u2190 \u53EA\u5199\u540D\u5B57\uFF0C\u5F15\u7528 \u4EBA\u7269.md \u91CC\u767B\u8BB0\u7684\u89D2\u8272/\u72B6\u6001
|
|
30
|
-
- \u9053\u5177: <\u9053\u51771>, <\u9053\u51772>(\u72B6\u6001), <\u9053\u51773>[\u72B6\u6001] \u2190 \u53EA\u5199\u540D\u5B57\uFF0C\u5F15\u7528 \u9053\u5177.md \u91CC\u767B\u8BB0\u7684\u9053\u5177/\u72B6\u6001
|
|
31
|
-
|
|
32
|
-
> [act] \u52A8\u4F5C\u6216\u73AF\u5883\u63CF\u5199\u3002
|
|
33
|
-
> [dlg|name] \u89D2\u8272\u5BF9\u767D\u539F\u6587\u3002
|
|
34
|
-
> [dlg|name|emotion] \u5E26\u60C5\u7EEA\u6807\u7B7E\u7684\u5BF9\u767D\u3002
|
|
35
|
-
> [dlg|system:<\u53D1\u58F0\u6E90\u540D>] \u975E\u4EBA\u7269\u53D1\u58F0\u6E90\u5BF9\u767D\u3002
|
|
36
|
-
> [dlg|prop:<\u9053\u5177\u540D>] \u9053\u5177\u53D1\u58F0\u5BF9\u767D\u3002
|
|
37
|
-
> [dlg|broadcast:<\u5E7F\u64AD\u540D>] \u5E7F\u64AD / \u5587\u53ED\u53D1\u58F0\u5BF9\u767D\u3002
|
|
38
|
-
> [dlg|<speaker1>/<speaker2>|simultaneous] \u591A\u4EBA\u540C\u65F6\u8BF4\u540C\u4E00\u53E5\u3002
|
|
39
|
-
> [dlg|overlap] <speaker1>:<line1> / <speaker2>:<line2>
|
|
40
|
-
> [think|name] \u89D2\u8272\u5FC3\u58F0/\u5185\u5FC3\u72EC\u767D\u3002
|
|
41
|
-
|
|
42
|
-
## \u573A\u666F 2
|
|
43
|
-
...
|
|
44
|
-
|
|
45
|
-
\u8D44\u4EA7 md \u7684\u683C\u5F0F\uFF1A\u6BCF\u4E2A\u8D44\u4EA7\u4E00\u4E2A\u9876\u7EA7 bullet\uFF0C\u5B83\u7684\u201C\u72B6\u6001\u201D\uFF08\u5916\u89C2\u9020\u578B\u6863\u4F4D\uFF09\u5199\u6210\u7F29\u8FDB\u7684\u5B50 bullet\u3002
|
|
46
|
-
- <\u8D44\u4EA7\u540D>: <\u8EAB\u4EFD/\u63CF\u8FF0>
|
|
47
|
-
- <\u72B6\u6001\u540D>: <\u8FD9\u4E2A\u72B6\u6001\u4E0B\u7684\u5177\u4F53\u53EF\u89C6\u5916\u89C2>
|
|
48
|
-
- <\u72B6\u6001\u540D>: ...
|
|
49
|
-
\uFF08\u4E5F\u63A5\u53D7\u6241\u5E73\u5199\u6CD5 \`- <\u8D44\u4EA7\u540D>|<\u72B6\u6001\u540D>: \u63CF\u8FF0\`\uFF1B\u4E24\u79CD\u90FD\u884C\uFF0C\u6700\u540E\u5408\u5E76\u53BB\u91CD\u3002\uFF09
|
|
50
|
-
\u6B63\u6587\u672A\u663E\u5F0F\u5199\u72B6\u6001\u65F6\uFF0Cparse \u4F1A\u81EA\u52A8\u7ED1\u5B9A\u8BE5\u8D44\u4EA7\u7684 \`\u9ED8\u8BA4\` \u72B6\u6001\uFF1B\u6CA1\u6709 \`\u9ED8\u8BA4\` \u4E14\u53EA\u6709\u4E00\u4E2A\u72B6\u6001\u65F6\uFF0C\u7ED1\u5B9A\u552F\u4E00\u72B6\u6001\u3002
|
|
51
|
-
\u591A\u4E2A\u975E\u9ED8\u8BA4\u72B6\u6001\u65E0\u6CD5\u786E\u5B9A\u65F6\u4FDD\u6301 state_id:null\uFF0C\u5E76\u7531 validate \u7ED9\u51FA warning\u3002
|
|
52
|
-
|
|
53
|
-
==================== 2. \u4EBA\u7269.md\uFF08\u89D2\u8272\u767B\u8BB0 + \u72B6\u6001\uFF09 ====================
|
|
54
|
-
# \u4EBA\u7269
|
|
55
|
-
- <\u89D2\u8272\u540D>: <\u89D2\u8272\u8EAB\u4EFD/\u5916\u8C8C\u63CF\u8FF0> \u2190 \u6BCF\u4E2A\u4F1A\u5728\u6B63\u6587\u51FA\u73B0\u7684\u89D2\u8272\u90FD\u8981\u767B\u8BB0\u4E14\u6709\u975E\u7A7A\u63CF\u8FF0
|
|
56
|
-
- \u9ED8\u8BA4: <\u8FD9\u4E2A\u89D2\u8272\u9ED8\u8BA4\u5F62\u8C61\u7684\u5177\u4F53\u5916\u89C2>
|
|
57
|
-
- <\u72B6\u6001\u540D>: <\u6362\u88C5/\u9020\u578B\u540E\u7684\u5177\u4F53\u5916\u89C2> \u2190 \u6301\u4E45\u5916\u89C2\u9020\u578B\u6863\u4F4D\uFF08\u6574\u5957\u7740\u88C5/\u53D1\u578B/\u6301\u7EED\u5986\u9020\uFF09
|
|
58
|
-
|
|
59
|
-
==================== 3. \u573A\u666F.md\uFF08\u5730\u70B9\u767B\u8BB0 + \u72B6\u6001\uFF09 ====================
|
|
60
|
-
# \u573A\u666F
|
|
61
|
-
- <\u5730\u70B9\u540D>: <\u5730\u70B9\u7528\u9014/\u6C1B\u56F4>
|
|
62
|
-
- \u9ED8\u8BA4: <\u9ED8\u8BA4\u73AF\u5883\u5916\u89C2>
|
|
63
|
-
- <\u72B6\u6001\u540D>: <\u4F8B\u5982 \u767D\u5929/\u591C\u665A/\u88AB\u6BC1\u540E \u7684\u5916\u89C2>
|
|
64
|
-
|
|
65
|
-
==================== 4. \u9053\u5177.md\uFF08\u9053\u5177\u767B\u8BB0 + \u72B6\u6001\uFF09 ====================
|
|
66
|
-
# \u9053\u5177
|
|
67
|
-
- <\u9053\u5177\u540D>: <\u9053\u5177\u63CF\u8FF0>
|
|
68
|
-
- \u9ED8\u8BA4: <\u9ED8\u8BA4\u5916\u89C2>
|
|
69
|
-
- <\u72B6\u6001\u540D>: <\u4F8B\u5982 \u7834\u635F/\u53D1\u5149 \u7684\u5916\u89C2>
|
|
70
|
-
|
|
71
|
-
==================== 5. \u53D1\u58F0\u6E90.md\uFF08\u975E\u4EBA\u7269\u53D1\u58F0\u6E90\u767B\u8BB0\uFF0C\u65E0\u72B6\u6001\uFF09 ====================
|
|
72
|
-
# \u53D1\u58F0\u6E90
|
|
73
|
-
- <\u53D1\u58F0\u6E90\u540D>(system): <\u58F0\u97F3\u63CF\u8FF0>
|
|
74
|
-
- <\u5E7F\u64AD\u540D>(broadcast)
|
|
75
|
-
- <\u7FA4\u4F53\u540D>(group)
|
|
76
|
-
|
|
77
|
-
==================== 6. \u6897\u6982.md\uFF08\u53EF\u9009\uFF0C\u6574\u90E8\u5168\u6587\u6897\u6982\uFF09 ====================
|
|
78
|
-
# \u6897\u6982
|
|
79
|
-
<\u6574\u90E8\u5168\u6587\u6897\u6982\uFF0C\u7EAF\u6587\u672C\uFF0C\u53EF\u591A\u884C>
|
|
80
|
-
|
|
81
|
-
==================== 7. \u5143\u4FE1\u606F.md\uFF08\u53EF\u9009\uFF0C\u6574\u90E8\u5143\u4FE1\u606F\uFF1B\u4E00\u822C\u7531 merger \u6536\u53E3\u65F6\u5199\uFF09 ====================
|
|
82
|
-
worldview: <\u4E16\u754C\u89C2\uFF0C\u53D6\u8FD9\u4E9B\u679A\u4E3E\u4E4B\u4E00\uFF1A`+bp.join(" / ")+`>
|
|
83
|
-
style: <\u98CE\u683C\uFF0C\u81EA\u7531\u6587\u672C\uFF0C\u5982 \u90FD\u5E02\u751C\u5BA0 / \u60AC\u7591\u590D\u4EC7>
|
|
84
|
-
title: <\u5267\u540D>
|
|
85
|
-
\u4E3B\u89D2: <\u4E3B\u89D2\u540D1>, <\u4E3B\u89D2\u540D2> \u2190 \u5217\u5728\u8FD9\u91CC\u7684\u8BBE\u4E3A role_type=\u4E3B\u89D2\uFF0C\u5176\u4F59\u89D2\u8272=\u914D\u89D2
|
|
86
|
-
|
|
87
|
-
Rules:
|
|
88
|
-
- \u6B63\u6587 \`- \u89D2\u8272/\u5730\u70B9/\u9053\u5177:\` \u548C\u5BF9\u767D anchor \u7528\u7684\u540D\u5B57\uFF0C\u5FC5\u987B\u662F\u5BF9\u5E94 md \u91CC\u767B\u8BB0\u7684\u89C4\u8303\u540D\u3002
|
|
89
|
-
- \u{1F534} \u72B6\u6001\u8981\u62BD\u5168\uFF1A\u51E1\u662F\u67D0\u89D2\u8272/\u5730\u70B9/\u9053\u5177\u5728\u5267\u4E2D\u51FA\u73B0\u53EF\u8FA8\u7684\u6301\u4E45\u5916\u89C2\u6863\u4F4D\uFF08\u6362\u88C5\u3001\u53D1\u578B\u3001\u663E\u8457
|
|
90
|
-
\u4F24\u5986\u3001\u573A\u666F\u767D\u5929/\u591C\u665A/\u88AB\u6BC1\u7B49\uFF09\uFF0C\u90FD\u8981\u5728\u5176\u4E0B\u767B\u4E00\u4E2A\u72B6\u6001\u5B50 bullet\uFF1B\u5E76\u5728\u6B63\u6587\u573A\u666F \`- \u89D2\u8272:\`
|
|
91
|
-
\u884C\u7528 \`\u540D(\u72B6\u6001\u540D)\` \u5F15\u7528\u5F53\u96C6\u6240\u5904\u72B6\u6001\uFF0C\u6CA1\u5199=\u9ED8\u8BA4\u3002\u7ED9\u6BCF\u4E2A\u8D44\u4EA7\u81F3\u5C11\u767B\u4E00\u4E2A \`\u9ED8\u8BA4\` \u72B6\u6001\u3002
|
|
92
|
-
- \u72B6\u6001\u63CF\u8FF0\u53EA\u5199\u7A33\u5B9A\u53EF\u89C6\u5916\u89C2\uFF0C\u4E0D\u5199\u955C\u5934/\u5267\u60C5\u8C03\u5EA6\uFF1B\u4E0D\u8981\u628A\u201C\u80CC\u5BF9\u955C\u5934\u3001\u6B63\u8138\u672A\u9732\u3001\u7279\u5199\u3001
|
|
93
|
-
\u521D\u59CB\u3001\u8F6C\u8EAB\u3001\u63A5\u8FC7\u624B\u3001\u62E5\u543B\u3001\u7AD9\u5728\u821E\u53F0\u4E0A\u201D\u7B49\u52A8\u4F5C\u3001\u906E\u6321\u3001\u673A\u4F4D\u6216\u60C5\u8282\u8BCD\u5199\u8FDB\u72B6\u6001\u63CF\u8FF0\u3002
|
|
94
|
-
- \u6BCF\u4E2A\u72B6\u6001\u53EF\u5728\u4E0B\u4E00\u884C\u5199 \`\u63D0\u53D6\u7F18\u7531:\`\uFF0C\u7528\u81EA\u7136\u8BED\u8A00\u8BF4\u660E\u539F\u6587\u8BC1\u636E\u548C\u4E3A\u4EC0\u4E48\u5B83\u662F\u72EC\u7ACB\u53EF\u590D\u7528
|
|
95
|
-
\u5916\u89C2\u72B6\u6001\uFF1B\u4E0D\u8981\u5199\u7ED3\u6784\u5316\u6807\u7B7E\u3002\u8FDE\u7EED\u53D8\u5316\u8FC7\u7A0B\u5E27\u3001\u5C40\u90E8\u5149\u6548\u5F3A\u5F31\u3001\u900F\u660E/\u6D88\u6563/\u51DD\u5B9E\u8FDB\u5EA6\u3001
|
|
96
|
-
\u660F\u8FF7\u5367\u5E8A\u3001\u666E\u901A\u4FBF\u88C5\u9ED8\u8BA4\u4E0D\u4F5C\u4E3A\u72EC\u7ACB\u72B6\u6001\u3002
|
|
97
|
-
- \u660E\u786E\u4EEA\u5F0F\u8EAB\u4EFD\u53EF\u4FDD\u5B88\u8865\u9020\u578B\u72B6\u6001\uFF1A\u5A5A\u793C\u91CC\u4F4D\u4E8E\u7EA2\u6BEF\u5C3D\u5934\u3001\u63A5\u8FC7\u65B0\u5A18\u624B\u3001\u821E\u53F0\u62E5\u543B\u7684\u65B0\u90CE\uFF0C
|
|
98
|
-
\u5E94\u767B\u8BB0\u201C\u65B0\u90CE\u9020\u578B/\u5A5A\u793C\u6B63\u88C5\u201D\u72B6\u6001\uFF1B\u6574\u5957\u670D\u88C5\u9020\u578B\u5C5E\u4E8E\u4EBA\u7269\u72B6\u6001\uFF0C\u4E0D\u4F5C\u4E3A\u9053\u5177\u3002
|
|
99
|
-
- \u8D44\u4EA7\u540D\u662F\u89C4\u8303\u5B9E\u4F53\u540D\uFF0C\u4E0D\u5939\u62EC\u53F7 / \u72B6\u6001 / \u60C5\u7EEA / \u8EAB\u4EFD\u6CE8\u89E3\uFF1B\u60C5\u7EEA / \u59FF\u6001 / \u4E34\u65F6\u810F\u6C61\u4F24\u53E3 /
|
|
100
|
-
\u5904\u5883\u4F18\u5148\u653E\u8FDB action \u6587\u672C\u6216 dlg \u7684 emotion \u6807\u7B7E\uFF0Cparse/direct \u4E0D\u4F1A\u6309\u5173\u952E\u8BCD\u81EA\u52A8\u5220\u9664
|
|
101
|
-
\u5DF2\u663E\u5F0F\u767B\u8BB0\u7684\u4EBA\u7269\u72B6\u6001\u3002
|
|
102
|
-
- \u573A\u666F\u540D\u4E0D\u8981\u5199\u6210\u300C\u591C\u665A\u7684\u6559\u5BA4 / \u9EC4\u660F\u7684\u8857\u9053\u300D\u8FD9\u79CD\u72B6\u6001\u5316\u8D44\u4EA7\uFF1B\u767B\u8BB0\u4E3A\u300C\u6559\u5BA4 / \u8857\u9053\u300D\uFF0C\u628A
|
|
103
|
-
\u591C\u665A / \u9EC4\u660F\u5199\u6210\u8BE5\u573A\u666F\u7684\u72B6\u6001\u3002parse/direct \u4F1A\u5BF9\u786E\u5B9A\u7684\u65F6\u95F4\u72B6\u6001\u505A\u4FDD\u5B88\u89C4\u8303\u5316\u3002
|
|
104
|
-
- \u4EBA\u7269\u6301\u6709\u6216\u4F69\u6234\u7684\u7269\u4EF6\u5E94\u663E\u5F0F\u767B\u8BB0 / \u5F15\u7528\u4E3A\u9053\u5177\uFF0C\u4E0D\u8981\u5199\u6210\u4EBA\u7269\u72B6\u6001\uFF1Bparse/direct \u4E0D\u4F1A
|
|
105
|
-
\u4ECE\u4EBA\u7269\u540D / \u4EBA\u7269\u5F15\u7528 / \u4EBA\u7269\u72B6\u6001\u6807\u7B7E\u81EA\u52A8\u62C6\u51FA\u9053\u5177\u3002
|
|
106
|
-
- \u9053\u5177\u662F\u9700\u8981\u4F5C\u4E3A\u72EC\u7ACB\u89C6\u89C9\u8D44\u4EA7\u8FFD\u8E2A\u7684\u5177\u4F53\u7269\u4EF6\uFF0C\u4E0D\u662F\u52A8\u4F5C\u91CC\u51FA\u73B0\u7684\u6240\u6709\u7269\u54C1\u540D\u3002\u53EA\u6709\u63A8\u52A8
|
|
107
|
-
\u5267\u60C5\u3001\u627F\u8F7D\u89C4\u5219 / \u8BC1\u636E / \u79D8\u5BC6 / \u4EFB\u52A1\u3001\u9700\u8981\u770B\u6E05\u7279\u5B9A\u6587\u5B57 / \u56FE\u6848 / \u7167\u7247 / \u754C\u9762\u3001\u8DE8\u573A
|
|
108
|
-
\u53CD\u590D\u51FA\u73B0\u9700\u4FDD\u6301\u5916\u89C2\u3001\u6216\u4F5C\u4E3A \`prop:<\u9053\u5177\u540D>\` \u53D1\u58F0\u65F6\uFF0C\u624D\u5199\u8FDB \u9053\u5177.md / \u6B63\u6587 \`- \u9053\u5177:\`\u3002
|
|
109
|
-
\u4E0D\u6EE1\u8DB3\u8FD9\u4E9B\u6761\u4EF6\u6216\u62FF\u4E0D\u51C6\u65F6\uFF0C\u4E0D\u8981\u63D0\u5347\u4E3A\u9053\u5177\u3002
|
|
110
|
-
\u4EC5\u4EC5\u88AB\u62FF\u8D77\u3001\u4F7F\u7528\u3001\u4F69\u6234\u3001\u770B\u89C1\u3001\u6254\u51FA\u3001\u643A\u5E26\u3001\u635F\u574F\u3001\u77ED\u6682\u53C2\u4E0E\u52A8\u4F5C\uFF0C\u4E0D\u6784\u6210\u9053\u5177\u767B\u8BB0\u7406\u7531\u3002
|
|
111
|
-
\u4E0D\u8981\u4E3A\u666E\u901A\u7269\u54C1\u7C7B\u522B\u521B\u5EFA\u201C\u67D0\u4EBA\u7684\u67D0\u7269\u201D\u8FD9\u7C7B\u4E13\u5C5E\u53D8\u4F53\uFF0C\u9664\u975E\u8FD9\u4E2A\u5B9E\u4F53\u672C\u8EAB\u9700\u8981\u8DE8\u573A\u8FDE\u7EED\uFF0C
|
|
112
|
-
\u6216\u5E26\u6709\u5FC5\u987B\u770B\u6E05\u7684\u5DEE\u5F02\u5316\u5185\u5BB9\u3002
|
|
113
|
-
\u666E\u901A\u52A8\u4F5C\u5DE5\u5177\u3001\u4E34\u65F6\u624B\u6301\u7269\u3001\u80CC\u666F\u6446\u8BBE\u3001\u666E\u901A\u751F\u6D3B\u7528\u54C1\u3001\u666E\u901A\u5BB6\u5177\u3001\u666E\u901A\u670D\u88C5\u914D\u4EF6\u53EA\u7559\u5728
|
|
114
|
-
action \u6587\u672C\u3002\u5E94\u62BD\uFF1A\u53EF\u8BFB\u89C4\u5219 / \u8BC1\u636E\u7269\u3001\u4EFB\u52A1\u6216\u79D8\u5BC6\u8F7D\u4F53\u3001\u51B2\u7A81\u5173\u952E\u6B66\u5668\u3001\u901A\u884C\u94A5\u5319\u6216\u51ED\u8BC1\u3001
|
|
115
|
-
\u53CD\u590D\u51FA\u73B0\u7684\u62A4\u8EAB\u7B26 / \u88C5\u7F6E\u3001\u4F1A\u53D1\u58F0\u7684\u7269\u4EF6\uFF1B\u4E0D\u5E94\u62BD\uFF1A\u666E\u901A\u901A\u8BAF\u8BBE\u5907\u3001\u5DE5\u5177\u3001\u9910\u5177\u3001\u4E66\u672C\u3001
|
|
116
|
-
\u8863\u7269\u3001\u5BB6\u5177\u3001\u88C5\u9970\u7269\u7B49\u4E00\u6B21\u6027\u52A8\u4F5C\u7EC6\u8282\u3002
|
|
117
|
-
- \u540C\u7C7B\u8D44\u4EA7\u540D\u6309 canonical key \u53BB\u91CD\uFF1A\u6298\u53E0\u7A7A\u767D\u3001\u5FFD\u7565\u7ED3\u6784\u6027\u6807\u70B9\u548C ASCII \u5927\u5C0F\u5199\uFF1B\u5982
|
|
118
|
-
\`\u674E\u56DB A\` / \`\u674E\u56DB a\` \u4F1A\u5408\u5E76\u4E3A\u9996\u4E2A\u663E\u793A\u540D\uFF0C\u5176\u4ED6\u540D\u5B57\u8FDB\u5165 aliases\u3002
|
|
119
|
-
- \u7FA4\u4F53\u8BCD\uFF08\u4F17\u4EBA / \u7FA4\u4F17 / \u56F4\u89C2\u8005 / \u8DEF\u4EBA\u4EEC\uFF09\u4E0D\u8FDB \u4EBA\u7269.md\uFF0C\u767B\u5230 \u53D1\u58F0\u6E90.md \u7528 group \u6216\u5199\u52A8\u4F5C\u65C1\u767D\u3002
|
|
120
|
-
- \u52A8\u4F5C / \u5BF9\u767D\u6B63\u6587\u9010\u5B57\u4FDD\u7559\uFF0C\u4E0D\u8981\u8F6C\u8FF0 / \u7FFB\u8BD1 / \u6982\u62EC / \u52A0\u6CE8\u91CA\uFF1B\u52A8\u4F5C\u79CD\u7C7B\u53EA\u6709 act/dlg/think\u3002
|
|
121
|
-
- \u6BCF\u4E2A\u51FA\u73B0\u5728\u6B63\u6587\u91CC\u7684\u89D2\u8272\uFF0C\u90FD\u8981\u5728 \u4EBA\u7269.md \u7ED9\u51FA\u975E\u7A7A\u63CF\u8FF0\uFF08\u5426\u5219\u6821\u9A8C\u62A5\u9519\uFF09\u3002
|
|
122
|
-
`,x=class extends Error{exitCode;errorCode;hint;data;constructor(t,n){super(t),this.name="CliError",this.exitCode=n.exitCode,this.errorCode=n.errorCode,this.hint=n.hint,this.data=n.data??{}}};function fh(e){return new Ur(e)}function vp(e){return fh(e).directDir}function xe(e){let t=e.script_path??e.scriptPath;return Ai.resolve(typeof t=="string"&&t.length>0?t:uh)}function ki(e){return Tr.readJson(e)}function ma(e,t){Tr.writeJson(e,t)}function ro(e){return Tr.exists(e)}function Se(e){return fa.createHash("sha256").update(e,"utf-8").digest("hex")}function ga(e){let t=fa.createHash("sha256"),n=Po.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=Po.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{Po.closeSync(n)}return t.digest("hex")}var yt={policy:["content_blocked"],network:["dns_failed","connection_refused","connection_reset","network_unreachable","tls_failed","network_failed"],timeout:["connect_timeout","request_timeout","media_processing_timeout"],rate_limit:["rate_limited"],authentication:["authentication_failed"],authorization:["permission_denied"],provider:["resource_not_found","provider_unavailable","request_rejected","attempts_exhausted"],media:["media_upload_failed","media_processing_failed","media_too_large","unsupported_media"],response:["output_truncated","empty_response","malformed_response"],pipeline:["serial_parse_failed","source_mismatch","pipeline_mismatch"],validation:["script_validation_failed"],cancelled:["cancelled"],unknown:["unknown","legacy_unclassified"]};function wt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Rp(e,t){switch(e){case"policy":return wt(t,yt.policy)?{failure_type:e,failure_code:t}:null;case"network":return wt(t,yt.network)?{failure_type:e,failure_code:t}:null;case"timeout":return wt(t,yt.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return wt(t,yt.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return wt(t,yt.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return wt(t,yt.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return wt(t,yt.provider)?{failure_type:e,failure_code:t}:null;case"media":return wt(t,yt.media)?{failure_type:e,failure_code:t}:null;case"response":return wt(t,yt.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return wt(t,yt.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return wt(t,yt.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return wt(t,yt.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return wt(t,yt.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function _t(e,t){return{...e,...t}}function Vo(e){switch(e.failure_type){case"policy":return{failure_type:e.failure_type,failure_code:e.failure_code};case"network":return{failure_type:e.failure_type,failure_code:e.failure_code};case"timeout":return{failure_type:e.failure_type,failure_code:e.failure_code};case"rate_limit":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authentication":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authorization":return{failure_type:e.failure_type,failure_code:e.failure_code};case"provider":return{failure_type:e.failure_type,failure_code:e.failure_code};case"media":return{failure_type:e.failure_type,failure_code:e.failure_code};case"response":return{failure_type:e.failure_type,failure_code:e.failure_code};case"pipeline":return{failure_type:e.failure_type,failure_code:e.failure_code};case"validation":return{failure_type:e.failure_type,failure_code:e.failure_code};case"cancelled":return{failure_type:e.failure_type,failure_code:e.failure_code};case"unknown":return{failure_type:e.failure_type,failure_code:e.failure_code}}}function bi(e){return{...e.provider!==void 0?{provider:e.provider}:{},...e.model!==void 0?{model:e.model}:{},...e.operation!==void 0?{operation:e.operation}:{},...e.http_status!==void 0?{http_status:e.http_status}:{},...e.system_code!==void 0?{system_code:e.system_code}:{},...e.provider_source!==void 0?{provider_source:e.provider_source}:{},...e.provider_reason!==void 0?{provider_reason:e.provider_reason}:{},...e.provider_reason_raw!==void 0?{provider_reason_raw:e.provider_reason_raw}:{},...e.finish_message!==void 0?{finish_message:e.finish_message}:{},...e.safety_ratings!==void 0?{safety_ratings:e.safety_ratings}:{},...e.details!==void 0?{details:e.details}:{}}}function Np(e,t){if(e.length===0)return _t({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:t});let n=e[0],i=e.every(r=>r.failure_type===n.failure_type&&r.failure_code===n.failure_code)?Vo(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return _t(i,{retryable:e.some(r=>r.retryable),message:t})}function Un(e){let t=e.provider||e.model?`${e.provider??"provider"}/${e.model??"model"} `:"",n=e.provider_reason?` provider_reason=${e.provider_reason}`:"",o=e.system_code?` system_code=${e.system_code}`:"",i=e.http_status!==void 0?` http_status=${e.http_status}`:"",r=e.details?.length?` | ${e.details.join(" | ")}`:"";return`${t}${e.failure_type}/${e.failure_code}${n}${o}${i}: ${e.message}${r}`}import*as zp from"node:crypto";import*as Hp from"node:fs";import*as Fp from"node:path";import*as $p from"node:crypto";var ln=["action","dialogue","inner_thought","transition"],Tt=new Set(ln),un=["system","broadcast","offscreen","group"],so=new Set(un),fn=["featured","background"],Et=new Set(fn),$o=["\u4E3B\u89D2","\u914D\u89D2"],Tn=new Set($o),Cr=["day","night","dawn","dusk"],ha=new Set(Cr);function Oi(e){return typeof e=="string"&&ha.has(e)}var ya=["interior","exterior"],Mp=new Set(ya);function Ze(e){return e.normalize("NFKC").toLowerCase()}function Lp(e){return JSON.stringify([e.code,e.path,e.message])}function wa(e){let t=new Map;for(let n of e){let o=Lp(n);t.set(o,(t.get(o)??0)+1)}return t}function _a(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=wa(e.errors),o=wa(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function Ea(e,t){let n=wa(e),o=[];for(let i of t){let r=Lp(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as mh}from"nanoid";var Do="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",xa=6,Go={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},gh=mh(Do,xa),hh=`[${Do}]`,Up=Object.fromEntries(Object.entries(Go).map(([e,t])=>[e,new RegExp(`^${t}${hh}{${xa}}$`)]));function T(e,t){return typeof t=="string"&&Up[e].test(t)}var Sa="ID_SPACE_EXHAUSTED";function vi(e,t=new Set,n=gh){let o=Go[e];for(let i=0;i<128;i++){let r=`${o}${n()}`;if(!t.has(r))return r}throw Object.assign(new Error(`Could not generate an unused ${e} ID after 128 attempts.`),{code:Sa})}var Ye=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},yh=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,wh=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function Tp(e){return e?Number(e.padEnd(3,"0")):0}function Cp(e,t){if(!Number.isSafeInteger(t))throw new Ye(e,"Timestamp exceeds the supported numeric range.");return t}function Pp(e,t){let n=Math.floor(e/1e3),o=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60,s=t?`.${t}`:"";return o>0?`${o}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`:`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`}function Cn(e){let t=e.trim();if(!t)throw new Ye(e,"Timestamp must not be empty.");let n=t.match(wh);if(n){let a=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new Ye(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new Ye(e,"Timestamp seconds must be between 00 and 59.");let f=Cp(e,((a*60+d)*60+p)*1e3+Tp(l));return{canonical:Pp(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(yh);if(!o)throw new Ye(e,"Use M:SS, MM:SS, or H:MM:SS with an optional 1-3 digit fraction.");let i=Number(o[1]),r=Number(o[2]),s=o[3];if(r>59)throw new Ye(e,"Timestamp seconds must be between 00 and 59.");let c=Cp(e,(i*60+r)*1e3+Tp(s));return{canonical:Pp(c,s),milliseconds:c,fractionDigits:s?.length??0}}function _h(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.extend;if(!(typeof t!="object"||t===null||Array.isArray(t)))return t.timestamp}function Pr(e,t,n){let o=null;e.forEach((i,r)=>{let s=_h(i);if(s===void 0)return;let c=`${t}[${r}].extend.timestamp`;if(typeof s!="string"){n("timestamp_invalid",c,"timestamp must be a string in M:SS, MM:SS, or H:MM:SS form");return}let a;try{a=Cn(s)}catch(d){if(!(d instanceof Ye))throw d;n("timestamp_invalid",c,d.message);return}o!==null&&a.milliseconds<o.timestamp.milliseconds&&n("timestamp_out_of_order",c,`timestamp ${a.canonical} is earlier than Action ${o.actionIndex+1} timestamp ${o.timestamp.canonical}; equal timestamps are allowed`),o={actionIndex:r,timestamp:a}})}var xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mn=e=>Array.isArray(e),Ee=e=>typeof e=="string",Eh=["state_changes","actor_id","speakers","lines"];function at(e){let t=[],n=[],o=(u,m,g,h)=>t.push({code:u,path:m,message:g,...h?{repair_hint:h}:{}}),i=(u,m,g)=>n.push({code:u,path:m,message:g});if(!xt(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==3&&o("version","$.version","version must be 3");for(let u of["title","worldview","style"])Ee(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,c=new Map,a=(u,m,g,h,w)=>{if(!mn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,E)=>{let S=`${w}[${E}]`;if(!xt(y)){o("asset",S,"asset must be an object");return}let _=y[g];if(!Ee(_)){o("asset_id",`${S}.${g}`,`${g} required`);return}if(s.has(_)&&o("dup_id",`${S}.${g}`,`duplicate id ${_}`),s.set(_,m),!Ee(y[h]))o("asset_name",`${S}.${h}`,`${h} required`);else if(m==="actor"){let R=Ze(y[h]),I=c.get(R);I!==void 0?o("dup_actor_name",`${S}.${h}`,`actor name ${y[h]} already belongs to ${I}`):c.set(R,_)}(!Ee(y.importance)||!fn.includes(y.importance))&&o("importance",`${S}.importance`,`importance must be one of ${fn.join("|")}`),Ee(y.description)||o("asset_desc",`${S}.description`,"description must be a string");let A=new Set,k=new Set,D=0;!mn(y.states)||y.states.length===0?o("states",`${S}.states`,"states must be a non-empty array"):y.states.forEach((R,I)=>{let M=`${S}.states[${I}]`;if(!xt(R)||!Ee(R.state_id)){o("state_id",M,"state_id required");return}A.has(R.state_id)&&o("dup_state",M,`duplicate state_id ${R.state_id}`),A.add(R.state_id),R.state_id==="default"&&D++,Ee(R.state_name)?(k.has(R.state_name)&&o("dup_state_name",`${M}.state_name`,`duplicate state_name ${R.state_name}`),k.add(R.state_name)):o("state_name",`${M}.state_name`,"state_name required")}),mn(y.states)&&D!==1&&o("default_state",`${S}.states`,`exactly one 'default' state required, found ${D}`),r.set(_,A)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,m,g,h)=>{if(s.get(u)!==g){o("ref",h,`${g} ${u} not found`);return}m!==void 0&&(!Ee(m)||!r.get(u)?.has(m))&&o("state_ref",h,`state ${String(m)} not materialized on ${u}`)},p=(u,m,g,h)=>{if(u===void 0){o("field",h,`${h} required (may be empty array)`);return}if(!mn(u)){o("field",h,`${h} must be an array`);return}u.forEach((w,y)=>{if(!xt(w)||!Ee(w[g])){o("ref",`${h}[${y}]`,`${g} required`);return}d(w[g],w.state_id,m,`${h}[${y}]`)})},l=(u,m,g,h)=>{if(!xt(u)){o("action",m,"action must be an object");return}for(let y of Eh)y in u&&o("legacy_field",`${m}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!Ee(w)||!ln.includes(w))&&o("action_type",`${m}.type`,`invalid action type ${String(w)}`),Ee(u.content)||o("content",`${m}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!xt(y))o("speaker",`${m}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!Ee(y.kind)||!un.includes(y.kind))&&o("speaker_kind",`${m}.speaker.kind`,"invalid non-actor speaker kind");else if(Ee(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${m}.speaker`),!g.has(y.actor_id)){let E=r.get(y.actor_id),S=Ee(y.state_id)&&E?.has(y.state_id)?y.state_id:E?.has("default")?"default":E?.values().next().value,_=h&&S?`scriptctl scene-ref ${h} actor:${y.actor_id} --state ${S} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${m}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,_)}}else o("speaker",`${m}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return mn(f)?f.forEach((u,m)=>{let g=`$.episodes[${m}]`;if(!xt(u)||!Ee(u.episode_id)){o("episode_id",g,"episode_id required");return}if(!mn(u.scenes)){o("scenes",`${g}.scenes`,"scenes must be an array");return}u.scenes.forEach((h,w)=>{let y=`${g}.scenes[${w}]`;if(!xt(h)){o("scene",y,"scene must be an object");return}"context"in h&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),Ee(h.scene_id)||o("scene_id",y,"scene_id required");let E=h.environment;E===void 0||xt(E)&&(!Ee(E.time)||E.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!xt(E)||E.space!==void 0&&!Ee(E.space)||!Ee(E.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Oi(E.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk");let S=h.location;if(S!==null&&(!xt(S)||!Ee(S.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(S.location_id,S.state_id,"location",`${y}.location`)),p(h.actors,"actor","actor_id",`${y}.actors`),p(h.props,"prop","prop_id",`${y}.props`),mn(h.props)){let A=new Set;h.props.forEach((k,D)=>{!xt(k)||!Ee(k.prop_id)||(A.has(k.prop_id)&&o("dup_prop_ref",`${y}.props[${D}]`,`duplicate prop ref ${k.prop_id}`),A.add(k.prop_id))})}let _=new Set(mn(h.actors)?h.actors.filter(A=>xt(A)).map(A=>A.actor_id).filter(A=>Ee(A)):[]);if(!mn(h.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=Ee(h.scene_id)?`${u.episode_id}/${h.scene_id}`:void 0;h.actions.forEach((k,D)=>l(k,`${y}.actions[${D}]`,_,A)),Pr(h.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var Xe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=e=>typeof e=="string",Wt=e=>Array.isArray(e);function Ia(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ia):Xe(e)&&Object.values(e).every(Ia)}function Jo(e,t,n){e!==void 0&&(!Xe(e)||!Object.values(e).every(Ia))&&n("extend",t,"extend must be an object containing JSON values")}function xh(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Ue(e){let t=[],n=[],o=(u,m,g,h)=>t.push({code:u,path:m,message:g,...h?{repair_hint:h}:{}}),i=(u,m,g,h)=>n.push({code:u,path:m,message:g,...h?{repair_hint:h}:{}});if(!Xe(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==4&&o("version","$.version","version must be 4");for(let u of["title","worldview","style"])ae(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!ae(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!Wt(e.main_characters)||!e.main_characters.every(u=>Xe(u)&&ae(u.name)&&ae(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),Jo(e.extend,"$.extend",o);let r=new Map,s=new Map,c=new Set,a=(u,m,g,h,w)=>{if(!Wt(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((E,S)=>{let _=`${w}[${S}]`;if(!Xe(E)){o("asset",_,"asset must be an object");return}let A=E[g];if(!T(m,A)){o("asset_id",`${_}.${g}`,`${g} must be ${m} ID`);return}if(y.has(A)&&o("dup_id",`${_}.${g}`,`duplicate ${g} ${A}`),y.add(A),r.set(A,m),!ae(E[h])||E[h].trim()==="")o("asset_name",`${_}.${h}`,`${h} must be a non-empty string`);else if(m==="actor"){let I=E[h].trim().toLocaleLowerCase();c.has(I)&&o("dup_actor_name",`${_}.${h}`,`duplicate actor name ${E[h]}`),c.add(I)}if((!ae(E.importance)||!fn.includes(E.importance))&&o("importance",`${_}.importance`,`importance must be ${fn.join("|")}`),m==="actor"&&E.role_type!==void 0&&(!ae(E.role_type)||!$o.includes(E.role_type))&&o("role_type",`${_}.role_type`,`role_type must be ${$o.join("|")}`),ae(E.description)||o("asset_desc",`${_}.description`,"description must be a string"),E.aliases!==void 0&&(!Wt(E.aliases)||!E.aliases.every(ae)))o("aliases",`${_}.aliases`,"aliases must be an array of strings");else if(Wt(E.aliases)&&E.aliases.every(ae)){let I=new Set,M=ae(E[h])?E[h]:"";E.aliases.forEach(($,U)=>{$===""&&o("alias_empty",`${_}.aliases[${U}]`,"alias must not be empty"),$===M&&o("alias_equals_name",`${_}.aliases[${U}]`,"alias must differ from the asset name"),I.has($)&&o("dup_alias",`${_}.aliases[${U}]`,`duplicate alias ${$}`),I.add($)})}Jo(E.extend,`${_}.extend`,o);let k=new Set,D=new Set,R=0;!Wt(E.states)||E.states.length===0?o("states",`${_}.states`,"states must be a non-empty array"):E.states.forEach((I,M)=>{let $=`${_}.states[${M}]`;if(!Xe(I)){o("state",$,"state must be an object");return}let U=I.state_id;if(U!=="default"&&!T("state",U)){o("state_id",`${$}.state_id`,"state_id must be default or st plus six Base58 characters");return}k.has(U)&&o("dup_state",`${$}.state_id`,`duplicate state_id ${U}`),k.add(U),U==="default"&&R++,!ae(I.state_name)||I.state_name.trim()===""?o("state_name",`${$}.state_name`,"state_name must be a non-empty string"):(D.has(I.state_name)&&o("dup_state_name",`${$}.state_name`,`duplicate state_name ${I.state_name}`),D.add(I.state_name)),ae(I.description)||o("state_description",`${$}.description`,"description must be a string"),Jo(I.extend,`${$}.extend`,o)}),R!==1&&o("default_state",`${_}.states`,`exactly one default state required, found ${R}`),s.set(A,k)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,m,g)=>{if(!Wt(m)||m.length===0||!m.every(ae))return o("state_ids",g,"state_ids must be a non-empty array of strings"),[];let h=m,w=new Set;return h.forEach((y,E)=>{w.has(y)&&o("dup_state_ref",`${g}[${E}]`,`duplicate state_id ${y}`),w.add(y),s.get(u)?.has(y)||o("state_ref",`${g}[${E}]`,`state ${y} not found on ${u}`)}),xh(h)||o("state_ids_order",g,"state_ids must be sorted lexically"),h},p=new Set,l=new Set,f=new Set;return Wt(e.episodes)?e.episodes.forEach((u,m)=>{let g=`$.episodes[${m}]`;if(!Xe(u)){o("episode",g,"episode must be an object");return}T("episode",u.episode_id)?(p.has(u.episode_id)&&o("dup_episode_id",`${g}.episode_id`,`duplicate episode_id ${u.episode_id}`),p.add(u.episode_id)):o("episode_id",`${g}.episode_id`,"episode_id must be ep plus six Base58 characters");for(let h of["title","synopsis"])u[h]!==void 0&&!ae(u[h])&&o("field",`${g}.${h}`,`${h} must be a string`);if(Jo(u.extend,`${g}.extend`,o),!Wt(u.scenes)){o("scenes",`${g}.scenes`,"scenes must be an array");return}u.scenes.forEach((h,w)=>{let y=`${g}.scenes[${w}]`;if(!Xe(h)){o("scene",y,"scene must be an object");return}T("scene",h.scene_id)?(l.has(h.scene_id)&&o("dup_scene_id",`${y}.scene_id`,`duplicate scene_id ${h.scene_id}`),l.add(h.scene_id)):o("scene_id",`${y}.scene_id`,"scene_id must be scn plus six Base58 characters"),Jo(h.extend,`${y}.extend`,o),h.environment===void 0||Xe(h.environment)&&(!ae(h.environment.time)||h.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!Xe(h.environment)||h.environment.space!==void 0&&!ae(h.environment.space)||!ae(h.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Oi(h.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),h.location!==null&&(!Xe(h.location)||!T("location",h.location.location_id)?o("location",`${y}.location`,"location must be null or a typed v4 location reference"):("state_id"in h.location&&o("v3_field",`${y}.location.state_id`,"Script v4 scene references use state_ids"),r.get(h.location.location_id)!=="location"&&o("location_ref",`${y}.location.location_id`,`location ${h.location.location_id} not found`),d(h.location.location_id,h.location.state_ids,`${y}.location.state_ids`)));let E=new Map,S=(_,A,k,D)=>{if(!Wt(_)){o("field",D,`${D} must be an array`);return}let R=new Set;_.forEach((I,M)=>{let $=`${D}[${M}]`;if(!Xe(I)||!T(A,I[k])){o("ref",$,`${k} must be a typed v4 ID`);return}let U=I[k];"state_id"in I&&o("v3_field",`${$}.state_id`,"Script v4 scene references use state_ids"),R.has(U)&&o("dup_asset_ref",`${$}.${k}`,`duplicate ${A} ref ${U}`),R.add(U),r.get(U)!==A&&o("asset_ref",`${$}.${k}`,`${A} ${U} not found`);let v=d(U,I.state_ids,`${$}.state_ids`);A==="actor"&&E.set(U,new Set(v))})};if(S(h.actors,"actor","actor_id",`${y}.actors`),S(h.props,"prop","prop_id",`${y}.props`),!Wt(h.actions)){o("actions",`${y}.actions`,"actions must be an array");return}h.actions.forEach((_,A)=>{let k=`${y}.actions[${A}]`;if(!Xe(_)){o("action",k,"action must be an object");return}if(T("action",_.action_id)?(f.has(_.action_id)&&o("dup_action_id",`${k}.action_id`,`duplicate action_id ${_.action_id}`),f.add(_.action_id)):o("action_id",`${k}.action_id`,"action_id must be ac plus six Base58 characters"),(!ae(_.type)||!ln.includes(_.type))&&o("action_type",`${k}.type`,`invalid action type ${String(_.type)}`),ae(_.content)||o("content",`${k}.content`,"content must be a string"),"emotion"in _&&o("v3_field",`${k}.emotion`,"Script v4 does not allow emotion"),Jo(_.extend,`${k}.extend`,o),_.type==="dialogue"||_.type==="inner_thought")if(_.parenthetical!==void 0&&!ae(_.parenthetical)&&o("parenthetical",`${k}.parenthetical`,"parenthetical must be a string"),!Xe(_.speaker))o("speaker",`${k}.speaker`,"dialogue/inner_thought requires a speaker");else if(ae(_.speaker.actor_id)){("kind"in _.speaker||"label"in _.speaker)&&o("speaker_shape",`${k}.speaker`,"actor speaker cannot contain non-actor speaker fields");let R=_.speaker.actor_id;(!T("actor",R)||r.get(R)!=="actor")&&o("speaker_actor",`${k}.speaker.actor_id`,`actor ${R} not found`);let I=E.get(R),M=s.get(R),$=ae(_.speaker.state_id)&&M?.has(_.speaker.state_id)?_.speaker.state_id:void 0,U=M?.has("default")?"default":M?.values().next().value,v=$?[$]:U?[U]:[],j=T("scene",h.scene_id)&&T("actor",R)&&v.length>0?`scriptctl scene-ref ${h.scene_id} ${R} ${v.map(Z=>`--state ${Z}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${k}.speaker.actor_id`,`actor ${R} is not referenced by this scene`,j),_.speaker.state_id!==void 0&&(!ae(_.speaker.state_id)||!I?.has(_.speaker.state_id))){let Z=$?[...new Set([...I??[],$])].sort():[],De=T("scene",h.scene_id)&&T("actor",R)&&Z.length>0?`scriptctl scene-ref ${h.scene_id} ${R} ${Z.map(B=>`--state ${B}`).join(" ")} -p "$SCRIPT"`:j;o("speaker_state",`${k}.speaker.state_id`,`speaker state ${String(_.speaker.state_id)} is not in this scene's actor state_ids`,De)}}else ae(_.speaker.kind)?(("actor_id"in _.speaker||"state_id"in _.speaker)&&o("speaker_shape",`${k}.speaker`,"non-actor speaker cannot contain actor speaker fields"),un.includes(_.speaker.kind)||o("speaker_kind",`${k}.speaker.kind`,"invalid non-actor speaker kind"),_.speaker.label!==void 0&&!ae(_.speaker.label)&&o("speaker_label",`${k}.speaker.label`,"speaker label must be a string")):o("speaker",`${k}.speaker`,"speaker needs actor_id or kind");else"parenthetical"in _&&o("parenthetical_type",`${k}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in _&&o("speaker_type",`${k}.speaker`,"speaker only belongs to speaking actions");if(_.transition_prompt!==void 0){let R=_.transition_prompt;!Xe(R)||!ae(R.target)||!ae(R.process)||R.process===""||!ae(R.contrast)||R.contrast===""?o("transition_prompt",`${k}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(R.target)||o("transition_target",`${k}.transition_prompt.target`,`asset ${R.target} not found`)}}),Pr(h.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function ao(e,t=new Set,n){try{return n?vi(e,t,n):vi(e,t)}catch(o){throw o?.code!==Sa?o:new x(`Could not generate an unused ${e} ID.`,{exitCode:b,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function ye(e,t=[]){throw new x(e,{exitCode:b,errorCode:"CREATIVE_DRAFT_INVALID",hint:"Use the readable creative draft schema; do not include Script IDs or .scriptctl syntax.",data:{actual:t.map(String)}})}function gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Q(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function Sh(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&ye(`${t} must be a positive integer.`,[e]),n}function Ih(e){return e===void 0?{}:(gn(e)||ye("Action extensions must be an object."),structuredClone(e))}function Ah(e){let t=new Set;for(let n of e.actors){t.add(n.actor_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.locations){t.add(n.location_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.props){t.add(n.prop_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.episodes){t.add(n.episode_id);for(let o of n.scenes){t.add(o.scene_id);for(let i of o.actions)t.add(i.action_id)}}return t}function Pn(e,t,n){for(let o=0;o<128;o+=1){let i=$p.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let c=0;c<6;c+=1)r+=Do[i[c]%Do.length];let s=`${Go[e]}${r}`;if(!n.has(s))return n.add(s),s}ye(`Could not allocate a stable ${e} ID.`)}function kh(e){let t=Q(e).match(/^(\d+):([0-5]\d)(?:\.(\d{1,3}))?$/u);return t?(Number(t[1])*60+Number(t[2]))*1e3+Number((t[3]??"").padEnd(3,"0")):null}function bh(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function Oh(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function vh(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(kh(n.extend?.timestamp)??t)+Oh(n);return t}function Dp(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(gn))&&ye("Asset variants must be an array of readable objects."),e)}function Rh(e,t){let n=e.assets;if(n===void 0)return[];gn(n)||ye("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(gn))&&ye(`assets.${t} must be an array.`),o)}function Nh(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function Mh(e,t){return e[t]}function Lh(e,t){return[Nh(e,t),...t.aliases??[]].map(Ze)}function Gp(e,t,n){let o=Ze(n);return Rh(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>Ze(Q(r))).includes(o))??null}function Jp(e,t){if(!e)return null;let n=Ze(t);return Dp(e.variants).find(o=>{let i=Ze(Q(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function Bp(e,t,n){let o=Jp(e,n),i=Q(o?.description);return(!o||!i)&&ye(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function Uh(e,t){let n=Q(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(Ze(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function Th(e,t,n,o,i,r){let s=Gp(t,n,o);s||ye(`${o} is not an existing ${n} asset and has no readable declaration.`);let c=Q(s.name,o),a=Dp(s.variants),d=Jp(s,"\u9ED8\u8BA4")??a[0]??null;n==="actors"&&!Q(s.description)&&ye(`${c} requires an identity description separate from its appearance variants.`),n==="actors"&&!Q(d?.description)&&ye(`${c} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:Uh(n,d),description:Q(d?.description,Q(s.description,`${c}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of a){let m=Q(u.name);if(u===d||!m||["default","\u9ED8\u8BA4"].includes(Ze(m)))continue;let g=Pn("state",`${n}:${c}:${m}`,i);p.push({state_id:g,state_name:m,description:Q(Bp(s,c,m).description)}),r.states.push(`${c}/${m}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>Q(u)).filter(u=>u&&u!==c))]:[],importance:s.importance==="background"?"background":"featured",description:Q(s.description,`${c}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:Pn("actor",c,i),actor_name:c,...s.roleType==="\u4E3B\u89D2"||s.roleType==="\u914D\u89D2"?{role_type:s.roleType}:{}};return e.actors.push(u),r.actors.push(c),u}if(n==="locations"){let u={...l,location_id:Pn("location",c,i),location_name:c};return e.locations.push(u),r.locations.push(c),u}let f={...l,prop_id:Pn("prop",c,i),prop_name:c};return e.props.push(f),r.props.push(c),f}function $r(e,t,n,o,i,r){let s=Q(o);s||ye(`${n} reference requires a readable name.`);let c=Ze(s);return Mh(e,n).find(d=>Lh(n,d).includes(c))??Th(e,t,n,s,i,r)}function Ri(e,t,n,o,i,r){let s=Q(t,"\u9ED8\u8BA4"),c=Ze(s),a=e.states.find(u=>Ze(u.state_name)===c||u.state_id==="default"&&["default","\u9ED8\u8BA4"].includes(c));if(a)return a.state_id;let d="actor_name"in e?e.actor_name:"location_name"in e?e.location_name:e.prop_name,p=Gp(n,o,d),l=Bp(p,d,s),f={state_id:Pn("state",`${d}:${s}`,i),state_name:s,description:Q(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function Vp(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(gn))&&ye(`${t} must be an array of readable references.`),e)}function Vr(e,t,n){let o=structuredClone(e);for(let i of t){let r=o.find(s=>n(s)===n(i));r?r.state_ids=[...new Set([...r.state_ids,...i.state_ids])].sort():o.push(structuredClone(i))}return o}function Ch(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&Q(e.environment?.space)===Q(t.environment?.space)&&Q(e.environment?.time)===Q(t.environment?.time))}function Ph(e,t,n,o,i,r,s,c){(!Array.isArray(e)||e.length===0||!e.every(gn))&&ye("scene.actions must contain at least one readable Action.");let a=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=Q(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||ye(`Action ${f+1} has an unsupported type.`,[u]);let m=Q(l.content);m||ye(`Action ${f+1} has empty content.`);let g=Math.max(400,Math.min(8e3,Math.round(Number(l.durationMs)||Number(l.weight||1)*1200))),h=Ih(l.extensions);h.timestamp=bh(d),h.duration_ms=g,h.rewrite_duration_ms!==void 0&&(h.rewrite_duration_ms=g);let w={action_id:Pn("action",`${i}:${f+1}:${m}`,s),type:u,content:m,extend:h};if(d+=g,u==="action"||u==="transition")return w;let y=Q(l.speaker);y||ye(`Action ${f+1} requires a speaker.`);let E=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${E}\\s*[:\uFF1A]`,"iu").test(m)&&ye(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(m)&&ye(`Action ${f+1} wraps dialogue content in quotation marks.`);let S=Ze(y);if(["\u65C1\u767D","narrator"].includes(S))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...Q(l.parenthetical)?{parenthetical:Q(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(S))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...Q(l.parenthetical)?{parenthetical:Q(l.parenthetical)}:{}};let _=$r(t,n,"actors",y,s,c),A=Q(l.speakerVariant),k=a.find(R=>R.actor_id===_.actor_id),D;if(A)D=Ri(_,A,n,"actors",s,c),k?k.state_ids=[...new Set([...k.state_ids,D])].sort():a.push({actor_id:_.actor_id,state_ids:[D]});else if(!k){let R=Ri(_,"\u9ED8\u8BA4",n,"actors",s,c);a.push({actor_id:_.actor_id,state_ids:[R]})}return{...w,speaker:{actor_id:_.actor_id,...D?{state_id:D}:{}},...Q(l.parenthetical)?{parenthetical:Q(l.parenthetical)}:{}}}),actorRefs:a}}function Kp(e,t){(!gn(t)||t.version!==1)&&ye("Creative draft version must be 1."),(!gn(t.episode)||!gn(t.scene))&&ye("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=Ah(r),c={actors:[],locations:[],props:[],states:[]},a=Sh(o.number,"episode.number");a>r.episodes.length+1&&ye("Episodes must be composed in order.",[a]);let d=r.episodes[a-1];d?(Q(d.title)||(d.title=Q(o.title,`\u7B2C ${a} \u96C6`)),Q(d.synopsis)||(d.synopsis=Q(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:Pn("episode",`episode:${a}`,s),title:Q(o.title,`\u7B2C ${a} \u96C6`),synopsis:Q(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=$r(r,n,"locations",i.location,s,c),l=Ri(p,i.locationVariant,n,"locations",s,c),f=Vp(i.actors,"scene.actors").map(I=>{let M=$r(r,n,"actors",I.name,s,c);return{actor_id:M.actor_id,state_ids:[Ri(M,I.variant,n,"actors",s,c)]}}),u=Vr([],f,I=>I.actor_id),m=Vp(i.props,"scene.props").map(I=>{let M=$r(r,n,"props",I.name,s,c);return{prop_id:M.prop_id,state_ids:[Ri(M,I.variant,n,"props",s,c)]}}),g=Vr([],m,I=>I.prop_id),h=d.scenes.at(-1),w={scene_id:Pn("scene",`episode:${a}:scene:${d.scenes.length+1}:${Q(i.title)}`,s),environment:{space:Q(i.space,"interior"),time:Q(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:g,actions:[],extend:{scene_title:Q(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=Q(i.boundary,"auto");["auto","new","continue"].includes(y)||ye("scene.boundary must be auto, new, or continue.");let E=Ch(h,w);y==="continue"&&!E&&ye("scene.boundary=continue requires the same location, space, and time as the previous scene.");let S=y!=="new"&&E,_=S&&h?h:w,A=S?d.scenes.length:d.scenes.length+1,k=Vr(_.actors,w.actors,I=>I.actor_id),D=Ph(i.actions,r,n,k,_.scene_id,vh(d),s,c);_.actors=D.actorRefs,_.props=Vr(_.props,w.props,I=>I.prop_id),_.location&&w.location&&(_.location.state_ids=[...new Set([..._.location.state_ids,...w.location.state_ids])].sort()),_.actions.push(...D.actions),S||d.scenes.push(_);let R=Ue(r);return R.ok||ye("Composed screenplay does not pass Script v4 validation.",R.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:R,episodeNumber:a,sceneNumber:A,sceneId:_.scene_id,actionIds:D.actions.map(I=>I.action_id),joinedPreviousScene:S,created:c}}function Ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Zt(e,t){return e[t]===void 0||typeof e[t]=="string"}function Aa(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Aa):Ge(e)&&Object.values(e).every(Aa)}function Bo(e){return e.extend===void 0||Ge(e.extend)&&Object.values(e.extend).every(Aa)}function ka(e){return e==="default"||T("state",e)}function Vh(e){return Ge(e)&&ka(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&Bo(e)}function ba(e){return typeof e.importance=="string"&&Et.has(e.importance)&&typeof e.description=="string"&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Vh)&&Bo(e)}function $h(e){return Ge(e)&&T("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&Tn.has(e.role_type))&&ba(e)}function Dh(e){return Ge(e)&&T("location",e.location_id)&&typeof e.location_name=="string"&&ba(e)}function Gh(e){return Ge(e)&&T("prop",e.prop_id)&&typeof e.prop_name=="string"&&ba(e)}function Oa(e){return Array.isArray(e)&&e.every(ka)}function Jh(e){return Ge(e)&&T("actor",e.actor_id)&&Oa(e.state_ids)}function Bh(e){return Ge(e)&&T("location",e.location_id)&&Oa(e.state_ids)}function Kh(e){return Ge(e)&&T("prop",e.prop_id)&&Oa(e.state_ids)}function jh(e){return T("actor",e.actor_id)&&(e.state_id===void 0||ka(e.state_id))}function zh(e){return typeof e.kind=="string"&&so.has(e.kind)&&Zt(e,"label")}function Hh(e){return!(!Ge(e)||!T("action",e.action_id)||typeof e.type!="string"||!Tt.has(e.type)||typeof e.content!="string"||!Zt(e,"parenthetical")||!Bo(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!Ge(e.speaker)||!jh(e.speaker)&&!zh(e.speaker))||e.transition_prompt!==void 0&&(!Ge(e.transition_prompt)||!T("actor",e.transition_prompt.target)&&!T("location",e.transition_prompt.target)&&!T("prop",e.transition_prompt.target)||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string"))}function Fh(e){return!(!Ge(e)||!T("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(Jh)||!Array.isArray(e.props)||!e.props.every(Kh)||!Array.isArray(e.actions)||!e.actions.every(Hh)||!Bo(e)||e.location!==null&&!Bh(e.location)||e.environment!==void 0&&(!Ge(e.environment)||!Zt(e.environment,"space")||!Zt(e.environment,"time")))}function Qh(e){return Ge(e)&&T("episode",e.episode_id)&&Zt(e,"title")&&Zt(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(Fh)&&Bo(e)}function Yh(e){return Ge(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&Zt(e,"worldview_raw")&&Zt(e,"synopsis")&&Zt(e,"logline")&&Zt(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>Ge(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every($h)&&Array.isArray(e.locations)&&e.locations.every(Dh)&&Array.isArray(e.props)&&e.props.every(Gh)&&Array.isArray(e.episodes)&&e.episodes.every(Qh)&&Bo(e)}function Dr(e){let t=Ue(e);if(t.ok)return e;throw new x("The local file is not a valid Script v4 document.",{exitCode:b,errorCode:"SCRIPT_V4_INVALID",hint:"Run `scriptctl validate --script-path <path>` and repair the reported v4 fields.",data:{expected:["A valid Script v4 document"],actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Xt(e){if(Yh(e))return e;throw new x("The local file is not a structurally readable Script v4 document.",{exitCode:b,errorCode:"SCRIPT_V4_SHAPE_INVALID",hint:"Repair the local Script v4 structure, then rerun the command.",data:{expected:["Script v4 with typed assets, episodes, scenes, references, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}import*as Ni from"node:crypto";import*as Me from"node:fs";import*as St from"node:path";import qh from"proper-lockfile";function Ra(e){if(Array.isArray(e))return e.map(Ra);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=Ra(t[o]);return n}return e}function Ce(e){let t=JSON.stringify(Ra(e));return`sha256:${Ni.createHash("sha256").update(t).digest("hex")}`}function Mi(e){return Me.existsSync(e)?`sha256:${Ni.createHash("sha256").update(Me.readFileSync(e)).digest("hex")}`:null}function Li(e,t){let n=Mi(e);if(n!==t)throw new x("The local script changed while the command was running.",{exitCode:b,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function Ui(e){let t=St.resolve(e),n=St.join(St.dirname(t),".scriptctl"),o=St.basename(t);return{scriptPath:t,stateDir:n,metadataPath:St.join(n,`${o}.working-copy.json`),lockPath:St.join(n,o)}}async function Gr(e,t){let n=Ui(e);Me.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await qh.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:60,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new x("Timed out waiting for the script file lock.",{exitCode:fe,errorCode:"WORKING_COPY_LOCK_TIMEOUT",hint:"Wait for the other scriptctl command to finish, then retry.",data:{actual:[n.scriptPath,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}function Je(e,t){Jr(e,`${JSON.stringify(t,null,2)}
|
|
123
|
-
`)}function Jr(e,t){let n=St.dirname(e);Me.mkdirSync(n,{recursive:!0});let o=St.join(n,`.${St.basename(e)}.${process.pid}.${Ni.randomUUID()}.tmp`),i=Me.openSync(o,"wx");try{Me.writeFileSync(i,t,"utf-8"),Me.fsyncSync(i)}finally{Me.closeSync(i)}Me.renameSync(o,e)}function Br(e){let t=Ui(e).metadataPath;if(!Me.existsSync(t))return null;let n;try{n=JSON.parse(Me.readFileSync(t,"utf-8"))}catch(i){throw va(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw va(t,"metadata root must be an object");let o=n;if(o.schemaVersion!==1||typeof o.projectGroupNo!="string"||o.projectGroupNo.length===0||typeof o.apiBaseUrl!="string"||o.apiBaseUrl.length===0||!Number.isInteger(o.baseRevision)||Number(o.baseRevision)<0||typeof o.baseContentHash!="string"||!o.baseContentHash.startsWith("sha256:"))throw va(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function Kr(e,t){Je(Ui(e).metadataPath,t)}function va(e,t){return new x("Working copy metadata is invalid.",{exitCode:b,errorCode:"WORKING_COPY_METADATA_INVALID",hint:"Run `scriptctl checkout --discard-local` to recreate the working copy metadata.",data:{expected:["valid scriptctl working-copy metadata"],actual:[e,t]}})}function kt(e,t){let n;try{n=JSON.parse(Me.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script changed while the command was running.",{exitCode:b,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=Ce(n);if(o!==t)throw new x("The local script changed while the command was running.",{exitCode:b,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[`loadedHash=${t}`,`currentHash=${o}`,e]}})}function O(e){return e==null?"":String(e)}function X(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hn(e){return Array.isArray(e)}function ee(e){return Array.isArray(e)?e:[]}function Na(e,t=[]){throw new x(e,{exitCode:G,errorCode:"CREATIVE_DRAFT_USAGE_INVALID",hint:"Run `scriptctl authoring compose <draft.json> --script-path <script.json>` and apply the returned plan digest.",data:{actual:t}})}function jp(e,t){let n=Fp.resolve(e),o;try{o=Hp.readFileSync(n)}catch{throw new x(`${t} does not exist.`,{exitCode:b,errorCode:"CREATIVE_DRAFT_SOURCE_UNAVAILABLE",data:{actual:[n]}})}try{return{path:n,bytes:o,value:JSON.parse(o.toString("utf-8"))}}catch(i){throw new x(`${t} is not valid JSON.`,{exitCode:b,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function Qp(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&Na("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=jp(n,"The creative draft"),i=xe(e),r=jp(i,"The target Script v4 file"),s=Xt(r.value),c=Ce(s),a=Kp(s,o.value),d=`sha256:${zp.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:c,proposed:Ce(a.script),episodeNumber:a.episodeNumber,sceneNumber:a.sceneNumber,sceneId:a.sceneId,actionIds:a.actionIds,joinedPreviousScene:a.joinedPreviousScene,created:a.created},l=`sha256:${Se(JSON.stringify(p))}`,f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&Na("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Na("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new x("The supplied plan does not match the current draft or script baseline.",{exitCode:b,errorCode:"CREATIVE_DRAFT_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});return f&&(kt(i,c),Je(i,a.script)),[{text:[`${f?"Applied":"Planned"} readable scene draft as episode ${a.episodeNumber}, scene ${a.sceneNumber}${a.joinedPreviousScene?" (joined previous scene)":""}`,`plan: ${l}`].join(`
|
|
124
|
-
`),data:{op:"compose",applied:f,source_path:o.path,source_digest:d,script_path:i,baseline:c,plan_digest:l,episode_number:a.episodeNumber,scene_number:a.sceneNumber,scene_id:a.sceneId,action_ids:a.actionIds,joined_previous_scene:a.joinedPreviousScene,created:a.created,validation:a.validation}},J]}import*as il from"node:fs";import*as rl from"node:path";var Ct={line:1,column:1};function Wh(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:Ct});for(let i of n.states)t.push(Ma("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:Ct});for(let i of n.states)t.push(Ma("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:Ct});for(let i of n.states)t.push(Ma("prop",n.prop_id,i))}return t}function Ma(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:Ct}}function Yp(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:Ct};return e.worldview_raw!==void 0&&(t.worldviewRaw=e.worldview_raw),e.synopsis!==void 0&&(t.synopsis=e.synopsis),e.logline!==void 0&&(t.logline=e.logline),e.theme!==void 0&&(t.theme=e.theme),e.main_characters!==void 0&&(t.mainCharacters=structuredClone(e.main_characters)),e.extend!==void 0&&(t.extend=structuredClone(e.extend)),{version:1,declarations:Wh(e),targets:[t],targetKind:"script"}}function Ko(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function Zh(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function Xh(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function ce(e,t,n){let o=[e,...t].map(Zh).join("|"),i=Xh(n);return`[${o}]${i.length>0?` ${i}`:""}`}function Ua(e){if(Array.isArray(e))return e.map(Ua);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Ua(e[n]);return t}return e}function yn(e){return e===void 0?[]:[ce("extensions",[],""),...Object.keys(e).sort().map(t=>ce("extend",[t],JSON.stringify(Ua(e[t]))))]}function ey(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function qp(e){let t=yn(e.extend);if(e.transition_prompt!==void 0&&t.push(ce("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast],"")),e.type==="dialogue"||e.type==="inner_thought"){let o=e.type==="dialogue"?"dlg":"think",i=[ey(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(ce(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(ce(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function Ta(e,t){let n=[...yn(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(ce("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(ce("environment",[e.environment.space],"")):n.push(ce("environment",[],""))),e.location===null)n.push(ce("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(ce("location",o,""))}for(let o of e.actors){let i=[o.actor_id];o.state_id!==void 0&&i.push(o.state_id),n.push(ce("cast",i,""))}for(let o of e.props){let i=[o.prop_id];o.state_id!==void 0&&i.push(o.state_id),n.push(ce("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...qp(o));return n.push("</body>","","</scene>"),n}function La(e){let t=[...yn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(ce("title",[],e.title)),e.synopsis!==void 0&&t.push(ce("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...Ta(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function ty(e){if(e.declarationKind==="state")return ny(e.ownerKind,e.ownerId,e.value);let t=e.value,n=yn(t.extend);t.aliases!==void 0&&n.push(ce("aliases",[],""));for(let o of t.aliases??[])n.push(ce("alias",[],o));if(e.declarationKind==="actor"){let o=e.value,i=[o.actor_id,o.actor_name,o.importance];o.role_type!==void 0&&i.push(o.role_type),n.push(ce("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(ce("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(ce("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function ny(e,t,n){return[...yn(n.extend),ce("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function oy(e){switch(e.kind){case"script":{let t=[...yn(e.extend),"<script>"];if(t.push(ce("title",[],e.title)),t.push(ce("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(ce("worldview-raw",[],e.worldviewRaw)),t.push(ce("style",[],e.style)),e.synopsis!==void 0&&t.push(ce("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(ce("logline",[],e.logline)),e.theme!==void 0&&t.push(ce("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(ce("main-characters",[],""));for(let n of e.mainCharacters)t.push(ce("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...La(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return La(e.value);case"episode-span":{let t=[...yn(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...La(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return Ta(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...yn(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...Ta(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...yn(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...qp(n));return t.push("</body>","</action-span>"),t}}}function Wp(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...ty(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...oy(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
|
|
125
|
-
`)}
|
|
126
|
-
`}function Be(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ct(e,t){return e[t]===void 0||typeof e[t]=="string"}function Ca(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ca):Be(e)&&Object.values(e).every(Ca)}function Vn(e){return e.extend===void 0||Be(e.extend)&&Object.values(e.extend).every(Ca)}function Pa(e){return Be(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&Vn(e)}function iy(e){return Be(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Et.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&(e.role_type===void 0||e.role_type==="\u4E3B\u89D2"||e.role_type==="\u914D\u89D2")&&Array.isArray(e.states)&&e.states.every(Pa)&&Vn(e)}function ry(e){return Be(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Et.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Pa)&&Vn(e)}function sy(e){return Be(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Et.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Pa)&&Vn(e)}function ay(e){if(!Be(e)||typeof e.type!="string"||!Tt.has(e.type)||typeof e.content!="string"||!ct(e,"emotion"))return!1;if(e.speaker!==void 0){if(!Be(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!ct(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!so.has(e.speaker.kind)||!ct(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!Be(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:Vn(e)}function cy(e){return!Be(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(ay)||!e.actors.every(t=>Be(t)&&typeof t.actor_id=="string"&&ct(t,"state_id"))||!e.props.every(t=>Be(t)&&typeof t.prop_id=="string"&&ct(t,"state_id"))||e.location!==null&&(!Be(e.location)||typeof e.location.location_id!="string"||!ct(e.location,"state_id"))||e.environment!==void 0&&(!Be(e.environment)||!ct(e.environment,"space")||!ct(e.environment,"time"))?!1:Vn(e)}function dy(e){return Be(e)&&typeof e.episode_id=="string"&&ct(e,"title")&&ct(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(cy)&&Vn(e)}function py(e){return Be(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&ct(e,"worldview_raw")&&ct(e,"synopsis")&&ct(e,"logline")&&ct(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>Be(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(iy)&&Array.isArray(e.locations)&&e.locations.every(ry)&&Array.isArray(e.props)&&e.props.every(sy)&&Array.isArray(e.episodes)&&e.episodes.every(dy)&&Vn(e)}function It(e){if(py(e))return e;throw new x("The local file is not a structurally readable Script v3 document.",{exitCode:b,errorCode:"SCRIPT_V3_SHAPE_INVALID",hint:"Repair the local Script v3 structure, then rerun authoring.",data:{expected:["Script v3 with typed assets, episodes, scenes, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}var Va=[3,4],ly={3:{version:3,require:It,requireStructurallyReadable:It,validate:at},4:{version:4,require:Dr,requireStructurallyReadable:Xt,validate:Ue}};function $n(e){return typeof e=="number"&&Va.some(t=>t===e)}function co(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new x("script.json must be an object with an explicit version.",{exitCode:b,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if($n(t))return t;throw new x("script.json must declare version 3 or version 4.",{exitCode:b,errorCode:t===void 0?"SCRIPT_VERSION_MISSING":"SCRIPT_VERSION_UNSUPPORTED",hint:"Use an explicit supported script version; scriptctl does not infer a version from document shape.",data:{expected:["version: 3 or version: 4"],actual:[String(t)]}})}function $a(e){return ly[co(e)]}function jr(e){return $a(e).require(e)}function zr(e){return $a(e).requireStructurallyReadable(e)}function Ti(e){return $a(e).validate(e)}function Hr(e){throw new x("Use a bare typed v4 ID or asset/state address.",{exitCode:G,errorCode:"V4_ADDRESS_INVALID",data:{expected:["ep\u2026 | scn\u2026 | ac\u2026 | act\u2026 | loc\u2026 | prp\u2026 | asset_id/state_id"],actual:[e||"<empty>"]}})}function Ci(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&Hr(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!T("state",i)&&Hr(t),T("actor",o)?{kind:"state",assetKind:"actor",assetId:o,stateId:i}:T("location",o)?{kind:"state",assetKind:"location",assetId:o,stateId:i}:T("prop",o)?{kind:"state",assetKind:"prop",assetId:o,stateId:i}:Hr(t)}return T("episode",t)?{kind:"episode",id:t}:T("scene",t)?{kind:"scene",id:t}:T("action",t)?{kind:"action",id:t}:T("actor",t)?{kind:"asset",assetKind:"actor",id:t}:T("location",t)?{kind:"asset",assetKind:"location",id:t}:T("prop",t)?{kind:"asset",assetKind:"prop",id:t}:Hr(t)}function po(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function wn(e){let t=[],n=0;return e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{t.push({episode:o,episodeIndex:i,scene:r,sceneIndex:s,globalSceneIndex:n}),n++})}),t}function lo(e){let t=[],n=0,o=0;return e.episodes.forEach((i,r)=>{i.scenes.forEach((s,c)=>{s.actions.forEach((a,d)=>{t.push({episode:i,episodeIndex:r,scene:s,sceneIndex:c,globalSceneIndex:n,action:a,actionIndex:d,globalActionIndex:o}),o++}),n++})}),t}function en(e,t){return po(e).find(n=>n.episode.episode_id===t)??null}function _n(e,t){return wn(e).find(n=>n.scene.scene_id===t)??null}function Dn(e,t){throw new x(t,{exitCode:G,errorCode:"ORDINAL_ANCHOR_INVALID",data:{expected:["@ep:N | @ep:N/scn:N | @ep:N/scn:N/ac:N | @scn:N | @scn:N/ac:N | @ac:N"],actual:[e]}})}function tn(e,t){return/^[1-9]\d*$/.test(e)||Dn(t,"Ordinal positions are 1-based positive integers."),Number(e)}function Fr(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=po(e)[tn(n[1],t)-1];return o||Dn(t,"Episode ordinal is outside the current script."),{kind:"episode",id:o.episode.episode_id}}if(n=/^@ep:(\d+)\/scn:(\d+)$/.exec(t),n){let o=po(e)[tn(n[1],t)-1],i=o?.episode.scenes[tn(n[2],t)-1];return(!o||!i)&&Dn(t,"Episode-local scene ordinal is outside the current script."),{kind:"scene",id:i.scene_id}}if(n=/^@ep:(\d+)\/scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=po(e)[tn(n[1],t)-1],i=o?.episode.scenes[tn(n[2],t)-1],r=i?.actions[tn(n[3],t)-1];return(!o||!i||!r)&&Dn(t,"Episode-local action ordinal is outside the current script."),{kind:"action",id:r.action_id}}if(n=/^@scn:(\d+)$/.exec(t),n){let o=wn(e)[tn(n[1],t)-1];return o||Dn(t,"Global scene ordinal is outside the current script."),{kind:"scene",id:o.scene.scene_id}}if(n=/^@scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=wn(e)[tn(n[1],t)-1],i=o?.scene.actions[tn(n[2],t)-1];return(!o||!i)&&Dn(t,"Scene-local action ordinal is outside the current script."),{kind:"action",id:i.action_id}}if(n=/^@ac:(\d+)$/.exec(t),n){let o=lo(e)[tn(n[1],t)-1];return o||Dn(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return Dn(t,"Ordinal anchor syntax is not supported.")}function jo(e,t){throw new x(e,{exitCode:G,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Zp(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:jo("Asset and state addresses are not narrative range anchors.",t)}function Xp(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function el(e,t,n){return t.startsWith("@")?(n||jo("Ordinal anchors are query-only.",t),Fr(e,t)):Ci(t)}function uy(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&jo("Range endpoint does not exist in the current script.",o);let s=Math.min(i,r),c=Math.max(i,r);return e.slice(s,c+1)}function Qr(e,t,n){let o=typeof t=="string"?t.trim():"";if(!o)return{isEmpty:!0,isWholeScript:!1,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};if(o==="*")return{isEmpty:!1,isWholeScript:!0,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};let i=po(e),r=wn(e),s=lo(e),c=i.map(h=>h.episode.episode_id),a=r.map(h=>h.scene.scene_id),d=s.map(h=>h.action.action_id),p=new Set,l=new Set,f=new Set,u=h=>{p.add(h);let w=i.find(y=>y.episode.episode_id===h)?.episode;w&&w.scenes.forEach(y=>{l.add(y.scene_id),y.actions.forEach(E=>f.add(E.action_id))})},m=h=>{l.add(h);let w=r.find(y=>y.scene.scene_id===h);w&&(p.add(w.episode.episode_id),w.scene.actions.forEach(y=>f.add(y.action_id)))},g=h=>{f.add(h);let w=s.find(y=>y.action.action_id===h);w&&(p.add(w.episode.episode_id),l.add(w.scene.scene_id))};for(let h of o.split(",")){let w=h.trim();w||jo("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&jo("Selector region has too many range delimiters.",w);let E=el(e,y[0].trim(),n.allowOrdinals),S=el(e,(y[1]??y[0]).trim(),n.allowOrdinals),_=Zp(E,w);Zp(S,w)!==_&&jo("Range endpoints must have the same kind.",w);let A=Xp(E),k=Xp(S),R=uy(_==="episode"?c:_==="scene"?a:d,A,k,w);_==="episode"?R.forEach(u):_==="scene"?R.forEach(m):R.forEach(g)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:h=>p.has(h),matchesScene:h=>l.has(h),matchesAction:h=>f.has(h)}}function Gn(e,t){throw new x(e,{exitCode:G,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function fy(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function my(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function te(e,t,n=""){let o=[e,...t].map(fy).join("|"),i=my(n);return`[${o}]${i?` ${i}`:""}`}function Ja(e){if(Array.isArray(e))return e.map(Ja);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Ja(e[n]);return t}return e}function Jn(e){return e===void 0?[]:[te("extensions",[]),...Object.keys(e).sort().map(t=>te("extend",[t],JSON.stringify(Ja(e[t]))))]}function gy(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function tl(e){let t=Jn(e.extend);if(e.transition_prompt!==void 0&&t.push(te("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast])),e.type==="dialogue"||e.type==="inner_thought"){let n=[e.action_id,gy(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(te(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(te(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function Ba(e,t){let n=[...Jn(e.extend),`<scene ${t}>`];if(e.environment!==void 0){let o=e.environment.time===void 0?e.environment.space===void 0?[]:[e.environment.space]:[e.environment.space??"",e.environment.time];n.push(te("environment",o))}n.push(e.location===null?te("location",[]):te("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(te("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(te("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...tl(o))),n.push("</body>","","</scene>"),n}function Ka(e){let t=[...Jn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(te("title",[],e.title)),e.synopsis!==void 0&&t.push(te("synopsis",[],e.synopsis)),e.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...Ba(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function Da(e,t){return[...Jn(t.extend),te("state",[e,t.state_id,t.state_name],t.description)]}function hy(e){let t=["<create>"];for(let n of e.actors){t.push(...Jn(n.extend)),n.aliases!==void 0&&(t.push(te("aliases",[])),n.aliases.forEach(i=>t.push(te("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(te("actor",o,n.description)),n.states.forEach(i=>t.push(...Da(n.actor_id,i)))}for(let n of e.locations)t.push(...Jn(n.extend)),n.aliases!==void 0&&(t.push(te("aliases",[])),n.aliases.forEach(o=>t.push(te("alias",[],o)))),t.push(te("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Da(n.location_id,o)));for(let n of e.props)t.push(...Jn(n.extend)),n.aliases!==void 0&&(t.push(te("aliases",[])),n.aliases.forEach(o=>t.push(te("alias",[],o)))),t.push(te("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Da(n.prop_id,o)));return t.push("</create>"),t}function yy(e){let t=[...Jn(e.extend),"<script>"];return t.push(te("title",[],e.title),te("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(te("worldview-raw",[],e.worldview_raw)),t.push(te("style",[],e.style)),e.synopsis!==void 0&&t.push(te("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(te("logline",[],e.logline)),e.theme!==void 0&&t.push(te("theme",[],e.theme)),e.main_characters!==void 0&&(t.push(te("main-characters",[])),e.main_characters.forEach(n=>t.push(te("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...Ka(n))),t.push("</script>"),t}function wy(e){return e.trim()||Gn("This export kind requires --in.",["<missing>"]),e.split(",").map(t=>{let n=t.trim().split("..");return n.length>2||!n[0]||n.length===2&&!n[1]?Gn("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function Ga(e,t,n,o,i){let r=-1;return wy(i).map(s=>{let c=f=>{if(!f.startsWith("@"))return f;let u=Fr(e,f);return u.kind!==t?Gn("Selector endpoint kind does not match the export kind.",[f,t]):u.id},a=o.indexOf(c(s.left)),d=o.indexOf(c(s.right));(a<0||d<0)&&Gn("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(a,d),l=Math.max(a,d);return p<=r&&Gn("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function nl(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...hy(e),"",...yy(e)),i=1;else if(t==="episodes"){let r=Qr(e,n,{allowOrdinals:!0}),s=e.episodes.filter(c=>r.matchesEpisode(c.episode_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Ka(c))}),i=s.length}else if(t==="episode-spans"){let r=Ga(e,"episode",e.episodes,e.episodes.map(s=>s.episode_id),n);for(let[s,c]of r.entries())s>0&&o.push(""),o.push(`<episode-span range=${c[0].episode_id}..${c.at(-1).episode_id}>`),c.forEach(a=>o.push(...Ka(a))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=Qr(e,n,{allowOrdinals:!0}),s=wn(e).filter(c=>r.matchesScene(c.scene.scene_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Ba(c.scene,`id=${c.scene.scene_id} parent=${c.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=wn(e),s=Ga(e,"scene",r,r.map(c=>c.scene.scene_id),n);for(let[c,a]of s.entries()){let d=a[0].episode.episode_id;a.every(p=>p.episode.episode_id===d)||Gn("A scene span must remain inside one episode.",[a[0].scene.scene_id,a.at(-1).scene.scene_id]),c>0&&o.push(""),o.push(`<scene-span parent=${d} range=${a[0].scene.scene_id}..${a.at(-1).scene.scene_id}>`),a.forEach(p=>o.push(...Ba(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=lo(e),s=Ga(e,"action",r,r.map(c=>c.action.action_id),n);for(let[c,a]of s.entries()){let d=a[0].scene.scene_id;a.every(p=>p.scene.scene_id===d)||Gn("An action span must remain inside one scene.",[a[0].action.action_id,a.at(-1).action.action_id]),c>0&&o.push(""),o.push(`<action-span parent=${d} range=${a[0].action.action_id}..${a.at(-1).action.action_id}>`,"<body>"),a.forEach(p=>o.push(...tl(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&Gn("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
|
|
127
|
-
`)}
|
|
128
|
-
`,targetCount:i}}function ie(e,t,n,o,i=b){throw new x(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function _y(e){let t=xe(e),n;try{n=JSON.parse(il.readFileSync(t,"utf-8"))}catch(o){ie("SCRIPT_JSON_UNAVAILABLE","The local script cannot be read as JSON.",[t,o instanceof Error?o.message:String(o)],"Provide a readable local Script v3 file.")}return zr(n)}function Pi(e){return e||ie("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",G),e.split(",").map(t=>{let n=t.trim();n||ie("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",G);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&ie("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",G);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&ie("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",G),{from:i,through:r}})}function Yr(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&ie("AUTHORING_SELECTOR_EMPTY",`The script contains no ${n}.`,["*"],"Choose a non-empty target kind."),[0,e.length-1];(e.filter(r=>r===t.from).length>1||e.filter(r=>r===t.through).length>1)&&ie("AUTHORING_SELECTOR_AMBIGUOUS",`${n} selector endpoint is not unique.`,[t.from,t.through],"Repair duplicate stable IDs before exporting this target.");let o=e.indexOf(t.from),i=e.indexOf(t.through);return(o<0||i<0)&&ie("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&ie("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function sl(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&ie("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function Vi(e,t){for(let n=1;n<e.length;n+=1){let o=e[n-1],i=e[n],r=Math.max(o.length,i.length),s=0;for(let c=0;c<r&&(s=(i[c]??0)-(o[c]??0),s===0);c+=1);s<=0&&ie("AUTHORING_SELECTOR_ORDER",`${t} selector regions are not in current document order.`,[`region=${n+1}`],"List disjoint selector regions from earlier to later document positions.")}}function Ey(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of Pi(t)){let[s,c]=Yr(o,r,"episode");n.push(...e.episodes.slice(s,c+1))}sl(n,r=>r.episode_id),Vi(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:Ct}));return Ko("episode",i)}function xy(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of Pi(t)){let[c,a]=Yr(n,s,"episode");for(let d=c;d<=a;d+=1)i.has(d)&&ie("AUTHORING_SELECTOR_OVERLAP","Episode span regions overlap.",[`${s.from}..${s.through}`],"Use non-overlapping regions."),i.add(d);o.push({kind:"episode-span",from:n[c],through:n[a],episodes:structuredClone(e.episodes.slice(c,a+1)),source:Ct}),r.push([c])}return Vi(r,"Episode span"),Ko("episode-span",o)}function Sy(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function ja(e){return`${e.episodeId}/${e.scene.scene_id}`}function Iy(e,t){let n=Sy(e),o=n.map(ja),i=[];for(let s of Pi(t)){let[c,a]=Yr(o,s,"scene");i.push(...n.slice(c,a+1))}sl(i,ja),Vi(i.map(s=>[o.indexOf(ja(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:Ct}));return Ko("scene",r)}function za(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||ie("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function Ay(e,t){let n=[],o=new Set,i=[];for(let r of Pi(t)){(r.from==="*"||r.through==="*")&&ie("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=za(r.from),c=za(r.through);s.episodeId!==c.episodeId&&ie("AUTHORING_SELECTOR_CROSS_PARENT","A scene span must remain inside one episode.",[r.from,r.through],"Split it into one region per episode.");let a=e.episodes.filter(u=>u.episode_id===s.episodeId);a.length===0&&ie("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),a.length>1&&ie("AUTHORING_SELECTOR_AMBIGUOUS","Scene span parent episode is not unique.",[s.episodeId],"Repair duplicate stable IDs before exporting.");let d=a[0],p=d.scenes.map(u=>u.scene_id),[l,f]=Yr(p,{from:s.sceneId,through:c.sceneId},"scene");for(let u=l;u<=f;u+=1){let m=`${d.episode_id}/${p[u]}`;o.has(m)&&ie("AUTHORING_SELECTOR_OVERLAP","Scene span regions overlap.",[m],"Use non-overlapping regions."),o.add(m)}n.push({kind:"scene-span",parent:d.episode_id,from:p[l],through:p[f],scenes:structuredClone(d.scenes.slice(l,f+1)),source:Ct}),i.push([e.episodes.indexOf(d),l])}return Vi(i,"Scene span"),Ko("scene-span",n)}function ol(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||ie("AUTHORING_SELECTOR_INVALID","Action selector endpoint must be ep/scn#index.",[e],"Use a zero-based ep_ID/scn_ID#index address.");let n=Number(t[2]);return Number.isSafeInteger(n)||ie("AUTHORING_SELECTOR_INVALID","Action index is outside the safe integer range.",[e],"Use a zero-based safe integer index."),{parent:t[1],index:n}}function ky(e,t){let n=[],o=new Set,i=[];for(let r of Pi(t)){(r.from==="*"||r.through==="*")&&ie("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=ol(r.from),c=ol(r.through);s.parent!==c.parent&&ie("AUTHORING_SELECTOR_CROSS_PARENT","An action span must remain inside one scene.",[r.from,r.through],"Split it into one region per scene.");let a=za(s.parent),d=e.episodes.filter(u=>u.episode_id===a.episodeId);d.length===0&&ie("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[a.episodeId],"Use an existing episode ID."),d.length>1&&ie("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent episode is not unique.",[a.episodeId],"Repair duplicate stable IDs before exporting.");let p=d[0],l=p.scenes.filter(u=>u.scene_id===a.sceneId);l.length===0&&ie("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&ie("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent scene is not unique.",[s.parent],"Repair duplicate stable IDs before exporting.");let f=l[0];s.index>c.index&&ie("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),c.index>=f.actions.length&&ie("AUTHORING_SELECTOR_NOT_FOUND","Action span endpoint is outside the current body.",[r.through,`actions=${f.actions.length}`],"Use current zero-based action indices.");for(let u=s.index;u<=c.index;u+=1){let m=`${s.parent}#${u}`;o.has(m)&&ie("AUTHORING_SELECTOR_OVERLAP","Action span regions overlap.",[m],"Use non-overlapping regions."),o.add(m)}n.push({kind:"action-span",parent:s.parent,from:s.index,through:c.index,actions:structuredClone(f.actions.slice(s.index,c.index+1)),source:Ct}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return Vi(i,"Action span"),Ko("action-span",n)}function al(e,t){let n=O(t.output).trim();n||ie("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",G);let o=_y(t),i=O(t.in).trim(),r=rl.resolve(n);if(o.version===4){let p=nl(Xt(o),e,i);return Jr(r,p.content),[{text:`Exported ${p.targetCount} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:e==="episodes"?"episode":e==="episode-spans"?"episode-span":e==="scenes"?"scene":e==="scene-spans"?"scene-span":e==="action-spans"?"action-span":"script",target_count:p.targetCount,bytes:Buffer.byteLength(p.content),script_version:4}},J]}let s=It(o),c;e==="script"?c=Yp(s):e==="episodes"?c=Ey(s,i):e==="episode-spans"?c=xy(s,i):e==="scenes"?c=Iy(s,i):e==="scene-spans"?c=Ay(s,i):c=ky(s,i);let a=Wp(c);return Jr(r,a),[{text:`Exported ${c.targets.length} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:c.targetKind,target_count:c.targets.length,bytes:Buffer.byteLength(a),script_version:3}},J]}import*as pc from"node:crypto";import*as Ji from"node:fs";import*as Tl from"node:path";function H(e,t,n,o,i=b){throw new x(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function re(e){return`line ${e.line}, column ${e.column}`}function qr(e){if(Array.isArray(e))return e.map(qr);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=qr(o);return t}return e}function Bn(e,t){return JSON.stringify(qr(e))===JSON.stringify(qr(t))}function $i(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function by(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function Oy(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function vy(e,t){"actor_id"in t.value?e.actors.push(t.value):"location_id"in t.value?e.locations.push(t.value):e.props.push(t.value)}function ml(e,t,n){return Oy(e,t).find(o=>$i(t,o)===n)}function Ry(e,t){for(let n of["actor","location","prop"]){let o=ml(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function Ny(e){let t=[],n=[],o={actor:0,location:1,prop:2},i=-1,r,s=!1,c=new Set;for(let a of e){if(a.declarationKind!=="state"){s&&H("AUTHORING_DECLARATION_ORDER","Asset declarations must precede standalone state declarations.",[re(a.source)],["Move standalone states to the end of <create>."]);let p=a.declarationKind;o[p]<i&&H("AUTHORING_DECLARATION_ORDER","Asset declaration groups are out of canonical order.",[re(a.source),p],["Order asset declarations as actor, location, then prop."]),i=o[p];let l=structuredClone(a.value);l.states=[];let f={kind:p,value:l,source:a.source},u=`${p}:${$i(p,l)}`;c.has(u)&&H("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[re(a.source),u],["Keep one declaration per asset."]),c.add(u),t.push(f),r=f;continue}let d=`${a.ownerKind}:${a.ownerId}`;if(r!==void 0&&r.kind===a.ownerKind&&$i(r.kind,r.value)===a.ownerId){r.value.states.push(structuredClone(a.value));continue}s=!0,r=void 0,n.push({kind:a.ownerKind,ownerId:a.ownerId,value:structuredClone(a.value),source:a.source})}for(let a of t){let d=$i(a.kind,a.value);(a.value.states.length===0||a.value.states[0].state_id!=="default")&&H("AUTHORING_DEFAULT_STATE_REQUIRED","Every declared asset must be immediately followed by its states, beginning with default.",[re(a.source),`${a.kind}:${d}`],[`Add [state|${a.kind}:${d}|default|...] directly after the asset declaration.`]),a.value.states.filter(l=>l.state_id==="default").length!==1&&H("AUTHORING_DEFAULT_STATE_DUPLICATE","Every declared asset must contain exactly one default state.",[re(a.source),`${a.kind}:${d}`],["Keep exactly one default state."]);let p=a.value.aliases??[];(new Set(p).size!==p.length||p.includes(by(a.kind,a.value)))&&H("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[re(a.source),`${a.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function My(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function gl(e,t){let n=Ny(t),o=My();for(let i of n.assets){let r=$i(i.kind,i.value),s=`${i.kind}:${r}`,c=Ry(e,r);if(c!==void 0){if(c.kind===i.kind&&Bn(c.value,i.value)){o.existingAssets.push(s),o.existingStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`));continue}H("AUTHORING_ASSET_CONFLICT","Create-only asset declaration conflicts with an existing asset.",[re(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}vy(e,i),o.createdAssets.push(s),o.createdStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`))}for(let i of n.states){let r=ml(e,i.kind,i.ownerId);r===void 0&&H("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[re(i.source),`${i.kind}:${i.ownerId}`],["Declare the asset before its states or use an existing asset ID."]);let s=r.states.find(a=>a.state_id===i.value.state_id);s!==void 0&&!Bn(s,i.value)&&H("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[re(i.source),`${i.kind}:${i.ownerId}/${i.value.state_id}`],["Use an unused state ID for this asset, or reuse the identical existing state."]);let c=`${i.kind}:${i.ownerId}/${i.value.state_id}`;s===void 0?(r.states.push(i.value),o.createdStates.push(c)):o.existingStates.push(c)}return o}function cl(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function dl(e){return{episodes:e===void 0?0:1,scenes:e?.scenes.length??0,actions:e?.scenes.reduce((t,n)=>t+n.actions.length,0)??0}}function Wr(e){return e.reduce((t,n)=>({episodes:t.episodes+1,scenes:t.scenes+n.scenes.length,actions:t.actions+n.scenes.reduce((o,i)=>o+i.actions.length,0)}),{episodes:0,scenes:0,actions:0})}function pl(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function Di(e,t){let n=new Set(e),o=new Set(t);return{retainedIds:t.filter(i=>n.has(i)),createdIds:t.filter(i=>!n.has(i)),removedIds:e.filter(i=>!o.has(i))}}function Ha(e,t){let n=[];e.location!==null&&!e.location.state_id&&n.push(`location:${e.location.location_id}`);for(let o of e.actors)o.state_id||n.push(`actor:${o.actor_id}`);for(let o of e.props)o.state_id||n.push(`prop:${o.prop_id}`);n.length>0&&H("AUTHORING_SCENE_REF_UNMATERIALIZED","Every scene asset reference in an authored block must bind a state.",[re(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function Fa(e,t){for(let n of e.scenes)Ha(n,t)}function uo(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Zr(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function hl(e,t,n){let o=uo(e,t);o<0&&H("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Zr(e.episodes[o],n);return i<0&&H("AUTHORING_SCENE_NOT_FOUND","Scene target does not exist.",[`${t}/${n}`],["Inspect scenes and use an existing target."]),[o,i]}function Ly(e,t){let n=Math.max(e.length,t.length);for(let o=0;o<n;o+=1){let i=(e[o]??0)-(t[o]??0);if(i!==0)return i}return 0}function Gi(e,t){for(let n=1;n<e.length;n+=1)Ly(e[n-1].coord,e[n].coord)>=0&&H("AUTHORING_TARGET_ORDER",t,[re(e[n].source)],["List replace targets in current document order without duplicates."],G)}function Uy(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let c=uo(e,s.value.episode_id);return c<0&&H("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[re(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[c],source:s.source}});Gi(r,"Episode replace targets are not in document order.")}for(let r of n){Fa(r.value,r.source);let s=uo(e,r.value.episode_id),c=s<0?void 0:e.episodes[s];o==="create"?c!==void 0?Bn(c,r.value)||H("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[re(r.source),r.value.episode_id],["Use --replace to replace it, or make the create block identical for a no-op retry."]):t.episodes.push(structuredClone(r.value)):t.episodes[s]=structuredClone(r.value),i.push({kind:"episode",address:r.value.episode_id,before:dl(c),after:dl(r.value),...Di(c?.scenes.map(a=>a.scene_id)??[],r.value.scenes.map(a=>a.scene_id)),untouchedSiblings:Math.max(0,e.episodes.length-(c===void 0?0:1))})}return i}function Ty(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:hl(e,s.parent,s.value.scene_id),source:s.source}));Gi(r,"Scene replace targets are not in document order.")}for(let r of n){Ha(r.value,r.source);let s=uo(e,r.parent);s<0&&H("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[re(r.source),r.parent],["Use an existing episode parent."]);let c=e.episodes[s],a=t.episodes[s],d=Zr(c,r.value.scene_id),p=d<0?void 0:c.scenes[d];o==="create"?p!==void 0?Bn(p,r.value)||H("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[re(r.source),`${r.parent}/${r.value.scene_id}`],["Use --replace or make the create block identical for a no-op retry."]):a.scenes.push(structuredClone(r.value)):(d<0&&H("AUTHORING_SCENE_NOT_FOUND","Scene replace target does not exist.",[re(r.source),`${r.parent}/${r.value.scene_id}`],["Use --create for a new scene or choose an existing scene."]),a.scenes[d]=structuredClone(r.value)),i.push({kind:"scene",address:`${r.parent}/${r.value.scene_id}`,before:cl(p),after:cl(r.value),...Di(p===void 0?[]:[p.scene_id],[r.value.scene_id]),untouchedSiblings:Math.max(0,c.scenes.length-(p===void 0?0:1))})}return i}function Cy(e,t,n){let o=n.map(r=>{let s=uo(e,r.from),c=uo(e,r.through);(s<0||c<0)&&H("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[re(r.source),`${r.from}..${r.through}`],["Use existing episode IDs as span endpoints."]),s>c&&H("AUTHORING_SPAN_REVERSED","Episode-span endpoints are reversed in current document order.",[re(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&H("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[re(r.source)],["Include at least one complete episode."]);for(let a of r.episodes)Fa(a,r.source);return{target:r,from:s,through:c}});Gi(o.map(r=>({coord:[r.from],source:r.target.source})),"Episode spans are not in document order.");for(let r=1;r<o.length;r+=1)o[r].from<=o[r-1].through&&H("AUTHORING_SPAN_OVERLAP","Episode spans overlap.",[re(o[r].target.source)],["Use disjoint episode spans."]);let i=o.map(({target:r,from:s,through:c})=>{let a=e.episodes.slice(s,c+1);return{kind:"episode-span",address:`${r.from}..${r.through}`,before:Wr(a),after:Wr(r.episodes),...Di(a.map(d=>d.episode_id),r.episodes.map(d=>d.episode_id)),untouchedSiblings:e.episodes.length-a.length}});for(let{target:r,from:s,through:c}of[...o].reverse())t.episodes.splice(s,c-s+1,...structuredClone(r.episodes));return i}function Py(e,t,n){let o=n.map(s=>{let c=uo(e,s.parent);c<0&&H("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[re(s.source),s.parent],["Use an existing parent episode."]);let a=e.episodes[c],d=Zr(a,s.from),p=Zr(a,s.through);(d<0||p<0)&&H("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[re(s.source),`${s.parent}:${s.from}..${s.through}`],["Use scene IDs from the same existing episode."]),d>p&&H("AUTHORING_SPAN_REVERSED","Scene-span endpoints are reversed in current document order.",[re(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&H("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[re(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)Ha(l,s.source);return{target:s,epIndex:c,from:d,through:p}});Gi(o.map(s=>({coord:[s.epIndex,s.from],source:s.target.source})),"Scene spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.from<=c.through&&H("AUTHORING_SPAN_OVERLAP","Scene spans overlap.",[re(a.target.source)],["Use disjoint scene spans."])}let i=o.map(({target:s,epIndex:c,from:a,through:d})=>{let p=e.episodes[c].scenes.slice(a,d+1);return{kind:"scene-span",address:`${s.parent}/${s.from}..${s.parent}/${s.through}`,before:pl(p),after:pl(s.scenes),...Di(p.map(l=>l.scene_id),s.scenes.map(l=>l.scene_id)),untouchedSiblings:e.episodes[c].scenes.length-p.length}}),r=new Map;for(let s of o)r.set(s.epIndex,[...r.get(s.epIndex)??[],s]);for(let[s,c]of r)for(let{target:a,from:d,through:p}of[...c].reverse())t.episodes[s].scenes.splice(d,p-d+1,...structuredClone(a.scenes));return i}function Vy(e,t,n){let o=n.map(s=>{let c=s.parent.indexOf("/");(c<1||c===s.parent.length-1)&&H("AUTHORING_SCENE_ADDRESS_INVALID","Action-span parent is not a complete scene address.",[re(s.source),s.parent],["Use parent=ep_ID/scn_ID."]);let a=s.parent.slice(0,c),d=s.parent.slice(c+1),[p,l]=hl(e,a,d),f=e.episodes[p].scenes[l];return s.from>s.through&&H("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[re(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.through>=f.actions.length&&H("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Action-span endpoint is outside the current scene body.",[re(s.source),`${s.from}..${s.through}`,`actions=${f.actions.length}`],["Use zero-based endpoints within the current body."]),s.actions.length===0&&H("AUTHORING_EMPTY_SPAN","Action-span replacement cannot be empty.",[re(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});Gi(o.map(s=>({coord:[s.epIndex,s.scIndex,s.from],source:s.target.source})),"Action spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.scIndex===c.scIndex&&a.from<=c.through&&H("AUTHORING_SPAN_OVERLAP","Action spans overlap.",[re(a.target.source)],["Use disjoint action spans."])}let i=o.map(({target:s,scene:c,from:a,through:d})=>({kind:"action-span",address:`${s.parent}#${a}..${s.parent}#${d}`,before:{episodes:0,scenes:0,actions:d-a+1},after:{episodes:0,scenes:0,actions:s.actions.length},retainedIds:[],createdIds:[],removedIds:[],untouchedSiblings:c.actions.length-(d-a+1)})),r=new Map;for(let s of o){let c=`${s.epIndex}/${s.scIndex}`;r.set(c,[...r.get(c)??[],s])}for(let s of r.values())for(let{target:c,epIndex:a,scIndex:d,from:p,through:l}of[...s].reverse())t.episodes[a].scenes[d].actions.splice(p,l-p+1,...structuredClone(c.actions));return i}function yl(e){let t=new Set,n=new Set;for(let o of e.episodes){t.has(o.episode_id)&&H("AUTHORING_EPISODE_ID_CONFLICT","Episode ID occurs more than once.",[o.episode_id],["Use globally unique episode IDs."]),t.add(o.episode_id);for(let i of o.scenes)n.has(i.scene_id)&&H("AUTHORING_SCENE_ID_CONFLICT","Scene ID occurs more than once.",[i.scene_id],["Use globally unique stable scene IDs."]),n.add(i.scene_id)}}function $y(e,t){let n=/^\$\.episodes\[(\d+)]/.exec(e);if(n===null)return e;let o=t.episodes[Number(n[1])];if(o===void 0)return e;let i=e.replace(n[0],`$.episodes[${o.episode_id}]`),r=/^(\$\.episodes\[\d+]\.scenes)\[(\d+)]/.exec(e);if(r!==null){let s=o.scenes[Number(r[2])];if(s!==void 0){let c=`${n[0]}.scenes[${r[2]}]`;i=e.replace(c,`$.episodes[${o.episode_id}].scenes[${s.scene_id}]`)}}return i}function ll(e,t){return`${e.code}\0${$y(e.path,t)}\0${e.message}`}function Dy(e){let t={episodeIds:new Set,sceneIds:new Set,fullEpisodeIds:new Set,fullSceneIds:new Set,actionSpans:[]},n=i=>{t.sceneIds.add(i.scene_id),t.fullSceneIds.add(i.scene_id)},o=i=>{t.episodeIds.add(i.episode_id),t.fullEpisodeIds.add(i.episode_id);for(let r of i.scenes)n(r)};for(let i of e)if(i.kind==="script")for(let r of i.episodes)o(r);else if(i.kind==="episode")o(i.value);else if(i.kind==="episode-span")for(let r of i.episodes)o(r);else if(i.kind==="scene")n(i.value);else if(i.kind==="scene-span")for(let r of i.scenes)n(r);else t.sceneIds.add(i.parent.split("/")[1]??""),t.actionSpans.push(i);return t}function Gy(e,t,n){let o=[],i=new Map(e?.episodes.map(a=>[a.episode_id,a])??[]),r=new Map;for(let a of e?.episodes??[])for(let d of a.scenes)r.set(d.scene_id,d);let s=new Map(t.episodes.map(a=>[a.episode_id,a])),c=new Map;for(let a of t.episodes)for(let d of a.scenes)c.set(d.scene_id,{episodeId:a.episode_id,scene:d});for(let a of n.fullEpisodeIds){let d=s.get(a);if(d===void 0||d.scenes.length>0)continue;let p=(i.get(a)?.scenes.length??0)>0;o.push({code:p?"authoring_episode_cleared":"authoring_empty_episode",path:`$.episodes[${a}]`,message:p?`authoring replaced episode ${a} with an empty scene list`:`authored episode ${a} has no scenes`})}for(let a of n.fullSceneIds){let d=c.get(a);if(d===void 0)continue;let p=`$.episodes[${d.episodeId}].scenes[${a}]`;if(d.scene.actions.length===0){let l=(r.get(a)?.actions.length??0)>0;o.push({code:l?"authoring_scene_cleared":"authoring_empty_scene",path:p,message:l?`authoring replaced scene ${a} with an empty body`:`authored scene ${a} has an empty body`})}d.scene.actions.forEach((l,f)=>{l.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${p}.actions[${f}]`,message:"authored action content is empty"})})}for(let a of n.actionSpans)a.actions.forEach((d,p)=>{d.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${a.parent}#replacement[${p}]`,message:"authored action-span replacement contains an action with empty content"})});return o}function ul(e,t,n){let o=at(t),i=Dy(n),r=()=>({...o,warnings:[...o.warnings,...Gy(e,t,i)]});if(o.ok||e!==null&&Bn(e,t))return r();let s=new Set(e===null?[]:at(e).errors.map(a=>ll(a,e))),c=o.errors.filter(a=>{if(!s.has(ll(a,t)))return!0;let d=/^\$\.episodes\[(\d+)]/.exec(a.path);if(!d)return!1;let p=t.episodes[Number(d[1])];if(p===void 0||i.episodeIds.has(p.episode_id))return!0;let l=/^\$\.episodes\[\d+]\.scenes\[(\d+)]/.exec(a.path),f=l===null?void 0:p.scenes[Number(l[1])];return f!==void 0&&i.sceneIds.has(f.scene_id)});return c.length>0&&H("AUTHORING_VALIDATION_FAILED","The proposed script has blocking validation errors.",c.map(a=>`${a.path}: ${a.code} ${a.message}`),["Repair the authoring source and rerun the plan."]),r()}function fl(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes){o.location!==null&&t.add(o.location.location_id);for(let i of o.actors)t.add(i.actor_id);for(let i of o.props)t.add(i.prop_id)}return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function Jy(e){let t=e.targets[0];t?.kind!=="script"&&H("AUTHORING_TARGET_MODE","Script create requires exactly one script target.",[],["Use a single <script> block."],G);for(let i of t.episodes)Fa(i,t.source);let n={version:3,title:t.title,worldview:t.worldview,style:t.style,actors:[],locations:[],props:[],episodes:structuredClone(t.episodes)};t.worldviewRaw!==void 0&&(n.worldview_raw=t.worldviewRaw),t.synopsis!==void 0&&(n.synopsis=t.synopsis),t.logline!==void 0&&(n.logline=t.logline),t.theme!==void 0&&(n.theme=t.theme),t.mainCharacters!==void 0&&(n.main_characters=structuredClone(t.mainCharacters)),t.extend!==void 0&&(n.extend=structuredClone(t.extend));let o=gl(n,e.declarations);return yl(n),{script:n,declarations:o}}function wl(e,t,n){if(t.targetKind==="script"){n!=="create"&&H("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],G);let a=Jy(t),d=a.script;e!==null&&!Bn(e,d)&&H("AUTHORING_CREATE_CONFLICT","The script target already exists with different content.",["script"],["Use episode replacement for an existing script, or write an identical script for a no-op retry."]);let p=e===null?a.declarations:{createdAssets:[],existingAssets:[...a.declarations.existingAssets,...a.declarations.createdAssets],createdStates:[],existingStates:[...a.declarations.existingStates,...a.declarations.createdStates]},l=ul(e,d,t.targets);return{script:d,changed:e===null||!Bn(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:Wr(e.episodes),after:Wr(d.episodes),...Di(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:fl(d),validation:l}}e===null&&H("AUTHORING_SCRIPT_NOT_FOUND","A local Script v3 file is required for this target kind.",["<missing>"],["Create a script first or select an existing --script-path."]),(t.targetKind==="episode-span"||t.targetKind==="scene-span"||t.targetKind==="action-span")&&n!=="replace"&&H("AUTHORING_TARGET_MODE",`${t.targetKind} supports replace only.`,[n],["Use --replace."],G);let o=structuredClone(e),i=structuredClone(e),r=gl(i,t.declarations),s;switch(t.targetKind){case"episode":{let a=t.targets.flatMap(d=>d.kind==="episode"?[d]:[]);a.length!==t.targets.length&&H("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],G),s=Uy(o,i,a,n);break}case"scene":{let a=t.targets.flatMap(d=>d.kind==="scene"?[d]:[]);a.length!==t.targets.length&&H("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],G),s=Ty(o,i,a,n);break}case"episode-span":{let a=t.targets.flatMap(d=>d.kind==="episode-span"?[d]:[]);a.length!==t.targets.length&&H("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],G),s=Cy(o,i,a);break}case"scene-span":{let a=t.targets.flatMap(d=>d.kind==="scene-span"?[d]:[]);a.length!==t.targets.length&&H("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],G),s=Py(o,i,a);break}case"action-span":{let a=t.targets.flatMap(d=>d.kind==="action-span"?[d]:[]);a.length!==t.targets.length&&H("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],G),s=Vy(o,i,a);break}default:H("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}yl(i);let c=ul(e,i,t.targets);return{script:i,changed:!Bn(e,i),declarations:r,targets:s,retainedOrphanAssets:fl(i),validation:c}}function C(e,t,n,o){return new x(e,{exitCode:b,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function Qa(e,t,n){let o="";for(let i=0;i<e.length;i+=1){let r=e[i];if(r!=="\\"){o+=r;continue}let s=e[i+1];if(s===void 0)throw C("Trailing escape is invalid.",{line:t.line,column:t.column+i},e,"Escape a supported character or remove the trailing backslash.");if(s==="\\"||s==="n"||n&&(s==="|"||s==="]")){o+=s==="n"?`
|
|
129
|
-
`:s,i+=1;continue}throw C("Unknown escape sequence.",{line:t.line,column:t.column+i},`\\${s}`,n?"Use only \\|, \\], \\\\, or \\n in a header.":"Use only \\\\ or \\n in record content.")}return o}function zo(e,t){let n={line:t,column:Math.max(1,e.indexOf("[")+1)},o=e.trimStart();if(!o.startsWith("["))throw C("Expected a bracket record.",n,e,"Start the semantic line with a known [type] record.");let i=-1,r=!1;for(let m=1;m<o.length;m+=1){let g=o[m];if(r){r=!1;continue}if(g==="\\"){r=!0;continue}if(g==="]"){i=m;break}}if(i<0)throw C("Bracket record is not closed.",n,e,"Add the closing ].");let s=o.slice(1,i),c=[],a="";r=!1;for(let m=0;m<s.length;m+=1){let g=s[m];r?(a+=`\\${g}`,r=!1):g==="\\"?r=!0:g==="|"?(c.push(a),a=""):a+=g}r&&(a+="\\"),c.push(a);let[d,...p]=c,l=Qa(d??"",n,!0);if(!l)throw C("Record type is empty.",n,e,"Use a known record type.");let f=o.slice(i+1),u=f.startsWith(" ")?f.slice(1):f;return{type:l,slots:p.map(m=>Qa(m,n,!0)),content:Qa(u,{line:t,column:i+2},!1),source:n}}function dt(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function En(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function pt(e){return e.extendPresent?e.extend:void 0}function Ya(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ya):typeof e!="object"?!1:Object.values(e).every(Ya)}function qa(e){if(Array.isArray(e))return e.map(qa);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=qa(e[n]);return t}return e}function _l(e){return e==="featured"||e==="background"}function By(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function Ky(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function jy(e){return e==="actor"||e==="location"||e==="prop"}function El(e,t,n,o){if(!/^\d+$/.test(e))throw C(`${n} must be an integer.`,t,e||"<empty>",`Use ${o?"a non-negative":"a positive"} integer.`);let i=Number(e);if(!Number.isSafeInteger(i)||(o?i<0:i<1))throw C(`${n} is out of range.`,t,e,`Use ${o?"a non-negative":"a positive"} safe integer.`);return i}function zy(e,t){let n=e.trim();if(!n.startsWith("<"))return null;let o={line:t,column:e.indexOf("<")+1},i=/^<\/([a-z-]+)>$/.exec(n);if(i)return{name:i[1],closing:!0,attrs:new Map,source:o};let r=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!r)throw C("Block tag syntax is invalid.",o,e,"Use <name key=value> or </name> on its own line.");let s=new Map,c=r[2]??"";if(c)for(let a of c.split(" ")){if(!a)throw C("Block attributes must use one space separators.",o,e,"Use canonical key=value attributes separated by one space.");let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);if(!d)throw C("Block attribute syntax is invalid.",o,a,"Use unquoted canonical key=value attributes.");if(s.has(d[1]))throw C("Block attribute is duplicated.",o,d[1],"Keep exactly one value for each attribute.");s.set(d[1],d[2])}return{name:r[1],closing:!1,attrs:s,source:o}}function nn(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));if(i.length>0||r.length>0)throw C(`Attributes for <${e.name}> are invalid.`,e.source,`missing=${r.join(",")||"-"} unknown=${i.join(",")||"-"}`,`Use ${[...t,...n].map(s=>`${s}=...`).join(" ")}.`)}function Hy(e,t){if(!e)throw C("Speaker is required.",t,"<empty>","Use act_ID[/state_ID] or system|broadcast|offscreen|group[:label].");let n=e.indexOf("/"),o=n>=0?e.slice(0,n):e;if(/^act_[A-Za-z0-9_-]+$/.test(o)){if(n<0)return{actor_id:o};let s=e.slice(n+1);if(!s||s.includes("/"))throw C("Actor speaker state is invalid.",t,e,"Use act_ID/state_ID.");return{actor_id:o,state_id:s}}let i=e.indexOf(":"),r=i>=0?e.slice(0,i):e;if(!so.has(r)||!Ky(r))throw C("Speaker kind is invalid.",t,e,"Use an actor ID or system, broadcast, offscreen, or group.");return i<0?{kind:r}:{kind:r,label:e.slice(i+1)}}function Fy(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!Tt.has(o))throw C("Body record type is invalid.",e.source,e.type,"Use [act], [dlg], [think], or [trans].");let i={type:o,content:e.content};if(o==="dialogue"||o==="inner_thought"){if(e.slots.length<1||e.slots.length>2)throw C("Speaker record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|speaker|emotion?].`);i.speaker=Hy(e.slots[0],e.source),e.slots.length===2&&(i.emotion=e.slots[1])}else{if(e.slots.length>1)throw C("Body record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|emotion?].`);e.slots.length===1&&(i.emotion=e.slots[0])}let r=pt(t);if(r!==void 0&&(i.extend=r),t.aliasesPresent)throw C("Alias cannot modify an action.",t.source??e.source,t.aliases.join(","),"Use [alias] only before an asset declaration.");return t.prompt!==void 0&&(i.transition_prompt=t.prompt),i}var Wa=class{lines;index=0;constructor(t){this.lines=t.replace(/\r\n?/g,`
|
|
130
|
-
`).split(`
|
|
131
|
-
`)}parse(){this.skipBlank();let t=this.takeOpen("authoring");if(nn(t,["version"]),t.attrs.get("version")!=="1")throw C("Authoring version is unsupported.",t.source,t.attrs.get("version")??"<missing>","Use <authoring version=1>.");let n=[],o=[],i=!1,r=dt();for(;;){if(this.skipBlank(),this.peekClose("authoring")){En(r)&&this.throwDangling(r),this.takeClose("authoring");break}let a=this.peekSemantic();if(a===null)throw this.eofError("authoring");if(a.record?.type==="extensions"||a.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(a.tag?.name==="create"&&!a.tag.closing){if(i)throw C("<create> must precede every target.",a.tag.source,"<create>","Move the single <create> block before the targets.");En(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=dt()}if(this.skipBlank(),this.index<this.lines.length){let a={line:this.index+1,column:1};throw C("Content exists after </authoring>.",a,this.lines[this.index],"Remove content outside the root block.")}if(o.length===0)throw C("Authoring file has no target.",t.source,"<authoring>","Add one or more homogeneous target blocks.");let s=o[0].kind,c=o.find(a=>a.kind!==s);if(c!==void 0)throw C("Authoring targets are not homogeneous.",c.source,c.kind,`Keep only ${s} targets in this file.`);if(s==="script"&&o.length!==1)throw C("A script authoring file has exactly one target.",o[1].source,"second <script>","Keep one <script> target.");return{version:1,declarations:n,targets:o,targetKind:s}}parseCreate(){let t=this.takeOpen("create");nn(t,[]);let n=[],o=dt();for(;;){if(this.skipBlank(),this.peekClose("create"))return En(o)&&this.throwDangling(o),this.takeClose("create"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="alias"||i.type==="prompt"){o=this.addModifier(o,i);continue}if(i.type==="actor"){if(i.slots.length<3||i.slots.length>4)throw C("Actor declaration slots are invalid.",i.source,i.slots.join("|"),"Use [actor|id|name|importance|role?] description.");let[r,s,c,a]=i.slots;if(!r||!s||!c||!Et.has(c)||!_l(c))throw C("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(a!==void 0&&(!Tn.has(a)||!By(a)))throw C("Actor role is invalid.",i.source,a,"Use \u4E3B\u89D2 or \u914D\u89D2, or omit the slot.");let d={actor_id:r,actor_name:s,importance:c,description:i.content,states:[]};a!==void 0&&(d.role_type=a),o.aliasesPresent&&(d.aliases=[...o.aliases]);let p=pt(o);p!==void 0&&(d.extend=p),o.prompt!==void 0&&this.throwUnsupportedModifiers(o,"actor"),n.push({declarationKind:"actor",value:d,source:i.source}),o=dt();continue}if(i.type==="location"||i.type==="prop"){if(i.slots.length!==3)throw C(`${i.type} declaration slots are invalid.`,i.source,i.slots.join("|"),`Use [${i.type}|id|name|importance] description.`);let[r,s,c]=i.slots;if(!r||!s||!c||!Et.has(c)||!_l(c))throw C(`${i.type} declaration is invalid.`,i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");o.prompt!==void 0&&this.throwUnsupportedModifiers(o,i.type);let a=pt(o);if(i.type==="location"){let d={location_id:r,location_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"location",value:d,source:i.source})}else{let d={prop_id:r,prop_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"prop",value:d,source:i.source})}o=dt();continue}if(i.type==="state"){if(i.slots.length!==3)throw C("State declaration slots are invalid.",i.source,i.slots.join("|"),"Use [state|kind:asset_id|state_id|state_name] description.");(o.aliasesPresent||o.prompt!==void 0)&&this.throwUnsupportedModifiers(o,"state");let[r,s,c]=i.slots,a=/^(actor|location|prop):(.+)$/.exec(r??""),d=a?.[1]??"";if(!a||!jy(d)||!s||!c)throw C("State declaration is invalid.",i.source,i.slots.join("|"),"Use a typed owner and non-empty state ID/name.");let p={state_id:s,state_name:c,description:i.content},l=pt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:a[2],value:p,source:i.source}),o=dt();continue}throw C("Record is not allowed in <create>.",i.source,i.type,"Use actor, location, prop, state, or a supported prefix modifier.")}}parseTarget(t){let n=this.peekTag();if(n===null||n.closing){let o=n?.source??{line:this.index+1,column:1};throw C("Expected a target block.",o,this.lines[this.index]??"<eof>","Add a supported target block.")}switch((t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,n.name),n.name){case"script":return this.parseScript(t);case"episode":return{kind:"episode",value:this.parseEpisode(t),source:n.source,...pt(t)?{extend:pt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return nn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...pt(t)?{extend:pt(t)}:{}};case"scene-span":return this.parseSceneSpan(t);case"action-span":return this.parseActionSpan(t);default:throw C("Unknown target block.",n.source,n.name,"Use script, episode, episode-span, scene, scene-span, or action-span.")}}parseScript(t){let n=this.takeOpen("script");nn(n,[]);let o=["title","worldview","worldview-raw","style","synopsis","logline","theme","main-characters","main-character"],i=new Map,r=[],s=[],c=-1,a=!1,d=dt();for(;;){if(this.skipBlank(),this.peekClose("script")){En(d)&&this.throwDangling(d),this.takeClose("script");break}let m=this.peekSemantic();if(m?.record!==void 0){let g=this.takeRecord();if(g.type==="extensions"||g.type==="extend"||g.type==="aliases"||g.type==="alias"||g.type==="prompt"){d=this.addModifier(d,g);continue}En(d)&&this.throwUnsupportedModifiers(d,g.type);let h=o.indexOf(g.type),w=g.type==="main-character";if(a||h<0||h<c||!w&&i.has(g.type))throw C("Metadata record in <script> is invalid or out of order.",g.source,g.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(c=h,g.type==="main-characters"){if(g.slots.length!==0||g.content!=="")throw C("Main characters marker is invalid.",g.source,g.content,"Use [main-characters] with no slots or content.");i.set(g.type,"")}else if(w){if(g.slots.length!==2||!g.slots[0]||!g.slots[1]||g.content!=="")throw C("Main character record is invalid.",g.source,g.slots.join("|"),"Use [main-character|name|role] with no content.");r.push({name:g.slots[0],role:g.slots[1]})}else{if(g.slots.length!==0)throw C("Script metadata record has unexpected slots.",g.source,g.slots.join("|"),`Use [${g.type}] content.`);i.set(g.type,g.content)}continue}if(m?.tag===void 0||m.tag.closing||m.tag.name!=="episode"){let g=m?.tag?.source??{line:this.index+1,column:1};throw C("Unexpected member in <script>.",g,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}a=!0,s.push(this.parseEpisode(d)),d=dt()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=pt(t);return{kind:"script",title:p,worldview:l,style:f,...i.get("worldview-raw")!==void 0?{worldviewRaw:i.get("worldview-raw")}:{},...i.get("synopsis")!==void 0?{synopsis:i.get("synopsis")}:{},...i.get("logline")!==void 0?{logline:i.get("logline")}:{},...i.get("theme")!==void 0?{theme:i.get("theme")}:{},...i.has("main-characters")||r.length>0?{mainCharacters:r}:{},episodes:s,source:n.source,...u!==void 0?{extend:u}:{}}}parseEpisode(t){let n=this.takeOpen("episode");nn(n,["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"episode");let o=this.parseMetadataAndChildren("episode",["title","synopsis"],"scene",s=>this.parseScene(s,!1)),i={episode_id:n.attrs.get("id"),scenes:o.children};o.values.has("title")&&(i.title=o.values.get("title")),o.values.has("synopsis")&&(i.synopsis=o.values.get("synopsis"));let r=pt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");nn(o,n?["id","parent"]:["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"scene");let i,r,s=[],c=[],a="environment",d;for(;;){if(this.skipBlank(),this.peekClose("scene")){this.takeClose("scene");break}let f=this.peekSemantic();if(f?.tag?.name==="body"&&!f.tag.closing){if(a==="body")throw C("Scene has more than one body.",f.tag.source,"<body>","Keep exactly one <body>.");a="body",d=this.parseBody();continue}if(f?.record===void 0){let m=f?.tag?.source??{line:this.index+1,column:1};throw C("Only scene records and <body> are allowed here.",m,this.lines[this.index]??"<eof>","Use environment, location, cast, prop, then body.")}let u=this.takeRecord();if(u.type==="extensions"||u.type==="extend"||u.type==="aliases"||u.type==="alias"||u.type==="prompt")throw C("Scene prefix modifier must directly precede <scene>.",u.source,u.type,"Move the modifier before the <scene> opening tag.");if(u.type==="environment"){if(a!=="environment"||i!==void 0||u.slots.length>2)throw C("Environment record is out of order or invalid.",u.source,u.slots.join("|"),"Place at most one [environment|space?|time?] first.");i={},u.slots.length>=1&&u.slots[0]!==""&&(i.space=u.slots[0]),u.slots.length>=2&&u.slots[1]!==""&&(i.time=u.slots[1]);continue}if(u.type==="location"){if(a==="cast"||a==="prop"||a==="body"||r!==void 0||u.slots.length>2)throw C("Location record is out of order or invalid.",u.source,u.slots.join("|"),"Place exactly one [location|id?|state?] before cast.");a="location";let m=u.slots[0];m===void 0||m===""?r=null:r=u.slots.length===2?{location_id:m,state_id:u.slots[1]}:{location_id:m};continue}if(u.type==="cast"){if(r===void 0||a==="prop"||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw C("Cast record is out of order or invalid.",u.source,u.slots.join("|"),"Place [cast|actor_id|state_id?] after location and before props.");a="cast",s.push(u.slots.length===2?{actor_id:u.slots[0],state_id:u.slots[1]}:{actor_id:u.slots[0]});continue}if(u.type==="prop"){if(r===void 0||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw C("Prop record is out of order or invalid.",u.source,u.slots.join("|"),"Place [prop|prop_id|state_id?] after cast and before body.");a="prop",c.push(u.slots.length===2?{prop_id:u.slots[0],state_id:u.slots[1]}:{prop_id:u.slots[0]});continue}throw C("Record is not allowed in a scene header.",u.source,u.type,"Use environment, location, cast, prop, or body records.")}if(r===void 0)throw C("Scene location record is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add [location] or [location|loc_ID|state_ID].");if(d===void 0)throw C("Scene body is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add one <body> block.");let p={scene_id:o.attrs.get("id"),location:r,actors:s,props:c,actions:d};i!==void 0&&(p.environment=i);let l=pt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");nn(t,[]);let n=[],o=dt();for(;;){if(this.skipBlank(),this.peekClose("body"))return En(o)&&this.throwDangling(o),this.takeClose("body"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="prompt"||i.type==="alias"){o=this.addModifier(o,i);continue}n.push(Fy(i,o)),o=dt()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");nn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=pt(t);return{kind:"episode-span",from:n.attrs.get("from"),through:n.attrs.get("through"),episodes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseSceneSpan(t){let n=this.takeOpen("scene-span");nn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=pt(t);return{kind:"scene-span",parent:n.attrs.get("parent"),from:n.attrs.get("from"),through:n.attrs.get("through"),scenes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseActionSpan(t){let n=this.takeOpen("action-span");nn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=pt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:El(n.attrs.get("from"),n.source,"action-span from",!0),through:El(n.attrs.get("through"),n.source,"action-span through",!0),actions:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseMetadataAndChildren(t,n,o,i){let r=new Map,s=[],c=-1,a=!1,d=dt();for(;;){if(this.skipBlank(),this.peekClose(t))return En(d)&&this.throwDangling(d),this.takeClose(t),{values:r,children:s};let p=this.peekSemantic();if(p?.record!==void 0){let f=this.takeRecord();if(f.type==="extensions"||f.type==="extend"||f.type==="aliases"||f.type==="alias"||f.type==="prompt"){d=this.addModifier(d,f);continue}En(d)&&this.throwUnsupportedModifiers(d,f.type);let u=n.indexOf(f.type);if(a||u<0||u<c||r.has(f.type)||f.slots.length!==0)throw C(`Metadata record in <${t}> is invalid or out of order.`,f.source,f.type,`Use each of ${n.join(", ")} at most once in canonical order before child blocks.`);c=u,r.set(f.type,f.content);continue}let l=p?.tag;if(l===void 0||l.closing||l.name!==o){let f=l?.source??{line:this.index+1,column:1};throw C(`Unexpected member in <${t}>.`,f,this.lines[this.index]??"<eof>",`Use metadata records followed by <${o}> blocks.`)}a=!0,s.push(i(d)),d=dt()}}parseOnlyChildren(t,n,o){let i=[],r=dt();for(;;){if(this.skipBlank(),this.peekClose(t))return En(r)&&this.throwDangling(r),this.takeClose(t),i;let s=this.peekSemantic();if(s?.record?.type==="extensions"||s?.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(s?.tag===void 0||s.tag.closing||s.tag.name!==n){let c=s?.tag?.source??s?.record?.source??{line:this.index+1,column:1};throw C(`Only <${n}> children are allowed in <${t}>.`,c,this.lines[this.index]??"<eof>",`Add complete <${n}> blocks.`)}i.push(o(r)),r=dt()}}addModifier(t,n){let o={extend:{...t.extend},extendPresent:t.extendPresent,aliases:[...t.aliases],aliasesPresent:t.aliasesPresent,phase:t.phase,...t.prompt!==void 0?{prompt:t.prompt}:{},source:t.source??n.source};if(n.type==="extensions"){if(o.phase!=="extend"||o.extendPresent||n.slots.length!==0||n.content!=="")throw C("Extensions marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [extensions] marker before extension records.");return o.extendPresent=!0,o}if(n.type==="extend"){if(o.phase!=="extend"||n.slots.length!==1||!n.slots[0])throw C("Extend modifier is invalid or out of order.",n.source,n.slots.join("|"),"Place unique [extend|key] records first.");let i=n.slots[0];if(Object.hasOwn(o.extend,i))throw C("Extend key is duplicated.",n.source,i,"Keep one value for each extension key.");let r;try{r=JSON.parse(n.content)}catch{throw C("Extension value is not valid JSON.",n.source,n.content,"Use one canonical JSON value.")}if(!Ya(r))throw C("Extension value is not JSON-compatible.",n.source,n.content,"Use string, number, boolean, null, array, or object.");return o.extendPresent=!0,o.extend[i]=qa(r),o}if(n.type==="aliases"){if(o.phase!=="extend"||o.aliasesPresent||n.slots.length!==0||n.content!=="")throw C("Aliases marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [aliases] marker after extensions and before alias records.");return o.phase="alias",o.aliasesPresent=!0,o}if(n.type==="alias"){if(o.phase==="prompt"||n.slots.length!==0||!n.content)throw C("Alias modifier is invalid or out of order.",n.source,n.content||"<empty>","Place non-empty [alias] records after extensions and before prompt.");if(o.phase="alias",o.aliasesPresent=!0,o.aliases.includes(n.content))throw C("Alias is duplicated.",n.source,n.content,"Keep each alias once.");return o.aliases.push(n.content),o}if(n.type==="prompt"){if(o.prompt!==void 0||n.slots.length!==3||n.slots.some(i=>!i))throw C("Prompt modifier is invalid.",n.source,n.slots.join("|"),"Use one [prompt|target|process|contrast] after extensions and aliases.");if(!/^(?:actor:act_|location:loc_|prop:prp_)[A-Za-z0-9_-]+$/.test(n.slots[0]))throw C("Prompt target is invalid.",n.source,n.slots[0],"Use actor:act_ID, location:loc_ID, or prop:prp_ID.");return o.phase="prompt",o.prompt={target:n.slots[0],process:n.slots[1],contrast:n.slots[2]},o}throw C("Unknown prefix modifier.",n.source,n.type,"Use extend, alias, or prompt.")}requiredMetadata(t,n,o){let i=t.get(n);if(i===void 0)throw C(`Script ${n} record is missing.`,o,"<script>",`Add [${n}] in canonical metadata order.`);return i}peekSemantic(){if(this.skipBlank(),this.index>=this.lines.length)return null;let t=this.lines[this.index],n=zy(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:zo(t,this.index+1)};let o={line:this.index+1,column:Math.max(1,t.search(/\S/)+1)};throw C("Semantic line is neither a tag nor a bracket record.",o,t,"Use only known tags, bracket records, or blank lines.")}peekTag(){return this.peekSemantic()?.tag??null}takeRecord(){let t=this.peekSemantic();if(t?.record===void 0){let n=t?.tag?.source??{line:this.index+1,column:1};throw C("Expected a bracket record.",n,this.lines[this.index]??"<eof>","Use the record required at this position.")}return this.index+=1,t.record}takeOpen(t){let n=this.peekTag();if(n===null||n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw C(`Expected <${t}>.`,o,this.lines[this.index]??"<eof>",`Open <${t}> here.`)}return this.index+=1,n}takeClose(t){let n=this.peekTag();if(n===null||!n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw C(`Expected </${t}>.`,o,this.lines[this.index]??"<eof>",`Close the current <${t}> block.`)}return this.index+=1,n}peekClose(t){let n=this.peekTag();return n!==null&&n.closing&&n.name===t}skipBlank(){for(;this.index<this.lines.length&&this.lines[this.index].trim()==="";)this.index+=1}eofError(t){return C(`Unexpected end of file inside <${t}>.`,{line:this.lines.length,column:1},"<eof>",`Add </${t}>.`)}throwDangling(t){throw C("Prefix modifier has no following node.",t.source??{line:this.index+1,column:1},"dangling modifier","Move it directly before a supported node.")}throwUnsupportedModifiers(t,n){throw C("Prefix modifier does not apply to this node.",t.source??{line:this.index+1,column:1},n,"Remove the unsupported modifier or move it before a supported node.")}};function xl(e){return new Wa(e).parse()}function N(e,t,n){throw new x(e,{exitCode:b,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function tc(e,t){let n=e.trim(),o=/^<\/([a-z-]+)>$/.exec(n);if(o)return{name:o[1],closing:!0,attrs:new Map,line:t};let i=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!i)return null;let r=new Map,s=i[2]??"",c=s===""?[]:s.split(" ");c.some(a=>a==="")&&N("Tag attributes need one-space separators.",t,n);for(let a of c){let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);(!d||r.has(d[1]))&&N("Tag attributes are invalid.",t,a),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function Le(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));(i.length>0||r.length>0)&&N("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var nc=class{lines;index=0;constructor(t){this.lines=t.split(/\r?\n/).map((n,o)=>({raw:n.replace(/^\s+/,""),line:o+1})).filter(n=>n.raw.trim()!=="")}peek(){let t=this.lines[this.index];return t||N("Unexpected end of authoring file.",this.lines.at(-1)?.line??1,"<eof>"),t}take(){let t=this.peek();return this.index++,t}tag(t,n){let o=this.take(),i=tc(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&N(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return zo(t.raw,t.line)}nextTag(){let t=this.peek();return tc(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?zo(t.raw,t.line):null}};function oc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(oc):typeof e=="object"&&Object.values(e).every(oc)}function fo(e){let t={},n=e.nextRecord();if(n?.type==="extensions"){e.record();let o={},i=null;for(;(n=e.nextRecord())?.type==="extend";){let r=e.record();(r.slots.length!==1||Object.hasOwn(o,r.slots[0]))&&N("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&N("extend keys must use ascending canonical order.",r.source.line,s);let c;try{c=JSON.parse(r.content)}catch{N("extend content must be JSON.",r.source.line,r.content)}oc(c)||N("extend value must be JSON-compatible.",r.source.line,r.content),o[s]=c,i=s}t.extend=o}if(n=e.nextRecord(),n?.type==="aliases"){e.record();let o=[];for(;(n=e.nextRecord())?.type==="alias";){let i=e.record();i.slots.length!==0&&N("alias takes no slots.",i.source.line,i.type),i.content===""&&N("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&N("alias must not be duplicated.",i.source.line,i.content),o.push(i.content)}t.aliases=o}if(n=e.nextRecord(),n?.type==="prompt"){let o=e.record();(o.slots.length!==3||o.slots.some(r=>r===""))&&N("prompt requires non-empty target, process, and contrast.",o.source.line,o.type);let i=o.slots[0];!T("actor",i)&&!T("location",i)&&!T("prop",i)&&N("prompt target must be an asset ID.",o.source.line,i),t.prompt={target:i,process:o.slots[1],contrast:o.slots[2]}}return t}function Za(e,t){return e!=="featured"&&e!=="background"&&N("Importance is invalid.",t,e),e}function Qy(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&N("Role type is invalid.",t,e),e}function sc(e,t){return e==="default"||T("state",e)?e:N("State ID is invalid.",t,e)}function Yy(e){let t=e.tag("create",!1);Le(t,[]);let n=[],o=new Map,i=null,r=0,s=a=>{if(i===null)return;let d=o.get(i);(!d||d.states.length===0||d.states[0].state_id!=="default")&&N("A new asset must be followed immediately by its default state.",a,i),i=null};for(;e.nextTag()?.name!=="create"||e.nextTag()?.closing!==!0;){let a=fo(e),d=e.record();if(d.type==="actor"){r>0&&N("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),a.prompt!==void 0&&N("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!T("actor",d.slots[0]))&&N("actor declaration is invalid.",d.source.line,d.type);let p=Qy(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:Za(d.slots[2],d.source.line),description:d.content,states:[],...p===void 0?{}:{role_type:p},...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};l.aliases?.includes(l.actor_name)&&N("An alias must differ from the asset name.",d.source.line,l.actor_name),n.push({kind:"actor",value:l}),o.set(l.actor_id,l),i=l.actor_id}else if(d.type==="location"||d.type==="prop"){let p=d.type==="location"?1:2;p<r&&N("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),a.prompt!==void 0&&N("prompt cannot modify an asset.",d.source.line,d.type);let l=d.type;if((d.slots.length!==3||(l==="location"?!T("location",d.slots[0]):!T("prop",d.slots[0])))&&N(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];T("location",f)||N("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:Za(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.location_name)&&N("An alias must differ from the asset name.",d.source.line,u.location_name),n.push({kind:l,value:u}),o.set(u.location_id,u),i=u.location_id}else{let f=d.slots[0];T("prop",f)||N("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:Za(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.prop_name)&&N("An alias must differ from the asset name.",d.source.line,u.prop_name),n.push({kind:l,value:u}),o.set(u.prop_id,u),i=u.prop_id}}else if(d.type==="state"){(d.slots.length!==3||a.aliases!==void 0||a.prompt!==void 0)&&N("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&N("States for a new asset must immediately follow that asset.",d.source.line,p),l||(s(d.source.line),r=3);let f={state_id:sc(d.slots[1],d.source.line),state_name:d.slots[2],description:d.content,...a.extend===void 0?{}:{extend:a.extend}};l?(l.states.length===0&&f.state_id!=="default"&&N("The first state of a new asset must be default.",d.source.line,f.state_id),l.states.push(f)):n.push({kind:"state",ownerId:p,value:f})}else s(d.source.line),N("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let c=e.tag("create",!0);return Le(c,[]),n}function qy(e,t){let n=e.indexOf("/"),o=n<0?e:e.slice(0,n);if(T("actor",o))return n<0?{actor_id:o}:{actor_id:o,state_id:sc(e.slice(n+1),t)};let i=e.indexOf(":"),r=i<0?e:e.slice(0,i);return["system","broadcast","offscreen","group"].includes(r)?i<0?{kind:r}:{kind:r,label:e.slice(i+1)}:N("Speaker is invalid.",t,e)}function Sl(e){let t=fo(e);t.aliases!==void 0&&N("aliases cannot modify an Action.",e.peek().line,"aliases");let n=e.record();return n.type==="act"||n.type==="trans"?((n.slots.length!==1||!T("action",n.slots[0]))&&N("Narrative Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="act"?"action":"transition",content:n.content,...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}}):n.type!=="dlg"&&n.type!=="think"?N("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!T("action",n.slots[0]))&&N("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:qy(n.slots[1],n.source.line),content:n.content,...n.slots.length===3?{parenthetical:n.slots[2]}:{},...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}})}function Xa(e,t){e.length===0&&N("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>sc(o,t));return new Set(n).size!==n.length&&N("Scene reference repeats a state.",t,n.join(",")),n.sort()}function ic(e,t,n,o){Le(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";T("scene",i)||N("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!T("episode",r)&&N("Scene parent must be an Episode ID.",t.line,r);let s,c,a=[],d=[],p=new Set,l=new Set,f=0;for(;e.nextTag()?.name!=="body";){let g=e.record(),h=g.type==="environment"?0:g.type==="location"?1:g.type==="cast"?2:g.type==="prop"?3:-1;h<f&&N("Scene records are not in canonical order.",g.source.line,g.type),f=h,g.type==="environment"?(s!==void 0&&N("Scene environment is duplicated.",g.source.line,g.type),g.slots.length>2&&N("environment has too many slots.",g.source.line,g.type),s={...g.slots[0]===void 0?{}:{space:g.slots[0]},...g.slots[1]===void 0?{}:{time:g.slots[1]}}):g.type==="location"?(c!==void 0&&N("Scene location is duplicated.",g.source.line,g.type),g.slots.length===0?c=null:(T("location",g.slots[0])||N("Location ref ID is invalid.",g.source.line,g.slots[0]),c={location_id:g.slots[0],state_ids:Xa(g.slots.slice(1),g.source.line)})):g.type==="cast"?(T("actor",g.slots[0])||N("Cast ref ID is invalid.",g.source.line,g.slots[0]??""),p.has(g.slots[0])&&N("Scene repeats an actor reference.",g.source.line,g.slots[0]),p.add(g.slots[0]),a.push({actor_id:g.slots[0],state_ids:Xa(g.slots.slice(1),g.source.line)})):g.type==="prop"?(T("prop",g.slots[0])||N("Prop ref ID is invalid.",g.source.line,g.slots[0]??""),l.has(g.slots[0])&&N("Scene repeats a prop reference.",g.source.line,g.slots[0]),l.add(g.slots[0]),d.push({prop_id:g.slots[0],state_ids:Xa(g.slots.slice(1),g.source.line)})):N("Unknown scene header record.",g.source.line,g.type)}c===void 0&&N("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);Le(u,[]);let m=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)m.push(Sl(e));return Le(e.tag("body",!0),[]),Le(e.tag("scene",!0),[]),{...r===void 0?{}:{parent:r},value:{scene_id:i,...s===void 0?{}:{environment:s},location:c,actors:a,props:d,actions:m,...o===void 0?{}:{extend:o}}}}function rc(e,t,n){Le(t,["id"]);let o=t.attrs.get("id")??"";T("episode",o)||N("Episode ID is invalid.",t.line,o);let i,r,s=[],c=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let a=fo(e);(a.aliases!==void 0||a.prompt!==void 0)&&N("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){c=2,e.take(),s.push(ic(e,d,o,a.extend).value);continue}a.extend!==void 0&&N("extend must precede a scene here.",e.peek().line,"extend");let p=e.record(),l=p.type==="title"?0:p.type==="synopsis"?1:-1;l<c&&N("Episode records are not in canonical order.",p.source.line,p.type),c=l,p.type==="title"?(i!==void 0&&N("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&N("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&N("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&N("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):N("Unknown episode record.",p.source.line,p.type)}return Le(e.tag("episode",!0),[]),{episode_id:o,...i===void 0?{}:{title:i},...r===void 0?{}:{synopsis:r},scenes:s,...n===void 0?{}:{extend:n}}}function ec(e,t){let n=e.attrs.get("range")??"",o=n.split("..");return(o.length!==2||!o[0]||!o[1]||!T(t,o[0])||!T(t,o[1]))&&N(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function Wy(e,t,n){Le(t,[]);let o,i,r,s,c,a,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=fo(e);(u.aliases!==void 0||u.prompt!==void 0)&&N("Invalid script child modifier.",e.peek().line,"modifier");let m=e.nextTag();if(m?.name==="episode"&&!m.closing){f=8,e.take(),l.push(rc(e,m,u.extend));continue}u.extend!==void 0&&N("extend must precede an episode here.",e.peek().line,"extend");let g=e.record(),h=g.type==="title"?0:g.type==="worldview"?1:g.type==="worldview-raw"?2:g.type==="style"?3:g.type==="synopsis"?4:g.type==="logline"?5:g.type==="theme"?6:g.type==="main-characters"||g.type==="main-character"?7:-1;h<f&&N("Script records are not in canonical order.",g.source.line,g.type),f=h,g.type!=="main-character"&&g.slots.length!==0&&N("Script metadata record takes no slots.",g.source.line,g.type),g.type==="title"?(o!==void 0&&N("Script title is duplicated.",g.source.line,g.type),o=g.content):g.type==="worldview"?(i!==void 0&&N("Script worldview is duplicated.",g.source.line,g.type),i=g.content):g.type==="worldview-raw"?(r!==void 0&&N("Script worldview-raw is duplicated.",g.source.line,g.type),r=g.content):g.type==="style"?(s!==void 0&&N("Script style is duplicated.",g.source.line,g.type),s=g.content):g.type==="synopsis"?(c!==void 0&&N("Script synopsis is duplicated.",g.source.line,g.type),c=g.content):g.type==="logline"?(a!==void 0&&N("Script logline is duplicated.",g.source.line,g.type),a=g.content):g.type==="theme"?(d!==void 0&&N("Script theme is duplicated.",g.source.line,g.type),d=g.content):g.type==="main-characters"?(p!==void 0&&N("Script main-characters is duplicated.",g.source.line,g.type),p=[]):g.type==="main-character"&&p!==void 0&&g.slots.length===2&&g.content===""?p.push({name:g.slots[0],role:g.slots[1]}):N("Unknown script record.",g.source.line,g.type)}return Le(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&N("Script target needs title, worldview, and style.",e.peek().line,"script"),{kind:"script",value:{title:o,worldview:i,style:s,episodes:l,...r===void 0?{}:{worldview_raw:r},...c===void 0?{}:{synopsis:c},...a===void 0?{}:{logline:a},...d===void 0?{}:{theme:d},...p===void 0?{}:{main_characters:p},...n===void 0?{}:{extend:n}}}}function Il(e){let t=new nc(e),n=t.tag("authoring",!1);Le(n,["version"]),n.attrs.get("version")!=="1"&&N("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?Yy(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=fo(t);(s.aliases!==void 0||s.prompt!==void 0)&&N("Invalid target modifier.",t.peek().line,"modifier");let c=t.take(),a=tc(c.raw,c.line);if((!a||a.closing)&&N("Expected an authoring target.",c.line,c.raw),a.name==="script")i.push(Wy(t,a,s.extend));else if(a.name==="episode")i.push({kind:"episode",value:rc(t,a,s.extend)});else if(a.name==="scene"){let d=ic(t,a,void 0,s.extend);d.parent||N("Top-level scene needs parent.",c.line,c.raw),i.push({kind:"scene",parent:d.parent,value:d.value})}else if(a.name==="episode-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),Le(a,["range"]);let[d,p]=ec(a,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=fo(t);(f.aliases!==void 0||f.prompt!==void 0)&&N("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(rc(t,u,f.extend))}Le(t.tag("episode-span",!0),[]),i.push({kind:"episode-span",from:d,through:p,values:l})}else if(a.name==="scene-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),Le(a,["parent","range"]);let[d,p]=ec(a,"scene"),l=a.attrs.get("parent")??N("scene-span needs parent.",c.line,c.raw);T("episode",l)||N("scene-span parent must be an Episode ID.",c.line,l);let f=[];for(;t.nextTag()?.name!=="scene-span"||t.nextTag()?.closing!==!0;){let u=fo(t);(u.aliases!==void 0||u.prompt!==void 0)&&N("Invalid scene child modifier.",t.peek().line,"modifier");let m=t.tag("scene",!1);f.push(ic(t,m,l,u.extend).value)}Le(t.tag("scene-span",!0),[]),i.push({kind:"scene-span",parent:l,from:d,through:p,values:f})}else if(a.name==="action-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),Le(a,["parent","range"]);let[d,p]=ec(a,"action"),l=a.attrs.get("parent")??N("action-span needs parent.",c.line,c.raw);T("scene",l)||N("action-span parent must be a Scene ID.",c.line,l),Le(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(Sl(t));Le(t.tag("body",!0),[]),Le(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else N("Unknown authoring target.",c.line,a.name)}Le(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&N("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||N("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function on(e){if(Array.isArray(e))return e.map(t=>on(t));if(X(e)){let t={};for(let n of Object.keys(e).sort())t[n]=on(e[n]);return t}return e}function ac(e){if(e.length===0)return[];let t={};for(let i of e){let r=O(i.severity);t[r]=(t[r]??0)+1}let n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${i}: ${r}`),o=e[0];return[n.join("; "),`first: ${o.code} - ${o.summary}`,...o.repair_hint?[`repair: ${o.repair_hint}`]:[]]}function Al(e,t){if(!(t.ok||e!==null&&_a(Ue(e),t)))throw new x("The proposed document is not a valid or strictly improved Script v4.",{exitCode:b,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function ve(e,t){throw new x(e,{exitCode:b,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function dc(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function Ho(e){return{ids:e.flatMap(t=>[t.scene_id,...t.actions.map(n=>n.action_id)]),counts:{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}}function Kn(e){return{ids:e.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])]),counts:{episodes:e.length,scenes:e.reduce((t,n)=>t+n.scenes.length,0),actions:e.reduce((t,n)=>t+n.scenes.reduce((o,i)=>o+i.actions.length,0),0)}}}function Zy(e){return e.kind==="script"?Kn(e.value.episodes):e.kind==="episode"?Kn([e.value]):e.kind==="episode-span"?Kn(e.values):e.kind==="scene"?Ho([e.value]):e.kind==="scene-span"?Ho(e.values):dc(e.values)}function Xy(e){return{actors:e.filter(t=>t.kind==="actor").map(t=>structuredClone(t.value)),locations:e.filter(t=>t.kind==="location").map(t=>structuredClone(t.value)),props:e.filter(t=>t.kind==="prop").map(t=>structuredClone(t.value))}}function cc(e,t){return JSON.stringify(on(e))===JSON.stringify(on(t))}function kl(e,t){let n=new Set(e===null?[]:[...e.actors.map(d=>d.actor_id),...e.locations.map(d=>d.location_id),...e.props.map(d=>d.prop_id)]),o=new Set(e===null?[]:[...e.actors.flatMap(d=>d.states.map(p=>`${d.actor_id}/${p.state_id}`)),...e.locations.flatMap(d=>d.states.map(p=>`${d.location_id}/${p.state_id}`)),...e.props.flatMap(d=>d.states.map(p=>`${d.prop_id}/${p.state_id}`))]),i=[],r=[],s=[],c=[],a=d=>{(o.has(d)?c:s).push(d)};for(let d of t){if(d.kind==="state"){n.has(d.ownerId)&&r.push(d.ownerId),a(`${d.ownerId}/${d.value.state_id}`);continue}let p=d.kind==="actor"?d.value.actor_id:d.kind==="location"?d.value.location_id:d.value.prop_id;(n.has(p)?r:i).push(p),d.value.states.forEach(l=>{a(`${p}/${l.state_id}`)})}return{createdAssets:i,existingAssets:[...new Set(r)],createdStates:s,existingStates:c}}function bl(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes)o.location&&t.add(o.location.location_id),o.actors.forEach(i=>t.add(i.actor_id)),o.props.forEach(i=>t.add(i.prop_id)),o.actions.forEach(i=>{i.transition_prompt&&t.add(i.transition_prompt.target)});return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function Ol(e){return[...e.actors.flatMap(t=>[t.actor_id,...t.states.map(n=>`${t.actor_id}/${n.state_id}`)]),...e.locations.flatMap(t=>[t.location_id,...t.states.map(n=>`${t.location_id}/${n.state_id}`)]),...e.props.flatMap(t=>[t.prop_id,...t.states.map(n=>`${t.prop_id}/${n.state_id}`)]),...e.episodes.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])])]}function vl(e,t){let n=e===null?[]:Ol(e),o=Ol(t),i=new Set(n),r=new Set(o);return{createdIds:o.filter(s=>!i.has(s)),removedIds:n.filter(s=>!r.has(s)),retainedIds:n.filter(s=>r.has(s))}}function ew(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&ve("Declaration cannot redefine an existing actor.",[n.value.actor_id]),e.actors.push(structuredClone(n.value));else if(n.kind==="location")e.locations.some(o=>o.location_id===n.value.location_id)&&ve("Declaration cannot redefine an existing location.",[n.value.location_id]),e.locations.push(structuredClone(n.value));else if(n.kind==="prop")e.props.some(o=>o.prop_id===n.value.prop_id)&&ve("Declaration cannot redefine an existing prop.",[n.value.prop_id]),e.props.push(structuredClone(n.value));else{let o=e.actors.find(i=>i.actor_id===n.ownerId)??e.locations.find(i=>i.location_id===n.ownerId)??e.props.find(i=>i.prop_id===n.ownerId);o||ve("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&ve("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function Pt(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&ve("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function tw(e,t){if(t.kind==="script")return[0,0];if(t.kind==="episode"||t.kind==="episode-span"){let o=e.episodes.map(i=>i.episode_id);return t.kind==="episode"?Pt(o,t.value.episode_id,t.value.episode_id):Pt(o,t.from,t.through)}if(t.kind==="scene"||t.kind==="scene-span"){let o=e.episodes.flatMap(i=>i.scenes.map(r=>r.scene_id));return t.kind==="scene"?Pt(o,t.value.scene_id,t.value.scene_id):Pt(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return Pt(n,t.from,t.through)}function nw(e,t){let n=-1;for(let o of t){let[i,r]=tw(e,o);i<=n&&ve("Replace targets must follow current document order without overlap.",[Ll(o)]),n=r}}function Ll(e){return e.kind==="script"?"script":e.kind==="episode"?e.value.episode_id:e.kind==="scene"?e.value.scene_id:`${e.from}..${e.through}`}function Rl(e,t){if(t.kind==="script")return{...Kn(e.episodes),siblings:0};if(t.kind==="episode"){let r=en(e,t.value.episode_id);return{...Kn(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=Pt(e.episodes.map(c=>c.episode_id),t.from,t.through);return{...Kn(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=_n(e,t.value.scene_id),s=en(e,t.parent)?.episode;return{...Ho(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=en(e,t.parent)?.episode;if(!r)return{...Ho([]),siblings:0};let[s,c]=Pt(r.scenes.map(a=>a.scene_id),t.from,t.through);return{...Ho(r.scenes.slice(s,c+1)),siblings:r.scenes.length-(c-s+1)}}let n=_n(e,t.parent)?.scene;if(!n)return{...dc([]),siblings:0};let[o,i]=Pt(n.actions.map(r=>r.action_id),t.from,t.through);return{...dc(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function Nl(e,t){let n=Zy(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:Ll(e),before:t.counts,after:n.counts,retainedIds:t.ids.filter(r=>i.has(r)),createdIds:n.ids.filter(r=>!o.has(r)),removedIds:t.ids.filter(r=>!i.has(r)),untouchedSiblings:t.siblings}}function ow(e,t){if(t.kind==="script"&&ve("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=en(e,t.value.episode_id);n||ve("Episode replacement target was not found.",[t.value.episode_id]),e.episodes[n.episodeIndex]=structuredClone(t.value)}else if(t.kind==="episode-span"){let[n,o]=Pt(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&ve("Episode span replacement cannot be empty.",[t.from,t.through]),e.episodes.splice(n,o-n+1,...structuredClone(t.values))}else if(t.kind==="scene"){let n=_n(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&ve("Scene replacement target was not found under its parent.",[t.parent,t.value.scene_id]),n.episode.scenes[n.sceneIndex]=structuredClone(t.value)}else if(t.kind==="scene-span"){let n=en(e,t.parent)?.episode;n||ve("Scene span parent was not found.",[t.parent]);let[o,i]=Pt(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&ve("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=_n(e,t.parent)?.scene;n||ve("Action span parent was not found.",[t.parent]);let[o,i]=Pt(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&ve("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function iw(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=en(e,t.parent)?.episode;n||ve("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else ve("This target kind does not support create against an existing script.",[t.kind])}function Ml(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return ve("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return ve("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...Xy(e.declarations)}}function Ul(e,t,n){let o;if(e===null)n!=="create"&&ve("A missing target requires one script create target.",[n,t.targetKind]),o=Ml(t);else if(n==="create"&&t.targetKind==="script")o=Ml(t),cc(o,e)||ve("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&nw(e,t.targets),ew(o,t.declarations);let r=t.targets.map(a=>Rl(e,a));if(n==="replace")for(let a of[...t.targets].reverse())ow(o,a);else for(let a of t.targets)iw(o,a);let s=t.targets.map((a,d)=>Nl(a,r[d])),c=Ue(o);return Al(e,c),{script:o,changed:!cc(e,o),validation:c,targets:s,declarations:kl(e,t.declarations),retainedOrphanAssets:bl(o),identity:vl(e,o)}}let i=Ue(o);return Al(e,i),{script:o,changed:e===null||!cc(e,o),validation:i,declarations:kl(e,t.declarations),retainedOrphanAssets:bl(o),identity:vl(e,o),targets:t.targets.map(r=>{let s=e===null?{...Kn([]),siblings:0}:Rl(e,r);return Nl(r,s)})}}function mo(e,t){throw new x(e,{exitCode:G,errorCode:"AUTHORING_USAGE_INVALID",hint:"Choose exactly one mode and pass a regular authoring source file.",data:{expected:["scriptctl authoring write <file> (--create|--replace) [--apply --plan <digest>]"],actual:t}})}function rw(e){(!e||e==="-")&&mo("Authoring input must be a named file.",[e||"<missing>"]);let t=Tl.resolve(e),n;try{n=Ji.statSync(t)}catch{throw new x("The authoring source file does not exist.",{exitCode:b,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||mo("Authoring input must be a regular file.",[t]);let o=Ji.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function sw(e){let t=Mi(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(Ji.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script is not valid JSON.",{exitCode:b,errorCode:"SCRIPT_JSON_INVALID",hint:"Repair the local JSON file, then rerun authoring.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=zr(n);return{script:o,baseline:Ce(o),fingerprint:t}}function aw(e){let t=e.create===!0,n=e.replace===!0;return t===n&&mo("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function Cl(e){return`sha256:${Se(JSON.stringify(e))}`}function cw(e){return e.targets.reduce((t,n)=>({before:{episodes:t.before.episodes+n.before.episodes,scenes:t.before.scenes+n.before.scenes,actions:t.before.actions+n.before.actions},after:{episodes:t.after.episodes+n.after.episodes,scenes:t.after.scenes+n.after.scenes,actions:t.after.actions+n.after.actions}}),{before:{episodes:0,scenes:0,actions:0},after:{episodes:0,scenes:0,actions:0}})}function dw(e){let t=e.targets.map((n,o)=>[`target[${o}]=${n.address}`,`kind=${n.kind}`,`before=${JSON.stringify(n.before)}`,`after=${JSON.stringify(n.after)}`,`retained=${JSON.stringify(n.retainedIds)}`,`created=${JSON.stringify(n.createdIds)}`,`removed=${JSON.stringify(n.removedIds)}`,`untouched_siblings=${n.untouchedSiblings}`].join(" "));t.push(`created_assets=${JSON.stringify(e.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(e.declarations.existingAssets)}`,`created_states=${JSON.stringify(e.declarations.createdStates)}`,`existing_states=${JSON.stringify(e.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(e.retainedOrphanAssets)}`,`validation_ok=${e.validation.ok} errors=${e.validation.errors.length} warnings=${e.validation.warnings.length}`);for(let n of e.validation.errors)t.push(`validation_error=${n.path} ${n.code} ${n.message}`);for(let n of e.validation.warnings)t.push(`validation_warning=${n.path} ${n.code} ${n.message}`);return t}function pw(e,t,n,o,i){let r=Il(t.text),s=i.script===null?null:Xt(i.script),c=Ul(s,r,n),a=`sha256:${pc.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:a,mode:n,targetKind:r.targetKind,targets:c.targets.map(h=>h.address),baseline:i.baseline,plan:{targets:c.targets,declarations:c.declarations,retainedOrphanAssets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation}},p=Cl(d),l=e.apply===!0,f=O(e.plan).trim();if(l&&!f&&mo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&mo("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new x("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:b,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[p],actual:[f]}});l&&c.changed&&(i.script===null?Li(o,i.fingerprint):kt(o,i.baseline),Je(o,c.script));let u=c.targets.map((h,w)=>`target[${w}]=${h.address} kind=${h.kind} before=${JSON.stringify(h.before)} after=${JSON.stringify(h.after)} retained=${JSON.stringify(h.retainedIds)} created=${JSON.stringify(h.createdIds)} removed=${JSON.stringify(h.removedIds)} untouched_siblings=${h.untouchedSiblings}`);return u.push(`created_assets=${JSON.stringify(c.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(c.declarations.existingAssets)}`,`created_states=${JSON.stringify(c.declarations.createdStates)}`,`existing_states=${JSON.stringify(c.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(c.retainedOrphanAssets)}`,`created_ids=${JSON.stringify(c.identity.createdIds)}`,`removed_ids=${JSON.stringify(c.identity.removedIds)}`,`retained_ids=${JSON.stringify(c.identity.retainedIds)}`),[{text:[`${l?"Applied":"Planned"} ${c.targets.length} ${r.targetKind} target(s); validation ${c.validation.ok?"passed":"needs repair"}`,`plan: ${p}`,...u].join(`
|
|
132
|
-
`),data:{op:"write",changed:c.changed,source_path:t.absolutePath,source_digest:a,script_path:o,baseline:i.baseline,script_hash:i.baseline==="missing"?null:i.baseline,plan_digest:p,plan:d.plan,mode:n,target_kind:r.targetKind,targets:c.targets,declarations:c.declarations,retained_orphan_assets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation,applied:l,script_version:4}},J]}function Pl(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=rw(n),i=aw(e),r=xe(e),s=sw(r);if(s.script===null||s.script.version===4)return pw(e,o,i,r,s);let c=xl(o.text),a=wl(It(s.script),c,i),d=`sha256:${pc.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,sourceDigest:d,mode:i,targetKind:c.targetKind,targets:a.targets.map(w=>w.address),baseline:s.baseline,plan:{targets:a.targets,declarations:a.declarations,retainedOrphanAssets:a.retainedOrphanAssets,validation:a.validation}},l=Cl(p),f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&mo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&mo("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new x("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:b,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});f&&a.changed&&(s.script===null?Li(r,s.fingerprint):kt(r,s.baseline),Je(r,a.script));let m=cw(a);return[{text:[`${f?"Applied":"Planned"} ${a.targets.length} ${c.targetKind} target(s); episodes ${m.before.episodes}\u2192${m.after.episodes}, scenes ${m.before.scenes}\u2192${m.after.scenes}, actions ${m.before.actions}\u2192${m.after.actions}`,`plan: ${l}`,...dw(a)].join(`
|
|
133
|
-
`),data:{op:"write",changed:a.changed,source_path:o.absolutePath,source_digest:d,script_path:r,baseline:s.baseline,script_hash:s.baseline==="missing"?null:s.baseline,plan_digest:l,plan:p.plan,mode:i,target_kind:c.targetKind,targets:a.targets,declarations:a.declarations,counts:m,validation:a.validation,retained_orphan_assets:a.retainedOrphanAssets,applied:f,script_version:3}},J]}function $l(e){return Array.isArray(e.rows)}function lw(e){return e.endsWith(`
|
|
134
|
-
`)?e:`${e}
|
|
135
|
-
`}function Vl(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function uw(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function fw(e){if(!$l(e)||e.rows.length===0||!Array.isArray(e.row_columns))return null;let t=e.row_columns.filter(n=>typeof n=="string");return t.length===0?null:[t.join(" "),...e.rows.map(n=>t.map(o=>uw(n[o])).join(" "))].join(`
|
|
136
|
-
`)}function Dl(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&$l(e.data)){if(e.data.rows.length===0){process.stdout.write("");return}let i=e.data.rows.map(r=>String(r.addr??""));if(i.every(r=>r.length>0)){process.stdout.write(i.join(`
|
|
137
|
-
`)+`
|
|
138
|
-
`);return}}if(n){let i={ok:t===J,exit_code:t,...e.data};i.ok=t===J,i.exit_code=t,process.stdout.write(JSON.stringify(i,null,2)+`
|
|
139
|
-
`)}else process.stdout.write(lw(fw(e.data)??e.text))}}function Bi(e,t){if(t){let n={ok:!1,exit_code:e.exitCode,error_code:e.errorCode,message:e.message,...e.hint?{hint:e.hint}:{},...e.data};n.ok=!1,n.exit_code=e.exitCode,n.error_code=e.errorCode,n.message=e.message,e.hint&&(n.hint=e.hint),process.stdout.write(JSON.stringify(n,null,2)+`
|
|
140
|
-
`)}else{let n=Vl(e.data.actual),o=Vl(e.data.expected),r=[`error: ${n.length>0?`${e.message.replace(/\.$/,"")}: ${n[0]}`:e.message}`];n.length>1&&r.push(`actual: ${n.slice(1).join("; ")}`),o.length>0&&r.push(`expected: ${o.join("; ")}`),e.hint&&r.push(e.hint),process.stderr.write(`${r.join(`
|
|
141
|
-
`)}
|
|
142
|
-
`)}return e.exitCode}var lc=new WeakMap;function mw(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function gw(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[mw(t),n]))}function hw(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function Y(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=gw(hw(o));i.length>0&&(r._args=i),t.jsonMode=!!r.json,t.format=typeof r.format=="string"?r.format:void 0;let s=async()=>e(r),[c,a]=lc.get(o)==="write"?await Gr(xe(r),s):await s();Dl(c,a,t.jsonMode,t.format),t.exitCode=a}}function Ie(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function se(e,t="write"){return lc.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function uc(e){return lc.set(e,"write"),e.option("-p, --script-path <path>","Local script JSON file (default: ./workspace/script.json)").option("--project-group-no <no>","Remote project group number")}function Gl(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=se(n.command("write <file>")).description("Plan or apply a complete structured authoring document").option("--create","Create the selected target").option("--replace","Replace the selected target").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(Y(Pl,t));Ie(o,["Structured .scriptctl file"]);let i=se(n.command("compose <file>")).description("Compile a readable scene JSON draft with generated identities and timing").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(Y(Qp,t));Ie(i,["Readable scene JSON file"]);let r=n.command("export").description("Export complete structured content, including identities and extensions"),s=["script","episodes","episode-spans","scenes","scene-spans","action-spans"];for(let c of s){let a=se(r.command(c),"read").description(`Export structured ${c}`).requiredOption("-o, --output <file>","Destination .scriptctl file");c!=="script"&&a.requiredOption("-i, --in <selector>","Formal ID or @ep:N selector / inclusive range"),a.action(Y(d=>al(c,d),t))}}import*as es from"node:fs";import*as _c from"node:path";import*as gc from"node:fs";import*as Fo from"node:path";import{fileURLToPath as yw}from"node:url";var mc="@lingjingai/scriptctl",fc="";function hc(){if(fc)return fc;let e=Fo.dirname(yw(import.meta.url));for(;;){try{let n=gc.readFileSync(Fo.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===mc)return fc=e,e}catch{}let t=Fo.dirname(e);if(t===e)throw new Error(`${mc} package root not found`);e=t}}function Qo(){let e=gc.readFileSync(Fo.join(hc(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${mc} package.json has no string version`);return t}var Jl=/^\d+\.\d+\.\d+$/,ww="unreleased";function Bl(){return _c.join(hc(),"changes")}function _w(){return Qo()}function Ki(e){if(!Jl.test(e))throw new x("Version must use x.y.z.",{exitCode:G,errorCode:"CHANGELOG_VERSION_INVALID",hint:"Pass a released version such as `scriptctl changelog 0.25.10`.",data:{expected:["x.y.z"],actual:[e||"<empty>"]}});let[t,n,o]=e.split(".").map(i=>Number(i));return[t,n,o]}function wc(e,t){let n=Ki(e),o=Ki(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function Ew(){let e=Bl();return es.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>Jl.test(t)).sort(wc)}function Xr(e){return es.readFileSync(_c.join(Bl(),`${e}.md`),"utf-8").trimEnd()}function yc(e,t){return new x(`No changelog entry exists for ${e}.`,{exitCode:b,errorCode:"CHANGELOG_VERSION_NOT_FOUND",hint:t.length>0?`Available versions: ${t.join(", ")}`:"Add changes/<version>.md first.",data:{expected:["existing changelog version"],actual:[e]}})}function xw(e,t){return new x(`No released changelog entries found after ${e} through ${t}.`,{exitCode:b,errorCode:"CHANGELOG_RANGE_EMPTY",hint:"Choose a wider range or run `scriptctl changelog <version>` for a known release.",data:{expected:["a version range containing released changelog entries"],actual:[`--from ${e}`,`--to ${t}`]}})}function Sw(e){return e.map(Xr).join(`
|
|
143
|
-
|
|
144
|
-
`)}function Kl(e){let t=e._args??[],n=t[0]?.trim()??"",o=String(e.from??"").trim(),i=String(e.to??"").trim(),r=!!e.unreleased;if(t.length>1)throw new x("changelog accepts at most one version argument.",{exitCode:G,errorCode:"CHANGELOG_TOO_MANY_ARGS",hint:"Pass a single version, or use --from/--to for a range.",data:{expected:["scriptctl changelog [version] [--from X] [--to Y] [--unreleased]"],actual:[t.join(" ")]}});if(r&&(n||o||i))throw new x("--unreleased cannot combine with version, --from, or --to.",{exitCode:G,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog --unreleased` by itself.",data:{expected:["either --unreleased, a version, or a --from/--to range"],actual:["--unreleased with another selector"]}});if(n&&(o||i))throw new x("A version argument cannot combine with --from or --to.",{exitCode:G,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog 0.25.10` or `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["either a version argument, or --from/--to"],actual:[n,o?`--from ${o}`:"",i?`--to ${i}`:""].filter(Boolean)}});if(r){let d=Xr(ww);return[{text:d,data:{content:d,versions:[],unreleased:!0}},J]}let s=Ew(),c=_w();if(n){if(Ki(n),!s.includes(n))throw yc(n,s);let d=Xr(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},J]}if(o||i){if(!o)throw new x("--from is required for range queries.",{exitCode:G,errorCode:"CHANGELOG_FROM_MISSING",hint:"Run `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["--from <x.y.z>"],actual:[i?`--to ${i}`:"<missing>"]}});Ki(o);let d=i||c;if(Ki(d),!s.includes(d))throw yc(d,s);let p=s.filter(f=>wc(f,o)>0&&wc(f,d)<=0);if(p.length===0)throw xw(o,d);let l=Sw(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},J]}if(!s.includes(c))throw yc(c,s);let a=Xr(c);return[{text:a,data:{content:a,versions:[c],unreleased:!1}},J]}import*as bt from"node:fs";import*as wo from"node:path";import{createRequire as k_}from"node:module";import*as xn from"node:fs";import*as jn from"node:path";import*as zl from"node:os";import{fileURLToPath as Iw}from"node:url";function jl(e){return e.startsWith("~")?jn.join(zl.homedir(),e.slice(1)):e}function Aw(e){let t=xn.readFileSync(e,"utf-8");for(let n of t.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;o.startsWith("export ")&&(o=o.slice(7).trim());let i=o.indexOf("=");if(i<0)continue;let r=o.slice(0,i).trim(),s=o.slice(i+1).trim();s.length>=2&&s[0]===s[s.length-1]&&(s[0]==="'"||s[0]==='"')&&(s=s.slice(1,-1)),r&&s&&!process.env[r]&&(process.env[r]=s)}}function Ec(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(jl(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(jn.join(jl(n),".env"));let o;try{o=Iw(import.meta.url)}catch{o=process.cwd()}let i=jn.resolve(o),r=new Set;for(;;){let s=jn.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(jn.join(s,".env")),i=s}return e}function Hl(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of Ec()){let o;try{o=xn.existsSync(n)?xn.realpathSync(n):n}catch{o=n}t.has(o)||!xn.existsSync(n)||!xn.statSync(n).isFile()||(t.add(o),Aw(n))}}var de=class extends Error{status;code;payload;configMissing;constructor(t,n={}){super(t),this.name="ScriptOutputApiError",this.status=n.status??null,this.code=n.code??null,this.payload=n.payload,this.configMissing=n.configMissing??null}};async function xc(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function Fl(e){let t=!!e?.remote,n=!!e?.local;if(t&&n)return{mode:null,conflict:!0};if(t)return{mode:"remote",conflict:!1};if(n)return{mode:"local",conflict:!1};let o=(process.env.SCRIPTCTL_OUTPUT_MODE??"").trim().toLowerCase();if(o==="local"||o==="remote")return{mode:o,conflict:!1};if(o!=="")return{mode:null,conflict:!1};let i=typeof e?.projectGroupNo=="string"?e.projectGroupNo.trim():"",r=(process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();return i!==""||r!==""?{mode:"remote",conflict:!1}:{mode:null,conflict:!1}}import*as Fi from"node:fs";import*as Yl from"node:os";import*as zi from"node:path";import{parseDocument as kw}from"yaml";function ne(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var Sn={"direct.episode-titles":ne("direct.episode-titles","tool",4096),"direct.batch-extract":ne("direct.batch-extract","text",16e3),"direct.episode-synopsis":ne("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":ne("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":ne("direct.script-synopsis","tool",2048),"direct.asset-grouping":ne("direct.asset-grouping","text",8e3),"direct.asset-curation":ne("direct.asset-curation","text",2e4),"direct.asset-curation-audit":ne("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":ne("direct.location-canonicalization","text",2e4),"direct.state-curation":ne("direct.state-curation","text",2e4),"direct.state-binding":ne("direct.state-binding","tool",16e3),"metadata.global":ne("metadata.global","text",16e3),"metadata.descriptions":ne("metadata.descriptions","text",16e3),"synopsis.chunk":ne("synopsis.chunk","text",4096),"synopsis.episode":ne("synopsis.episode","text",4096),"synopsis.arc":ne("synopsis.arc","text",16e3),"synopsis.script-overview":ne("synopsis.script-overview","text",16e3),"ingest.body-start":ne("ingest.body-start","text",16e3),"ingest.arc-summary":ne("ingest.arc-summary","text",4096),"ingest.text-normalize":ne("ingest.text-normalize","text",32e3),"ingest.episode-assets":ne("ingest.episode-assets","tool",32e3),"ingest.name-fix":ne("ingest.name-fix","tool",16e3),"ingest.mention-resolve":ne("ingest.mention-resolve","text",8e3),"ingest.asset-extract":ne("ingest.asset-extract","text",8e3),"ingest.asset-curate":ne("ingest.asset-curate","text",32e3),"ingest.asset-recall":ne("ingest.asset-recall","text",65536),"ingest.asset-refine":ne("ingest.asset-refine","text",32e3),"ingest.state-reconcile":ne("ingest.state-reconcile","text",32e3),"ingest.asset-audit":ne("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":ne("ingest.speaker-audit","tool",16e3),"ingest.video-serial":ne("ingest.video-serial","video",65536)},Ql=Object.keys(Sn).filter(Sc);function Sc(e){return Object.hasOwn(Sn,e)}var bw=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts"]),Ow=new Set(["provider","model","thinking","reasoning","temperature"]),vw=new Set(["env"]),Rw=new Set(["budgetTokens"]);function Ke(e,t=[]){return new x(e,{exitCode:b,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration or environment and rerun `scriptctl doctor`.",data:{expected:["valid scriptctl LLM YAML configuration"],actual:t}})}function kc(e,t){let n;try{n=new URL(e)}catch{throw Ke(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Ke(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function bc(e,t="provider base URL"){return kc(e,t)}function Nw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function zn(e,t){if(!Nw(e))throw Ke(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function go(e,t){if(typeof e!="string"||!e.trim())throw Ke(`${t} must be a non-empty string.`);return e.trim()}function Ac(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Ke(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function Hi(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Ke(`${n} contains unknown fields.`,o)}function Mw(e,t){let n=zn(t,`providers.${e}`);Hi(n,bw,`providers.${e}`);let o=go(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Ke(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:kc(go(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"){let s=zn(n.apiKey,`providers.${e}.apiKey`);if(Hi(s,vw,`providers.${e}.apiKey`),r=go(s.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Ke(`providers.${e}.apiKey.env must be an environment variable name.`)}return{protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:Ac(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:Ac(n.maxAttempts,`providers.${e}.maxAttempts`,1,6)}}function Lw(e,t,n){let o=zn(t,`models.${e}`);Hi(o,Ow,`models.${e}`);let i=go(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Ke(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:go(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=go(o.reasoning,`models.${e}.reasoning`)),o.temperature!==void 0){let c=o.temperature;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw Ke(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=c}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Ke(`models.${e}.thinking is only valid for anthropic providers.`);let c=zn(o.thinking,`models.${e}.thinking`);Hi(c,Rw,`models.${e}.thinking`),s.thinkingBudgetTokens=Ac(c.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function Uw(e,t){let n=zn(e,"config");if(Hi(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Ke("config.version must be 1.");let o=zn(n.providers,"providers"),i={};for(let[a,d]of Object.entries(o))i[a]=Mw(a,d);let r=zn(n.models,"models"),s={};for(let[a,d]of Object.entries(r))s[a]=Lw(a,d,i);if(!s.default)throw Ke("models.default is required.");let c={};if(n.tasks!==void 0){let a=zn(n.tasks,"tasks");for(let[d,p]of Object.entries(a)){if(!Sc(d))throw Ke("tasks contains an unknown task id.",[d]);let l=go(p,`tasks.${d}`);if(!s[l])throw Ke(`tasks.${d} references an unknown model profile.`,[l]);c[d]=l}}return{version:1,providers:i,models:s,tasks:c,source:"file",sourcePath:t}}var ji={version:1,providers:{gw:{protocol:"openai-compatible",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"google-gemini":{protocol:"google-vertex",baseUrl:null,apiKeyEnv:"",timeoutMs:6e5,maxAttempts:3}},models:{default:{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-low":{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-normalize":{provider:"gw",model:"claude-sonnet-4-6-aihubmix",temperature:0},"ingest-video":{provider:"google-gemini",model:"gemini-3.8-flash"},"review-agent":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0}},tasks:{"ingest.body-start":"ingest-low","ingest.arc-summary":"ingest-low","ingest.text-normalize":"ingest-low","ingest.mention-resolve":"ingest-low","ingest.asset-recall":"ingest-low","ingest.asset-audit":"ingest-normalize","ingest.episode-assets":"ingest-normalize","ingest.name-fix":"ingest-normalize","ingest.video-serial":"ingest-video"},source:"builtin",sourcePath:null};function Tw(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?kc(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...ji,providers:{gw:{...ji.providers.gw,baseUrl:t},"google-gemini":{...ji.providers["google-gemini"]}},models:{...ji.models},tasks:{...ji.tasks}}}function Cw(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?zi.join(e,"scriptctl","llm.yaml"):zi.join(Yl.homedir(),".config","scriptctl","llm.yaml")}function Ic(e){if(!Fi.existsSync(e))throw Ke("LLM configuration file does not exist.",[e]);let t=kw(Fi.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Ke("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return Uw(n,zi.resolve(e))}function Yo(e){let t=(e??"").trim();if(t)return Ic(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return Ic(n);let o=Cw();return Fi.existsSync(o)?Ic(o):Tw()}import*as uu from"node:crypto";import $w,{APIConnectionError as Dw,APIConnectionTimeoutError as Gw,APIError as Jw,APIUserAbortError as Bw}from"@anthropic-ai/sdk";var Oc=1e8;function Pw(e){switch(e){case"auth":return{failure_type:"authentication",failure_code:"authentication_failed"};case"permission_denied":return{failure_type:"authorization",failure_code:"permission_denied"};case"endpoint":return{failure_type:"provider",failure_code:"resource_not_found"};case"network":return{failure_type:"network",failure_code:"network_failed"};case"timeout":return{failure_type:"timeout",failure_code:"request_timeout"};case"rate_limited":return{failure_type:"rate_limit",failure_code:"rate_limited"};case"request_failed":return{failure_type:"provider",failure_code:"request_rejected"};case"truncated":return{failure_type:"response",failure_code:"output_truncated"};case"content_filtered":return{failure_type:"policy",failure_code:"content_blocked"};case"empty_response":return{failure_type:"response",failure_code:"empty_response"};case"invalid_response":return{failure_type:"response",failure_code:"malformed_response"};case"cancelled":return{failure_type:"cancelled",failure_code:"cancelled"}}}var P=class extends Error{code;retryable;details;failure;modelFailures;attempts;usage;constructor(t,n,o={}){super(n),this.name="LlmTransportError",this.code=t,this.retryable=o.retryable??!1,this.details=o.details??[],this.attempts=o.attempts??1,this.usage=o.usage??{},this.failure=_t(o.classification??Pw(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function Vw(e){return new Promise(t=>setTimeout(t,e))}function Vt(e={},t={}){let n=c=>e[c]===void 0&&t[c]===void 0?void 0:(e[c]??0)+(t[c]??0),o=n("inputTokens"),i=n("outputTokens"),r=n("cachedInputTokens"),s=n("cacheCreationTokens");return{...o!==void 0?{inputTokens:o}:{},...i!==void 0?{outputTokens:i}:{},...r!==void 0?{cachedInputTokens:r}:{},...s!==void 0?{cacheCreationTokens:s}:{}}}async function $t(e,t){let n={};for(let o=1;o<=e;o+=1)try{return{value:await t(),attempts:o,failedUsage:n}}catch(i){if(i instanceof P&&(n=Vt(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof P)||!i.retryable||o===e)throw i;await Vw(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function ql(e){let t=e.usage;if(!t)return{};let n=t.cache_read_input_tokens??0,o=t.cache_creation_input_tokens??0;return{inputTokens:(t.input_tokens??0)+n+o,outputTokens:t.output_tokens??0,cachedInputTokens:n,cacheCreationTokens:o}}function Wl(e){if(e instanceof P)return e;if(e instanceof Bw)return new P("request_failed","Anthropic request was aborted.");if(e instanceof Gw)return new P("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof Dw)return new P("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof Jw){let n=e.status??0,o=n===408||n===429||n>=500,i=n===401||n===403?"auth":n===429?"rate_limited":"request_failed";return new P(i,"Anthropic request failed.",{retryable:o,details:[`status: ${n}`,e.message.slice(0,500)]})}let t=e instanceof Error?e.message:String(e);return new P("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var ts=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new $w({...i,maxRetries:0})}provider;model;client;params(t){let n={model:this.model.model,max_tokens:t.maxOutputTokens,stream:!1,messages:[{role:"user",content:t.user}]};return t.system.trim()&&(n.system=t.system),this.model.thinkingBudgetTokens!==void 0&&(n.thinking={type:"enabled",budget_tokens:this.model.thinkingBudgetTokens}),n}async generateText(t){let n=await $t(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=ql(o);if(o.stop_reason==="max_tokens")throw new P("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new P("content_filtered","Provider filtered the response.",{usage:i});let r=o.content.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
145
|
-
`).trim();if(!r)throw new P("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Wl(o)}});return{...n.value,attempts:n.attempts,usage:Vt(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await $t(this.provider.maxAttempts,async()=>{try{let o={name:t.tool.name,description:t.tool.description,input_schema:{type:"object",...t.tool.inputSchema}},i=await this.client.messages.create({...this.params(t),tools:[o],tool_choice:{type:"tool",name:t.tool.name,disable_parallel_tool_use:!0}},{timeout:this.provider.timeoutMs,signal:t.signal}),r=ql(i);if(i.stop_reason==="max_tokens")throw new P("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new P("content_filtered","Provider filtered the response.",{usage:r});let s=i.content.find(c=>c.type==="tool_use"&&c.name===t.tool.name);if(!s||s.type!=="tool_use")throw new P("invalid_response","Provider did not return the required tool call.",{usage:r});return{input:s.input,finishReason:i.stop_reason??"",usage:r,raw:i}}catch(o){throw Wl(o)}});return{...n.value,attempts:n.attempts,usage:Vt(n.failedUsage,n.value.usage)}}};import*as Zl from"node:fs";import*as Xl from"node:path";import{File as Qw}from"node:buffer";import{Agent as Yw,fetch as os,FormData as qw}from"undici";function Kw(e){return typeof e=="object"&&e!==null}function vc(e){let t=[],n=new Set,o=e;for(;Kw(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function ns(e){for(let t of vc(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function jw(e){for(let t of vc(e))if(typeof t.code=="string")return t.code}function zw(e){for(let t of vc(e))if(typeof t.name=="string")return t.name}function Hw(e){let t=zw(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function Fw(e){return e?["ENOTFOUND","EAI_AGAIN"].includes(e)?{failure_type:"network",failure_code:"dns_failed"}:e==="ECONNREFUSED"?{failure_type:"network",failure_code:"connection_refused"}:["ECONNRESET","EPIPE","UND_ERR_SOCKET"].includes(e)?{failure_type:"network",failure_code:"connection_reset"}:["ENETUNREACH","EHOSTUNREACH"].includes(e)?{failure_type:"network",failure_code:"network_unreachable"}:e.startsWith("ERR_TLS_")||e.startsWith("ERR_SSL_")||e.startsWith("CERT_")||["DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"].includes(e)?{failure_type:"network",failure_code:"tls_failed"}:["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT"].includes(e)?{failure_type:"timeout",failure_code:"connect_timeout"}:{failure_type:"network",failure_code:"network_failed"}:{failure_type:"network",failure_code:"network_failed"}}function ho(e,t,n,o,i={}){if(t?.aborted)return new P("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=jw(e),s=Hw(e)?{failure_type:"timeout",failure_code:"request_timeout"}:Fw(r),c=s.failure_type==="timeout"?"timeout":"network";return new P(c,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function yo(e,t,n,o={}){let i,r,s=!1;return e===401?(i="auth",r={failure_type:"authentication",failure_code:"authentication_failed"}):e===403?(i="permission_denied",r={failure_type:"authorization",failure_code:"permission_denied"}):e===404?(i="endpoint",r={failure_type:"provider",failure_code:"resource_not_found"}):e===408?(i="timeout",r={failure_type:"timeout",failure_code:"request_timeout"},s=!0):e===413&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_too_large"}):e===415&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"unsupported_media"}):e===429?(i="rate_limited",r={failure_type:"rate_limit",failure_code:"rate_limited"},s=!0):e>=500?(i="request_failed",r={failure_type:"provider",failure_code:"provider_unavailable"},s=!0):o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_upload_failed"}):(i="request_failed",r={failure_type:"provider",failure_code:"request_rejected"}),new P(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var Ww=2e3;function Zw(e){return new Promise(t=>setTimeout(t,e))}function Rc(e,t,n,o){if(e instanceof P)return e;let i=e instanceof Error?e.message:String(e),r=ns(e),s={provider:"doubao",model:o,operation:n};return r!==null?yo(r,`Doubao ${n} failed.`,i.slice(0,500),s):ho(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function Xw(e){if(!e)return{};let t=n=>typeof n=="number"?n:void 0;return{inputTokens:t(e.input_tokens),outputTokens:t(e.output_tokens)}}function e_(e){let t=[];for(let n of e.output??[])if(n.type==="message")for(let o of n.content??[])o.type==="output_text"&&typeof o.text=="string"&&t.push(o.text);return t.join("").trim()}var is=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??t_(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await $t(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Rc(i,t.signal,"upload",this.model)}});if(!n.id)throw new P("invalid_response","Doubao upload returned no file id.");let o=await this.pollActive(n.id,t.signal);try{return await this.generateOnce(o,t)}finally{await this.client.deleteFile({id:o}).catch(()=>{})}}async pollActive(t,n){let o=Date.now()+this.timeoutMs,i="processing";for(;i==="processing"||i==="";){if(n?.aborted)throw new P("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new P("timeout","Doubao file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});await Zw(Ww);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Rc(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new P("invalid_response","Doubao file processing failed.",{classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});return t}async generateOnce(t,n){let o={model:this.model,input:[{role:"user",content:[{type:"input_video",file_id:t},{type:"input_text",text:n.user}]}]};return n.system?.trim()&&(o.instructions=n.system),n.responseJsonSchema&&(o.text={format:{type:"json_schema",name:"video_serial",schema:n.responseJsonSchema}}),this.generateResponse(o,n.signal,!!n.responseJsonSchema)}async generateText(t){let n=this.textParams(t);return t.responseFormat&&(n.text={format:{type:t.responseFormat}}),this.generateResponse(n,t.signal,!!t.responseFormat)}async generateTool(t){let n=this.textParams(t);n.text={format:{type:"json_schema",name:t.tool.name,description:t.tool.description,schema:t.tool.inputSchema}};let o=await this.generateResponse(n,t.signal,!0);return{input:JSON.parse(o.text),finishReason:o.finishReason,attempts:o.attempts,usage:o.usage,raw:o.raw}}textParams(t){return{model:this.model,instructions:t.system,input:[{role:"user",content:[{type:"input_text",text:t.user}]}]}}async generateResponse(t,n,o){let{value:i,attempts:r,failedUsage:s}=await $t(this.maxAttempts,async()=>{let c;try{c=await this.client.createResponse(t,n)}catch(l){throw Rc(l,n,"generate",this.model)}let a=(c.status??"").toLowerCase(),d=Xw(c.usage);if(a==="incomplete"){let l=c.incomplete_details?.reason??"unknown";throw l==="max_output_tokens"||l==="length"?new P("truncated","Doubao output was truncated.",{usage:d}):new P("content_filtered",`Doubao response incomplete (reason=${l}).`,{usage:d})}let p=e_(c);if(!p)throw new P("empty_response","Doubao returned an empty response.",{retryable:!0,usage:d});if(o)try{JSON.parse(p)}catch{throw new P("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:d,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:p,usage:d,raw:c}});return{text:i.text,finishReason:"STOP",attempts:r,usage:Vt(s,i.usage),raw:i.raw}}},Nc=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function t_(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new Yw({headersTimeout:n,bodyTimeout:n});function s(a){let d=AbortSignal.timeout(n);return a?AbortSignal.any([a,d]):d}async function c(a){let d=await a.text().catch(()=>"");throw new Nc(a.status,d.slice(0,500))}return{async uploadFile({filePath:a,mimeType:d,fps:p}){let l=new qw,f=Zl.readFileSync(a);l.append("file",new Qw([f],Xl.basename(a),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await os(`${o}/files`,{method:"POST",headers:i,body:l,signal:s(),dispatcher:r});return u.ok||await c(u),await u.json()},async getFile({id:a}){let d=await os(`${o}/files/${a}`,{headers:i,signal:s(),dispatcher:r});return d.ok||await c(d),await d.json()},async createResponse(a,d){let p=await os(`${o}/responses`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(a),signal:s(d),dispatcher:r});return p.ok||await c(p),await p.json()},async deleteFile({id:a}){let d=await os(`${o}/files/${a}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await c(d)}}}import{GoogleAuth as n_}from"google-auth-library";function rs(){let e=process.env.GOOGLE_CLOUD_PROJECT?.trim();if(!e)throw new Error("GOOGLE_CLOUD_PROJECT is required for official Vertex AI");return e}var eu=new n_({scopes:["https://www.googleapis.com/auth/cloud-platform"]});import*as ru from"node:fs";import{createRequire as p_}from"node:module";import*as ss from"node:fs";import*as o_ from"node:http";import*as i_ from"node:https";import{HttpsProxyAgent as r_}from"https-proxy-agent";var nu="https://generativelanguage.googleapis.com";function s_(e,t){let n=new URL(e??nu);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function a_(e,t){let n=new URL(t??nu),o=new URL(e,n);if(!t)return o;o.protocol=n.protocol,o.host=n.host;let i=n.pathname.replace(/\/+$/,"");return i&&o.pathname!==i&&!o.pathname.startsWith(`${i}/`)&&(o.pathname=`${i}/${o.pathname.replace(/^\/+/,"")}`),o}function qo(e,t){if(!t)return e;let n=e.split(t).join("[REDACTED]"),o=encodeURIComponent(t);return o!==t&&(n=n.split(o).join("[REDACTED]")),n}function c_(e){return e?new r_(e):void 0}function tu(e,t,n,o){return new Promise((i,r)=>{let c=(e.protocol==="http:"?o_:i_).request({...t,agent:e.protocol==="https:"?t.agent:void 0,protocol:e.protocol,hostname:e.hostname,port:e.port||void 0,path:`${e.pathname}${e.search}`},a=>{let d="";a.on("data",p=>d+=p),a.on("end",()=>i({status:a.statusCode??0,headers:a.headers,body:d}))});if(c.on("error",r),o){if(o.aborted){c.destroy(new Error("aborted"));return}o.addEventListener("abort",()=>c.destroy(new Error("aborted")),{once:!0})}n&&typeof n.pipe=="function"?n.pipe(c):(n&&c.write(n),c.end())})}function d_(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function ou(e){let t=ss.statSync(e.filePath).size,o={agent:c_(e.proxyUrl??""),timeout:e.timeoutMs},i=s_(e.baseUrl,e.apiKey),r=l=>qo(l,e.apiKey),s;try{s=await tu(i,{...o,method:"POST",headers:{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(t),"X-Goog-Upload-Header-Content-Type":e.mimeType,"Content-Type":"application/json"}},JSON.stringify({file:{}}),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ho(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let c=d_(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw yo(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!c)throw new P("invalid_response","Gemini upload start returned no upload URL.",{details:[r(s.body).slice(0,300)],context:{operation:"upload",http_status:s.status}});let a=a_(c,e.baseUrl),d;try{d=await tu(a,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},ss.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ho(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw yo(d.status,"Gemini upload transfer failed.",r(d.body).slice(0,300),{operation:"upload"});let p;try{p=JSON.parse(d.body)}catch{throw new P("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new P("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var l_=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),u_=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function Mc(e){switch(e){case"SAFETY":case"PROHIBITED_CONTENT":case"BLOCKLIST":case"SPII":case"RECITATION":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":case"ESCALATION":case"OTHER":return e;case"":case"BLOCK_REASON_UNSPECIFIED":case"FINISH_REASON_UNSPECIFIED":return"UNSPECIFIED";default:return"UNKNOWN"}}function iu(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function f_(e){if(typeof e!="object"||e===null)return{};let t=e,n=o=>typeof o=="number"?o:void 0;return{inputTokens:n(t.promptTokenCount),outputTokens:n(t.candidatesTokenCount)}}function m_(e){return/-c\d+$/.test(e)}function g_(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t<0||n<t)throw new SyntaxError("JSON object not found");return e.slice(t,n+1)}var h_=2e3;function y_(e){return new Promise(t=>setTimeout(t,e))}function Lc(e,t,n,o,i,r){if(e instanceof P)return new P(e.code,qo(e.message,o),{retryable:e.retryable,details:e.details.map(d=>qo(d,o)),attempts:e.attempts,usage:e.usage,classification:Vo(e.failure),context:{...bi(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=qo(e instanceof Error?e.message:String(e),o),c=ns(e),a={provider:i,model:r,operation:n};return c!==null?yo(c,`Gemini ${n} failed.`,s.slice(0,500),a):ho(e,t,`Gemini ${n} failed.`,s.slice(0,500),a)}var as=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??__(o,t.timeoutMs,t.baseUrl,t.protocol==="google-vertex")}provider;model;apiKey;client;async prepare(t,n,o,i){return o==="base64"||this.provider.protocol==="google-vertex"?{kind:"base64",data:ru.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await $t(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw Lc(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new P("invalid_response","Gemini upload returned no file reference.",{context:{provider:this.model.provider,model:this.model.model,operation:"upload"}});return{name:r.name,uri:r.uri,mimeType:r.mimeType??n}}async pollActive(t,n){let o=t,i=Date.now()+this.provider.timeoutMs;for(;(o.state??"").toUpperCase()==="PROCESSING";){if(n?.aborted)throw new P("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new P("timeout","Gemini file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(await y_(h_),!o.name)throw new P("invalid_response","Gemini upload returned no file name to poll.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});try{o=await this.client.files.get({name:o.name})}catch(r){throw Lc(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new P("invalid_response","Gemini file processing failed.",{details:[qo(o.error?.message??"unknown media error",this.apiKey)],classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});return o}async generate(t){if(t.media.kind==="local-fallback"||t.media.kind==="local")throw new P("invalid_response","A local fallback video cannot be sent to Gemini.");let n=!!t.responseJsonSchema&&m_(this.model.model),o={mediaResolution:"MEDIA_RESOLUTION_HIGH"},i=[t.system?.trim(),n?`\u8F93\u51FA\u5FC5\u987B\u662F\u4E00\u4E2A\u53EF\u89E3\u6790\u7684 JSON \u5BF9\u8C61\u3002\u53EA\u8FD4\u56DE JSON\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u989D\u5916\u6587\u5B57\u6216 Markdown \u4EE3\u7801\u5757\u3002
|
|
146
|
-
\u4EE5\u4E0B\u662F\u5B8C\u6574\u8F93\u51FA JSON Schema\u3002\u4E25\u683C\u9075\u5B88\u6240\u6709\u5C42\u7EA7\u7684\u5B57\u6BB5\u540D\u3001\u7C7B\u578B\u3001required\u3001\u679A\u4E3E\u3001\u683C\u5F0F\u7EA6\u675F\u548C description\uFF1B\u4E0D\u5F97\u81EA\u884C\u6539\u540D\u6216\u7701\u7565\u5FC5\u586B\u5B57\u6BB5\u3002\u8FD4\u56DE\u7B26\u5408\u8BE5\u5B9A\u4E49\u7684\u6570\u636E\u5BF9\u8C61\uFF0C\u4E0D\u8981\u8FD4\u56DE schema \u672C\u8EAB\u3002
|
|
147
|
-
<output_json_schema>
|
|
148
|
-
${JSON.stringify(t.responseJsonSchema,null,2)}
|
|
149
|
-
</output_json_schema>`:""].filter(Boolean).join(`
|
|
150
|
-
|
|
151
|
-
`);i&&(o.systemInstruction=i),t.responseJsonSchema&&!n&&(o.responseMimeType="application/json",o.responseJsonSchema=t.responseJsonSchema);let r={model:this.model.model,contents:[{role:"user",parts:[t.media.kind==="file-api"?{fileData:{fileUri:t.media.file.uri,mimeType:t.media.file.mimeType},videoMetadata:{fps:t.fps}}:{inlineData:{data:t.media.data,mimeType:t.media.mimeType},videoMetadata:{fps:t.fps}},{text:n?`${t.user}
|
|
152
|
-
|
|
153
|
-
\u53EA\u8FD4\u56DE JSON \u5BF9\u8C61\u672C\u8EAB\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u89E3\u91CA\u3001\u524D\u8A00\u3001Markdown \u4EE3\u7801\u5757\u6216\u5176\u4ED6\u6587\u5B57\u3002`:t.user}]}],config:o},{value:s,attempts:c,failedUsage:a}=await $t(this.provider.maxAttempts,async()=>{let d;try{if(this.client.models.generateContentStream){let h="",w={},y=await this.client.models.generateContentStream(r);for await(let E of y)E.text&&(h+=E.text),w={...w,...E,usageMetadata:E.usageMetadata??w.usageMetadata,promptFeedback:E.promptFeedback??w.promptFeedback,candidates:E.candidates??w.candidates};d={...w,text:h}}else d=await this.client.models.generateContent(r)}catch(h){throw Lc(h,t.signal,"generate",this.apiKey,this.model.provider,this.model.model)}let p=d.candidates?.[0],l=p?.finishReason??"",f=d.promptFeedback?.blockReason??"",u=f_(d.usageMetadata),m={provider:this.model.provider,model:this.model.model,operation:"generate"};if(l==="MAX_TOKENS")throw new P("truncated","Gemini output was truncated.",{usage:u,context:m});if(f)throw new P("content_filtered",`Gemini blocked the prompt (blockReason=${f}).`,{usage:u,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"prompt",provider_reason:Mc(f),...Mc(f)==="UNKNOWN"?{provider_reason_raw:f}:{},safety_ratings:iu(d.promptFeedback?.safetyRatings)}});if(l_.has(l))throw new P("content_filtered",`Gemini filtered the response (finishReason=${l}).`,{usage:u,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"candidate",provider_reason:Mc(l),finish_message:p?.finishMessage,safety_ratings:iu(p?.safetyRatings)}});let g=(d.text??"").trim();if(!g)throw u_.has(l)?new P("invalid_response",`Gemini returned no usable response (finishReason=${l}).`,{usage:u,context:{...m,provider_reason_raw:l,finish_message:p?.finishMessage}}):new P("empty_response",`Gemini returned an empty response (finishReason=${l||"none"}).`,{retryable:!0,usage:u,context:m});if(t.responseJsonSchema)try{let h=n?g_(g):g;return JSON.parse(h),{text:h,finishReason:l,usage:u,raw:d}}catch{throw new P("invalid_response","Gemini returned malformed JSON for a structured video response.",{retryable:!0,usage:u,context:m})}return{text:g,finishReason:l,usage:u,raw:d}});return{text:s.text,finishReason:s.finishReason,attempts:c,usage:Vt(a,s.usage),raw:s.raw}}async release(t,n){if(!(t.kind==="base64"||t.kind==="local-fallback"||t.kind==="local"))try{await this.client.files.delete({name:t.file.name})}catch(o){}}},w_=p_(import.meta.url);function __(e,t,n,o){let{GoogleGenAI:i}=w_("@google/genai"),r=new i({...o?{vertexai:!0,project:rs(),location:"global"}:{apiKey:e},httpOptions:{timeout:t,...n?{baseUrl:n}:{}}}),s=(process.env.https_proxy??process.env.HTTPS_PROXY??process.env.http_proxy??process.env.HTTP_PROXY??"").trim();return s&&!(process.env.NODE_USE_ENV_PROXY??"").trim()&&process.stderr.write(`\u26A0\uFE0F \u68C0\u6D4B\u5230\u4EE3\u7406 ${s}\uFF0C\u4F46\u672A\u8BBE NODE_USE_ENV_PROXY=1\u3002
|
|
154
|
-
Gemini \u4E0A\u4F20\u4F1A\u6210\u529F\u3001\u968F\u540E\u7684\u6587\u4EF6\u8F6E\u8BE2/\u751F\u6210\u4F1A\u6302\uFF08Node \u5185\u7F6E fetch \u9ED8\u8BA4\u4E0D\u8D70\u4EE3\u7406\uFF09\u3002
|
|
155
|
-
\u8BF7\u5728\u547D\u4EE4\u524D\u52A0 NODE_USE_ENV_PROXY=1 \u91CD\u8DD1\u3002
|
|
156
|
-
`),{files:{upload:c=>ou({apiKey:e,filePath:c.file,mimeType:c.config?.mimeType??"video/mp4",timeoutMs:t,proxyUrl:s,baseUrl:n}),get:c=>r.files.get(c),delete:c=>r.files.delete(c)},models:{generateContent:c=>r.models.generateContent(c),generateContentStream:c=>r.models.generateContentStream(c)}}}function su(e,t){if(!In(e)||!In(e.usage))return{};let n=e.usage,o=a=>{let d=typeof a=="number"?a:0;return Number.isFinite(d)?d:0},i=In(n.prompt_tokens_details)?n.prompt_tokens_details:{},r=o(n.prompt_tokens),s=o(i.cached_tokens)||o(n.cache_read_input_tokens),c=o(i.cache_creation_tokens)||o(n.cache_creation_input_tokens);return{inputTokens:t?r:r+s+c,outputTokens:o(n.completion_tokens),cachedInputTokens:s,cacheCreationTokens:c}}function In(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function E_(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function au(e){return!In(e)||!Array.isArray(e.choices)?null:e.choices.find(In)??null}function cu(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function pu(e){return e&&In(e.message)?e.message:null}function x_(e){let t=pu(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>In(n)&&typeof n.text=="string"?[n.text]:[]).join(`
|
|
157
|
-
`).trim():""}function du(e){try{return JSON.parse(e)}catch{throw new P("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var cs=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new P("endpoint","OpenAI-compatible provider endpoint (baseUrl) is not set \u2014 the built-in gateway reads PROJECT_LITELLM_GATEWAY_BASE_URL.");this.url=t.protocol==="google-vertex"?`https://aiplatform.googleapis.com/v1/projects/${rs()}/locations/global/endpoints/openapi/chat/completions`:E_(t.baseUrl);try{this.host=new URL(this.url).host}catch{this.host=this.url}}provider;model;apiKey;url;host;async post(t,n){let o=await $t(this.provider.maxAttempts,async()=>{let i=AbortSignal.timeout(this.provider.timeoutMs),r=n?AbortSignal.any([n,i]):i,s;try{s=await fetch(this.url,{method:"POST",headers:{authorization:`Bearer ${this.provider.protocol==="google-vertex"?await eu.getAccessToken():this.apiKey}`,"content-type":"application/json"},body:JSON.stringify(t),signal:r})}catch(a){let d=a instanceof Error?a.message:String(a),p=r.aborted&&!n?.aborted;throw new P(p?"timeout":"request_failed",p?`OpenAI-compatible request timed out reaching ${this.host}.`:`OpenAI-compatible request could not reach ${this.host}: ${d}`,{retryable:!n?.aborted,details:[d.slice(0,500)]})}let c=await s.text();if(!s.ok){let a=s.status===408||s.status===429||s.status>=500,d=s.status===401||s.status===403?"auth":s.status===429?"rate_limited":"request_failed";throw new P(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:a,details:[`status: ${s.status}`,c.slice(0,500)]})}return du(c)});return{payload:o.value,attempts:o.attempts,failedUsage:o.failedUsage}}baseBody(t){let n=[];return t.system.trim()&&n.push({role:"system",content:t.system}),n.push({role:"user",content:t.user}),{model:this.provider.protocol==="google-vertex"?`google/${this.model.model.replace(/^google\//,"")}`:this.model.model,messages:n,...t.responseFormat==="json_object"?{response_format:{type:"json_object"}}:{},...this.model.reasoning?{reasoning_effort:this.model.reasoning}:{},...this.model.temperature!==void 0?{temperature:this.model.temperature}:{}}}async generateText(t){let{payload:n,attempts:o,failedUsage:i}=await this.post(this.baseBody(t),t.signal),r=Vt(i,su(n,this.provider.protocol==="google-vertex"));try{let s=au(n),c=cu(s);if(c==="length")throw new P("truncated","Provider output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new P("content_filtered",`Provider filtered the response (${c}).`);let a=x_(s);if(!a)throw new P("empty_response","Provider returned an empty text response.");return{text:a,finishReason:c,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof P&&(s.attempts=o,s.usage=r),s}}async generateTool(t){let{payload:n,attempts:o,failedUsage:i}=await this.post({...this.baseBody(t),tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.inputSchema}}],tool_choice:{type:"function",function:{name:t.tool.name}},parallel_tool_calls:!1},t.signal),r=Vt(i,su(n,this.provider.protocol==="google-vertex"));try{let s=au(n),c=cu(s);if(c==="length")throw new P("truncated","Provider tool output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new P("content_filtered",`Provider filtered the response (${c}).`);let a=pu(s)?.tool_calls;if(!Array.isArray(a))throw new P("invalid_response","Provider did not return a tool call.");for(let d of a){if(!In(d)||!In(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:du(p.arguments),finishReason:c,attempts:o,usage:r,raw:n}}throw new P("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof P&&(s.attempts=o,s.usage=r),s}}};var rn={model:"ep-20260721150136-98dj9",modelEnv:"ARK_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},S_=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function I_(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function Uc(e,t,n){let o=Sn[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:I_(t.baseUrl),model:n.model,thinkingBudgetTokens:n.thinkingBudgetTokens??null});return uu.createHash("sha256").update(i).digest("hex")}function et(e,t,n){return new x(e,{exitCode:b,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function Qi(e){return new x("The selected LLM provider credential is not configured.",{exitCode:fe,errorCode:"LLM_CREDENTIAL_MISSING",hint:"Configure the credential and rerun `scriptctl doctor`.",data:{expected:["credential environment variable referenced by the selected provider"],actual:[`provider: ${e}`,"credential: missing"]}})}function Yi(e,t){return _t(Vo(e.failure),{...bi(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function ds(e,t){if(t.length===1)return e;let n=Np(t,"All configured model routes failed.");return new P(e.code,n.message,{retryable:n.retryable,classification:Vo(n),context:bi(n),modelFailures:t,details:t.map(Un)})}function A_(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function lu(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...S_.map(o=>t+o)])].map(o=>{if(o===e.info.model)return e;let i={...e.modelConfig,model:o};return{...e,modelConfig:i,info:{...e.info,model:o,fingerprint:Uc(e.info.task,e.providerConfig,i)}}})}function qi(e,t){return!t?.aborted&&e instanceof P&&e.code!=="cancelled"}var Wi=class{constructor(t,n={}){this.config=t;this.options=n}config;options;adapters=new Map;videoAdapters=new Map;doubaoAdapters=new Map;resolvedRoutes=new Map;usageLog=[];get configSource(){return this.config.source}resolve(t){let n=this.resolvedRoutes.get(t);if(n)return n;let o=Sn[t];if(o.mode==="video"&&this.options.videoProvider?.provider==="doubao"){let l=this.resolveDoubao(t,!0);return this.resolvedRoutes.set(t,l),l}let i=this.config.tasks[t]??o.defaultProfile,r=this.config.models[i];if(!r)throw et("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw et("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw et("OpenAI-compatible providers require an explicit endpoint \u2014 set the provider's baseUrl, or PROJECT_LITELLM_GATEWAY_BASE_URL for the built-in gateway.",["provider.baseUrl"],[`provider: ${r.provider}`]);if(r.thinkingBudgetTokens!==void 0&&o.mode==="tool")throw et("Anthropic thinking cannot be combined with a forced tool call.",["a text task or a profile without thinking"],[`task: ${t}`,`profile: ${i}`]);if(r.thinkingBudgetTokens!==void 0&&r.thinkingBudgetTokens>=o.maxOutputTokens)throw et("The thinking token budget must be smaller than the task output budget.",[`thinking budget < ${o.maxOutputTokens}`],[`task: ${t}`,`thinking budget: ${r.thinkingBudgetTokens}`]);let c=o.mode==="video"?this.options.videoProvider:void 0,a=c?.baseUrl?{...s,protocol:"google-gemini",baseUrl:bc(c.baseUrl,"--provider-base-url")}:s,d=c?.model?{...r,model:c.model.trim()}:r;if(c?.model!==void 0&&!d.model)throw et("The video provider model cannot be empty.",["non-empty --provider-model"],["model: empty"]);let p={info:{task:t,profile:i,provider:r.provider,protocol:a.protocol,baseUrl:a.baseUrl,model:d.model,fingerprint:Uc(t,a,d)},providerConfig:a,modelConfig:d};return this.resolvedRoutes.set(t,p),p}route(t){return this.resolve(t).info}routes(){return Ql.map(t=>this.route(t))}emptyUsage(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0}}recordReuse(t){let n=new Date().toISOString();this.recordEvent(this.route(t),"reused",n,n,0,{})}usage(){let t=new Map;for(let n of this.usageLog){let o=`${n.task}\0${n.provider}\0${n.protocol}\0${n.model}\0${n.fingerprint}`,i=t.get(o)??{task:n.task,profile:n.profile,provider:n.provider,protocol:n.protocol,baseUrl:n.baseUrl,model:n.model,fingerprint:n.fingerprint,...this.emptyUsage()};n.status==="reused"?i.reused+=1:(i.calls+=1,i[n.status]+=1,i.attempts+=n.attempts,i.durationMs+=n.durationMs,i.inputTokens+=n.inputTokens,i.outputTokens+=n.outputTokens,i.cachedInputTokens+=n.cachedInputTokens,i.cacheCreationTokens+=n.cacheCreationTokens),t.set(o,i)}return[...t.values()]}usageEvents(){return this.usageLog.map(t=>({...t}))}recordEvent(t,n,o,i,r,s,c=0,a){this.usageLog.push({...t,sequence:this.usageLog.length+1,status:n,attempts:c,startedAt:o,endedAt:i,durationMs:r,inputTokens:s.inputTokens??0,outputTokens:s.outputTokens??0,cachedInputTokens:s.cachedInputTokens??0,cacheCreationTokens:s.cacheCreationTokens??0,...a?{errorCode:a}:{}})}async tracked(t,n){let o=Date.now(),i=new Date(o).toISOString();try{let r=await n(),s=Date.now();return this.recordEvent(t,"succeeded",i,new Date(s).toISOString(),s-o,r.usage??{},r.attempts),r}catch(r){let s=Date.now(),c=r instanceof P?r:null;throw this.recordEvent(t,"failed",i,new Date(s).toISOString(),s-o,c?.usage??{},c?.attempts??1,c?.code),r}}resolveDoubao(t,n){let o=n?this.options.videoProvider:void 0,i=n?(o?.model??process.env.ARK_MODEL??"").trim():this.doubaoModel();if(!i)throw et("Doubao requires --provider-model or ARK_MODEL.",["--provider-model <id> or ARK_MODEL"],["model: empty"]);let r={protocol:"openai-compatible",baseUrl:o?.baseUrl?bc(o.baseUrl,"--provider-base-url"):rn.baseUrl,apiKeyEnv:rn.apiKeyEnv,timeoutMs:rn.timeoutMs,maxAttempts:rn.maxAttempts},s={provider:"doubao",model:i};return{info:{task:t,profile:n?"doubao":"doubao-fallback",provider:"doubao",protocol:r.protocol,baseUrl:r.baseUrl,model:i,fingerprint:Uc(t,r,s)},providerConfig:r,modelConfig:s}}doubaoRoute(t){return this.resolveDoubao(t,!1).info}adapter(t){let n=`${t.info.provider}\0${t.info.model}\0${t.modelConfig.thinkingBudgetTokens??""}`,o=this.adapters.get(n);if(o)return o;let i=(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&t.providerConfig.protocol!=="google-vertex")throw Qi(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new ts(t.providerConfig,t.modelConfig,i):new cs(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw et("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${t.info.provider}`,`protocol: ${t.providerConfig.protocol}`]);let n=t.info.model,o=`${t.info.provider} ${t.providerConfig.baseUrl??"official"} ${n}`,i=this.videoAdapters.get(o);if(i)return i;let r=this.videoCredential(t);if(!r&&t.providerConfig.protocol!=="google-vertex")throw Qi(t.info.provider);let s=new as(t.providerConfig,t.modelConfig,r);return this.videoAdapters.set(o,s),s}videoCredential(t){let n=this.options.videoProvider?.apiKey,o=n?.kind==="literal"?n.value.trim():n?.kind==="env"?(process.env[n.name]??"").trim():(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!o&&(n||t.providerConfig.protocol!=="google-vertex"))throw Qi(t.info.provider);return o}videoPort(t){let n=Sn[t];if(n.mode!=="video")throw et("The task does not support video generation.",["video task"],[`task: ${t}`]);let o=this.resolve(t);if(this.options.videoProvider?.provider==="doubao"){let r=this.doubaoAdapter(o);if(!r)throw Qi("doubao");return{prepare:async(s,c,a,d)=>{if(a!=="file-api")throw et("Doubao requires file-api upload mode.",["file-api"],[a]);return d?.throwIfAborted(),{kind:"local",path:s,mimeType:c}},generate:s=>{if(s.media.kind!=="local")throw et("Doubao requires locally prepared video.",["local media"],[s.media.kind]);s.signal?.throwIfAborted();let{path:c,mimeType:a}=s.media;return this.tracked(o.info,()=>r.run({localPath:c,localMime:a,user:s.user,fps:s.fps,maxOutputTokens:n.maxOutputTokens,...s.system?{system:s.system}:{},...s.responseJsonSchema?{responseJsonSchema:s.responseJsonSchema}:{},...s.signal?{signal:s.signal}:{}}))},release:async()=>{}}}if(!["google-gemini","google-vertex"].includes(o.providerConfig.protocol))throw et("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${o.info.provider}`,`protocol: ${o.providerConfig.protocol}`]);let i=this.videoAdapter(o);return{prepare:async(r,s,c,a)=>{let d=Date.now();try{return await i.prepare(r,s,c,a)}catch(p){if(!qi(p,a)||!this.doubaoAdapter())throw p;return this.recordEvent(o.info,"failed",new Date(d).toISOString(),new Date().toISOString(),Date.now()-d,p.usage,p.attempts,p.code),{kind:"local-fallback",path:r,mimeType:s,primaryFailure:Yi(p,o.info)}}},release:(r,s)=>r.kind==="local-fallback"?Promise.resolve():i.release(r,s),generate:async r=>{if(r.signal?.throwIfAborted(),r.media.kind==="local-fallback")return this.generateDoubaoVideo(t,r,[r.media.primaryFailure]);let s=lu(o),c=[];for(let[a,d]of s.entries()){r.signal?.throwIfAborted();try{return await this.tracked(d.info,()=>this.videoAdapter(d).generate({...r,maxOutputTokens:n.maxOutputTokens}))}catch(p){if(!qi(p,r.signal))throw p;let l=Yi(p,d.info);c.push(l);let f=s[a+1];if(f){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${f.info.model} (${Un(l)})
|
|
158
|
-
`);continue}if(!this.doubaoAdapter()||!r.localPath)throw ds(p,c);return this.generateDoubaoVideo(t,r,c)}}throw new Error("Gemini model routes cannot be empty.")}}}async generateDoubaoVideo(t,n,o){let i=this.doubaoAdapter();if(!i)throw Qi("doubao");let r=n.media.kind==="local-fallback"?n.media.path:n.localPath;if(!r)throw et("Doubao video fallback requires the local video.",["localPath"],["localPath: missing"]);let s=n.localMime??(n.media.kind==="file-api"?n.media.file.mimeType:n.media.mimeType),c=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F Gemini \u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${c.model}
|
|
159
|
-
`);try{return await this.tracked(c,()=>i.run({localPath:r,localMime:s,user:n.user,fps:n.fps,maxOutputTokens:Sn[t].maxOutputTokens,...n.system?{system:n.system}:{},...n.responseJsonSchema?{responseJsonSchema:n.responseJsonSchema}:{},...n.signal?{signal:n.signal}:{}}))}catch(a){throw qi(a,n.signal)?ds(a,[...o,Yi(a,c)]):a}}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(){return this.arkAdapter()}arkAdapter(t){let n=t?this.videoCredential(t):(process.env[rn.apiKeyEnv]??"").trim();if(!n)return null;let o=t?.info.model??this.doubaoModel(),i=t?.providerConfig.baseUrl??rn.baseUrl,r=`doubao ${i} ${o}`,s=this.doubaoAdapters.get(r);if(s)return s;let c=new is(o,rn.timeoutMs,rn.maxAttempts,n,i);return this.doubaoAdapters.set(r,c),c}doubaoModel(){return(process.env[rn.modelEnv]??"").trim()||rn.model}async withTextFallback(t,n,o){let i=this.resolve(t),r=A_(i.info),s=r?lu(i):[i],c=[];for(let[a,d]of s.entries()){n?.throwIfAborted();let p=this.adapter(d);try{return await this.tracked(d.info,()=>o(p))}catch(l){if(!qi(l,n)||!r&&l.code!=="content_filtered")throw l;let f=Yi(l,d.info);c.push(f);let u=s[a+1];if(u){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.model} (${Un(f)})
|
|
160
|
-
`);continue}let m=this.doubaoTextAdapter();if(!m)throw ds(l,c);let g=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u4E3B\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${g.model}
|
|
161
|
-
`);try{return await this.tracked(g,()=>o(m))}catch(h){throw qi(h,n)?ds(h,[...c,Yi(h,g)]):h}}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=Sn[t];if(o.mode!=="text")throw et("The task does not support text generation.",["text task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateText({...n,maxOutputTokens:o.maxOutputTokens}))}async generateTool(t,n){let o=Sn[t];if(o.mode!=="tool")throw et("The task does not support tool generation.",["tool task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateTool({...n,maxOutputTokens:o.maxOutputTokens}))}};function fu(e,t){return new Wi(Yo(e),t)}var b_=k_(import.meta.url);function ps(e){try{return b_.resolve(e),!0}catch{return!1}}function O_(e){let t=!1;try{bt.statSync(e).isDirectory()&&(bt.accessSync(e,bt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=bt.statSync(wo.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function v_(){return wo.join(wo.dirname(wo.resolve("workspace")),"output")}function mu(e={}){let t=Ec(),n=[],o=new Set;for(let v of t)try{if(!bt.existsSync(v)||!bt.statSync(v).isFile())continue;let j=bt.realpathSync(v);if(o.has(j))continue;o.add(j),n.push(v)}catch{}let i=typeof e.llm_config=="string"?e.llm_config.trim():"",r=Yo(i||void 0),c=new Wi(r).routes(),a=Object.entries(r.providers).map(([v,j])=>({alias:v,configured:!!(process.env[j.apiKeyEnv]??"").trim(),env:j.apiKeyEnv})),d=Object.entries(r.providers).filter(([,v])=>v.protocol==="openai-compatible").map(([v,j])=>{let Z="not set";if(j.baseUrl)try{Z=new URL(j.baseUrl).host}catch{Z=j.baseUrl}return{alias:v,host:Z}}),{mode:p}=Fl(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||v_(),f=p==="local"?O_(l):null,u=!!process.env.AWB_BASE_URL,m=!!process.env.LINGJING_AWB_ACCESS_KEY,g=!!process.env.SANDBOX_PROJECT_GROUP_NO,h={"@anthropic-ai/sdk":ps("@anthropic-ai/sdk"),"@google/genai":ps("@google/genai"),jszip:ps("jszip"),"fast-xml-parser":ps("fast-xml-parser")},w=Object.entries(h).filter(([,v])=>!v).map(([v])=>v),y=process.versions.node,E=`env_file: ${n[0]??"missing"}`,S=v=>v?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",E,`llm config: ${r.source}`,`llm routes: ${c.length}`,...a.map(v=>`llm provider ${v.alias}: ${S(v.configured)}`),...d.map(v=>`llm provider ${v.alias} endpoint: ${v.host}`)];p===null?A.push("output target: not configured"):p==="local"&&f?(A.push(`output writable: ${S(f.writable)}`),A.push(`output snapshot: ${f.hasScript?"present":"absent"}`)):(A.push(`gateway endpoint: ${S(u)}`),A.push(`gateway access credential: ${S(m)}`),A.push(`gateway project identifier: ${S(g)}`));for(let[v,j]of Object.entries(h))A.push(`dependency ${v}: ${j?"ok":"missing"}`);let k=[];w.length>0&&k.push("Install missing CLI dependencies (see above)."),a.some(v=>!v.configured)&&k.push("Configure every credential referenced by the selected LLM configuration."),d.some(v=>v.host==="not set")&&k.push("An openai-compatible provider has no endpoint \u2014 set PROJECT_LITELLM_GATEWAY_BASE_URL (built-in gateway) or the provider's baseUrl."),p===null?k.push("Configure an output target before running `publish` / script CRUD."):p==="local"?f&&!f.writable&&k.push("Output target is not writable; check directory permissions."):(!u||!m||!g)&&k.push("Configure gateway credentials before running `publish` / script CRUD against the remote project."),k.length===0&&k.push("Environment looks ready.");let[D,R]=y.split(".").map(v=>parseInt(v,10)),I=(D??0)>20||(D??0)===20&&(R??0)>=0,M=p===null?{configured:!1}:p==="local"?{dir:{ok:!!f?.writable,writable:!!f?.writable,hasScript:!!f?.hasScript}}:{endpoint:{ok:u},access:{ok:m},project:{ok:g}},$={node:{version:y,ok:I},storage:{backend:"local-filesystem",ok:!0},env:{ok:n.length>0,paths:n},llm:{config_source:r.source,...r.sourcePath?{config_path:r.sourcePath}:{},providers:a.map(v=>({alias:v.alias,ok:v.configured,credential_env:v.env,...d.find(j=>j.alias===v.alias)?{endpoint:d.find(j=>j.alias===v.alias).host}:{}})),profiles:Object.keys(r.models),routes:c.map(v=>({task:v.task,profile:v.profile,provider:v.provider,protocol:v.protocol,model:v.model}))},output:M,dependencies:h};return[{text:[...A,...k].join(`
|
|
162
|
-
`),data:{checks:$}},J]}import{spawn as R_}from"node:child_process";var ls="@lingjingai/scriptctl",N_=`${ls}@latest`,Tc="npm";function M_(){return Qo()}function L_(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${ls}@~${t[1]}.${t[2]}.0`:null}function U_(e){return["install","-g",e]}function T_(e,t){return[e,...t].join(" ")}function C_(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function P_(e,t){return new Promise(n=>{let o=R_(e,[...t],{stdio:["ignore","pipe","pipe"]}),i=[],r=[];o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",s=>i.push(s)),o.stderr.on("data",s=>r.push(s)),o.once("error",s=>{n({exitCode:null,signal:null,stdout:i.join(""),stderr:r.join(""),error:s})}),o.once("close",(s,c)=>{n({exitCode:s,signal:c,stdout:i.join(""),stderr:r.join("")})})})}async function gu(e,t=P_,n=M_){let o=!!e.patch,i=n(),r=o?L_(i):N_;if(!r)throw new x(`Cannot compute a patch update range from version ${i}.`,{exitCode:fe,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...U_(r)],c=T_(Tc,s),a={package:ls,package_spec:r,command:Tc,args:s,command_line:c};if(e.dry_run)return[{text:[`package: ${ls}`,`command: ${c}`,"dry-run: no update performed"].join(`
|
|
163
|
-
`),data:{op:"update",changed:!1,update:a}},J];let d=await t(Tc,s);if(d.error)throw new x(`Failed to start npm: ${d.error.message}`,{exitCode:fe,errorCode:"UPDATE_SPAWN_FAILED",hint:`Run '${c}' after fixing the npm installation.`,data:{update:a,cause:d.error.message}});if(d.exitCode!==J){let f=[`exit: ${d.exitCode===null?`signal ${d.signal??"unknown"}`:String(d.exitCode)}`,...C_(d.stderr,5).map(u=>`stderr: ${u}`)];throw new x("npm could not update scriptctl.",{exitCode:fe,errorCode:"UPDATE_COMMAND_FAILED",hint:`Run '${c}' after resolving the npm error.`,data:{update:a,actual:f}})}let p=n(),l=p!==i;return[{text:l?`Updated ${i} \u2192 ${p}.`:`Already up to date (${p}).`,data:{op:"update",changed:l,status:l?"updated":"already_latest",previous_version:i,version:p}},J]}function hu(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(Y(mu,t)),e.command("update").description("Update scriptctl to the latest release").option("-n, --dry-run","Show the update without installing").option("--patch","Allow a patch-level update").action(Y(gu,t));let n=e.command("changelog [version]").description("Show release notes").option("--from <version>","Start version").option("--to <version>","End version").option("--unreleased","Show unreleased changes").action(Y(Kl,t));Ie(n,["Release version"])}import*as Zi from"node:fs";import*as fs from"node:path";import{fileURLToPath as V_,pathToFileURL as $_}from"node:url";var D_="review-agent";function G_(e,t){let n=t||D_,o=e.models[n];if(!o)throw new x(`LLM profile "${n}" is not defined.`,{exitCode:b,errorCode:"REVIEW_PROFILE_UNKNOWN",hint:`Define it under models, or pick one of: ${Object.keys(e.models).join(", ")}.`,data:{expected:["a defined models entry"],actual:[n]}});let i=e.providers[o.provider];if(!i)throw new x(`Provider "${o.provider}" is not defined.`,{exitCode:b,errorCode:"REVIEW_PROVIDER_UNKNOWN",hint:`Available providers: ${Object.keys(e.providers).join(", ")}.`,data:{expected:["a defined providers entry"],actual:[o.provider]}});let r=(process.env[i.apiKeyEnv]??"").trim();if(!r&&i.protocol!=="google-vertex")throw new x(`${i.apiKeyEnv} is not set.`,{exitCode:b,errorCode:"REVIEW_API_KEY_MISSING",hint:`Export ${i.apiKeyEnv} for provider ${o.provider}.`,data:{expected:[i.apiKeyEnv],actual:["<empty>"]}});return{provider:o.provider,model:o.model,baseUrl:i.baseUrl,apiKey:r,maxAttempts:i.maxAttempts}}async function yu(){let e=fs.dirname(V_(import.meta.url)),t=fs.join(e,"review-agent.js"),n=Zi.existsSync(t)?$_(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new x("The review agent is not installed.",{exitCode:fe,errorCode:"REVIEW_AGENT_MISSING",hint:"Reinstall scriptctl without --omit=optional, or install @mastra/core and @ai-sdk/google.",data:{expected:["@lingjingai/review-agent"],actual:[String(o.message).slice(0,200)]}})}}function wu(e){let t=e.trim();if(!t)return;let n=t.split(",").map(o=>Number(o.trim()));if(n.some(o=>!Number.isInteger(o)||o<1))throw new x("--episodes takes a comma-separated list of 1-based episode numbers.",{exitCode:b,errorCode:"REVIEW_EPISODES_INVALID",hint:"For example: --episodes 1,2,5",data:{expected:["1-based episode numbers"],actual:[t]}});return n}function us(e,t,n){let o=e[t];if(o===void 0)return n;let i=Number(o);if(!Number.isFinite(i)||i<=0)throw new x(`--${t.replace(/_/g,"-")} must be a positive number.`,{exitCode:b,errorCode:"REVIEW_OPTION_INVALID",hint:`Pass a positive number for --${t.replace(/_/g,"-")}.`,data:{expected:["a positive number"],actual:[String(o)]}});return i}async function _u(e){let t=Yo(O(e.llm_config).trim()||void 0),n=O(e.model).trim(),o=G_(t,n);if(e.check){let l=typeof(await yu()).reviewScript=="function";return[{text:l?`ready: ${o.provider}/${o.model}`:"the review agent bundle is present but exports no reviewScript",data:{ready:l,provider:o.provider,model:o.model,llm_config:t.sourcePath??"builtin"}},l?J:fe]}let i=xe(e);if(!Zi.existsSync(i))throw new x("Local script file not found.",{exitCode:b,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[i]}});let r=(Array.isArray(e.video)?e.video:[]).map(p=>p.trim()).filter(p=>p.length>0),s=r.filter(p=>!Zi.existsSync(p));if(s.length>0)throw new x("A --video path does not exist.",{exitCode:b,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass --video once per episode, in episode order.",data:{expected:["existing video files"],actual:s.slice(0,5)}});let c=O(e.source_path).trim();if(c&&!Zi.existsSync(c))throw new x("Video source not found.",{exitCode:b,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass -s to a video file or a directory of per-episode videos, or omit it for a script-only review.",data:{expected:["existing video file or directory"],actual:[c]}});let{reviewScript:a}=await yu(),d=p=>process.stdout.write(JSON.stringify(p)+`
|
|
164
|
-
`);try{await a({scriptPath:i,...c?{source:c}:{},...r.length>0?{videos:r}:{},...wu(O(e.episodes))?{episodes:wu(O(e.episodes))}:{},concurrency:us(e,"concurrency",5),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,apiKey:o.apiKey,maxAttempts:o.maxAttempts,model:o.model,mediaModel:o.model,...o.baseUrl?{baseUrl:o.baseUrl}:{},maxSteps:us(e,"max_steps",300),mediaBudget:us(e,"media_budget",1),episodeTimeoutMs:us(e,"episode_timeout_ms",8*6e4),onEvent:d})}catch(p){throw p instanceof x?p:new x("Review failed.",{exitCode:fe,errorCode:"REVIEW_FAILED",hint:"Read the error details, NDJSON asr-compared/episode reports and .review/asr/ evidence before retrying.",data:{expected:["a completed review run"],actual:[p instanceof Error?p.message:String(p)]}})}return[{text:"",data:{}},J]}function Eu(e,t){se(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5C31\u6309\u539F\u89C6\u9891\u62C9\u7247\u6838\u5BF9\uFF0C\u4E0D\u7ED9\u5C31\u7EAF\u5267\u672C\u5BA1\u6838").option("-s, --source-path <path>","\u539F\u89C6\u9891\u6587\u4EF6\u6216\u6BCF\u96C6\u4E00\u4E2A\u89C6\u9891\u7684\u76EE\u5F55").option("--video <path>","\u7B2C N \u96C6\u7684\u89C6\u9891\uFF1B\u6309\u96C6\u987A\u5E8F\u91CD\u590D\u4F20\uFF0C\u8986\u76D6 -s \u7684\u76EE\u5F55\u6392\u5E8F",(n,o)=>[...o,n],[]).option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\uFF09").option("--concurrency <n>","\u540C\u65F6\u5728\u98DE\u7684\u96C6\u6570",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF1B\u5230\u70B9\u6536\u5C3E\u5E76\u4FDD\u7559\u5DF2\u8BB0\u5F55\u7684\u7ED3\u8BBA",Number).option("--max-steps <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--media-budget <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B21\u89C6\u9891\u6838\u5BF9",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u655B\uFF0C\u4E0D\u91CD\u65B0\u5BA1\u6838\u5404\u96C6").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u655B\u9636\u6BB5").option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u9ED8\u8BA4 review-agent\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA\uFF0C\u4E0D\u5BA1\u6838").action(Y(_u,t))}import*as Yu from"node:fs";import*as Fn from"node:fs";var xu=null,J_=0;function z(e,t){xu&&xu.push({fn:e,note:t,ms:Math.round((performance.now()-J_)*100)/100})}var B_=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function Hn(e){return Array.isArray(e)?e:[]}function we(e){return typeof e=="string"?e:""}function An(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function Pc(e){return ms(JSON.parse(Fn.readFileSync(e,"utf8")),e)}function ms(e,t=""){let n=e?.version;if(n!==3&&n!==4)throw new Error(`Unsupported script.version: ${JSON.stringify(n)} (expected 3 or 4)`);let o={version:n,path:t,raw:e,episodes:[],assets:[],byId:new Map,eps:new Map,scenes:new Map,actions:new Map};for(let[a,d,p]of B_)for(let l of Hn(e[d])){let f={id:we(l[`${p}_id`]),kind:a,name:we(l[`${p}_name`]),aliases:Hn(l.aliases).map(we).filter(Boolean),importance:we(l.importance),desc:we(l.description),states:Hn(l.states).map(u=>({id:we(u.state_id),name:we(u.state_name),desc:we(u.description)})),raw:l,label:""};o.assets.push(f),o.byId.set(f.id,f)}let i=new Map;for(let a of o.assets)for(let d of[a.name,...a.aliases])i.set(d,(i.get(d)??0)+1);for(let a of o.assets)a.label=[a.name,...a.aliases].filter(d=>i.get(d)===1).sort((d,p)=>d.length-p.length)[0]??a.name;let r=new Set,s=0,c=0;Hn(e.episodes).forEach((a,d)=>{let p={anchor:String(d+1),id:we(a.episode_id),no:d+1,title:we(a.title)||void 0,synopsis:we(a.synopsis)||void 0,scenes:[],raw:a};Hn(a.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?we(l.scene_id):`${d+1}-${f+1}`,id:we(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:Cc(l.location,"location_id"),actors:Hn(l.actors).map(m=>Cc(m,"actor_id")).filter(Boolean),props:Hn(l.props).map(m=>Cc(m,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};Hn(l.actions).forEach((m,g)=>{c++;let h={anchor:n===4?we(m.action_id):`${d+1}-${f+1}-${g+1}`,no:g+1,gno:c,type:we(m.type)||"action",content:we(m.content),speaker:K_(m.speaker),paren:typeof m.parenthetical=="string"?m.parenthetical:typeof m.emotion=="string"?m.emotion:void 0,ts:we(m.extend?.timestamp)||void 0,raw:m,scene:u};u.actions.push(h),An(o.actions,h.anchor,h,r),An(o.actions,`${d+1}-${f+1}-${g+1}`,h,r),n===3&&An(o.actions,`${p.id}/${u.id}#${g}`,h,r)}),p.scenes.push(u),An(o.scenes,u.anchor,u,r),An(o.scenes,`${d+1}-${f+1}`,u,r),An(o.scenes,`${p.id}/${u.id}`,u,r),An(o.scenes,u.id,u,r)}),o.episodes.push(p),An(o.eps,String(d+1),p,r),An(o.eps,p.id,p,r)});for(let a of r)o.actions.delete(a),o.scenes.delete(a),o.eps.delete(a);return z(t?"model.load":"model.parse",`v${n} \xB7 ${o.episodes.length} ep \xB7 ${o.scenes.size} scene keys \xB7 ${o.actions.size} action keys \xB7 ${o.assets.length} assets \xB7 ${r.size} ambiguous keys dropped`),o}function Cc(e,t){if(!e||typeof e!="object")return null;let n=we(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(we):e.state_id?[we(e.state_id)]:[];return{id:n,states:o,raw:e}}function K_(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:we(e.actor_id),state:we(e.state_id)||void 0};if(e.kind)return{kind:we(e.kind),label:we(e.label)||void 0}}}function Re(e,t){let n=t.trim();if(!n)return{t:"script",doc:e};let o=n.indexOf("/");if(o>0&&!e.scenes.has(n)){let p=n.slice(0,o),l=n.slice(o+1),f=e.byId.get(p)??j_(e,p);if(f){let u=f.states.filter(m=>m.id===l||m.name===l);if(u.length===1)return z("resolve",`"${n}" -> state ${f.id}/${u[0].id} "${u[0].name}"`),{t:"state",asset:f,state:u[0]};throw u.length>1?new Error(`${f.name} has ${u.length} states named "${l}"; address it by state id`):new Error(`${f.name} has no state "${l}" (has: ${f.states.map(m=>`${m.id}(${m.name})`).join(", ")})`)}}let i=e.actions.get(n);if(i)return z("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return z("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return z("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let c=e.byId.get(n);if(c)return z("resolve",`"${n}" -> asset id hit -> ${c.name}`),{t:"asset",asset:c};let a=e.assets.filter(p=>p.name===n||p.aliases.includes(n));if(a.length===1)return z("resolve",`"${n}" -> exact name/alias -> ${a[0].id} ${a[0].name}`),{t:"asset",asset:a[0]};if(a.length>1)throw new Error(`Ambiguous name "${n}": ${a.map(p=>`${p.id}(${p.name})`).join(", ")}`);let d=e.assets.filter(p=>p.name.includes(n)||p.aliases.some(l=>l.includes(n)));if(d.length===1)return z("resolve",`"${n}" -> substring name match -> ${d[0].id} ${d[0].name}`),{t:"asset",asset:d[0]};throw new Error(`Unknown address "${n}". Use an ordinal (3 / 3-2 / 3-2-5), a canonical ID, or an asset name.`+(d.length?` Did you mean: ${d.slice(0,5).map(p=>p.name).join(", ")}?`:""))}function j_(e,t){let n=e.assets.filter(i=>i.name===t||i.aliases.includes(t));if(n.length===1)return n[0];if(n.length>1)return;let o=e.assets.filter(i=>i.name.includes(t)||i.aliases.some(r=>r.includes(t)));return o.length===1?o[0]:void 0}function _o(e,t){return e.byId.get(t)?.label||t}function Eo(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function Qn(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var z_={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function Yn(e,t){let n=vi(z_[e],t);return t.add(n),z("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function _e(e){if(Object.assign(e,ms(e.raw,e.path)),!e.path){z("save","skipped: document is not bound to a file");return}Su(e,e.path)}function Su(e,t=e.path){if(!t)throw new Error("commit needs a path: this document is not bound to a file");let n=`${t}.tmp-${process.pid}`;Fn.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
|
|
165
|
-
`),Fn.renameSync(n,t),z("commit",`${Fn.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var H_={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},Iu="\u5FC3\u58F0";function F_(e,t){if(t.kind)return H_[t.kind]??t.kind;let n=_o(e,t.id);return t.state?`${n}\xB7${Eo(e,t.id,t.state)}`:n}function Xi(e,t,n,o={}){let i=(o.plain?"":t.anchor).padEnd(n),r=o.timestamps?`${t.ts??"[\u65F6\u95F4\u7F3A\u5931]"} `:!o.plain&&t.ts?`${t.ts} `:"",s=(()=>{if(t.type==="transition")return`\u2192 ${t.content}`;if(t.type==="dialogue"||t.type==="inner_thought"){let a=t.speaker?F_(e,t.speaker):"?",d=[t.type==="inner_thought"?Iu:"",t.paren??""].filter(Boolean);return`${t.speaker?.kind&&t.speaker.label?`${a}\xB7${t.speaker.label}`:a}${d.length?`(${d.join("/")})`:""}\uFF1A${t.content}`}return t.content})(),c=`${i}${i?" ":""}`;return`${o.timestamps?r+c:c+r}${s}`.replace(/\n/g,"\\n")}function Vc(e,t){let n=_o(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>Eo(e,t.id,o)).join("+")})`}function Wo(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?Vc(e,t.location):"\u2014",i=`## ${t.ep.no}-${t.no} ${t.anchor===`${t.ep.no}-${t.no}`?t.id:t.anchor} ${n||"\u2014"} ${o} ${t.actions.length} actions`,r=t.actors.map(a=>Vc(e,a)).join(", "),s=t.props.map(a=>Vc(e,a)).join(", "),c=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return c?`${i}
|
|
166
|
-
# ${c}`:i}function $c(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return z("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[Wo(e,t),...t.actions.map(i=>Xi(e,i,o,n))].join(`
|
|
167
|
-
`)}var Q_=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function Au(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(Q_);i&&(o=i[1],n=n.slice(i[0].length)),n=n.replace(/\\n/g,`
|
|
168
|
-
`);let r,s=n.match(/^((?:\d+:)?\d+:\d{2}(?:\.\d{1,3})?)\s/);if(s&&(r=s[1],n=n.slice(s[0].length)),n.startsWith("\u2192"))return{anchor:o,ts:r,type:"transition",content:n.slice(1).trim()};let c=n.indexOf("\uFF1A");if(c>0){let d=n.slice(0,c).match(/^([^()]+)(?:\((.*)\))?$/);if(d&&t(d[1].trim())){let p=(d[2]??"").split("/").map(u=>u.trim()).filter(Boolean),l=p[0]===Iu,f=(l?p.slice(1):p).join("/");return{anchor:o,ts:r,type:l?"inner_thought":"dialogue",speakerName:d[1].trim(),paren:f||void 0,content:n.slice(c+1).trim()}}}return{anchor:o,ts:r,type:"action",content:n.trim()}}var Y_=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,q_=/^[A-Z.\/]+$/,W_=/^\d+\s+actions?$/,Z_={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function ku(e){let t=e.findIndex(i=>i.startsWith("##"));if(t<0)return{body:e};let n=e[t+1]?.startsWith("#")&&!e[t+1].startsWith("##"),o=e.filter((i,r)=>r!==t&&!(n&&r===t+1));return{head:e[t],meta:n?e[t+1]:void 0,body:o}}function Dc(e,t){let n={env:{},cast:[],props:[]},o=e.replace(/^##\s*/,"").split(/\s{2,}/).map(i=>i.trim()).filter(Boolean);for(let i of o)if(!(/^\d+-\d+$/.test(i)||W_.test(i))){if(Y_.test(i)){n.anchor=i;continue}if(q_.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=Z_[r]??r.toLowerCase()),s&&(n.env.time=s.toLowerCase());continue}i!=="\u2014"&&n.location===void 0&&(n.location=i)}if(t){let i=t.replace(/^#\s*/,""),r=i.match(/cast:\s*([^]*?)(?:\s\sprops:|$)/),s=i.match(/props:\s*([^]*)$/),c=a=>(a??"").split(",").map(d=>d.trim()).filter(Boolean);n.cast=c(r?.[1]),n.props=c(s?.[1])}return n}function bu(e){let t=e.trim().match(/^(.*?)\s*\(([^)]*)\)$/);return t?{name:t[1].trim(),states:t[2].split("+").map(n=>n.trim()).filter(Boolean)}:{name:e.trim(),states:[]}}function Zo(e,t){throw Object.assign(new Error(e),t)}function Jc(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions.map((o,i)=>({address:e.version===4?o.anchor:`${t.id}/${n.id}#${i}`,episodeId:t.id,episodeNo:t.no,timestamp:o.ts}))))}function Gc(e){try{return Cn(e.timestamp??"")}catch(t){if(!(t instanceof Ye))throw t;return Zo(`Action ${e.address} has an invalid stored timestamp.`,{code:"ACTION_SPAN_TIMESTAMP_INVALID",hint:`Fix it with \`scriptctl edit ${e.address} --ts <time>\` or remove it.`,data:{expected:["valid action.extend.timestamp"],actual:[`${e.address}: ${JSON.stringify(e.timestamp??"")}`]}})}}function Ou(e,t){return Zo("Action timestamps run backward within the selected episode.",{code:"ACTION_SPAN_TIMESTAMP_NON_MONOTONIC",hint:"Fix the stored timestamps so they do not move backward in document order, then rerun `span`.",data:{actual:[`${e.address}: ${e.timestamp}`,`${t.address}: ${t.timestamp}`]}})}function Bc(e,t){t.length===0&&Zo("The action selection matched nothing.",{code:"ACTION_SPAN_NO_MATCH",hint:"Check the selector with `scriptctl actions` and rerun with `--span`.",data:{actual:["0 matched actions"]}});let n=new Set(t),o=e.filter(m=>n.has(m.address));o.length!==n.size&&Zo("The resolved action selection is inconsistent with the script timeline.",{code:"ACTION_SPAN_SELECTION_INCONSISTENT",data:{expected:[`${n.size} timeline actions`],actual:[`${o.length} timeline actions`]}});let i=new Set(o.map(m=>m.episodeId));i.size!==1&&Zo("An action timestamp span must stay within one episode.",{code:"ACTION_SPAN_CROSSES_EPISODES",hint:"Split the selector into one `span` call per episode.",data:{actual:[...i]}});let r=o[0],s=o[o.length-1];r.timestamp||Zo(`The first selected Action ${r.address} has no timestamp.`,{code:"ACTION_SPAN_START_TIMESTAMP_MISSING",hint:`Set it with \`scriptctl timestamp ${r.address} --set <time>\`, then rerun.`,data:{actual:[r.address]}});let c=Gc(r),a=r,d=c,p="";for(let m of o){if(!m.timestamp)continue;let g=Gc(m);g.milliseconds<d.milliseconds&&Ou(a,m),a=m,d=g,m.address===s.address&&(p=g.canonical)}let l=e.findIndex(m=>m.address===s.address),f,u;for(let m=l+1;m<e.length;m+=1){let g=e[m];if(g.episodeId!==r.episodeId)break;if(!g.timestamp)continue;let h=Gc(g);if(h.milliseconds<d.milliseconds&&Ou(a,g),h.milliseconds!==d.milliseconds){f=g,u=h;break}}return z("span",`${r.episodeId} ${c.canonical}..${u?.canonical??"(open)"} over ${o.length} action(s)`),{episode_id:r.episodeId,ep_no:r.episodeNo,start_timestamp:c.canonical,last_selected_timestamp:p,end_timestamp:u?.canonical??"",end_open:u===void 0,end_exclusive:!0,start_action:r.address,last_action:s.address,end_boundary_action:f?.address??"",matched_actions:o.length}}var Kc=["episode_id","ep_no","start_timestamp","last_selected_timestamp","end_timestamp","end_open","end_exclusive","start_action","last_action","end_boundary_action","matched_actions"];function jc(e,t){return t.map(n=>{if(e.version===4)return n.anchor;let o=n.scene.actions.indexOf(n);return`${n.scene.ep.id}/${n.scene.id}#${o}`})}function zc(e,t,n={}){let o=n.offset??0,i=n.limit??20,r=n.context??3;for(let[f,u,m]of[["offset",o,0],["limit",i,1],["context",r,0]])if(!Number.isSafeInteger(u)||u<m)throw new Error(`${f} must be an integer >= ${m}`);let s=Re(e,t);if(s.t!=="asset"&&s.t!=="state")throw new Error("references requires an asset or asset/state address; use read for episodes/scenes/actions");let c=s.asset,a=s.t==="state"?s.state.id:null,d=[...new Set([c.id,c.name,...c.aliases])].filter(Boolean),p=[];for(let f of e.episodes)for(let u of f.scenes){let m=[...u.location?[u.location]:[],...u.actors,...u.props].filter(g=>g.id===c.id&&(a===null||g.states.includes(a)));m.length&&p.push({kind:"scene_binding",scene:u,matched:m.flatMap(g=>g.states)});for(let g of u.actions)if(g.speaker?.id===c.id&&(a===null||g.speaker.state===a)&&p.push({kind:"speaker",scene:u,action:g,matched:[c.id]}),a===null){let h=d.filter(w=>g.content.includes(w));h.length&&p.push({kind:"text_mention",scene:u,action:g,matched:h})}}let l=o+i;return{asset_id:c.id,state_id:a,total:p.length,next_offset:l<p.length?l:null,items:p.slice(o,l).map(({kind:f,scene:u,action:m,matched:g})=>{let h=m?u.actions.indexOf(m):-1,w=m?u.actions.slice(Math.max(0,h-r),h+r+1):[],y=Math.max(0,...w.map(E=>E.anchor.length));return{kind:f,address:m?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:g,text:[Wo(e,u),...w.map(E=>(E===m?"> ":" ")+Xi(e,E,y))].join(`
|
|
169
|
-
`)}})}}function Hc(e){return[`${e.asset_id}${e.state_id===null?"":"/"+e.state_id} ${e.total} references \xB7 showing ${e.items.length}`,"scene_binding=explicit scene presence; speaker=explicit speaker; text_mention=name/alias mention only (not proof of presence).",...e.items.map(t=>`${t.address} ${t.kind} ep=${t.episode}
|
|
170
|
-
${t.text}`),e.next_offset===null?"end":`Continue: --offset ${e.next_offset}`].join(`
|
|
171
|
-
|
|
172
|
-
`)}var X_=["\u65C1\u767D","\u5E7F\u64AD","\u753B\u5916","\u7FA4\u58F0"],eE={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function tE(e){let t=new Set(X_);for(let n of e.assets){t.add(n.name);for(let o of n.aliases)t.add(o)}return n=>t.has(n)||t.has(n.split("\xB7")[0])}function hs(e,t="",n={}){let o=Re(e,t);switch(z("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return oE(e);case"ep":return iE(e,o.ep,n);case"scene":return $c(e,o.scene,n);case"asset":return rE(e,o.asset);case"state":return sE(e,o.asset,o.state);case"action":{let i=n.context??3,r=o.action.scene.actions,s=r.indexOf(o.action),c=r.slice(Math.max(0,s-i),s+i+1),a=n.plain?0:Math.max(...c.map(l=>l.anchor.length)),d=o.action.raw.transition_prompt,p=Object.entries(o.action.raw.extend??{}).filter(([l])=>l!=="timestamp");return[Wo(e,o.action.scene),...c.map(l=>(l===o.action?"> ":" ")+Xi(e,l,a,n)),d?`transition: ${_o(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
|
|
173
|
-
`)}}}function nE(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function oE(e){let t=e.raw,n=e.episodes.reduce((r,s)=>r+s.scenes.length,0),o=e.episodes.reduce((r,s)=>r+s.scenes.reduce((c,a)=>c+a.actions.length,0),0),i=[`${t.title||"(untitled)"} v${e.version} ${e.episodes.length} ep \xB7 ${n} scenes \xB7 ${o} actions`];for(let r of["logline","theme","synopsis","worldview","style"])t[r]&&i.push(`${r}: ${er(String(t[r]),300)}`);Array.isArray(t.main_characters)&&t.main_characters.length&&i.push(`main: ${t.main_characters.map(r=>`${r.name}=${r.role}`).join(", ")}`);for(let r of["actor","location","prop"]){let s=e.assets.filter(c=>c.kind===r);if(s.length){i.push("",`${r}s (${s.length})`);for(let c of s.slice(0,40)){let a=c.aliases.length?` ~${c.aliases.join(",")}`:"",d=c.importance?` [${c.importance}]`:"";i.push(` ${c.id} ${c.name}${d} ${c.states.length}st${a}`)}s.length>40&&i.push(` \u2026 ${s.length-40} more`)}}i.push("","episodes");for(let r of e.episodes){let s=r.scenes.reduce((c,a)=>c+nE(a),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${er(r.synopsis,120)}`:""))}return i.join(`
|
|
174
|
-
`)}function iE(e,t,n){let o=`# EP${String(t.no).padStart(2,"0")} ${t.id} ${t.scenes.length} scenes`+(t.title?` ${t.title}`:"");return n.depth==="outline"?[o,...t.scenes.map(i=>Wo(e,i))].join(`
|
|
175
|
-
`):[o,...t.scenes.map(i=>$c(e,i,n))].join(`
|
|
176
|
-
|
|
177
|
-
`)}function rE(e,t){let n=t.raw.role_type?` <${t.raw.role_type}>`:"",o=[`${t.id} ${t.name} ${t.kind}${t.importance?` [${t.importance}]`:""}${n}`];t.aliases.length&&o.push(`aliases: ${t.aliases.join(", ")}`),t.desc&&o.push(t.desc),o.push(`states (${t.states.length})`);for(let s of t.states)o.push(` ${s.id} ${s.name} ${er(s.desc,160)}`);let i=[],r=new Map;for(let s of e.episodes)for(let c of s.scenes){let a=[c.location,...c.actors,...c.props].find(d=>d&&d.id===t.id);if(a){i.push(c);for(let d of a.states)r.set(d,(r.get(d)??0)+1)}}if(i.length){let s=[...new Set(i.map(a=>a.ep.no))];o.push(`appears: ${i.length} scenes across ${s.length} ep first ${i[0].ep.no}-${i[0].no} last ${i.at(-1).ep.no}-${i.at(-1).no}`),o.push(`state usage: ${[...r].map(([a,d])=>`${Eo(e,t.id,a)}\xD7${d}`).join(", ")}`);let c=t.states.filter(a=>!r.has(a.id));c.length&&o.push(`unused states: ${c.map(a=>`${a.id}(${a.name})`).join(", ")}`)}else o.push("appears: never referenced");return o.join(`
|
|
178
|
-
`)}function sE(e,t,n){let o=[];for(let r of e.episodes)for(let s of r.scenes)[s.location,...s.actors,...s.props].find(a=>a&&a.id===t.id)?.states.includes(n.id)&&o.push(s);let i=Qn(e).filter(r=>r.speaker?.id===t.id&&r.speaker.state===n.id);return[`${t.id}/${n.id} ${n.name} (${t.kind} ${t.name})`,n.desc,o.length?`bound in ${o.length} scene(s): ${o.slice(0,12).map(r=>`${r.ep.no}-${r.no}`).join(", ")}`+(o.length>12?" \u2026":""):"bound in no scene",i.length?`named by ${i.length} speaker reference(s)`:""].filter(Boolean).join(`
|
|
179
|
-
`)}function er(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function Qc(e,t){let n=Qn(e);if(z("find",`pool = all actions (${n.length})`),t.in){let o=Re(e,t.in);if(o.t==="ep")n=o.ep.scenes.flatMap(i=>i.actions);else if(o.t==="scene")n=o.scene.actions;else if(o.t==="action")n=[o.action];else throw new Error(`--in must address an episode, scene or action (got ${o.t})`);z("find",`--in ${t.in} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),z("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=Re(e,t.speaker);if(o.t!=="asset")throw new Error("--speaker must name an actor");n=n.filter(i=>i.speaker?.id===o.asset.id),z("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function Mu(e,t,n={}){let o=Qc(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));z("find",`regex /${t}/ -> ${r.length} hits`);let s=n.limit??40,c=n.window??16,a=r.slice(0,s),d=Math.max(0,...a.map(f=>f.anchor.length)),p=`${r.length} hit${r.length===1?"":"s"}`+(t?` for /${t}/`:"")+(r.length>a.length?` (showing ${a.length})`:""),l=a.map(f=>{let u=`${f.scene.ep.no}-${f.scene.no}-${f.no}`,m=u===f.anchor?"":u.padEnd(8)+" ",g=f.speaker?.id?_o(e,f.speaker.id)+"\uFF1A":"",h=n.full||!i?f.content:aE(f.content,i,c);return`${f.anchor.padEnd(d)} ${m}${g}${h}`});return[p,...l].join(`
|
|
180
|
-
`)}function aE(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return er(e,n*2);let i=Math.max(0,o.index-n),r=Math.min(e.length,o.index+o[0].length+n);return(i>0?"\u2026":"")+e.slice(i,r)+(r<e.length?"\u2026":"")}function Yc(e,t){return Bc(Jc(e),jc(e,Qc(e,{in:t})))}function Lu(e,t){let n=Yc(e,t);return Kc.map(o=>`${o}=${n[o]}`).join(" ")}var cE=["content","paren","speaker","ts","type","transition"],dE=["name","desc","importance","aliases","role"],pE=["name","desc"],lE=["title","synopsis"],uE=["space","time"],fE=["title","worldview","style","synopsis","logline","theme","main"];function tr(e,t,n,o){let i=Object.keys(n).filter(s=>n[s]!==void 0);if(!i.length)throw new Error(`Nothing to change on ${e}; pass at least one field`);let r=i.filter(s=>!o.includes(s));if(r.length){let s=/^[aeiou]/.test(t)?"an":"a";throw new Error(`${e} is ${s} ${t}; it has no ${r.join(", ")} \u2014 ${s} ${t} takes ${o.join(", ")}`)}return i}function Uu(e,t,n){let o=Re(e,t);if(o.t==="asset")return gE(e,t,o.asset,n);if(o.t==="state")return hE(e,t,o.asset,o.state,n);if(o.t==="script")return vu(e,t||"script","script",o.doc.raw,n,fE);if(o.t==="ep")return vu(e,t,"episode",o.ep.raw,n,lE);if(o.t==="scene")return mE(e,t,o.scene,n);let i=o.action,r=i.raw,s=tr(i.anchor,"action",n,cE),c=tt(e);if(z("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=xo("type",n.type,Tt,ln)),n.content!==void 0&&(r.content=n.content),n.paren!==void 0&&gs(e,r,n.paren),n.speaker!==void 0&&(r.speaker=qc(e,n.speaker)),n.ts!==void 0&&Pu(r,n.ts),n.transition!==void 0)if(n.transition===null)delete r.transition_prompt;else{let[a,d,p]=n.transition.split("|").map(f=>f.trim());if(!a||!d||!p)throw new Error(`transition takes "target|process|contrast" (got "${n.transition}")`);let l=Re(e,a);if(l.t!=="asset")throw new Error(`transition target must be an asset (got ${a})`);r.transition_prompt={target:l.asset.id,process:d,contrast:p}}return _e(e),`${i.anchor} ${s.join("+")} ${ys(r)}`+Te(e,c)}function vu(e,t,n,o,i,r){let s=tr(t,n,i,r),c=tt(e);for(let a of s)if(a==="main")o.main_characters=i.main.split(",").map(d=>{let[p,l]=d.split("=").map(f=>f.trim());if(!p||!l)throw new Error(`main takes "\u540D\u5B57=\u89D2\u8272\u5B9A\u4F4D,\u2026" (got "${d}")`);return{name:p,role:l}});else{if(a==="aliases"||a==="role")throw new Error(`${t} is ${n}; it has no ${a}`);o[a]=i[a]}return z("edit",`${n} ${t}: ${s.join(", ")}`),_e(e),`${t} ${s.join("+")}`+Te(e,c)}function mE(e,t,n,o){let i=tr(t,"scene",o,uE),r=tt(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=xo("space",o.space,Mp,ya)),o.time!==void 0&&(s.time=xo("time",o.time,ha,Cr)),n.raw.environment=s,z("edit",`scene ${n.anchor}: ${i.join(", ")}`),_e(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+Te(e,r)}function gE(e,t,n,o){let i=tr(t,"asset",o,dE),r=tt(e);if(o.name!==void 0){let s=e.assets.find(c=>c!==n&&(c.name===o.name||c.aliases.includes(o.name)));if(s)throw new Error(`"${o.name}" already names ${s.kind} ${s.id}`);n.raw[`${n.kind}_name`]=o.name}if(o.desc!==void 0&&(n.raw.description=o.desc),o.importance!==void 0&&(n.raw.importance=Bu(o.importance)),o.role!==void 0){if(n.kind!=="actor")throw new Error(`role only applies to actors (${n.name} is a ${n.kind})`);o.role?n.raw.role_type=xo("role",o.role,Tn,$o):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),z("edit",`asset ${n.id}: ${i.join(", ")}`),_e(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+Te(e,r)}function hE(e,t,n,o,i){let r=tr(t,"state",i,pE),s=tt(e),c=n.raw.states.find(a=>a.state_id===o.id);if(i.name!==void 0){if(n.states.some(a=>a.id!==o.id&&a.name===i.name))throw new Error(`${n.name} already has a state named "${i.name}"`);c.state_name=i.name}return i.desc!==void 0&&(c.description=i.desc),z("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),_e(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+Te(e,s)}function Tu(e,t,n,o,i,r,s){let c=Re(e,t);if(c.t!=="action")throw new Error(`${t} is a ${c.t}; insert needs a sibling action`);let a=c.action,d=tt(e),p={type:xo("type",o,Tt,ln),content:i};if(e.version===4&&(p.action_id=Yn("ac",new Set(e.actions.keys()))),o==="dialogue"||o==="inner_thought"){if(!r)throw new Error(`a ${o} needs a speaker`);p.speaker=qc(e,r),s!==void 0&&gs(e,p,s)}else if(r||s)throw new Error(`a ${o} takes neither speaker nor paren`);let l=a.scene.raw.actions,f=l.indexOf(a.raw)+(n==="before"?0:1);return l.splice(f,0,p),z("insert",`${p.action_id??`${a.scene.anchor}#${f}`} ${n} ${a.anchor}`),_e(e),`${p.action_id??`${a.scene.anchor}#${f}`} ${n} ${a.anchor} ${ys(p)}`+Te(e,d)}function Cu(e,t,n,o="after"){let i=Re(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=Re(e,n);if(r.t!=="action")throw new Error(`${n} is a ${r.t}; move --to takes a sibling action`);if(i.action===r.action)throw new Error(`${t} cannot move relative to itself`);let s=tt(e),c=i.action.scene.raw.actions;c.splice(c.indexOf(i.action.raw),1);let a=r.action.scene.raw.actions;return a.splice(a.indexOf(r.action.raw)+(o==="before"?0:1),0,i.action.raw),z("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),_e(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+Te(e,s)}function gs(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function Pu(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=Cn(t).canonical}catch(o){throw o instanceof Ye?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function qc(e,t){let n=e.assets.find(a=>a.name===t||a.aliases.includes(t)),[o,i]=n?[t,void 0]:yE(t,"\xB7"),r=eE[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=Re(e,o);if(s.t!=="asset"||s.asset.kind!=="actor")throw new Error(`Not an actor: ${t}`);let c={actor_id:s.asset.id};if(i){let a=s.asset.states.find(d=>d.name===i||d.id===i);if(!a)throw new Error(`Unknown state "${i}" on ${s.asset.name}`);c.state_id=a.id}return c}function yE(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function ys(e){return er(String(e.content??""),40)}function Vu(e,t,n,o={}){let i=ms(structuredClone(e.raw)),r=wE(i,t,n,o);return e.raw=i.raw,_e(e),r}function wE(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=Yn("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),z("write",`appending episode ${e.episodes.length+1}`),Ru(e,r,e.episodes.length+1,n,o,!0)}let i=Re(e,t);if(i.t==="scene")return _E(e,i.scene,n,o);if(i.t==="ep")return Ru(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function _E(e,t,n,o){let i=tt(e),r=Du(e,t.raw,t,n,new Set(e.actions.keys()),o);return _e(e),$u(t.anchor,r)+Te(e,i)}function $u(e,t){return`${e}: ${t.total} actions (${t.kept} kept, ${t.created} new, ${t.dropped.length} deleted)`+(t.dropped.length?`
|
|
181
|
-
deleted: ${t.dropped.map(n=>`${n.anchor} ${ys(n.raw)}`).join(`
|
|
182
|
-
`)}`:"")}function Du(e,t,n,o,i,r,s,c){let a=tE(e),{head:d,meta:p,body:l}=ku(o.split(`
|
|
183
|
-
`));if(d){let y=Dc(d,p);t.environment=y.env.space||y.env.time?y.env:void 0,t.environment===void 0&&delete t.environment,t.location=y.location?Fc(e,y.location,"location"):null,t.actors=y.cast.map(E=>Fc(e,E,"actor")),t.props=y.props.map(E=>Fc(e,E,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=c??new Set,m=new Set,g=[],h=0,w=n?n.anchor:"this new scene";for(let y of l){let E=Au(y,a);if(!E)continue;let S=E.anchor?f.get(E.anchor):void 0;if(E.anchor&&!S)throw new Error(`Anchor ${E.anchor} is not in ${w} \u2014 move it with \`move\`, or drop the anchor to create a new action`);if(S&&u.has(S.anchor))throw new Error(`Anchor ${E.anchor} appears twice in ${w} \u2014 drop the anchor from the copy to make it a new action`);let _=S?S.raw:{};!S&&e.version===4&&(_.action_id=Yn("ac",i)),_.type=xo("type",E.type,Tt,ln),_.content=E.content,E.type==="dialogue"||E.type==="inner_thought"?(_.speaker=qc(e,E.speakerName),gs(e,_,E.paren??null)):(delete _.speaker,gs(e,_,null)),Pu(_,E.ts??null),S?(m.add(S.anchor),u.add(S.anchor)):h++,g.push(_)}if(!g.length&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`That would leave ${w} with no actions${n?` (deleting all ${n.actions.length})`:""} \u2014 the body after the \`##\` header is empty; pass --allow-delete if that is the intent`);if(g.length&&!m.size&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`None of the ${g.length} line(s) carry an anchor from ${w}, so all ${n.actions.length} existing action(s) would be replaced by new ids \u2014 \`read --plain\` output cannot be written back; re-read without --plain, or pass --allow-delete to rewrite the scene from scratch`);return t.actions=g,{total:g.length,kept:m.size,created:h,dropped:s?[]:(n?.actions??[]).filter(y=>!m.has(y.anchor))}}function Ru(e,t,n,o,i,r){let s=tt(e),c=r?[]:e.episodes[n-1].scenes,a=new Map;for(let S of c)a.set(S.anchor,S),a.set(S.id,S);let d=[];for(let S of o.split(`
|
|
184
|
-
`))S.startsWith("##")?d.push(S):d.length&&(d[d.length-1]+=`
|
|
185
|
-
`+S);if(!d.length)throw new Error("No scene headers found \u2014 an episode body needs `## \u2026` lines");let p=new Set(e.actions.keys()),l=new Set(e.scenes.keys()),f=new Map;for(let S of c)for(let _ of S.actions)f.set(_.anchor,_);let u=new Set,m=new Set,g=[],h=[],w=0;for(let S of d){let _=Dc(S.split(`
|
|
186
|
-
`)[0]),A=_.anchor?a.get(_.anchor):void 0;if(_.anchor&&!A)throw new Error(`Scene ${_.anchor} is not in episode ${n} \u2014 drop the id from the header to create a new scene here`);let k=A?A.raw:{};A?m.add(A.anchor):(e.version===4?k.scene_id=Yn("scn",l):k.scene_id=`scn_${String(c.length+w+1).padStart(3,"0")}`,w++);let D=Du(e,k,A??null,S,p,i,f,u);g.push(k),h.push($u(A?A.anchor:`new ${k.scene_id}`,D))}let y=[...f.values()].filter(S=>!u.has(S.anchor));if(y.length&&!i.allowDelete)throw new Error(`This would delete ${y.length} action(s) from episode ${n}: `+y.slice(0,6).map(S=>`${S.anchor}(${S.scene.anchor})`).join(", ")+(y.length>6?" \u2026":"")+" \u2014 keep their lines, or pass --allow-delete if that is the intent");let E=c.filter(S=>!m.has(S.anchor));if(E.length&&!i.allowDelete)throw new Error(`This would delete ${E.length} whole scene(s) from episode ${n}: `+E.map(S=>`${S.anchor}(${S.actions.length} actions)`).join(", ")+" \u2014 include their `##` headers to keep them, or pass --allow-delete if that is the intent");return z("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${E.length} deleted`),t.scenes=g,_e(e),`EP${n}: ${g.length} scenes (${g.length-w} kept, ${w} new, ${E.length} deleted, ${y.length} actions deleted)
|
|
187
|
-
`+h.map(S=>" "+S.replace(/\n/g,`
|
|
188
|
-
`)).join(`
|
|
189
|
-
`)+(E.length?`
|
|
190
|
-
deleted scenes: ${E.map(S=>S.anchor).join(", ")}`:"")+Te(e,s)}function Fc(e,t,n){let{name:o,states:i}=bu(t),r=Re(e,o);if(r.t!=="asset"||r.asset.kind!==n)throw new Error(`"${o}" is not a registered ${n} \u2014 create it with \`asset\` first`);let s=(i.length?i:["default"]).map(d=>{let p=r.asset.states.filter(l=>l.name===d||l.id===d);if(!p.length)throw new Error(`${r.asset.name} has no state "${d}" (has: ${r.asset.states.map(l=>l.name).join(", ")})`);if(p.length>1)throw new Error(`${r.asset.name} has ${p.length} states named "${d}"; use the state id`);return p[0].id}),c=[...new Set(s)].sort(),a=`${n}_id`;return e.version===4?{[a]:r.asset.id,state_ids:c}:{[a]:r.asset.id,state_id:c[0]}}function Gu(e,t,n,o,i=!1){let r=Re(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,c=Re(e,n);if(c.t!=="asset")throw new Error(`${n} is a ${c.t}; ref takes an actor, location or prop`);let a=c.asset,d=a.kind==="actor"?"actors":a.kind==="prop"?"props":"location",p=tt(e);if(i){if(a.kind==="location"){if(s.location?.id!==a.id)throw new Error(`${s.anchor}'s location is ${s.location?_o(e,s.location.id):"empty"}, not ${a.name}`);s.raw.location=null}else{let g=s.raw[d],h=g.findIndex(w=>w[`${a.kind}_id`]===a.id);if(h<0)throw new Error(`${s.anchor} does not reference ${a.name}`);g.splice(h,1)}return z("ref",`${s.anchor} -= ${a.id}`),_e(e),`${s.anchor} removed ${a.name}`+Te(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${a.name} (has: ${a.states.map(g=>g.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(g=>{let h=a.states.filter(w=>w.name===g||w.id===g);if(!h.length)throw new Error(`${a.name} has no state "${g}" (has: ${a.states.map(w=>w.name).join(", ")})`);if(h.length>1)throw new Error(`${a.name} has ${h.length} states named "${g}"; use the state id`);return h[0].id}))].sort(),f=`${a.kind}_id`,u=e.version===4?{[f]:a.id,state_ids:l}:{[f]:a.id,state_id:l[0]};if(e.version===3&&l.length>1)throw new Error("Script v3 holds one state per reference; pass a single state");let m;if(a.kind==="location")m=s.location?s.location.id===a.id?"restated":"replaced":"set",s.raw.location=u;else{let g=s.raw[d],h=g.findIndex(w=>w[f]===a.id);h<0?(g.push(u),m="added"):(g[h]=u,m="restated")}return z("ref",`${s.anchor} ${m} ${a.id} = [${l.join(", ")}]`),_e(e),`${s.anchor} ${m} ${a.name}(${l.map(g=>Eo(e,a.id,g)).join("+")})`+Te(e,p)}function Ju(e,t,n,o={}){if(!t)throw new Error("replace needs a pattern; an empty one would rewrite every action");let i=new RegExp(t,"gu"),r=tt(e),s=Qc(e,o),c=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(z("replace",`/${t}/ matched ${c.length} of ${s.length} actions in scope`),!c.length)return`0 hits for /${t}/ \u2014 nothing to do`;let a=Math.max(...c.map(p=>p.anchor.length)),d=c.map(p=>{let l=p.content.replace(i,n);return`${p.anchor.padEnd(a)} ${p.scene.ep.no}-${p.scene.no}-${p.no}
|
|
191
|
-
${" ".repeat(a)} - ${p.content}
|
|
192
|
-
${" ".repeat(a)} + ${l}`});if(!o.apply)return`${c.length} action(s) would change (dry run \u2014 pass apply to write)
|
|
193
|
-
`+d.join(`
|
|
194
|
-
`);for(let p of c)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return _e(e),z("replace",`wrote ${c.length} actions`),`${c.length} action(s) changed`+Te(e,r)+`
|
|
195
|
-
`+d.join(`
|
|
196
|
-
`)}function xo(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function Bu(e){return xo("importance",e,Et,fn)}function Xo(e){return e.version===4?Ue(e.raw):at(e.raw)}function Ku(e){let t=Xo(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${Qn(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...Zc([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
|
|
197
|
-
`)}function Wc(e,t={}){let n=Xo(e),o=[...n.errors.map(i=>["error",i]),...n.warnings.map(i=>["warning",i])];return t.severity&&(o=o.filter(([i])=>i===t.severity)),t.code&&(o=o.filter(([,i])=>i.code===t.code)),z("issues",`${o.length} matching issue(s)`),o.length?Zc(o).join(`
|
|
198
|
-
`):"No issues."}function Zc(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
|
|
199
|
-
fix: ${n.repair_hint}`:""))}function tt(e){return Xo(e)}function Te(e,t){let n=Xo(e),o=[...Ea(t.errors,n.errors).map(i=>["error",i]),...Ea(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(z("check",`${o.length} issue(s) introduced by this edit`),`
|
|
200
|
-
introduced ${o.length} issue(s):
|
|
201
|
-
`+Zc(o).join(`
|
|
202
|
-
`)):""}var Xc={actor:"actors",location:"locations",prop:"props"},Nu={actor:"act",location:"loc",prop:"prp"};function ju(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=tt(e),c=e.assets.find(l=>l.name===n||l.aliases.includes(n));if(c)throw new Error(`"${n}" already names ${c.kind} ${c.id}; read it instead`);let a=Xc[t],d=e.version===4?Yn(Nu[t],new Set(e.assets.map(l=>l.id))):`${Nu[t]}_${String(e.raw[a].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:Bu(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[a].push(p),z("asset",`${t} ${d} "${n}" + default state`),_e(e),`${d} ${n} ${t} states: default`+Te(e,s)}function zu(e,t,n,o){let i=Re(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=tt(e);if(i.asset.states.some(c=>c.name===n))throw new Error(`${i.asset.name} already has a state named "${n}"`);let s=e.version===4?Yn("st",new Set(i.asset.states.map(c=>c.id))):`st_${String(i.asset.states.length).padStart(3,"0")}`;return i.asset.raw.states.push({state_id:s,state_name:n,description:o}),z("state",`${i.asset.id} + ${s} "${n}"`),_e(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+Te(e,r)}function EE(e,t){let n=Re(e,t);switch(n.t){case"script":return{raw:n.doc.raw,label:"script"};case"ep":return{raw:n.ep.raw,label:n.ep.id};case"scene":return{raw:n.scene.raw,label:n.scene.anchor};case"action":return{raw:n.action.raw,label:n.action.anchor};case"asset":return{raw:n.asset.raw,label:n.asset.id};case"state":return{raw:n.asset.raw.states.find(i=>i.state_id===n.state.id),label:`${n.asset.id}/${n.state.id}`}}}function Hu(e,t,n,o,i=!1){let{raw:r,label:s}=EE(e,t),c=r.extend??{};if(!n){let a=Object.keys(c);return a.length?`${s} extend:
|
|
203
|
-
`+a.map(d=>` ${d} = ${JSON.stringify(c[d])}`).join(`
|
|
204
|
-
`):`${s} has no extend data`}if(i){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return delete c[n],Object.keys(c).length?r.extend=c:delete r.extend,z("ext",`${s} -= ${n}`),_e(e),`${s} removed extend.${n}`}if(o===void 0){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return`${s} extend.${n} = ${JSON.stringify(c[n])}`}return r.extend={...c,[n]:o},z("ext",`${s} extend.${n} = ${o}`),_e(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function Fu(e,t,n={}){let o=Re(e,t),i=tt(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),z("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),_e(e),`deleted ${o.action.anchor} ${ys(o.action.raw)}`+Te(e,i)}if(o.t==="scene"){if(o.scene.actions.length&&!n.force)throw new Error(`${o.scene.anchor} still holds ${o.scene.actions.length} action(s) \u2014 pass --force to delete the scene and everything in it`);let r=o.scene.ep.raw.scenes;return r.splice(r.indexOf(o.scene.raw),1),z("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),_e(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+Te(e,i)}if(o.t==="ep"){let r=o.ep.scenes.reduce((c,a)=>c+a.actions.length,0);if(o.ep.scenes.length&&!n.force)throw new Error(`episode ${o.ep.no} still holds ${o.ep.scenes.length} scene(s) / ${r} action(s) \u2014 pass --force to delete the episode and everything in it`);let s=e.raw.episodes;return s.splice(s.indexOf(o.ep.raw),1),z("del",`episode ${o.ep.no}`),_e(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return xE(e,o.asset,n)+Te(e,i);if(o.t==="state")return SE(e,o.asset,o.state,n)+Te(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function Qu(e,t){let n=[];for(let o of e.episodes)for(let i of o.scenes)[i.location,...i.actors,...i.props].some(r=>r&&r.id===t)&&n.push(i);return{scenes:n,speakers:Qn(e).filter(o=>o.speaker?.id===t)}}function xE(e,t,n){let{scenes:o,speakers:i}=Qu(e,t.id),r=o.length+i.length;if(r&&!n.replacement&&!n.force)throw new Error(`${t.name} is still referenced by ${o.length} scene(s) and ${i.length} speaker(s) \u2014 merge it into another asset with \`merge ${t.id} <other>\`, or pass --force to strip every reference`);if(n.replacement)return ed(e,t.id,n.replacement);for(let a of o){a.raw.location?.[`${t.kind}_id`]===t.id&&(a.raw.location=null);for(let d of["actors","props"]){let p=a.raw[d];if(!p)continue;let l=p.findIndex(f=>f[`${t.kind}_id`]===t.id);l>=0&&p.splice(l,1)}}for(let a of i)delete a.raw.speaker;let s=Xc[t.kind],c=e.raw[s];return c.splice(c.indexOf(t.raw),1),z("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),_e(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
|
|
205
|
-
stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function SE(e,t,n,o){if(n.id==="default")throw new Error("every asset keeps its default state; delete the asset instead");let i=e.episodes.flatMap(d=>d.scenes).filter(d=>[d.location,...d.actors,...d.props].some(p=>p&&p.id===t.id&&p.states.includes(n.id))),r=Qn(e).filter(d=>d.speaker?.id===t.id&&d.speaker.state===n.id),s=i.length+r.length,c="";if(s){if(!o.replacement&&!o.force)throw new Error(`${t.name}/${n.name} is bound in ${i.length} scene(s) and named by ${r.length} speaker(s) \u2014 pass --replacement <state> to rewire them, or --force to drop the bindings`);let d;if(o.replacement){let p=t.states.filter(l=>l.id===o.replacement||l.name===o.replacement);if(p.length!==1)throw new Error(`${t.name} has no single state "${o.replacement}"`);if(p[0].id===n.id)throw new Error("replacement must differ from the state being deleted");d=p[0].id}for(let p of i)for(let l of[p.raw.location,...p.raw.actors??[],...p.raw.props??[]])if(!(!l||l[`${t.kind}_id`]!==t.id))if(e.version===4){let f=new Set(l.state_ids.filter(u=>u!==n.id));d&&f.add(d),f.size||f.add("default"),l.state_ids=[...f].sort()}else l.state_id=d??"default";for(let p of r)d?p.raw.speaker.state_id=d:delete p.raw.speaker.state_id;c=`
|
|
206
|
-
${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${Eo(e,t.id,d)}`:""}`}let a=t.raw.states;return a.splice(a.findIndex(d=>d.state_id===n.id),1),z("del",`state ${t.id}/${n.id}`),_e(e),`deleted state ${t.id}/${n.id} ${n.name}`+c}function ed(e,t,n){let o=Re(e,t),i=Re(e,n);if(o.t!=="asset"||i.t!=="asset")throw new Error("merge takes two assets");if(o.asset===i.asset)throw new Error(`cannot merge ${o.asset.name} into itself`);if(o.asset.kind!==i.asset.kind)throw new Error(`cannot merge a ${o.asset.kind} into a ${i.asset.kind}`);let r=tt(e),s=o.asset,c=i.asset,a=`${s.kind}_id`,d=new Set(c.states.map(m=>m.id)),p=new Map;for(let m of s.states){let g=c.states.find(w=>w.name===m.name);if(g){p.set(m.id,g.id);continue}if(m.id==="default"){p.set(m.id,"default");continue}let h=e.version===4?Yn("st",d):`st_${String(c.states.length+p.size).padStart(3,"0")}`;c.raw.states.push({state_id:h,state_name:m.name,description:m.desc}),p.set(m.id,h)}let{scenes:l,speakers:f}=Qu(e,s.id);for(let m of l)for(let g of["location","actors","props"]){let h=m.raw[g],w=g==="location"?h?[h]:[]:h??[];for(let y of w)y[a]===s.id&&(y[a]=c.id,e.version===4?y.state_ids=[...new Set(y.state_ids.map(E=>p.get(E)??"default"))].sort():y.state_id=p.get(y.state_id)??"default");if(g!=="location"&&Array.isArray(h)){let y=[];for(let E of h){let S=y.find(_=>_[a]===E[a]);if(!S){y.push(E);continue}e.version===4&&(S.state_ids=[...new Set([...S.state_ids,...E.state_ids])].sort())}m.raw[g]=y}}for(let m of f)m.raw.speaker.actor_id=c.id,m.raw.speaker.state_id&&(m.raw.speaker.state_id=p.get(m.raw.speaker.state_id)??"default");let u=e.raw[Xc[s.kind]];return u.splice(u.indexOf(s.raw),1),z("merge",`${s.id} -> ${c.id}: ${l.length} scenes, ${f.length} speakers`),_e(e),`merged ${s.id} ${s.name} into ${c.id} ${c.name}
|
|
207
|
-
moved ${l.length} scene reference(s), ${f.length} speaker(s), ${[...p].filter(([m,g])=>m!==g).length} state mapping(s)`+Te(e,r)}var qn="\u5730\u5740\uFF1A\u96C6 `3`\u3001\u573A `3-2`\u3001\u5355\u6761 `3-2-5`\u3001\u6B63\u5F0F ID\u3001\u8D44\u4EA7\u540D\u3001\u6216 `<\u8D44\u4EA7>/<\u72B6\u6001>`";function Pe(e){let t=xe(e);if(!Yu.existsSync(t))throw new x("Local script file not found.",{exitCode:b,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[t]}});return Pc(t)}function le(e,t){let n=e[t];return typeof n=="string"?n:void 0}function So(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new x(`--${t} must be a number.`,{exitCode:b,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function ue(e,t=0){return(e._args??[])[t]??""}function td(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function qe(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},J]}catch(o){throw o instanceof x?o:new x(o instanceof Error?o.message:String(o),{exitCode:b,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function qu(e,t){let n=se(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${qn}`).option("--outline","\u53EA\u8981\u573A\u7ED3\u6784\uFF0C\u4E0D\u8981\u6B63\u6587").option("--context <n>","\u5355\u6761 action \u524D\u540E\u5404\u5E26\u51E0\u6761\uFF08\u9ED8\u8BA4 3\uFF09").option("--plain","\u53BB\u6389\u951A\u70B9\u4E0E\u65F6\u95F4\u6233\uFF08\u53EA\u8BFB\uFF0C\u4E0D\u53EF\u56DE\u5199\uFF09").action(Y(y=>{let E=Pe(y);return qe(()=>hs(E,ue(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...So(y,"context")!==void 0?{context:So(y,"context")}:{}}),"read",()=>ue(y)?{}:{document:E.raw})},t));Ie(n,[qn]);let o=se(e.command("scan <episode>"),"read").description("\u4E00\u6B21\u8FD4\u56DE\u67D0\u96C6\u7684\u5B8C\u6574\u4E0A\u4E0B\u6587\uFF1A\u573A\u7ED3\u6784 + \u5168\u90E8\u6B63\u6587 + \u5F53\u524D\u6821\u9A8C\u95EE\u9898").action(Y(y=>qe(()=>{let E=Pe(y),S=ue(y);return[`## \u573A\u7ED3\u6784
|
|
208
|
-
${hs(E,S,{depth:"outline"})}`,`## \u6B63\u6587
|
|
209
|
-
${hs(E,S)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
|
|
210
|
-
${Wc(E,{})}`].join(`
|
|
211
|
-
|
|
212
|
-
`)},"scan"),t));Ie(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=se(e.command("find [query]"),"read").description("\u6309\u6B63\u6587\u6B63\u5219 / \u8BF4\u8BDD\u4EBA / \u7C7B\u578B\u5B9A\u4F4D action\uFF0C\u8FD4\u56DE\u951A\u70B9 + \u547D\u4E2D\u7A97\u53E3").option("-i, --in <addr>",`\u9650\u5236\u8303\u56F4\uFF0C${qn}`).option("-a, --speaker <name>","\u4EBA\u7269\u540D\u6216 actor id").option("-t, --type <type>","action | dialogue | inner_thought | transition").option("--limit <n>","\u6700\u591A\u8FD4\u56DE\u51E0\u6761\uFF08\u9ED8\u8BA4 40\uFF09").option("--full","\u8FD4\u56DE\u6574\u6761\u6B63\u6587\u800C\u4E0D\u662F\u547D\u4E2D\u7A97\u53E3").action(Y(y=>qe(()=>Mu(Pe(y),ue(y),{...le(y,"in")?{in:le(y,"in")}:{},...le(y,"speaker")?{speaker:le(y,"speaker")}:{},...le(y,"type")?{type:le(y,"type")}:{},...So(y,"limit")!==void 0?{limit:So(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Ie(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=se(e.command("refs <addr>"),"read").description("\u53EA\u8BFB\u5B9A\u4F4D\u8D44\u4EA7/\u9020\u578B\u7684\u573A\u666F\u7ED1\u5B9A\u3001\u8BF4\u8BDD\u5F15\u7528\u548C\u6B63\u6587\u63D0\u53CA\uFF0C\u8FD4\u56DE\u53EF read \u7684\u5730\u5740\u53CA\u4E0A\u4E0B\u6587").option("--offset <n>","\u4ECE\u7B2C\u51E0\u6761\u5F15\u7528\u7EE7\u7EED\uFF08\u4ECE 0 \u5F00\u59CB\uFF09").option("--limit <n>","\u672C\u6279\u5F15\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09").option("--context <n>","\u6B63\u6587\u547D\u4E2D\u524D\u540E\u5404\u51E0\u6761 action\uFF08\u9ED8\u8BA4 3\uFF09").action(Y(y=>{let E=zc(Pe(y),ue(y),{offset:So(y,"offset"),limit:So(y,"limit"),context:So(y,"context")});return[{text:Hc(E),data:{op:"refs",changed:!1,...E}},J]},t));Ie(r,["\u4EBA\u7269/\u573A\u666F/\u9053\u5177 ID \u6216\u540D\u79F0\uFF0C\u6216 <\u8D44\u4EA7>/<\u9020\u578B>\uFF1B\u6B63\u6587\u63D0\u53CA\u4E0D\u7B49\u4E8E\u5B9E\u9645\u51FA\u573A"]);let s=se(e.command("span <range>"),"read").description("\u628A\u4E00\u6BB5 action \u6362\u7B97\u6210\u96C6\u5185\u89C6\u9891\u65F6\u95F4\u7A97\u53E3\uFF08\u534A\u5F00\u533A\u95F4\uFF09").action(Y(y=>{let E=Pe(y);return qe(()=>Lu(E,ue(y)),"span",()=>({rows:[Yc(E,ue(y))]}))},t));Ie(s,[`${qn}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),se(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(Y(y=>{let E=Pe(y),S=Xo(E);return[{text:Ku(E),data:{op:"script.validate",changed:!1,passed:S.ok,script_path:E.path,stats:{actors:E.assets.filter(_=>_.kind==="actor").length,locations:E.assets.filter(_=>_.kind==="location").length,props:E.assets.filter(_=>_.kind==="prop").length,episodes:E.episodes.length,scenes:E.episodes.reduce((_,A)=>_+A.scenes.length,0),actions:Qn(E).length},issues:[...S.errors.map(_=>({..._,severity:"error"})),...S.warnings.map(_=>({..._,severity:"warning"}))]}},S.ok?J:Ln]},t)),se(e.command("issues"),"read").description("\u5217\u5F53\u524D\u6821\u9A8C\u95EE\u9898").option("--severity <severity>","error | warning").option("--code <code>","\u6309 issue code \u8FC7\u6EE4").action(Y(y=>qe(()=>Wc(Pe(y),{...le(y,"severity")?{severity:le(y,"severity")}:{},...le(y,"code")?{code:le(y,"code")}:{}}),"issues"),t));let c=se(e.command("edit <addr>"),"write").description(`\u6539\u4E00\u4E2A\u8282\u70B9\u7684\u5B57\u6BB5\uFF1B\u5730\u5740\u51B3\u5B9A\u54EA\u4E9B\u5B57\u6BB5\u5408\u6CD5\u3002${qn}`).option("--content <text>","action \u6B63\u6587").option("--paren <text>","\u8868\u6F14\u63D0\u793A").option("--no-paren","\u5220\u9664\u8868\u6F14\u63D0\u793A\u5B57\u6BB5").option("--speaker <name>","\u4EBA\u7269\u540D\u6216 `\u540D\u5B57\xB7\u72B6\u6001`\uFF1B\u65C1\u767D/\u5E7F\u64AD/\u753B\u5916/\u7FA4\u58F0\u4EA6\u53EF").option("--ts <time>","\u65F6\u95F4\u6233").option("--no-ts","\u5220\u9664\u65F6\u95F4\u6233").option("--type <type>","action | dialogue | inner_thought | transition").option("--transition <spec>","\u8F6C\u573A\u63D0\u793A `\u76EE\u6807|\u8FC7\u7A0B|\u5BF9\u6BD4`").option("--no-transition","\u5220\u9664\u8F6C\u573A\u63D0\u793A").option("--name <text>","\u8D44\u4EA7 / \u72B6\u6001\u540D").option("--desc <text>","\u8D44\u4EA7 / \u72B6\u6001\u63CF\u8FF0").option("--importance <tier>","featured | background").option("--role <type>","\u4E3B\u89D2 | \u914D\u89D2").option("--alias <list>","\u8D44\u4EA7\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").option("--space <space>","\u573A\uFF1Ainterior | exterior").option("--time <time>","\u573A\uFF1Aday | night | dawn | dusk").option("--title <text>","\u96C6 / \u5267\u672C\u6807\u9898").option("--synopsis <text>","\u96C6 / \u5267\u672C\u6897\u6982").option("--logline <text>","\u5267\u672C logline").option("--theme <text>","\u5267\u672C\u4E3B\u9898").option("--worldview <text>","\u5267\u672C\u4E16\u754C\u89C2").option("--style <text>","\u5267\u672C\u98CE\u683C").option("--main <list>","\u4E3B\u8981\u4EBA\u7269 `\u540D\u5B57=\u5B9A\u4F4D,\u2026`").action(Y(y=>{let E={};for(let S of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let _=le(y,S);_!==void 0&&(E[S]=_)}for(let S of["paren","ts","transition"])if(y[S]===!1)E[S]=null;else{let _=le(y,S);_!==void 0&&(E[S]=_)}return y.alias!==void 0&&(E.aliases=td(y.alias)),qe(()=>Uu(Pe(y),ue(y),E),"edit")},t));Ie(c,[qn]);let a=se(e.command("insert <addr> <content>"),"write").description("\u5728\u67D0\u6761 action \u524D/\u540E\u63D2\u5165\u4E00\u6761\u65B0 action").requiredOption("-t, --type <type>","action | dialogue | inner_thought | transition").option("--before","\u63D2\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").option("-a, --speaker <name>","dialogue / inner_thought \u5FC5\u586B").option("--paren <text>","\u8868\u6F14\u63D0\u793A").action(Y(y=>qe(()=>Tu(Pe(y),ue(y),y.before?"before":"after",le(y,"type"),ue(y,1),le(y,"speaker"),le(y,"paren")),"insert"),t));Ie(a,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=se(e.command("move <addr> <to>"),"write").description("\u628A\u4E00\u6761 action \u632A\u5230\u53E6\u4E00\u6761\u65C1\u8FB9\uFF1B\u8DE8\u573A\u4E5F\u4FDD\u6301 action_id").option("--before","\u632A\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").action(Y(y=>qe(()=>Cu(Pe(y),ue(y),ue(y,1),y.before?"before":"after"),"move"),t));Ie(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=se(e.command("write <addr>"),"write").description("\u7528 read \u8F93\u51FA\u7684\u540C\u4E00\u4EFD\u6B63\u6587\u683C\u5F0F\u56DE\u5199\u6574\u573A / \u6574\u96C6 / \u65B0\u96C6\uFF08`+`\uFF09").option("-f, --file <path>","\u6B63\u6587\u6587\u4EF6\uFF1B\u7701\u7565\u5219\u8BFB stdin").option("--allow-delete","\u5141\u8BB8\u5220\u9664\u6587\u672C\u91CC\u6D88\u5931\u7684\u573A / action").action(Y(async y=>{let E=await import("node:fs"),S=le(y,"file"),_=S?E.readFileSync(S,"utf8"):E.readFileSync(0,"utf8");return qe(()=>Vu(Pe(y),ue(y),_,{allowDelete:!!y.allow_delete}),"write")},t));Ie(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=se(e.command("replace <pattern> <to>"),"write").description("\u6279\u91CF\u66FF\u6362\u6B63\u6587\uFF1B\u9ED8\u8BA4\u53EA\u9884\u89C8\uFF0C--apply \u624D\u843D\u76D8\u3002\u8FC7\u6EE4\u53C2\u6570\u4E0E find \u76F8\u540C").option("-i, --in <addr>","\u9650\u5236\u8303\u56F4").option("-a, --speaker <name>","\u9650\u5B9A\u8BF4\u8BDD\u4EBA").option("-t, --type <type>","\u9650\u5B9A action \u7C7B\u578B").option("--apply","\u771F\u7684\u5199\u5165").action(Y(y=>qe(()=>Ju(Pe(y),ue(y),ue(y,1),{...le(y,"in")?{in:le(y,"in")}:{},...le(y,"speaker")?{speaker:le(y,"speaker")}:{},...le(y,"type")?{type:le(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Ie(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=se(e.command("ref <scene> <asset>"),"write").description("\u6539\u4E00\u4E2A\u573A\u5BF9\u67D0\u8D44\u4EA7\u7684\u5F15\u7528\uFF1B--state \u662F\u5B8C\u6574\u72B6\u6001\u96C6\u5408\u800C\u975E\u8FFD\u52A0").option("--state <list>","\u5B8C\u6574\u72B6\u6001\u96C6\u5408\uFF08\u540D\u5B57\u6216 ID\uFF09\uFF0C\u9017\u53F7\u5206\u9694\u6216\u91CD\u590D\u7ED9\u51FA",AE,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(Y(y=>qe(()=>Gu(Pe(y),ue(y),ue(y,1),td(y.state).flatMap(E=>E.split(",")).map(E=>E.trim()).filter(Boolean),!!y.remove),"ref"),t));Ie(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=se(e.command("asset <kind> <name>"),"write").description("\u767B\u8BB0\u4E00\u4E2A\u65B0\u7684 actor / location / prop").requiredOption("--desc <text>","\u63CF\u8FF0").option("--importance <tier>","featured | background","featured").option("--alias <list>","\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").action(Y(y=>qe(()=>ju(Pe(y),ue(y),ue(y,1),le(y,"desc")??"",le(y,"importance")??"featured",td(y.alias)),"asset"),t));Ie(u,["actor | location | prop","\u540D\u5B57"]);let m=se(e.command("state <asset> <name>"),"write").description("\u7ED9\u5DF2\u6709\u8D44\u4EA7\u52A0\u4E00\u4E2A\u72B6\u6001\uFF08\u9020\u578B\u6863\u4F4D\uFF09").requiredOption("--desc <text>","\u63CF\u8FF0").action(Y(y=>qe(()=>zu(Pe(y),ue(y),ue(y,1),le(y,"desc")??""),"state"),t));Ie(m,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let g=se(e.command("del <addr>"),"write").description("\u5220\u9664 action / \u573A / \u96C6 / \u8D44\u4EA7 / \u72B6\u6001").option("--replacement <state>","\u5220\u72B6\u6001\u65F6\u628A\u5F15\u7528\u6539\u5199\u5230\u8FD9\u4E2A\u72B6\u6001").option("--force","\u5BB9\u5668\u975E\u7A7A\u65F6\u4ECD\u7136\u5220\u9664").action(Y(y=>qe(()=>Fu(Pe(y),ue(y),{...le(y,"replacement")?{replacement:le(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Ie(g,[qn]);let h=se(e.command("merge <src> <dst>"),"write").description("\u628A\u4E00\u4E2A\u8D44\u4EA7\u5E76\u5165\u53E6\u4E00\u4E2A\uFF1A\u5168\u90E8\u573A\u666F\u5F15\u7528\u4E0E speaker \u6539\u5199\u8FC7\u53BB").action(Y(y=>qe(()=>ed(Pe(y),ue(y),ue(y,1)),"merge"),t));Ie(h,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=se(e.command("ext <addr> [key] [value]"),"write").description("\u8BFB\u6216\u5199\u4EFB\u610F\u8282\u70B9\u7684 extend \u6570\u636E").option("--remove","\u5220\u9664\u8BE5 key").action(Y(y=>qe(()=>Hu(Pe(y),ue(y),ue(y,1)||void 0,ue(y,2)||void 0,!!y.remove),"ext"),t));Ie(w,[qn,"extend key","\u503C"])}function AE(e,t){return[...t,e]}import*as pg from"node:path";import*as _s from"node:fs";import*as Es from"node:path";var kE=[".txt",".md",".docx"],nd={".mp4":"video/mp4",".mov":"video/mov",".avi":"video/avi",".mpeg":"video/mpeg",".mpg":"video/mpg",".webm":"video/webm",".flv":"video/x-flv",".wmv":"video/wmv"},ws=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function Wu(e){return Es.extname(e).toLowerCase()}function Zu(e){return Object.hasOwn(nd,e)}function Wn(e){if(_s.statSync(e).isDirectory()){let o=_s.readdirSync(e).filter(i=>!i.startsWith(".")).filter(i=>Zu(Wu(i))).sort().map(i=>Es.join(e,i));if(o.length===0)throw new ws(`directory has no supported video files: ${e}`);return{kind:"video-directory",path:e,files:o}}let n=Wu(e);if(kE.includes(n))return{kind:"text",path:e,ext:n};if(Zu(n))return{kind:"video-file",path:e,ext:n};throw new ws(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video only)`)}var kn={createExecutor:fu};import*as Md from"node:fs";import*as ci from"node:path";var sn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var nr=e=>String(e).padStart(3,"0"),od=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function Xu(e,t={}){let n=[],o=[],i=null,r=null,s=0,c=0,a=new Map,d=(l,f)=>{let u=`text:${l}:${f.chunk}:${f.line_start}:${f.line_end}`,m=(a.get(u)??0)+1;return a.set(u,m),`${u}:${m}`},p=(l,f)=>{let u=l.actors.find(m=>od(m.name)===od(f.name));u?f.state&&!u.state&&(u.state=f.state):l.actors.push(f)};for(let l of e)switch(l.kind){case"episode":{s++,i={identity_key:d("episode",l.source),episode_id:`ep_${nr(s)}`,scenes:[]},l.title!==void 0&&(i.title=l.title),n.push(i),r=null;break}case"scene":{i||(s++,i={identity_key:d("synthetic-episode",l.source),episode_id:`ep_${nr(s)}`,scenes:[]},n.push(i)),c++,r={identity_key:d("scene",l.source),scene_id:`scn_${nr(c)}`,location:l.location?{...l.location}:null,actors:(l.actors??[]).map(f=>({...f})),props:(l.props??[]).map(f=>({...f})),actions:[]},l.environment&&(r.environment=l.environment),i.scenes.push(r);break}case"note":o.push({content:l.content,...l.category?{category:l.category}:{},source:l.source});break;case"action":case"transition":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}r.actions.push({identity_key:d(l.kind,l.source),type:l.kind,content:l.content});break}case"dialogue":case"inner_thought":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}let f={identity_key:d(l.kind,l.source),type:l.kind,content:l.content,speaker:l.speaker};l.emotion!==void 0&&(f.emotion=l.emotion),r.actions.push(f),"name"in l.speaker&&p(r,l.speaker.state!==void 0?{name:l.speaker.name,state:l.speaker.state}:{name:l.speaker.name});break}}return{script:{title:t.title??"",episodes:n},notes:o}}var or=class{constructor(t,n,o){this.prefix=t;this.kind=n;this.nextStateId=o}prefix;kind;nextStateId;byNorm=new Map;order=[];ensure(t,n){let o=od(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${nr(this.order.length+1)}`,kind:this.kind,names:[],states:[],occurrences:[]},this.byNorm.set(o,i),this.order.push(i)),i.names.includes(t)||i.names.push(t),i.occurrences.push(n),i}stateId(t,n){let o=sn(n),i=t.states.find(s=>sn(s.name)===o);if(i)return i.id;let r=this.nextStateId();return t.states.push({name:n,id:r}),r}list(){return this.order}};function bE(e){let t=[{state_id:"default",state_name:"default",description:""}];for(let n of e.states)t.push({state_id:n.id,state_name:n.name,description:""});return t}function xs(e){let t=0,n=()=>`st_${nr(++t)}`,o=new or("act","actor",n),i=new or("loc","location",n),r=new or("prp","prop",n),s={episode:{},scene:{},action:{}},c={episode:new Set,scene:new Set,action:new Set},a=(u,m,g)=>{if(!g||c[u].has(g))throw new Error(`Duplicate or missing ${u} source identity: ${g}`);c[u].add(g),s[u][m]=g},d=(u,m,g,h)=>{let w=u.ensure(m.name,g),y={[h]:w.provisional_id};return m.state!==void 0&&(y.state_id=u.stateId(w,m.state)),y},p=e.episodes.map((u,m)=>(a("episode",u.episode_id,u.identity_key),{episode_id:u.episode_id,...u.title?{title:u.title}:{},scenes:u.scenes.map((g,h)=>{let w=`${u.episode_id}/${g.scene_id}`;a("scene",w,g.identity_key);let y={episode:m,scene:h},E=g.location?d(i,g.location,y,"location_id"):null,S=g.actors.map(k=>d(o,k,y,"actor_id")),_=g.props.map(k=>d(r,k,y,"prop_id")),A=g.actions.map((k,D)=>{a("action",`${w}#${D}`,k.identity_key);let R={type:k.type,content:k.content};if(k.speaker)if("name"in k.speaker){let I=o.ensure(k.speaker.name,y),M={actor_id:I.provisional_id};k.speaker.state!==void 0&&(M.state_id=o.stateId(I,k.speaker.state)),R.speaker=M}else R.speaker=k.speaker.label!==void 0?{kind:k.speaker.kind,label:k.speaker.label}:{kind:k.speaker.kind};return(k.type==="dialogue"||k.type==="inner_thought")&&(k.parenthetical!==void 0?R.emotion=k.parenthetical:k.emotion!==void 0&&(R.emotion=k.emotion)),k.extend!==void 0&&(R.extend=k.extend),R});return{scene_id:g.scene_id,...g.environment?{environment:g.environment}:{},location:E,actors:S,props:_,actions:A}})})),l=(u,m,g)=>u.list().map(h=>({[m]:h.provisional_id,[g]:h.names[0]??h.provisional_id,aliases:h.names.slice(1),description:"",states:bE(h)}));return{script:{version:3,title:e.title,worldview:"",style:"",actors:l(o,"actor_id","actor_name"),locations:l(i,"location_id","location_name"),props:l(r,"prop_id","prop_name"),episodes:p},assets:[...o.list(),...i.list(),...r.list()],identityKeys:s}}function ef(e,t={}){let n=t.maxChars??500,o=e.split(`
|
|
213
|
-
`),i=[],r=0,s=0,c=a=>{let d=o.slice(r,a).join(`
|
|
214
|
-
`);return d.trim()===""?!1:(i.push({index:i.length,core_line_start:r,core_line_end:a,text:d}),r=a,s=0,!0)};for(let a=0;a<o.length;a++){let d=o[a],l=s+(a===r?0:1)+d.length;d.trim()!==""&&a>r&&l>n&&c(a)?s=d.length:s=l}return c(o.length),i}var tf=["episode","scene","action","dialogue","inner_thought","transition","note"];var OE={day:"day",\u65E5:"day",\u767D\u5929:"day",\u65E5\u95F4:"day",\u663C:"day",\u663C\u95F4:"day",night:"night",\u591C:"night",\u591C\u665A:"night",\u591C\u95F4:"night",\u665A:"night",dawn:"dawn",\u6668:"dawn",\u6E05\u6668:"dawn",\u65E9\u6668:"dawn",\u9ECE\u660E:"dawn",\u62C2\u6653:"dawn",dusk:"dusk",\u660F:"dusk",\u9EC4\u660F:"dusk",\u508D\u665A:"dusk",\u65E5\u843D:"dusk"};function ei(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return OE[t]}var me=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function ni(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dt(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new me(`unknown field '${o}'`,n)}function vE(e,t){if(!ni(e))throw new me("missing source",t);Dt(e,["chunk","line_start","line_end"],t);let{chunk:n,line_start:o,line_end:i}=e;if(![n,o,i].every(r=>typeof r=="number"&&Number.isInteger(r)&&r>=0))throw new me("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new me("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function ti(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new me(`'${t}' must be a non-empty string`,n);return o}function Zn(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new me(`'${t}' must be a non-empty string`,n);return o}function nf(e,t,n){if(!Array.isArray(e))throw new me(`'${t}' must be an array`,n);return e.map(o=>{if(!ni(o))throw new me(`'${t}' entries must be objects`,n);Dt(o,["name","state"],n);let i={name:ti(o,"name",n)},r=Zn(o,"state",n);return r!==void 0&&(i.state=r),i})}function RE(e,t){if(!ni(e))throw new me("dialogue/inner_thought needs a speaker",t);if("kind"in e){Dt(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!un.includes(r))throw new me(`speaker.kind must be one of ${un.join("|")}`,t);let s={kind:r},c=Zn(e,"label",t);return c!==void 0&&(s.label=c),s}Dt(e,["name","state"],t);let n=ti(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new me("speaker.name must contain a letter or number",t);let o={name:n},i=Zn(e,"state",t);return i!==void 0&&(o.state=i),o}function NE(e,t){let n=e.kind;if(typeof n!="string"||!tf.includes(n))throw new me(`unknown or missing kind '${String(n)}'`,t);let o=vE(e.source,t);switch(n){case"episode":{Dt(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new me("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=Zn(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{Dt(e,["kind","scene","environment","location","actors","props","source"],t);let i={kind:n,source:o};if("scene"in e&&e.scene!==void 0){if(typeof e.scene!="number"||!Number.isInteger(e.scene))throw new me("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!ni(e.environment))throw new me("environment must be an object",t);Dt(e.environment,["space","time"],t);let r={},s=Zn(e.environment,"space",t);s!==void 0&&(r.space=s);let c=Zn(e.environment,"time",t);if(c!==void 0){let a=ei(c);if(!a)throw new me("environment.time must be day|night|dawn|dusk or a recognized Chinese equivalent",t);r.time=a}i.environment=r}if("location"in e&&e.location!==void 0){if(!ni(e.location))throw new me("location must be an object",t);Dt(e.location,["name","state"],t);let r={name:ti(e.location,"name",t)},s=Zn(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=nf(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=nf(e.props,"props",t)),i}case"action":case"transition":{Dt(e,["kind","content","source"],t);let i=ti(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{Dt(e,["kind","speaker","content","emotion","source"],t);let i=ti(e,"content",t),r=RE(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},c=Zn(e,"emotion",t);return c!==void 0&&(s.emotion=c),s}case"note":{Dt(e,["kind","content","category","source"],t);let i=ti(e,"content",t),r={kind:n,content:i,source:o};if("category"in e&&e.category!==void 0){let s=e.category;if(s!=="author_note"&&s!=="format_note"&&s!=="unclassified")throw new me("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new me(`unhandled kind '${n}'`,t)}}function ir(e,t=0){let n=[],o=e.split(`
|
|
215
|
-
`);for(let i=0;i<o.length;i++){let r=o[i].trim();if(r==="")continue;let s;try{s=JSON.parse(r)}catch{throw new me("invalid JSON",i+1+t)}if(!ni(s))throw new me("record must be a JSON object",i+1+t);n.push(NE(s,i+1+t))}return n}var q=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Io=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},ME=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,rd=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,af=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),cf=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),sd={recentEpisodes:6,synopsisChars:3500,arcFold:10},LE=1e4;function df(e){let t=0,n=0;for(let o of e){n++;let i=o.codePointAt(0);(i>=13312&&i<=40959||i>=12288&&i<=12543||i>=65280&&i<=65519||i>=63744&&i<=64255)&&t++}return Math.round(t*.7+(n-t)*.25)}function pf(e,t=LE){let n=[],o=0,i=0;for(let r=0;r<e.length;r++)r>o&&i+e[r]>t&&(n.push([o+1,r]),o=r,i=0),i+=e[r];return o<e.length&&n.push([o+1,e.length]),n}var UE={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function Ot(e,t){let n=q(t);return e.entities.find(o=>q(o.canonical)===n||o.aliases.some(i=>q(i)===n))}var of=(e,t)=>{q(t)!==q(e.canonical)&&!e.aliases.some(n=>q(n)===q(t))&&e.aliases.push(t)},TE=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function CE(e,t){let n=q(e),o=q(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!TE.some(r=>i===r||i.startsWith(r))}function PE(e){let t=e.filter(n=>e.some(o=>o!==n&&CE(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var rf=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u8DEF\u4EBA","\u884C\u4EBA","\u770B\u5BA2","\u56F4\u89C2\u8005","\u6751\u6C11","\u58EB\u5175","\u767E\u59D3","\u5B66\u751F","\u540C\u5B66","\u4E2B\u9B1F","\u968F\u4ECE","\u4F8D\u536B","\u5BB6\u4E01","\u4EC6\u4EBA","\u4E0B\u4EBA","\u5B69\u5B50","\u8F7F\u592B","\u62A4\u536B","\u624B\u4E0B","\u5C0F\u5F1F","\u55BD\u5570","\u5B98\u5175","\u8859\u5F79","\u592A\u76D1","\u5BAB\u5973","\u5A62\u5973","\u5546\u8D29","\u98DF\u5BA2"],VE=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],$E=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function lt(e){let t=q(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||rf.includes(t)||VE.some(n=>t.endsWith(n))?!0:$E.test(t)&&rf.some(n=>t.endsWith(n)):!1}function Xn(e,t){let n=Io(t);return Ot(e,n)?.canonical??n}function DE(e,t){let n=q(t);return e.looks.find(o=>q(o.name)===n||o.aliases.some(i=>q(i)===n))?.name??t}var GE=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function ad(e){if(e.looks.length!==0)return(e.looks.find(t=>GE.some(n=>t.name.includes(n)))??e.looks[0]).name}function id(e,t,n,o){let i=q(Io(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(q(r.canonical)===i||r.aliases.some(s=>q(s)===i)))}function sf(e){let t=[e.canonical,...e.aliases],n=PE(t);q(n)!==q(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>q(o)!==q(n)))}function rr(e,t,n,o=n){for(let r of t.newEntities){let s=Io(r.name);if(!s)continue;let c=id(e,r.kind,s);if(!c){let d=[];for(let p of r.aliases){let l=Io(p);l&&q(l)!==q(s)&&!id(e,r.kind,l)&&d.push(l)}e.entities.push({kind:r.kind,canonical:s,aliases:[...new Set(d)],description:r.description,looks:[{name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}],lastSeen:o});continue}for(let d of r.aliases){let p=Io(d);p&&!id(e,r.kind,p,c)&&of(c,p)}!c.description&&r.description&&(c.description=r.description);let a=c.looks.find(d=>q(d.name)===q(r.defaultLook.name));a?a.description=r.defaultLook.description:c.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),sf(c)}for(let{from:r,into:s}of t.merges){let c=Io(s);if(!c)continue;let a=Ot(e,c);if(!a)continue;let d=Io(r);!d||q(d)===q(a.canonical)||Ot(e,d)||(of(a,d),sf(a))}for(let{entity:r,names:s,description:c}of t.looks){let a=Ot(e,r);if(!a)continue;let d=s.map(f=>f.trim()).filter(Boolean);if(!d.length)continue;let p=d[0],l=a.looks.find(f=>q(f.name)===q(p)||d.some(u=>f.aliases.some(m=>q(m)===q(u))));if(l){c&&(l.description=c);for(let f of d)q(f)!==q(l.name)&&!l.aliases.some(u=>q(u)===q(f))&&l.aliases.push(f)}else a.looks.push({name:p,aliases:d.slice(1),description:c})}for(let r of t.lookChanges){let s=r.scene.trim(),c=Xn(e,r.entity),a=r.look.trim();if(!s||!c||!a)continue;let d=Ot(e,c),p=d?DE(d,a):a;(e.lookChanges[s]??=[]).push({entity:c,look:p}),d&&(d.currentLook=p)}let i=new Set;for(let r of t.newEntities){i.add(r.name);for(let s of r.aliases)i.add(s)}for(let r of t.merges)i.add(r.from),i.add(r.into);for(let r of t.looks)i.add(r.entity);for(let r of t.lookChanges)i.add(r.entity);for(let r of i){let s=Ot(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var JE=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function lf(e,t=sd){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+JE(o),0)>6e3;){let n=e.recent.shift();n.summary.trim()&&e.synopsis.push({startEp:n.startEp,endEp:n.endEp,line:n.summary.trim()})}return e}function cd(e,t=sd){return e.synopsis.reduce((o,i)=>o+i.line.length,0)<=t.synopsisChars||e.synopsis.length<=t.arcFold?null:e.synopsis.slice(0,t.arcFold)}function uf(e,t,n=sd){let o=e.synopsis.splice(0,n.arcFold);o.length&&e.synopsis.unshift({startEp:o[0].startEp,endEp:o[o.length-1].endEp,line:t.trim()})}var BE=6;function Ss(e,t){let n=i=>t===void 0||i.lastSeen>=t-BE,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${UE[i]}`);for(let s of r){let c=[...s.aliases.length?[`\u522B\u540D ${s.aliases.join("\u3001")}`]:[],...s.currentLook?[`\u5F53\u524D\u9020\u578B ${s.currentLook}`]:[]];if(o.push(`- ${s.canonical}\uFF5C${c.join("\uFF5C")}`),!!n(s)){s.description&&o.push(` \u7B80\u4ECB\uFF1A${s.description}`);for(let a of s.looks){let d=a.aliases.length?`${a.name}(=${a.aliases.join("=")})`:a.name;o.push(` \u9020\u578B ${d}${a.description?`\uFF1A${a.description}`:""}`)}}}}}if(e.synopsis.length){o.push("","# \u524D\u60C5");for(let i of e.synopsis)o.push(`- ${rd(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${ME(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
|
|
216
|
-
`)}var KE=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function Is(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{lt(o.actor_name)&&n("production_crowd_actor",`$.actors[${i}].actor_name`,`${o.actor_name} is a group speaker, not an actor asset`)}),e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{let c=`$.episodes[${i}].scenes[${s}]`;r.location===null&&n("production_location_missing",`${c}.location`,"production scene needs one stable location"),r.actions.forEach((a,d)=>{let p=`${c}.actions[${d}]`;if(a.type==="action"){let l=KE.exec(a.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var je=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nt=e=>Array.isArray(e),As=e=>String(e).padStart(3,"0"),dd=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function ks(e){if(!je(e))throw new Error("renumberIds expects a script object");let t=JSON.parse(JSON.stringify(e)),n={episodes:{},scenes:{},actors:{},locations:{},props:{},states:{}},o={actors:[],locations:[],props:[]},i={actors:new Set,locations:new Set,props:new Set},r=(a,d)=>{typeof d=="string"&&!i[a].has(d)&&(i[a].add(d),o[a].push(d))};for(let a of nt(t.episodes)?t.episodes:[])if(!(!je(a)||!nt(a.scenes))){for(let d of a.scenes)if(je(d)){je(d.location)&&r("locations",d.location.location_id);for(let p of nt(d.actors)?d.actors:[])je(p)&&r("actors",p.actor_id);for(let p of nt(d.props)?d.props:[])je(p)&&r("props",p.prop_id);for(let p of nt(d.actions)?d.actions:[])je(p)&&je(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:a,idField:d}of dd)for(let p of nt(t[a])?t[a]:[])je(p)&&r(a,p[d]);for(let{key:a,prefix:d}of dd)o[a].forEach((p,l)=>{n[a][p]=`${d}_${As(l+1)}`});for(let{key:a,idField:d}of dd){let p=(nt(t[a])?t[a]:[]).filter(je),l=n[a],f=new Map;for(let u of p){let m=u[d],g=l[m]??m;u[d]=g;let h=0;for(let w of nt(u.states)?u.states:[]){if(!je(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${As(++h)}`;n.states[w.state_id]=y,w.state_id=y}f.set(g,u)}t[a]=[...f.entries()].sort((u,m)=>u[0]<m[0]?-1:1).map(u=>u[1])}let s=0;(nt(t.episodes)?t.episodes:[]).forEach((a,d)=>{if(je(a)){if(typeof a.episode_id=="string"){let p=`ep_${As(d+1)}`;n.episodes[a.episode_id]=p,a.episode_id=p}for(let p of nt(a.scenes)?a.scenes:[])if(je(p)&&typeof p.scene_id=="string"){let l=`scn_${As(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let c=(a,d,p)=>{!je(a)||typeof a[d]!="string"||(a[d]=n[p][a[d]]??a[d],typeof a.state_id=="string"&&n.states[a.state_id]&&(a.state_id=n.states[a.state_id]))};for(let a of nt(t.episodes)?t.episodes:[])if(!(!je(a)||!nt(a.scenes))){for(let d of a.scenes)if(je(d)){c(d.location,"location_id","locations");for(let p of nt(d.actors)?d.actors:[])c(p,"actor_id","actors");for(let p of nt(d.props)?d.props:[])c(p,"prop_id","props");for(let p of nt(d.actions)?d.actions:[])je(p)&&c(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as jE}from"node:crypto";function sr(e){let t=O(e).trim();if(!t.includes(":"))throw new x("Target invalid.",{exitCode:G,errorCode:"TARGET_INVALID",hint:"Use a concrete asset target.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t||"<empty>"]}});let n=t.indexOf(":"),o=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(!Op.has(o)||!i)throw new x("Target invalid.",{exitCode:G,errorCode:"TARGET_INVALID",hint:"Use actor, location, or prop with a non-empty id.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t]}});return[o,i]}function oi(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function vt(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function ii(e,t=oi(),n={}){if(t.version!==3)throw new Error(`Unsupported v4 identity map version: ${String(t.version)}`);let o=structuredClone(t),i={actor:new Map,location:new Map,prop:new Map},r={actor:new Set,location:new Set,prop:new Set,episode:new Set,scene:new Set,action:new Set},s=(I,M,$,U)=>{let v=$[M];if(v!==void 0){if(!T(I,v))throw new Error(`Invalid persisted ${I} ID for ${M}: ${v}`);if(U.has(v))throw new Error(`Duplicate persisted ${I} ID: ${v}`);return U.add(v),v}let j=ao(I,U);return U.add(j),$[M]=j,j},c=(I,M)=>n[I]?.[M]??M;for(let I of e.actors){let M=s("actor",c("actor",I.actor_id),o.actor,r.actor);i.actor.set(I.actor_id,M)}for(let I of e.locations){let M=s("location",c("location",I.location_id),o.location,r.location);i.location.set(I.location_id,M)}for(let I of e.props){let M=s("prop",c("prop",I.prop_id),o.prop,r.prop);i.prop.set(I.prop_id,M)}let a=new Map,d=(I,M,$)=>{let U=new Map,v=new Set,j=c(I,M),Z=o.state[j]??{};o.state[j]=Z;let De=$.map(B=>{let be;if(B.state_id==="default")be="default";else{let Qe=n.state?.[M]?.[B.state_id]??B.state_id,L=Z[Qe];if(L!==void 0){if(!T("state",L))throw new Error(`Invalid persisted state ID for ${M}/${B.state_id}: ${L}`);if(v.has(L))throw new Error(`Duplicate persisted state ID on ${M}: ${L}`);be=L}else be=ao("state",v),Z[Qe]=be}return v.add(be),U.set(B.state_id,be),{...B,state_id:be}});return a.set(M,U),De},p=(I,M)=>M===void 0?void 0:vt(a.get(I)??new Map,M),l=e.actors.map(I=>({...I,actor_id:vt(i.actor,I.actor_id),states:d("actor",I.actor_id,I.states)})),f=e.locations.map(I=>({...I,location_id:vt(i.location,I.location_id),states:d("location",I.location_id,I.states)})),u=e.props.map(I=>({...I,prop_id:vt(i.prop,I.prop_id),states:d("prop",I.prop_id,I.states)})),m=I=>{if("actor_id"in I){let M=p(I.actor_id,I.state_id);return{actor_id:vt(i.actor,I.actor_id),...M===void 0?{}:{state_id:M}}}return I.label===void 0?{kind:I.kind}:{kind:I.kind,label:I.label}},g=I=>{if(I.includes(":")){let[$,U]=sr(I);return vt($==="actor"?i.actor:$==="location"?i.location:i.prop,U)}let M=i.actor.get(I)??i.location.get(I)??i.prop.get(I);if(M===void 0)throw new Error(`Missing transition target mapping for ${I}`);return M},h=(I,M)=>{let $=s("action",M,o.action,r.action),U=I.transition_prompt===void 0?{}:{transition_prompt:{...I.transition_prompt,target:g(I.transition_prompt.target)}};if(I.type==="dialogue"||I.type==="inner_thought"){if(I.speaker===void 0)throw new Error(`Speaking action ${I.content.slice(0,40)} has no speaker`);return{action_id:$,type:I.type,content:I.content,speaker:m(I.speaker),...I.emotion===void 0?{}:{parenthetical:I.emotion},...U,...I.extend===void 0?{}:{extend:I.extend}}}return{action_id:$,type:I.type,content:I.content,...U,...I.extend===void 0?{}:{extend:I.extend}}},w=(I,M)=>[p(I,M??"default")??"default"],y=(I,M)=>{let $=new Map;for(let U of I){let v=vt(i.actor,U.actor_id),j=$.get(v)??new Set;w(U.actor_id,U.state_id).forEach(Z=>j.add(Z)),$.set(v,j)}for(let U of M){if(U.speaker===void 0||!("actor_id"in U.speaker))continue;let v=U.speaker.actor_id,j=vt(i.actor,v),Z=$.get(j)??new Set;w(v,U.speaker.state_id).forEach(De=>Z.add(De)),$.set(j,Z)}return[...$].map(([U,v])=>({actor_id:U,state_ids:[...v].sort()}))},E=I=>{let M=new Map;for(let $ of I){let U=vt(i.prop,$.prop_id),v=M.get(U)??new Set;w($.prop_id,$.state_id).forEach(j=>v.add(j)),M.set(U,v)}return[...M].map(([$,U])=>({prop_id:$,state_ids:[...U].sort()}))},S=new Set,_=new Set,A=new Set,k={version:4,title:e.title,worldview:e.worldview,style:e.style,...e.worldview_raw===void 0?{}:{worldview_raw:e.worldview_raw},...e.synopsis===void 0?{}:{synopsis:e.synopsis},...e.logline===void 0?{}:{logline:e.logline},...e.theme===void 0?{}:{theme:e.theme},...e.main_characters===void 0?{}:{main_characters:e.main_characters},...e.extend===void 0?{}:{extend:e.extend},actors:l,locations:f,props:u,episodes:e.episodes.map(I=>{let M=n.episode?.[I.episode_id]??I.episode_id;S.add(M);let $=s("episode",M,o.episode,r.episode);return{...I,episode_id:$,scenes:I.scenes.map(U=>{let v=`${I.episode_id}/${U.scene_id}`,j=n.scene?.[v]??v;_.add(j);let Z=s("scene",j,o.scene,r.scene),De=new Map;return{...U,scene_id:Z,location:U.location===null?null:{location_id:vt(i.location,U.location.location_id),state_ids:w(U.location.location_id,U.location.state_id)},actors:y(U.actors,U.actions),props:E(U.props),actions:U.actions.map((B,be)=>{let Qe=`${v}#${be}`,L=JSON.stringify(on(B)),oe=(De.get(L)??0)+1;De.set(L,oe);let he=jE("sha256").update(L).digest("hex"),rt=n.action?.[Qe]??`${j}:action:${he}:${oe}`;return A.add(rt),h(B,rt)})}})}})},D=(I,M)=>{for(let $ of Object.keys(I))M.has($)||delete I[$]};D(o.actor,new Set(e.actors.map(I=>c("actor",I.actor_id)))),D(o.location,new Set(e.locations.map(I=>c("location",I.location_id)))),D(o.prop,new Set(e.props.map(I=>c("prop",I.prop_id)))),D(o.episode,S),D(o.scene,_),D(o.action,A);let R=[...e.actors.map(I=>({id:c("actor",I.actor_id),oldId:I.actor_id,states:I.states})),...e.locations.map(I=>({id:c("location",I.location_id),oldId:I.location_id,states:I.states})),...e.props.map(I=>({id:c("prop",I.prop_id),oldId:I.prop_id,states:I.states}))];D(o.state,new Set(R.map(I=>I.id)));for(let I of R)D(o.state[I.id]??{},new Set(I.states.map(M=>n.state?.[I.oldId]?.[M.state_id]??M.state_id)));return{script:k,identityMap:o}}import*as Ef from"node:fs";import*as ff from"node:fs";import mf from"jszip";import{XMLParser as FE}from"fast-xml-parser";function gf(e){return e==null?"":String(e)}function Rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ae(e){return Array.isArray(e)}function hf(e){if(e.length===0)return"";let t=[],n="";for(let o=1;o<e.length;o++){let i=e[o];if(i.filter(p=>p).length===0)continue;let s=i[0]??"";if(s.includes("\u{1F3AC}")||/第\s*\d+\s*集/.test(s)){t.push(`
|
|
217
|
-
${s}`);continue}let c=i.length>1?i[1]??"":"";c||(c=n),n=c;let a=[];s&&a.push(`${s}.`);let d=i.slice(2).filter(p=>p);c&&d.length>0?a.push(`${c}\uFF0C${d.join(" ")}`):c?a.push(c):a.push(...d),t.push(a.join(" "))}return t.join(`
|
|
218
|
-
`)}function ri(e,t){let n=e[":@"];return Rt(n)?gf(n[t]).trim():""}function bs(e,t){for(let[n,o]of Object.entries(e))if(bn(n)===t&&Ae(o))return o;return null}function Os(e){let t=[],n=o=>{if(Ae(o)){for(let i of o)if(Rt(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push(gf(s)):r!==":@"&&Ae(s)&&n(s)}};return n(e),t.join("")}function vs(e){let t=yf.parse(e);if(!Ae(t))throw new Error("xlsx xml part has an unexpected shape");return t}function eo(e,t){let n=[],o=i=>{let r=Ae(i)?i.filter(Rt):Rt(i)?[i]:[];for(let s of r)for(let[c,a]of Object.entries(s))bn(c)===t&&Ae(a)&&n.push(s),Ae(a)&&o(a)};return o(e),n}function QE(e){let t=/^[A-Z]+/i.exec(e.trim());if(!t)return null;let n=0;for(let o of t[0].toUpperCase())n=n*26+o.charCodeAt(0)-64;return n-1}function YE(e,t){let o=(t.startsWith("/")?t.slice(1):`${e}/${t}`).split("/"),i=[];for(let r of o)!r||r==="."||(r===".."?i.pop():i.push(r));return i.join("/")}async function Rs(e,t){let n=e.file(t);return n?n.async("string"):null}async function qE(e){let t=await Rs(e,"xl/sharedStrings.xml");if(!t)return[];let n=vs(t),o=[];for(let i of eo(n,"si"))o.push(Os(bs(i,"si")??[]));return o}async function WE(e){let t=await Rs(e,"xl/workbook.xml"),n=await Rs(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of eo(vs(n),"Relationship")){let s=ri(r,"@_Id"),c=ri(r,"@_Target");s&&c&&o.set(s,YE("xl",c))}let i=[];for(let r of eo(vs(t),"sheet")){let s=ri(r,"@_name"),c=ri(r,"@_r:id"),a=o.get(c);s&&a&&i.push({name:s,path:a})}if(i.length===0)throw new Error("xlsx workbook contains no readable sheets");return i}function ZE(e,t){let n=ri(e,"@_t");if(n==="inlineStr"){let s=eo(e,"is")[0],c=s?bs(s,"is"):null;return c?Os(c).trim():""}let o=eo(e,"v")[0],i=o?bs(o,"v"):null,r=i?Os(i).trim():"";if(!r&&n==="str"){let s=eo(e,"is")[0],c=s?bs(s,"is"):null;return c?Os(c).trim():""}if(n==="s"){let s=Number.parseInt(r,10);return Number.isInteger(s)?(t[s]??"").trim():""}return n==="b"?r==="1"?"TRUE":r==="0"?"FALSE":r:r}async function XE(e){let t=await mf.loadAsync(e),[n,o]=await Promise.all([qE(t),WE(t)]),i=[];for(let r of o){let s=await Rs(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let c=[];for(let a of eo(vs(s),"row")){let d=[];for(let p of eo(a,"c")){let l=ri(p,"@_r"),f=l?QE(l):null,u=ZE(p,n),m=f??d.length;for(;d.length<m;)d.push("");d[m]=u.trim()}d.some(p=>p)&&c.push(d)}i.push({name:r.name,rows:c})}return i}var yf=new FE({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function bn(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function pd(e){let t=[];function n(o){if(Ae(o)){for(let i of o)if(Rt(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let c=bn(r);if(c==="t"){if(Ae(s)){for(let a of s)if(Rt(a)){let d=a["#text"];typeof d=="string"&&t.push(d)}}}else c==="tab"?t.push(" "):c==="br"||c==="cr"?t.push(`
|
|
219
|
-
`):Ae(s)&&n(s)}}}return n(e),t.join("").trim()}function ex(e){let t=[];for(let n of e)if(Rt(n))for(let[o,i]of Object.entries(n)){if(bn(o)!=="tr")continue;let r=[];if(Ae(i)){for(let s of i)if(Rt(s)){for(let[c,a]of Object.entries(s))if(bn(c)==="tc"&&Ae(a)){let d=[],p=l=>{if(Ae(l)){for(let f of l)if(Rt(f))for(let[u,m]of Object.entries(f))if(bn(u)==="p"&&Ae(m)){let g=pd(m);g&&d.push(g)}else Ae(m)&&p(m)}};p(a),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return hf(t)}async function tx(e){let t=[],n=[];e.forEach(i=>{i.includes("embeddings")&&i.endsWith(".xlsx")&&n.push(i)}),n.sort();let o=0;for(let i of n){o+=1;let r=e.file(i);if(!r)continue;let s=await r.async("nodebuffer"),c=await XE(s);for(let a of c)a.rows.length>0&&t.push([`Embedded Sheet ${o}: ${a.name}`,hf(a.rows)])}return t}async function wf(e){let t;try{t=await mf.loadAsync(ff.readFileSync(e))}catch{throw new Error("source is not a valid docx zip file")}let n=t.file("word/document.xml");if(!n)throw new Error("docx missing word/document.xml");let o=await n.async("string"),i=yf.parse(o),r=null,s=d=>{if(Ae(d)){for(let p of d)if(Rt(p))for(let[l,f]of Object.entries(p)){if(bn(l)==="body"&&Ae(f)){r=f;return}Ae(f)&&s(f)}}};s(i);let c=[];if(r===null){let d=p=>{if(Ae(p)){for(let l of p)if(Rt(l))for(let[f,u]of Object.entries(l))if(bn(f)==="p"&&Ae(u)){let m=pd(u);m&&c.push(m)}else Ae(u)&&d(u)}};d(i)}else for(let d of r)if(Rt(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!Ae(l))continue;let f=bn(p);if(f==="p"){let u=pd(l);u&&c.push(u)}else if(f==="tbl"){let u=ex(l);u&&c.push(u)}}let a=await tx(t);for(let[d,p]of a)c.push(`
|
|
220
|
-
## ${d}
|
|
221
|
-
`),c.push(p);return[c.join(`
|
|
222
|
-
|
|
223
|
-
`),a.length>0]}var ld=class extends Error{};function _f(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
224
|
-
`)}function nx(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new ld("source is not valid UTF-8")}}async function xf(e,t){if(t===".docx"){let[n]=await wf(e);return _f(n)}return _f(nx(Ef.readFileSync(e)))}import*as ke from"node:fs";import*as Ao from"node:path";function Sf(e,t){let n=Ao.dirname(e);ke.mkdirSync(n,{recursive:!0});let o=Ao.join(n,`.${Ao.basename(e)}.${process.pid}.tmp`),i=ke.openSync(o,"w");try{ke.writeFileSync(i,t),ke.fsyncSync(i)}finally{ke.closeSync(i)}ke.renameSync(o,e)}function ox(e,t){Sf(e,JSON.stringify(t,null,2)+`
|
|
225
|
-
`)}function ix(e){return JSON.parse(ke.readFileSync(e,"utf-8"))}var At=class{constructor(t){this.root=t}root;abs(t){return Ao.join(this.root,t)}ensure(){ke.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return ke.mkdirSync(n,{recursive:!0}),n}readText(t){return ke.readFileSync(this.abs(t),"utf-8")}writeText(t,n){Sf(this.abs(t),n)}writeJson(t,n){ox(this.abs(t),n)}readJson(t){return ix(this.abs(t))}has(t){return ke.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);ke.existsSync(n)&&ke.rmSync(n)}};function Gt(e,t){e=e-0;let n=ud(),o=n[e];if(Gt.wCYmoh===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};Gt.ccSjUe=i,Gt.dKlJjl={},Gt.wCYmoh=!0}let r=n[0];Gt.sBhMJx!==r&&(Gt.dKlJjl={},Gt.sBhMJx=r);let s=Gt.dKlJjl[e];return s===void 0?(o=Gt.ccSjUe(o),Gt.dKlJjl[e]=o):o=s,o}var F=Gt,rx=[F(40),F(37),F(24),F(75),F(5),F(21),"",F(65),F(13),F(34),F(62),"",F(70),F(35),F(42),F(27),F(39),F(43),F(0),F(68),F(55),"",F(77),F(18),F(58),F(10),F(11),F(51),F(59),F(66),F(8),F(3),F(76),"",F(15),F(4),F(9),F(6),F(20),F(14),F(45),F(48),F(38),F(54)][F(74)](`
|
|
226
|
-
`);function sx(e){let t=F,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
|
|
227
|
-
`)}function Ns(e,t){let n=F;return new x(e,{exitCode:fe,errorCode:n(12),hint:n(44),data:{actual:t}})}function ax(e){let t=F;return typeof e!==t(29)||e===null||Array[t(46)](e)?!1:Object[t(61)](e)[t(1)]===1&&t(33)in e&&Array[t(46)](e[t(33)])}function fd(e,t){let n=F;if(!ax(e))throw Ns(n(19)+t[n(73)]+n(63),[n(31)]);let o={chunk:t[n(73)],line_start:t[n(64)],line_end:t[n(36)]},i;try{let r=e[n(33)][n(25)](s=>{let c=n;if(typeof s!==c(29)||s===null||Array[c(46)](s)||Object[c(26)](s,c(56))){if(c(72)!==c(30))throw new me(c(57),1);if(typeof _0x5a19bf!==c(29)||_0x5b66f6===null||_0x10f05d[c(46)](_0x23b052)||_0x733702[c(26)](_0x1cb121,c(56)))throw new _0x3dba95(c(57),1);return _0x5020a9[c(32)]({..._0x80cb75,source:_0x442727})}return JSON[c(32)]({...s,source:o})})[n(74)](`
|
|
228
|
-
`);i=ir(r)}catch(r){throw r instanceof me?Ns(n(19)+t[n(73)]+": "+r[n(17)],[r[n(17)]]):r}if(i[n(1)]===0&&t[n(53)][n(52)]()!=="")throw n(60)===n(22)?_0x1b2e63(n(19)+_0x2d4dff[n(73)]+n(63),[n(31)]):Ns(n(19)+t[n(73)]+n(69),[n(2)]);return i}function ud(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy3rPB24Uy29UDgvUDd1G5lIa55Uy5l6B5zob5lUo5Qgm5lIk5O6j6jc977Ym5PwJ6jc95lIa5zYW44ccyooaGUs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wuG5zkmigLUBMvYx3rOB3vNAhqG55QeignVBNrLBNqG6ycq5A2x5l+D55wz5RQq5PAh5PYS5A6E6zMf6k+T6kIa5lIo5As55P2c6k+T6kIa77Ym57UD5lIn57+76k+r77YB6zMK5Q2K5lUL5Asw77Ymywn0Aw9U44cbDhjHBNnPDgLVBUoaGw5VDgxJGifLBw90Aw9Uios7PEwpIUwCUUAzR+EAHoMaMUEuQowCSoEcUEApJ+I/SoMdVEs9V+EuQoIhQUEeTUoaGEwhHUEHRUEAHoEUGos9K+s4REAwH+oaGUs6UUEjQEwNK+wqJEwCQcbZCgvHA2vYlM5HBwxJGifZy2vUzs5Hy3rVCNpJGifHy3rPB24G5zkm5zco57UT6lwe5lQN55M76k6W5lIT6yo95B+f6Ag75Rk/55sO5RQq5PAh5PYS55Qe5y6F5AEl5OU85yAz77Ym5lIn57+76k+r44cb5lIn6z+Z6k+r44cb5lIn5Ps55OIq5lIT5PAh5zcn77YB5zob54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return ud=function(){return e},ud()}async function If(e,t,n){let o=F,i=await e[o(41)](o(71),{system:rx,user:sx(t),responseFormat:o(16),...n?{signal:n}:{}}),r;try{r=JSON[o(28)](i[o(53)])}catch{if(o(67)!==o(67))_0x10022d=_0x3c4a29[o(28)](_0x5ecbb9[o(53)]);else throw Ns(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:fd(r,t)}}var gd=Jt,cx=gd(1);function dx(e){let t=gd,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function md(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRLROpNMOtOTBFLP4VOOyZLJ7FJGiikcUoaKoATO+AwH+MvV+s7Gos5IoAGT+oaKEMaKowCUUEAHowjP+ACRo+8MUs7PEoaJoESRe7PM4BJGi3KUlRPM4BLPltVViZKUiVPNAlNTkFOT5/JGiZLNlPylvKGioAxPs/LHOuG5zYW54k544cn6l+z56En5BIM5zY65QYH57Yw5y+355Qe5zY65PMV5As077Ym5yAn5B6a5lIl5PIV44cm5lI76kAb5lQ654MP77YAl+s6UUEjQE+8MUoaJEwsJos4GoADOEADOEs7PsdILRmG5BYa5As055Qe5yQO5l2C44cb5lUL5y+k5BIM6k+06k+D5lQ655Qe5y+W6k+n44cc6l+z5OMn5PIV5Q2J5PAh44cccGRJGjdLIy3OQidPLB/KU4dKUyJMOlFVViZNU53KUi3NRPFMRApMLOFJGjhVVjOklsdPOBNNM67LN7RMNkZKV6hMGA8GlYdNRzBLIjlLPkFNURiGlYdPOPJMNzdMOiFNRB4GlYdKUidLJ6xOR53MLyxKUOSGlYdMOlJLV4pNNiVNGRNVVjSklsdO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AFMNkZMRApMLOFMMk/LKkBLNkJOV5NMRRxPH4ZLVidLP4VVViZMJiNMOlZLVi/LJ6RLM57KUidOOyZJGiikcG"];return md=function(){return e},md()}async function Af(e,t,n){let o=gd,i=await e[o(4)](o(2),{system:cx,user:o(6)+t,...n?{signal:n}:{}});return dx(i[o(0)])}function Jt(e,t){e=e-0;let n=md(),o=n[e];if(Jt.sLepLJ===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};Jt.TPTWLA=i,Jt.iYuNay={},Jt.sLepLJ=!0}let r=n[0];Jt.inDmHY!==r&&(Jt.iYuNay={},Jt.inDmHY=r);let s=Jt.iYuNay[e];return s===void 0?(o=Jt.TPTWLA(o),Jt.iYuNay[e]=o):o=s,o}var kf=50,px=10;async function bf(e,t,n){let o=t.split(`
|
|
229
|
-
`),i=kf-px;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+kf,o.length),c=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
|
|
230
|
-
`),a=await Af(e,c,n);if(a.found&&a.line!==null)return{line:Math.min(Math.max(a.line-1,0),o.length-1),scannedLines:s,found:!0};if(s>=o.length)break}}catch(r){return{line:0,scannedLines:0,found:!1,error:r instanceof Error?r.message:String(r)}}return{line:0,scannedLines:o.length,found:!1}}async function Of(e,t,n){let o=new Array(e.length),i=0,r=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;;){let s=i++;if(s>=e.length)return;try{o[s]={index:s,ok:!0,value:await n(e[s],s)}}catch(c){o[s]={index:s,ok:!1,error:c}}}});return await Promise.all(r),o}var Nt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Bt=e=>Array.isArray(e);function hd(e){let t=new Map;if(!Bt(e))return t;for(let n of e){if(!Nt(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function lx(e){let t=[],n=(o,i)=>{!Nt(o)||typeof o[i]!="string"||t.push({assetId:o[i],holder:o,explicit:typeof o.state_id=="string"?o.state_id:void 0})};for(let o of Bt(e.episodes)?e.episodes:[])if(!(!Nt(o)||!Bt(o.scenes))){for(let i of o.scenes)if(Nt(i)){n(i.location,"location_id");for(let r of Bt(i.actors)?i.actors:[])n(r,"actor_id");for(let r of Bt(i.props)?i.props:[])n(r,"prop_id");for(let r of Bt(i.actions)?i.actions:[])Nt(r)&&n(r.speaker,"actor_id")}}return t}function ux(e,t){let n=e.filter(i=>(t.get(i.state_id)??0)>0);if(n.length===0)return null;let o=n[0];for(let i of n.slice(1)){let r=t.get(i.state_id)??0,s=t.get(o.state_id)??0;(r>s||r===s&&i.state_name<o.state_name)&&(o=i)}return o.state_id}function Ms(e){if(!Nt(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of Bt(t.episodes)?t.episodes:[])if(!(!Nt(p)||!Bt(p.scenes)))for(let l of p.scenes){if(!Nt(l))continue;let f=Bt(l.actors)?l.actors.filter(Nt):[],u=new Set(f.map(m=>m.actor_id).filter(m=>typeof m=="string"));for(let m of Bt(l.actions)?l.actions:[])!Nt(m)||!Nt(m.speaker)||typeof m.speaker.actor_id!="string"||u.has(m.speaker.actor_id)||(f.push({actor_id:m.speaker.actor_id}),u.add(m.speaker.actor_id));l.actors=f}let n=hd(t.actors),o=hd(t.locations),i=hd(t.props),r=new Map([...n,...o,...i]),s=lx(t),c=new Map;for(let p of s){if(p.explicit===void 0)continue;c.has(p.assetId)||c.set(p.assetId,new Map);let l=c.get(p.assetId);l.set(p.explicit,(l.get(p.explicit)??0)+1)}let a=new Map;for(let[p,l]of r){let f=(Bt(l.states)?l.states:[]).filter(Nt),u=new Map,m=ux(f,c.get(p)??new Map),g;if(m===null){let h=f.find(w=>w.state_id==="default");g=[{state_id:"default",state_name:h?.state_name??"default",description:h?.description??""}]}else{g=[];for(let h of f)h.state_id!=="default"&&(h.state_id===m?(u.set(h.state_id,"default"),g.unshift({state_id:"default",state_name:h.state_name,description:h.description??""})):(u.set(h.state_id,h.state_id),g.push({state_id:h.state_id,state_name:h.state_name,description:h.description??""})))}l.states=g,a.set(p,u)}let d=new Map;for(let p of s){let l=a.get(p.assetId),f;p.explicit!==void 0?(f=l?.get(p.explicit)??p.explicit,d.set(p.assetId,f)):f=d.get(p.assetId)??"default",p.holder.state_id=f}return t}var vf=Kt;function Kt(e,t){e=e-0;let n=yd(),o=n[e];if(Kt.vcGzia===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};Kt.alaGPc=i,Kt.IPZchV={},Kt.vcGzia=!0}let r=n[0];Kt.cEXTRr!==r&&(Kt.IPZchV={},Kt.cEXTRr=r);let s=Kt.IPZchV[e];return s===void 0?(o=Kt.alaGPc(o),Kt.IPZchV[e]=o):o=s,o}var fx=vf(6);async function Rf(e,t,n,o){let i=vf;return(await e[i(4)](i(2),{system:fx,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function yd(){let e=["5OQk5lIl6z2Iia","DhjPBq","Aw5Nzxn0lMfYyY1ZDw1Tyxj5","ioEAHoMaKoADOEwjP+AdHEA1K+E8QEAiKos4GoAUTEEVH+EROoAIL+AMGIGYmddIGjmZmJaG5A2xloI/NUI0R+AiKoAUTsZKUi3OPOhPGjdPM4BNVzFLI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return yd=function(){return e},yd()}var Uf={type:"object",required:["issues"],additionalProperties:!1,properties:{issues:{type:"array",items:{type:"object",required:["type","asset_ids","state_ids","names","evidence","recommendation","suggested_survivor","action","confidence"],additionalProperties:!1,properties:{type:{type:"string",enum:["duplicate_actor","duplicate_location","duplicate_prop","duplicate_state","suspicious_singleton_state","unused_state","needs_human_review"]},asset_ids:{type:"array",items:{type:"string"}},state_ids:{type:"array",items:{type:"string"}},names:{type:"array",items:{type:"string"}},evidence:{type:"string"},recommendation:{type:"string"},suggested_survivor:{type:["string","null"]},action:{type:"string",enum:["merge","delete","review"]},confidence:{type:"string",enum:["high","medium","low"]}}}}}},wd={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},bR={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...wd,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...wd,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...wd,items:{type:"object",required:["prop_id","state_id"],additionalProperties:!1,properties:{prop_id:{type:"string"},state_id:{type:["string","null"]}}}},state_changes:{type:"array",items:{type:"object",required:["action_index","target_kind","target_id","to_state_id"],additionalProperties:!1,properties:{action_index:{type:"integer"},target_kind:{type:"string",enum:["actor","location","prop"]},target_id:{type:"string"},from_state_id:{type:["string","null"]},to_state_id:{type:"string"},effective_from:{type:"string",enum:["before_action","after_action"]}}}}}}}}},Tf={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:{type:"string",enum:["\u5E38\u6001"],description:"\u5B9E\u4F53\u9996\u6B21\u767B\u8BB0\u65F6\u7684\u9ED8\u8BA4\u9020\u578B\u540D\uFF0C\u56FA\u5B9A\u4E3A\u5E38\u6001"},description:{type:"string",description:"\u9ED8\u8BA4\u9020\u578B\u7684\u53EF\u89C1\u5916\u89C2\uFF0C\u53EA\u5199\u5916\u8C8C\u3001\u670D\u9970\u3001\u6750\u8D28\u3001\u989C\u8272\u3001\u5E03\u666F\u6216\u5F62\u5236\uFF0C\u975E\u7A7A"}}},Cf={type:"object",required:["newEntities","merges","looks","lookChanges","subEvents","summary"],additionalProperties:!1,properties:{newEntities:{type:"array",description:"\u672C\u6BB5\u65B0\u767B\u8BB0\u7684\u5B9E\u4F53(\u4EBA\u7269/\u573A\u666F/\u9053\u5177)\u3002name=canonical\uFF0Caliases \u5217\u5168\u8FD9\u6BB5\u91CC\u5B83\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D\uFF0C\u4E0D\u542B\u62EC\u53F7/\u659C\u6760/\u8BD1\u540D\u5939\u6CE8/\u5BF9\u767D\u6807\u8BB0"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8BF4\u660E\u8FD9\u4E2A\u5B9E\u4F53\u672C\u8EAB\u662F\u8C01/\u4EC0\u4E48\u8EAB\u4EFD/\u4EC0\u4E48\u4E1C\u897F\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u53EA\u5199\u8EAB\u4EFD\u3001\u89D2\u8272\u548C\u5173\u7CFB\uFF0C\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u8FD9\u6BB5\u91CC\u8BE5\u5B9E\u4F53\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5\uFF1A\u522B\u540D/\u8BD1\u540D/\u524D\u4E16\u540D/\u77ED\u540D\u5168\u540D/\u5BF9\u767D\u8BF4\u8BDD\u4EBA\u5728\u6B63\u6587\u91CC\u7684\u5199\u6CD5\uFF0C\u9010\u4E2A\u5355\u5217(\u7EAF\u540D\uFF0C\u4E0D\u5E26\u5BF9\u767D/\u60C5\u7EEA\u6807\u8BB0)"},defaultLook:Tf}}},merges:{type:"array",description:"\u672C\u6BB5\u91CC\u67D0\u4E2A\u5C1A\u672A\u767B\u8BB0\u7684\u79F0\u547C\uFF0C\u5176\u5B9E\u662F\u67D0\u4E2A\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u672C\u6BB5\u8FD9\u4E2A\u79F0\u547C(\u5C1A\u672A\u4F5C\u4E3A\u72EC\u7ACB\u5B9E\u4F53\u767B\u8BB0\u8FC7)"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684 canonical \u540D"}}}},looks:{type:"array",description:"\u9ED8\u8BA4\u9020\u578B\u4E4B\u5916\u3001\u9700\u8981\u5355\u72EC\u590D\u73B0\u7684\u65B0\u589E\u9020\u578B",items:{type:"object",required:["entity","name","aliases","description"],additionalProperties:!1,properties:{entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},name:{type:"string",description:"\u9020\u578B\u540D\uFF0C\u5FC5\u987B\u4E2D\u6587\uFF0C\u82F1\u6587\u4E13\u540D\u5148\u8BD1\u6210\u4E2D\u6587"},aliases:{type:"array",items:{type:"string"},description:"\u540C\u4E49\u9020\u578B\u540D"},description:{type:"string",description:"\u8FD9\u5957\u5916\u89C2\u4E00\u53E5\u8BDD"}}}},lookChanges:{type:"array",description:"\u9020\u578B\u53D8\u5316\uFF1A\u540C\u4E00\u573A\u540C\u4E00\u5B9E\u4F53\u53EF\u6309\u6B63\u6587\u987A\u5E8F\u5217\u51FA\u53D8\u5316\u524D\u540E\u5168\u90E8\u9020\u578B\uFF0C\u6700\u540E\u4E00\u6761\u7531\u540E\u7EED\u4E0D\u53D8\u7684\u573A\u7EE7\u627F\uFF1B\u56DE\u5FC6/\u9884\u6F14\u53CA\u8FD4\u56DE\u73B0\u5B9E\u5747\u663E\u5F0F\u6807\u72B6\u6001",items:{type:"object",required:["scene","entity","look"],additionalProperties:!1,properties:{scene:{type:"string",description:"\u53D8\u5316\u53D1\u751F\u7684\u573A\u666F id\uFF0C\u5982 scn_012"},entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},look:{type:"string",description:"\u672C\u573A\u5B9E\u9645\u51FA\u73B0\u7684\u5DF2\u767B\u8BB0\u9020\u578B\u540D\uFF1B\u540C\u573A\u591A\u9879\u6309\u6B63\u6587\u5148\u540E\u6392\u5217"}}}},subEvents:{type:"array",items:{type:"string"},description:"\u672C\u6BB5\u5173\u952E\u5267\u60C5\u539F\u5B50\uFF0C\u6BCF\u6761\u4E00\u53E5\u8BDD"},summary:{type:"string",description:"\u672C\u6BB5\u4E00\u53E5\u8BDD\u6897\u6982"}}},mx={type:"string",enum:["actor","location","prop"]},Pf={type:"string",description:"\u9020\u578B\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6027\u6587\u5B57"},Nf={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9]$",description:"\u5FC5\u586B\u4E14\u4E0D\u5F97\u4E3A\u7A7A\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u65F6\u95F4\u6233\uFF0C\u4E25\u683C\u4F7F\u7528 MM:SS\uFF08\u4F8B\u5982\u300E00:03\u300F\uFF09\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60\u3001null\u3001\u672A\u77E5\u503C\u6216\u5C0F\u6570\u79D2"},Mf={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:Pf,description:{type:"string",description:"\u8BE5\u72B6\u6001\u53EF\u590D\u73B0\u7684\u6301\u7EED\u53EF\u89C1\u5916\u89C2\uFF0C\u975E\u7A7A\u3002\u4EBA\u7269\u7EFC\u5408\u591A\u4E2A\u6E05\u6670\u955C\u5934\u5E76\u4ECE\u5934\u5230\u811A\u5199\u8BE5\u9020\u578B\u7279\u6709\u7684\u5986\u53D1\u5934\u9970\u3001\u9888\u9970\u3001\u5916\u5957\u3001\u4E0A\u88C5\u3001\u4E0B\u88C5/\u8FDE\u4F53\u8863\u88D9\u3001\u889C\u7C7B\u3001\u978B\u5C65\u3001\u624B\u5957\u548C\u9970\u54C1\uFF1B\u6BCF\u4EF6\u53EF\u89C1\u5355\u54C1\u5199\u989C\u8272\u3001\u6750\u8D28/\u5149\u6CFD/\u7EB9\u7406\u3001\u7248\u578B\u677E\u7D27\u3001\u9886\u8896\u7ED3\u6784\u3001\u5F00\u5408\u3001\u8170\u7EBF\u3001\u957F\u5EA6\u3001\u4E0B\u6446\u3001\u56FE\u6848\u6587\u5B57\u3001\u6EDA\u8FB9\u91D1\u5C5E\u4EF6\u3001\u53E0\u7A7F\u5173\u7CFB\u4E0E\u6240\u5728\u4F4D\u7F6E\uFF1B\u6301\u7EED\u7834\u635F\u6C61\u6E0D\u5199\u90E8\u4F4D\u3001\u8303\u56F4\u548C\u989C\u8272\u3002\u53EA\u7701\u7565\u770B\u4E0D\u89C1\u6216\u4E0D\u80FD\u786E\u8BA4\u7684\u9879\uFF0C\u4E0D\u7528\u4E00\u53E5\u7B3C\u7EDF\u670D\u88C5\u6982\u62EC\uFF0C\u4E0D\u4ECE\u5C40\u90E8\u8865\u9020\u5168\u8EAB\u3002\u5730\u70B9\u548C\u9053\u5177\u5199\u76F8\u5BF9\u5E38\u6001\u7684\u6301\u7EED\u5916\u89C2\u5DEE\u5F02\u3002\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u5199\u52A8\u4F5C\u3001\u59FF\u6001\u3001\u60C5\u7EEA\u3001\u5FC3\u7406\u6216\u5267\u60C5\u8BC4\u4EF7"}}},Lf={type:"object",required:["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","persistent_marks","voice"],additionalProperties:!1,properties:{apparent_gender:{type:"string",description:"\u753B\u9762\u5448\u73B0\u7684\u6027\u522B\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},apparent_age:{type:"string",description:"\u53EF\u89C1\u5E74\u9F84\u6BB5\uFF0C\u4F7F\u7528\u7A84\u800C\u5BA1\u614E\u7684\u8303\u56F4\uFF0C\u5982\u300E\u7EA625-30\u5C81\u300F\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},face_shape:{type:"string",description:"\u8138\u90E8\u8F6E\u5ED3\u3001\u98A7\u9AA8\u3001\u4E0B\u988C\u4E0E\u4E0B\u5DF4\u7684\u5BA2\u89C2\u5F62\u6001\uFF1B\u4E0D\u5199\u5BA1\u7F8E\u3001\u6C14\u8D28\u3001\u8868\u60C5\u6216\u5267\u60C5\u5F62\u6001"},brows_eyes:{type:"string",description:"\u7709\u5F62\u3001\u7709\u8272\u3001\u773C\u578B\u3001\u773C\u8DDD\u3001\u5355\u53CC\u773C\u76AE\u53CA\u773C\u5C3E\u7684\u9759\u6001\u5F62\u6001\uFF1B\u4E0D\u5199\u76EE\u5149\u3001\u795E\u60C5\u3001\u60C5\u7EEA\u3001\u5986\u5BB9\u3001\u9690\u5F62\u773C\u955C\u6216\u53D8\u8EAB\u989C\u8272"},nose:{type:"string",description:"\u9F3B\u6881\u3001\u9F3B\u5934\u3001\u9F3B\u7FFC\u7684\u5BA2\u89C2\u5F62\u6001"},mouth:{type:"string",description:"\u9759\u6B62\u65F6\u7684\u5507\u539A\u8584\u3001\u5507\u5CF0\u3001\u5634\u89D2\u7ED3\u6784\u548C\u53E3\u5468\u7279\u5F81\uFF1B\u4E0D\u5199\u8BF4\u8BDD\u52A8\u4F5C\u3001\u8868\u60C5\u6216\u5507\u5986"},skin_features:{type:"string",description:"\u7A33\u5B9A\u80A4\u8272\u3001\u9762\u90E8\u7EB9\u7406\u3001\u75E3\u3001\u96C0\u6591\u3001\u65E7\u75A4\u7B49\u8DE8\u573A\u666F\u53EF\u89C1\u7279\u5F81\uFF1B\u4E0D\u5199\u4E34\u65F6\u4F24\u75D5\u3001\u8840\u8FF9\u3001\u6C61\u6E0D\u6216\u5986\u5BB9"},hair:{type:"string",description:"\u7A33\u5B9A\u53D1\u8272\u3001\u53D1\u9645\u7EBF\u3001\u957F\u5EA6\u3001\u5377\u76F4\u548C\u5E38\u6001\u53D1\u578B\uFF1B\u4E0D\u5199\u5047\u53D1\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u4E00\u6B21\u6027\u9020\u578B\uFF0C\u4E34\u65F6\u5DEE\u5F02\u5199\u5165 states"},build:{type:"string",description:"\u53EF\u7531\u753B\u9762\u786E\u8BA4\u7684\u8EAB\u9AD8\u76F8\u5BF9\u5173\u7CFB\u3001\u80A9\u5BBD\u3001\u9AA8\u67B6\u548C\u4F53\u578B\uFF1B\u4E0D\u5199\u59FF\u6001\u3001\u52A8\u4F5C\u3001\u6C14\u8D28\u6216\u5BA1\u7F8E\u8BCD"},persistent_marks:{type:"array",items:{type:"string"},description:"\u7EB9\u8EAB\u3001\u65E7\u75A4\u3001\u75E3\u3001\u80CE\u8BB0\u3001\u56FA\u5B9A\u7A7F\u5B54\u7B49\u4E0D\u53EF\u968F\u6362\u88C5\u6458\u9664\u7684\u8EAB\u4F53\u6807\u8BB0\uFF1B\u4E0D\u5199\u8033\u73AF\u3001\u9879\u94FE\u3001\u773C\u955C\u7B49\u914D\u9970\uFF0C\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},voice:{type:"string",description:"\u4ECE\u6E05\u6670\u539F\u58F0\u53EF\u786E\u8BA4\u7684\u97F3\u9AD8\u3001\u97F3\u8272\u3001\u8BED\u901F\u3001\u53E3\u97F3\u6216\u7A33\u5B9A\u53D1\u58F0\u8D28\u611F\uFF1B\u4E0D\u5199\u5F53\u4E0B\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u89D2\u8272\u6027\u683C\uFF0C\u542C\u4E0D\u6E05\u586B\u7A7A\u4E32"}}},Vf={type:"object",required:["synopsis","scenes","registry_delta","open_threads"],additionalProperties:!1,properties:{synopsis:{type:"string",description:"\u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C"},scenes:{type:"array",minItems:1,description:"\u672C\u96C6\u6240\u6709\u573A\u666F\u5355\u5143\uFF0C\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u3002\u573A\u5185\u5C3D\u91CF\u5FE0\u5B9E\u8FD8\u539F\u539F\u7247\u5206\u955C\uFF1A\u6BCF\u6B21\u5207\u955C\u3001\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u53D8\u5316\u3001\u53EF\u89C1\u8868\u6F14\u548C\u58F0\u97F3\u4E8B\u4EF6\u6309\u5B9E\u9645\u65F6\u95F4\u4EA4\u9519\u4FDD\u7559\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u5730\u70B9\u3001\u660E\u663E\u65F6\u6BB5\u6216\u53D9\u4E8B\u7EBF\u53D8\u5316\u65F6\u62C6\u573A\uFF0C\u666E\u901A\u5207\u955C\u4E0D\u5355\u72EC\u62C6 scene\uFF1B\u540C\u4E00\u8FDE\u7EED\u573A\u5185\u7684\u4EBA\u7269\u9020\u578B\u53D8\u5316\u4FDD\u7559\u5728\u540C\u4E00\u573A\uFF1B\u8DE8\u5730\u70B9\u8499\u592A\u5947\u62C6\u6210\u591A\u4E2A\u77ED\u573A",items:{type:"object",required:["space","time","timeRange","location","characters","props","shots","voices"],additionalProperties:!1,properties:{space:{type:"string",description:"\u5185\u666F\u586B\u300C\u5185\u300D/\u5916\u666F\u586B\u300C\u5916\u300D\uFF1B\u4E0D\u786E\u5B9A\u586B\u7A7A\u4E32"},time:{type:"string",enum:["\u65E5","\u591C","\u6668","\u660F"],description:"\u672C\u573A\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A\u65F6\u6BB5\uFF1A\u767D\u5929/\u65E5\u95F4\u586B\u300C\u65E5\u300D\uFF0C\u591C\u665A/\u591C\u95F4\u586B\u300C\u591C\u300D\uFF0C\u6E05\u6668/\u9ECE\u660E\u586B\u300C\u6668\u300D\uFF0C\u9EC4\u660F/\u508D\u665A\u586B\u300C\u660F\u300D\u3002\u7ED3\u5408\u7167\u660E\u3001\u4F5C\u606F\u3001\u5929\u7A7A\u548C\u5267\u60C5\u4E0A\u4E0B\u6587\u5224\u65AD\uFF0C\u4E0D\u5F97\u7559\u7A7A"},timeRange:{type:"string",description:"\u672C\u573A\u8D77\u6B62\u65F6\u95F4 MM:SS-MM:SS\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60"},location:{type:"string",description:"\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u540D\uFF0C\u6CBF\u7528\u89C4\u8303\u540D\uFF1B\u5BA2\u5385/\u5367\u5BA4/\u536B\u751F\u95F4/\u5927\u5385/\u5E7F\u573A/\u821E\u53F0/\u540E\u53F0\u5206\u522B\u5EFA\u5730\u70B9\uFF0C\u76F8\u5173\u7A7A\u95F4\u7528\u300E\u8C6A\u5B85\xB7\u5BA2\u5385\u300F\u5F0F\u547D\u540D"},characters:{type:"array",description:"\u672C\u573A\u5728\u573A\u7684\u5177\u4F53\u5355\u4EBA\u89D2\u8272\uFF08\u7FA4\u4F17\u4E0D\u5217\uFF09\u3002\u540C\u4E00\u89D2\u8272\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\uFF1B\u5176 states \u586B\u672C\u573A\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u7A33\u5B9A\u9020\u578B/\u72B6\u6001\u96C6\u5408",items:{type:"object",required:["name","states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89D2\u8272\u89C4\u8303\u540D"},states:{type:"array",items:Pf,description:"\u672C\u573A\u8BE5\u89D2\u8272\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u9020\u578B/\u72B6\u6001\u540D\u96C6\u5408\u3002\u6BCF\u4E2A\u72B6\u6001\u662F\u6574\u5957\u7740\u88C5\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6587\u5B57\uFF08\u9519\u8BEF\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\uFF08\u8EAB\u7A7F\u6536\u94F6\u77ED\u8896\uFF09\u300F\u300E\u9ED1\u4E1D\u77ED\u88D9/\u7EF7\u5E26\u77ED\u88D9\u300F\uFF1B\u6B63\u786E\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\u300F\uFF09\u3002\u540C\u4E00\u5957\u9020\u578B\u6CBF\u7528\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u7684\u65E2\u6709\u540D\uFF1B\u6CA1\u6362\u88C5\u6216\u770B\u4E0D\u6E05\u586B\u7A7A\u6570\u7EC4\u3002\u4E0D\u5F97\u4E3A\u540C\u4E00\u89D2\u8272\u62C6\u6210\u591A\u6761\u8BB0\u5F55"}}}},props:{type:"array",items:{type:"string"},description:"\u672C\u573A\u5728\u573A\u7684\u5173\u952E\u9053\u5177\u540D"},shots:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u9010\u955C\u6E05\u5355\uFF0C\u4E0E\u58F0\u97F3\u5206\u5F00\u76D8\u70B9\u3002\u539F\u7247\u6BCF\u6B21\u5207\u955C\u90FD\u5FC5\u987B\u6709\u4E00\u6761\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u6216\u8868\u6F14\u53D8\u5316\u53E6\u589E\u4E00\u6761\u3002\u4E0D\u56E0\u4E3A\u53F0\u8BCD\u8FDE\u7EED\u6216\u5267\u60C5\u76EE\u7684\u76F8\u540C\u800C\u7701\u7565\u5206\u955C",items:{type:"object",required:["ts","camera","visual"],additionalProperties:!1,properties:{ts:Nf,camera:{type:"string",description:"\u672C\u955C\u5934\u53EF\u786E\u8BA4\u7684\u5207\u6362\u5173\u7CFB\u3001\u666F\u522B\u3001\u89D2\u5EA6\u3001\u673A\u4F4D\u3001\u8FD0\u955C\u3001\u6784\u56FE\u3001\u7126\u70B9\u548C\u753B\u9762\u4E3B\u4F53\uFF1B\u53EA\u5199\u539F\u7247\u80FD\u786E\u8BA4\u7684\u6444\u5F71\u4E8B\u5B9E\uFF0C\u4E0D\u63A8\u6D4B\u955C\u5934\u53C2\u6570\u6216\u62CD\u6444\u610F\u56FE"},visual:{type:"string",description:"\u672C\u955C\u5934\u5B9E\u9645\u53EF\u89C1\u7684\u73AF\u5883\u3001\u4EBA\u7269\u5360\u4F4D\u4E0E\u7AD9\u4F4D\u3001\u59FF\u6001\u3001\u9762\u5411\u3001\u89C6\u7EBF\u3001\u8868\u60C5\u3001\u63A5\u89E6\u3001\u52A8\u4F5C\u5BF9\u8C61\u3001\u9053\u5177\u548C\u7ED3\u679C\uFF1B\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u7528\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6982\u62EC"}}}},voices:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u58F0\u97F3\u6E05\u5355\u3002\u5B8C\u6574\u4FDD\u7559\u51FA\u955C\u5BF9\u767D\u3001\u753B\u5916\u5BF9\u767D\u3001\u89D2\u8272\u5185\u5FC3\u72EC\u767D/\u81EA\u8FF0\u3001\u5BA2\u89C2\u65C1\u767D\u3001\u7535\u8BDD/\u5E7F\u64AD/\u8BBE\u5907\u58F0\u548C\u7FA4\u4F53\u58F0\u3002\u53F0\u8BCD\u8DE8\u955C\u65F6\u6309\u81EA\u7136\u8BED\u53E5\u62C6\u5206\uFF0C\u4E0D\u5F97\u628A\u8DE8\u591A\u4E2A\u955C\u5934\u7684\u591A\u53E5\u53F0\u8BCD\u5408\u5E76\u6210\u4E00\u6761",items:{type:"object",required:["kind","speaker","parenthetical","ts","content"],additionalProperties:!1,properties:{kind:{type:"string",enum:["dlg","think"],description:"dlg=\u4EBA\u7269\u5BF9\u4ED6\u4EBA\u8BF4\u51FA\u7684\u58F0\u97F3\u6216\u5BA2\u89C2\u65C1\u767D\uFF1Bthink=\u97F3\u8F68\u5B9E\u9645\u5305\u542B\u3001\u660E\u786E\u5C5E\u4E8E\u67D0\u89D2\u8272\u7684\u5185\u5FC3\u72EC\u767D/\u7B2C\u4E00\u4EBA\u79F0\u81EA\u8FF0"},speaker:{type:"string",description:"\u8BF4\u8BDD\u4EBA\u89C4\u8303\u540D\uFF1B\u5BA2\u89C2\u53D9\u8FF0\u8005\u6216\u8EAB\u4EFD\u4E0D\u660E\u65C1\u767D\u7528\u300Ebroadcast:\u65C1\u767D\u300F\uFF0C\u5E7F\u64AD\u7528\u300Ebroadcast:\u540D\u300F\uFF0C\u65E0\u6CD5\u533A\u5206\u6210\u5458\u7684\u7FA4\u4F53\u5171\u540C\u53D1\u58F0\u7528\u300Egroup:\u7FA4\u4F53\u540D\u300F"},parenthetical:{type:"string",description:"\u53EF\u786E\u8BA4\u7684\u53D1\u58F0\u65B9\u5F0F\u3001\u58F0\u97F3\u6765\u6E90\uFF0C\u6216\u4E0E\u53F0\u8BCD\u540C\u65F6\u53D1\u751F\u7684\u77ED\u4FC3\u53EF\u89C1\u8868\u6F14\uFF1B\u6CA1\u6709\u5219\u586B\u7A7A\u4E32\u3002\u6444\u5F71\u8C03\u5EA6\u548C\u5F71\u54CD\u8FDE\u7EED\u6027\u7684\u52A8\u4F5C\u5C5E\u4E8E shots\uFF0C\u4E0D\u5199\u5728\u8FD9\u91CC\uFF1B\u4E0D\u7528\u62BD\u8C61\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6807\u7B7E"},ts:Nf,content:{type:"string",description:"\u9010\u5B57\u4FDD\u7559\u97F3\u8F68\u5B9E\u9645\u8BED\u8A00\u548C\u5939\u6742\u8BED\u8A00\uFF0C\u4E0D\u7FFB\u8BD1\u3001\u4E0D\u6539\u5199\u3001\u4E0D\u7528\u7FFB\u8BD1\u5B57\u5E55\u66FF\u6362\u5916\u8BED\u539F\u58F0"}}}}}}},registry_delta:{type:"object",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u7684\u589E\u91CF\u7EF4\u62A4\u3002\u5DF2\u6709\u4E14\u65E0\u65B0\u4FE1\u606F\u7684\u5B9E\u4F53\u4E00\u4E2A\u5B57\u90FD\u522B\u5199",required:["new_entities","enrich","canonicalize"],additionalProperties:!1,properties:{new_entities:{type:"array",description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u3001\u4E14\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u6CA1\u6709\u7684\u5B9E\u4F53\u3002\u5FC5\u987B\u8986\u76D6 scenes.location\u3001scenes.characters\u3001scenes.props \u548C\u4EBA\u7269 voices.speaker \u4E2D\u6240\u6709\u65E0\u6CD5\u89E3\u6790\u5230\u5DF2\u77E5\u8BBE\u5B9A\u6216 canonicalize \u76EE\u6807\u7684\u540D\u79F0\uFF1B\u53EA\u767B\u8BB0\u5177\u4F53\u5355\u4EBA\u89D2\u8272\u3001\u7A33\u5B9A\u5730\u70B9\u548C\u5173\u952E\u9053\u5177\uFF0C\u7FA4\u4F17\u4E0D\u767B\u8BB0",items:{type:"object",required:["name","kind","status","importance","recognition_anchors","identity_profile","appearance","role","states","aliases"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89C4\u8303\u540D\uFF1B\u8BA4\u4E0D\u51FA\u4E14\u65E0\u672C\u540D\u7684\u4EBA\u7528\u300E\u7A33\u5B9A\u5916\u89C2\u7279\u5F81+\u5E74\u9F84\u6BB5+\u6027\u522B\u300F\u6784\u6210\u4E0D\u542B\u59D3\u7684\u63CF\u8FF0\u540D\uFF0C\u7EDD\u4E0D\u7F16\u5E26\u59D3\u5047\u540D"},kind:mx,status:{type:"string",enum:["canonical","provisional"],description:"canonical=\u8EAB\u4EFD\u5DF2\u786E\u8BA4\uFF1Bprovisional=\u8BA4\u4E0D\u51FA/\u672A\u70B9\u540D\uFF0C\u5F85\u540E\u7EED\u7528\u76F4\u63A5\u547D\u540D\u8BC1\u636E\u5347\u7EA7\u89C4\u8303\u540D"},importance:{type:"string",enum:["featured","background"]},recognition_anchors:{type:"array",items:{type:"string"},description:"\u4EBA\u7269\u586B\u5199 3-6 \u6761\u8DE8\u96C6\u91CD\u8BA4\u951A\u70B9\uFF0C\u6BCF\u6761\u7EC4\u5408\u81F3\u5C11\u4E24\u4E2A\u53EF\u5728 identity_profile \u627E\u5230\u4F9D\u636E\u7684\u7A33\u5B9A\u7279\u5F81\uFF1B\u7981\u6B62\u670D\u88C5\u3001\u53F7\u7801\u3001\u5E3D\u5B50\u3001\u773C\u955C/\u914D\u9970\u3001\u5986\u5BB9\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u4F24\u75D5\u6C61\u6E0D\u3001\u5267\u60C5\u8EAB\u4EFD\u80FD\u529B\u5173\u7CFB\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u573A\u666F\u7269\u4EF6\uFF1B\u5730\u70B9/\u9053\u5177\u586B\u7A7A\u6570\u7EC4"},identity_profile:Lf,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u7684\u7A33\u5B9A\u53EF\u89C1\u63CF\u8FF0\uFF0C\u4EBA\u7269\u586B\u7A7A\u4E32\u3002\u5730\u70B9\u5199\u7A7A\u95F4\u7ED3\u6784\u3001\u6750\u8D28\u3001\u8272\u5F69\u548C\u56FA\u5B9A\u9648\u8BBE\uFF1B\u9053\u5177\u5199\u5F62\u5236\u3001\u6750\u8D28\u3001\u989C\u8272\u548C\u5C3A\u5BF8\u5173\u7CFB"},role:{type:"string",description:"\u5B9E\u4F53\u7684\u8EAB\u4EFD\u3001\u5173\u7CFB\u6216\u7528\u9014\uFF0C\u975E\u7A7A\uFF1B\u53EA\u5199\u539F\u7247\u53EF\u786E\u8BA4\u7684\u8BBE\u5B9A"},states:{type:"array",items:Mf,description:"\u672C\u96C6\u8BE5\u5B9E\u4F53\u51FA\u73B0\u7684\u6301\u4E45\u89C6\u89C9\u72B6\u6001\u3002\u6BCF\u9879\u540C\u65F6\u7ED9\u51FA\u7B80\u6D01\u7A33\u5B9A\u72B6\u6001\u540D\u4E0E\u4ECE\u591A\u4E2A\u6E05\u6670\u955C\u5934\u6C47\u603B\u7684\u53EF\u590D\u73B0\u8BE6\u7EC6\u63CF\u8FF0\uFF1B\u6CA1\u6709\u72EC\u7ACB\u72B6\u6001\u586B\u7A7A\u6570\u7EC4"},aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u89C1\u5230\u7684\u5176\u5B83\u79F0\u547C"}}}},enrich:{type:"array",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u5DF2\u6709\u5B9E\u4F53\u7684\u8865\u5145/\u66F4\u6B63\uFF0C\u53EA\u5199\u53D1\u751F\u53D8\u5316\u7684\u5B57\u6BB5\uFF1B\u65E0\u53D8\u5316\u7684\u5B57\u6BB5\u586B\u7A7A\u4E32/\u7A7A\u6570\u7EC4\uFF0C\u6574\u4F53\u65E0\u53D8\u5316\u7684\u5B9E\u4F53\u4E0D\u8981\u51FA\u73B0",items:{type:"object",required:["name","add_recognition_anchors","identity_profile_patch","appearance","role","add_aliases","add_states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u5DF2\u77E5\u5B9E\u4F53\u7684\u89C4\u8303\u540D"},add_recognition_anchors:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u589E\u3001\u4E14\u6BCF\u4E2A\u8BCD\u90FD\u80FD\u7531 identity_profile \u7A33\u5B9A\u5B57\u6BB5\u652F\u6301\u7684\u9AD8\u533A\u5206\u5EA6\u4EBA\u7269\u91CD\u8BA4\u951A\u70B9\uFF1B\u7981\u6B62\u670D\u88C5\u914D\u9970\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u5916\u89C2\u3001\u5267\u60C5\u8BBE\u5B9A\u548C\u53D8\u8EAB\u5F62\u6001\uFF1B\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},identity_profile_patch:Lf,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u66F4\u51C6\u786E\u7684\u7A33\u5B9A\u5916\u89C2\uFF1B\u4EBA\u7269\u6216\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},role:{type:"string",description:"\u66F4\u660E\u786E\u7684\u8EAB\u4EFD\uFF1B\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},add_aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u51FA\u73B0\u7684\u79F0\u547C"},add_states:{type:"array",items:Mf,description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u7684\u65B0\u72B6\u6001\uFF0C\u6216\u672C\u96C6\u4ECE\u66F4\u591A\u89D2\u5EA6\u83B7\u5F97\u4E86\u66F4\u6E05\u6670\u7EC6\u8282\u7684\u65E2\u6709\u72B6\u6001\uFF1B\u65E2\u6709\u72B6\u6001\u9010\u5B57\u6CBF\u7528\u5176 name\uFF0C\u4EE5\u540C\u540D\u9879\u8865\u5168\u6216\u66F4\u65B0\u8BE6\u7EC6 description\uFF0C\u4E0D\u53E6\u5EFA\u8FD1\u4E49\u72B6\u6001"}}}},canonicalize:{type:"array",description:"\u4EC5\u51ED\u672C\u96C6\u76F4\u63A5\u51FA\u73B0\u7684\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u628A\u5DF2\u77E5\u4EBA\u7269\u7684\u63CF\u8FF0\u540D\u3001\u7B80\u79F0\u6216\u4E0D\u5B8C\u6574\u59D3\u540D\u5347\u7EA7\u4E3A\u66F4\u51C6\u786E\u7684\u89C4\u8303\u540D\uFF1B\u5267\u60C5\u63A8\u65AD\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u6539\u540D\u8BC1\u636E",items:{type:"object",required:["from_name","canonical_name","evidence"],additionalProperties:!1,properties:{from_name:{type:"string",description:"\u5DF2\u77E5\u8BBE\u5B9A\u4E2D\u7684\u5F53\u524D\u89C4\u8303\u540D\u6216\u65E2\u6709\u522B\u540D"},canonical_name:{type:"string",description:"\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u76F4\u63A5\u8BF4\u51FA\u7684\u672C\u540D"},evidence:{type:"string",description:"\u76F4\u63A5\u547D\u540D\u8BC1\u636E\uFF0C\u5FC5\u987B\u5305\u542B MM:SS \u65F6\u95F4\u6233\u4EE5\u53CA\u753B\u9762\u539F\u6587\u6216\u542C\u5230\u7684\u539F\u8BDD"}}}}}},open_threads:{type:"object",required:["opened","closed"],additionalProperties:!1,properties:{opened:{type:"array",description:"\u672C\u96C6\u65B0\u5F00\u3001\u5C1A\u672A\u4EA4\u4EE3\u7ED3\u679C\u7684\u60AC\u5FF5/\u5173\u7CFB\u53D8\u5316",items:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}},closed:{type:"array",description:"\u672C\u96C6\u4EA4\u4EE3\u4E86\u7ED3\u679C\u3001\u8981\u5173\u95ED\u7684\u5DF2\u77E5\u7EBF\u7D22 id\uFF08\u5982 t3_1\uFF09",items:{type:"object",required:["ref"],additionalProperties:!1,properties:{ref:{type:"string"}}}}}}}},$f={type:"object",required:["merges","newEntities"],additionalProperties:!1,properties:{merges:{type:"array",description:"\u672A\u767B\u8BB0\u540D\u5B57\u5176\u5B9E\u662F\u67D0\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u8FD9\u4E2A\u672A\u767B\u8BB0\u7684\u540D\u5B57"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53 canonical \u540D"}}}},newEntities:{type:"array",description:"\u786E\u5B9E\u662F\u5168\u65B0\u5B9E\u4F53\u7684\u540D\u5B57\uFF0C\u5404\u767B\u8BB0\u4E00\u6761",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8EAB\u4EFD\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u5176\u4ED6\u53EB\u6CD5"},defaultLook:Tf}}}}};var K=jt;function jt(e,t){e=e-0;let n=_d(),o=n[e];if(jt.AowUYu===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};jt.vGSHGD=i,jt.ykrKeL={},jt.AowUYu=!0}let r=n[0];jt.qbkWqr!==r&&(jt.ykrKeL={},jt.qbkWqr=r);let s=jt.ykrKeL[e];return s===void 0?(o=jt.vGSHGD(o),jt.ykrKeL[e]=o):o=s,o}var gx=[K(37),K(84),K(100),K(83),K(39),"",K(71),K(55),K(1),K(47),K(10),K(70),K(56),K(46),K(92),K(2),K(61),K(24),K(82),K(51),K(79),K(88),K(58),K(30),K(65),K(73),K(27),K(59),K(86)][K(33)](`
|
|
231
|
-
`);function hx(e,t){let n=K;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
|
|
232
|
-
`)}async function Df(e,t,n,o){let i=K,r=await e[i(45)](i(69),{system:gx,user:hx(t,n),tool:{name:i(44),description:i(22),inputSchema:Cf},...o?{signal:o}:{}});return{delta:ar(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var yx=new Set([K(60),K(40),K(99)]),Oo=e=>typeof e===K(78)&&e!==null&&!Array[K(13)](e),On=e=>typeof e===K(9)?e[K(50)]():"";function Ls(e,t){let n=K,o=On(e);if(!o)throw new Ne(t+n(36));return o}function wx(e,t){let n=K;if(!Oo(e))throw new Ne(t+n(31));let o=Ls(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new Ne(t+n(29));return{name:o,description:Ls(e[n(15)],t+n(93))}}var Ne=class extends Error{[K(12)]=K(34);constructor(t){let n=K;super(t),this[n(32)]=n(0)}};function _x(e){let t=K,n="",o=!1;for(let i=0;i<e[t(28)];i++){let r=e[i];if(!o)if(t(48)!==t(67)){n+=r,r==='"'&&(o=!0);continue}else throw new _0x293dd1(_0x17bbe5+t(89)+(_0x24ef46 instanceof _0x59e65f?_0x136fee[t(20)]:_0x3dfec6(_0x4eb04e)));if(r==="\\"&&i+1<e[t(28)]){n+=r+e[i+1],i++;continue}if(r==='"'){let s=i+1;for(;s<e[t(28)]&&/\s/[t(77)](e[s]);)s++;let c=s<e[t(28)]?e[s]:"";if(c===""||c===","||c==="}"||c==="]"||c===":")if(t(35)===t(35))n+=r,o=!1;else return[t(4),_0x49903e[t(50)]()||t(5),"",t(66),_0x1df459[t(50)]()][t(33)](`
|
|
233
|
-
`);else n+='\\"';continue}n+=r}return n}function Ex(e,t){let n=K,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=_x(e);if(s===e)throw new Ne(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(c){throw new Ne(t+n(26)+(c instanceof Error?c[n(20)]:String(c)))}}if(!Array[n(13)](i))if(n(6)===n(54))_0x291b73=_0x1aa471(_0x238c2b);else throw new Ne(t+n(91)+typeof i);return i}function ko(e,t){let n=K;if(e==null)return[];if(Array[n(13)](e))return e;if(typeof e===n(9)){let o=e[n(50)]();return o?Ex(o,t):[]}throw new Ne(t+n(19)+typeof e)}var xx=/[((]([^))]*)[))]?/;function _d(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3JGihNN63LKi0V5ywO5zcn44cb6iUX5PAh5y6F5zcn77YmkIRLSktLHBBLR7NNMB3OR7tOR53KURRLNkJMRApMLOFPH4ZNMOtLHPNMS5uQkUoaGUATO+AwH+IVToIVNEs6UUwgMEoaJUs8IUAwH8k35BId6Bkb5ywl5PAV44cp6icm5l2GignHBM9UAwnHBcdMMk/JGi7LPkFNIzVJGi/IHPiG5OQk44co5lYk5PAhWRFLUipPSOhLHyVMLQ/JGi/MLl7OV5SGywXPyxnLC++8M+wgMEoaJUwKP+MQQooaJ+IaJcbJyw5VBMLJywWG5PIV44co5AsN6AQO5As044cp4OAsigfSAwfZzxmG5Ps+44co5AsN6AQO44cp44cc57o757UF6z2GigfSAwfZzxmG5OQk5Q2J5PAh6yEm55Qe6k+06k+D5lQ6l+ENSowrVow9KUwiSos9OoI/MEs4QUwUNUs9K++8JcOQywXPyxnLCYdMVi/KUOBLSlhKVjRMLRdPGkdPH43L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OV4FNMOtLRP7KVzpKUi3OPOhPH43LPi3NMBVORRdVVjVOI6xLROpOV5NMRRxMNiNKUOBMLRdLJ6VMS5xVViZNLkGGBwvYz2vZioIHPE+8Jos4JEEuQowCQcbUzxDfBNrPDgLLCYdLHO3LIjFKUidPGy3JGii","lMrLC2nYAxb0Aw9U","Bg9VA3mUywXPyxnLCW","DgPUuMy","C3vIrxzLBNrZ","C3vTBwfYEq","C2XPy2u","ChjVCa","kIRJGjdMNkZMRRxMRApMLOFJGjhLJ6/OG73LJixLKkVOI6xLUBlPM4yQkU+8IoAVJ+MBHUs7PsbGiYbLCf9otK5Giow8GowKTo+8IE+8M+AkIUwUG+s7Row9K+s9NoI/NUE7REAoQoI/M+EAHos4GoAUTEAvTos9K+wKHoEqHU+8JoI3QoMBHUAYV+EuQowqJos4GcbJyw5VBMLJywWG5zcn5A2x44cc","CgfYC2u","C3bSAxq","Bg9VAW"];return _d=function(){return e},_d()}function Ed(e){let t=K,n=On(e),o=xx[t(14)](n);if(!o)return{name:n,aliases:[]};let i=n[t(98)](0,o[t(64)])[t(50)]();if(!i)return{name:n,aliases:[]};let r=(o[1]??"")[t(102)](/[//,,、;;]/)[t(63)](s=>s[t(50)]())[t(18)](Boolean);return{name:i,aliases:r}}var bo=e=>Ed(On(e))[K(32)];function Sx(e){let t=K;if(Oo(e))return e;if(typeof e===t(9))if(t(74)!==t(72)){let n=e[t(50)]();if(!n)return null;let o;try{t(41)!==t(8)?o=JSON[t(101)](n):_0x2b8a69+='\\"'}catch(i){throw t(23)!==t(23)?new _0x35d905(t(21)+typeof _0x315295):new Ne(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!Oo(o)){if(t(3)===t(3))throw new Ne(t(21)+typeof o);{let i=_0x2bdcc7(_0x2ac405);if(i===_0x1e5cf5)throw new _0x4316f0(_0x174809+t(89)+(_0x4121a6 instanceof _0x360b19?_0x4fe8c8[t(20)]:_0x4a58de(_0x51367b)));try{_0x35ac52=_0x593204(i)}catch(r){throw new _0x445300(_0x1d355a+t(26)+(r instanceof _0xcc0770?r[t(20)]:_0x4eee3d(r)))}}}return o}else _0x2ddf79+=_0x1d0308,_0x1ed397=!1;return null}function ar(e){let t=K,n=af(),o=Sx(e);if(!o)return n;for(let i of ko(o[t(25)],t(25))){if(!Oo(i))continue;let r=On(i[t(52)]),{name:s,aliases:c}=Ed(On(i[t(32)]));if(!yx[t(62)](r)||!s)continue;let a=Ls(i[t(15)],t(81)+s+t(93)),d=wx(i[t(75)],t(81)+s+t(43)),p=[...c];for(let f of ko(i[t(16)],t(68))){let{name:u,aliases:m}=Ed(On(f));u&&p[t(76)](u),p[t(76)](...m)}let l=[...new Set(p[t(18)](f=>f&&f!==s))];n[t(25)][t(76)]({name:s,kind:r,description:a,aliases:l,defaultLook:d})}for(let i of ko(o[t(57)],t(57))){if(!Oo(i))continue;let r=bo(i[t(11)]),s=bo(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of ko(o[t(42)],t(42))){if(t(95)!==t(95))throw new _0x2df008(_0x519dc7+t(26)+(_0x40bcf4 instanceof _0x3611af?_0x4f83a8[t(20)]:_0x281cd0(_0x1f7db9)));{if(!Oo(i))continue;let r=bo(i[t(17)]),s=bo(i[t(32)]);if(!r||!s)continue;let c=[s,...ko(i[t(16)],t(94))[t(63)](bo)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:c,description:Ls(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of ko(o[t(85)],t(85))){if(!Oo(i))continue;let r=On(i[t(87)]),s=bo(i[t(17)]),c=bo(i[t(103)]);r&&s&&c&&n[t(85)][t(76)]({scene:r,entity:s,look:c})}return n[t(96)]=ko(o[t(96)],t(96))[t(63)](On)[t(18)](Boolean),n[t(97)]=On(o[t(97)]),n}var ze=zt,Ix=[ze(1),ze(29),ze(18),ze(32),ze(0),ze(7),ze(15),ze(8),ze(3)][ze(21)](`
|
|
234
|
-
`);function Ax(e,t){let n=ze;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
|
|
235
|
-
`)][n(21)](`
|
|
236
|
-
`)}async function Gf(e,t,n,o){let i=ze,r=await e[i(24)](i(26),{system:Ix,user:Ax(t,n),tool:{name:i(11),description:i(12),inputSchema:$f},...o?{signal:o}:{}});return{delta:Sd(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var Us=e=>e[ze(23)](ze(6))[ze(31)](/\s+/g," ")[ze(27)]();function Sd(e,t=[]){let n=ze,o=ar(e),i=new Set;for(let s of o[n(22)])i[n(9)](Us(s[n(33)]));for(let s of o[n(25)]){i[n(9)](Us(s[n(10)]));for(let c of s[n(28)])i[n(9)](Us(c))}let r=t[n(20)](s=>!i[n(2)](Us(s)));if(r[n(17)])throw new Ne(n(16)+r[n(21)]("\u3001"));return o}function zt(e,t){e=e-0;let n=xd(),o=n[e];if(zt.brkHeO===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};zt.xoIkcy=i,zt.GcFqUp={},zt.brkHeO=!0}let r=n[0];zt.pyAYZq!==r&&(zt.GcFqUp={},zt.pyAYZq=r);let s=zt.GcFqUp[e];return s===void 0?(o=zt.xoIkcy(o),zt.GcFqUp[e]=o):o=s,o}function xd(){let e=["5PAW5lQ654MP55QeignHBM9UAwnHBcbUyw1LioEBToAoPEs9V+EuQooaKow+HEw9KUs4GowqJEwTL+oaKEMhJoEAHowoN+AwH+wNK+wqJEAlVowgME+8M+wKLUIVREwNK+wqJEs4JEE/U+IVKEoaGEs4JEMFS+IVKEoaGEs4JEAuUEAiKos4REAwH+wqJEoaGG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idLJ6xOR53OUQVKU70PlcbHBgLHC2vZlcbKzwzHDwX0tg9VAZP7BMfTztON5BI45OcbjYWGzgvZy3jPChrPB2465y+V6kEb5Asw6kEcFx3JGii","zNjVBq"];return xd=function(){return e},xd()}var ut=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ft=e=>Array.isArray(e),kx=5,vo=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Jf=e=>{try{return JSON.parse(e)}catch{return null}},bx=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),Hf=e=>!!e&&typeof e=="object"&&"code"in e&&bx.has(String(e.code)),Ff=e=>new Promise(t=>setTimeout(t,e)),si=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function Bf(e,t,n,o,i,r){for(let s=1;;s++)try{return await Df(e,o,i,r)}catch(c){if(Hf(c)&&s<3&&!r?.aborted){await Ff(3e3*s);continue}throw new x(`serial govern failed at ${si(t,n)}.`,{exitCode:b,errorCode:"INGEST_SERIAL_FAILED",hint:c instanceof Ne?`Model returned a malformed serial delta (${c.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${si(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${si(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}function Qf(e,t){let n=t.merges.map(o=>o.into).filter(o=>!Ot(e,o));if(n.length)throw new Ne(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function Kf(e,t,n,o,i,r,s){for(let c=1;;c++)try{let a=await Gf(e,o,i,s);return Qf(r,a.delta),a}catch(a){if(Hf(a)&&c<3&&!s?.aborted){await Ff(3e3*c);continue}throw new x(`serial name repair failed at ${si(t,n)}.`,{exitCode:b,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:a instanceof Ne?`Model returned an incomplete name repair (${a.message}). Rerun \`scriptctl ingest\` to retry ${si(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${si(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}async function Yf(e,t){let n=cf(),o=e.episodes??[],i=0,r=o.map(Nx),s=pf(r.map(df),t.windowTokens);for(let a=0;a<s.length;a++){let[d,p]=s[a],l=Ss(n,p),f=r.slice(d-1,p).join(`
|
|
237
|
-
|
|
238
|
-
`),u=t.sourceRef?`# \u539F\u6587\u8BBE\u5B9A\uFF08\u53C2\u8003\uFF0C\u6765\u81EA\u539F\u7A3F\u5F00\u5934\uFF09
|
|
239
|
-
${t.sourceRef}
|
|
240
|
-
|
|
241
|
-
${l}`:l,m=Date.now(),g=t.force?void 0:t.checkpoint?.readUpdate(d,p),h,w=!1;if(g!==void 0){let E=Jf(g);try{if(E==null)throw new Ne("checkpoint top-level JSON is unparseable");h=ar(E),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(S){if(!(S instanceof Ne))throw S;let _=await Bf(t.executor,d,p,u,f,t.signal);h=_.delta,t.checkpoint?.writeStep(d,p,l,_.raw)}}else{let E=await Bf(t.executor,d,p,u,f,t.signal);h=E.delta,t.checkpoint?.writeStep(d,p,l,E.raw)}rr(n,h,d,p);let y=Ox(o.slice(d-1,p),n);if(y.length){let E=t.force?void 0:t.checkpoint?.readNameFix?.(d,p);if(E!==void 0){let S=Jf(E);try{if(S==null)throw new Ne("name-fix checkpoint top-level JSON is unparseable");let _=Sd(S,y);Qf(n,_),rr(n,_,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(_){if(!(_ instanceof Ne))throw _;let A=await Kf(t.executor,d,p,Ss(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),rr(n,A.delta,d,p)}}else{let S=await Kf(t.executor,d,p,Ss(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,S.raw),rr(n,S.delta,d,p)}}lf(n);for(let E=cd(n);E;E=cd(n)){let S=E[0].startEp,_=E[E.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(S,_),k;if(A!==void 0)k=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let D=E.map(R=>`${rd(R)}\uFF1A${R.line}`).join(`
|
|
242
|
-
`);k=await Rf(t.executor,`\u7B2C${S}\u96C6\u2013\u7B2C${_}\u96C6`,D,t.signal),t.checkpoint?.writeArc?.(S,_,k)}uf(n,k)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-m,cached:w,index:a,total:s.length,totalEpisodes:o.length})}return{...Mx(e,n),episodes:o.length,reused:i}}function Ox(e,t){let n=new Set,o=i=>{if(!i)return;let r=Xn(t,i);lt(r)||Ot(t,r)||n.add(r)};for(let i of e)for(let r of i.scenes){o(r.location?.name);for(let s of r.actors)o(s.name);for(let s of r.actions)s.speaker&&"name"in s.speaker&&o(s.speaker.name)}return[...n]}var vx={interior:"\u5185",exterior:"\u5916"},Rx={day:"\u65E5",night:"\u591C"};function Nx(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[vx[n.environment?.space??""],Rx[n.environment?.time??""]].filter(Boolean).join(" ");o&&t.push(`\u65F6\u7A7A\uFF1A${o}`),n.location?.name&&t.push(`\u5730\u70B9\uFF1A${n.location.name}`),n.actors.length&&t.push(`\u5728\u573A\uFF1A${n.actors.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`),n.props.length&&t.push(`\u9053\u5177\uFF1A${n.props.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`);for(let i of n.actions){let r=i.speaker?"name"in i.speaker?i.speaker.name:`[${i.speaker.kind}]`:"",s=i.emotion?`\uFF08${i.emotion}\uFF09`:"";i.type==="dialogue"?t.push(`${r}${s}\uFF1A${i.content}`):i.type==="inner_thought"?t.push(`${r}\uFF08\u5FC3\uFF09${s}\uFF1A${i.content}`):i.type==="transition"?t.push(`\u3010\u8F6C\u573A\u3011${i.content}`):t.push(i.content)}}return t.join(`
|
|
243
|
-
`)}function Mx(e,t){let n=JSON.parse(JSON.stringify(e)),o=new Map;for(let c of n.episodes)for(let a of c.scenes){let d=h=>!!Ot(t,h),p=a.location?Xn(t,a.location.name):null,l=jf(a.actors.map(h=>Xn(t,h.name)).filter(h=>!lt(h)&&d(h))),f=jf(a.props.map(h=>Xn(t,h.name)).filter(d)),u=[];for(let h of a.actions)if(h.speaker&&"name"in h.speaker){let w=Xn(t,h.speaker.name);lt(w)?h.speaker={kind:"group",label:w}:(h.speaker.name=w,d(w)&&u.push(w))}for(let h of u)l.some(w=>vo(w)===vo(h))||l.push(h);let m=new Map;for(let h of t.lookChanges[a.scene_id]??[]){let w=Xn(t,h.entity),y=m.get(w)??[];y.includes(h.look)||y.push(h.look),m.set(w,y),o.set(w,h.look)}let g=h=>m.get(h)?.map(w=>({name:h,state:w}))??[zf(t,h,o)];a.location=p&&d(p)?zf(t,p,o):null,a.actors=l.flatMap(g),a.props=f.flatMap(g)}let i=xs(n),r=i.script;Tx(r,t),Cx(r);let s=Ms(r);return Ux(s),Px(s),{doc:s,identityKeys:i.identityKeys}}var Lx="\u5E38\u6001";function jf(e){let t=new Set;return e.filter(n=>{let o=vo(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function zf(e,t,n){let o=Ot(e,t),i=n.get(t)??(o?ad(o):void 0)??Lx;return{name:t,state:i}}function Ux(e){for(let t of["actors","locations","props"])for(let n of ft(e[t])?e[t]:[])if(ut(n))for(let o of ft(n.states)?n.states:[])ut(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function Tx(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of ft(e[n])?e[n]:[]){if(!ut(i))continue;let r=Ot(t,String(i[o])),s=ft(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...ft(i.aliases)?i.aliases:[],...r.aliases])]);let c=ad(r),a=c?r.looks.find(d=>vo(d.name)===vo(c))?.description??"":"";for(let d of s){if(!ut(d))continue;if(d.state_id==="default"){a&&(d.description=a);continue}let p=r.looks.find(l=>vo(l.name)===vo(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function Cx(e){let t=new Map,n=new Map,o=new Map,i=0,r=c=>{typeof c=="string"&&(t.has(c)||t.set(c,i),n.set(c,i),o.set(c,(o.get(c)??0)+1))};for(let c of ft(e.episodes)?e.episodes:[])if(!(!ut(c)||!ft(c.scenes)))for(let a of c.scenes){if(!ut(a))continue;let p=[...ft(a.actors)?a.actors:[],...ft(a.props)?a.props:[],...ut(a.location)?[a.location]:[]].filter(ut).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of ft(a.actions)?a.actions:[])ut(l)&&ut(l.speaker)&&typeof l.speaker.actor_id=="string"&&r(l.speaker.actor_id),i++}let s=c=>(o.get(c)??0)>=2&&n.get(c)-t.get(c)>=kx;for(let[c,a]of[["actors","actor_id"],["props","prop_id"]])for(let d of ft(e[c])?e[c]:[])ut(d)&&(d.importance=s(String(d[a]))?"featured":"background");for(let c of ft(e.locations)?e.locations:[])ut(c)&&(c.importance="featured")}function Px(e){let t=n=>typeof n=="string"?n.trim():"";for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of ft(e[n])?e[n]:[]){if(!ut(i))continue;let r=String(i[o]??""),s=ft(i.states)?i.states:[];if(!t(i.description))throw new x(`Ingested asset "${r}" is missing its identity description.`,{exitCode:b,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let c of s){if(!ut(c)||t(c.description))continue;let a=String(c.state_name??"");throw new x(`Ingested asset "${r}" has no visual description for look "${a}".`,{exitCode:b,errorCode:c.state_id==="default"?"DEFAULT_LOOK_DESCRIPTION_MISSING":"LOOK_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this look."})}}}var an=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),vn=e=>Array.isArray(e)?e:[],He=e=>typeof e=="string"?e.trim():"";function Id(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var Vx={actor:{list:"actors",id:"actor_id",name:"actor_name"},location:{list:"locations",id:"location_id",name:"location_name"},prop:{list:"props",id:"prop_id",name:"prop_name"}},qf=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function Wf(e){let t=an(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let c of["actor","location","prop"]){let a=Vx[c];for(let d of vn(t[a.list])){if(!an(d))continue;let p=He(d[a.id]),l=He(d[a.name]);if(!p)continue;let f=[...new Set(vn(d.aliases).map(He).filter(Boolean))],u=new Map,m=[];for(let h of vn(d.states)){if(!an(h))continue;let w=He(h.state_id);if(!w)continue;let y=He(h.state_name),E={address:`${p}/${w}`,state_id:w,state_name:y,description:He(h.description),format_key:Id(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};m.push(E),u.set(w,E)}let g={kind:c,id:p,name:l,aliases:f,description:He(d.description),importance:He(d.importance),format_key:Id(l),alias_format_keys:f.map(Id),reference_count:0,episode_count:0,scene_count:0,references:[],states:m,episodeIds:new Set,sceneIds:new Set,stateById:u};n[c].push(g),o.set(p,g)}}let i=c=>{let a=vn(c.state_ids).map(He).filter(Boolean);if(a.length>0)return[...new Set(a)];let d=He(c.state_id);return d?[d]:[]},r=(c,a,d,p,l,f)=>{let u=o.get(a);if(!u||u.kind!==c)return;u.reference_count+=1,u.episodeIds.add(p),u.sceneIds.add(`${p}/${l}`),qf(u.references,f);let m=d.length>0?d:u.stateById.has("default")?["default"]:[];for(let g of m){let h=u.stateById.get(g);h&&(h.reference_count+=1,h.episodeIds.add(p),h.sceneIds.add(`${p}/${l}`),qf(h.references,f))}};for(let c of vn(t.episodes)){if(!an(c))continue;let a=He(c.episode_id)||"<episode>";for(let d of vn(c.scenes)){if(!an(d))continue;let p=He(d.scene_id)||"<scene>",l=`${a}/${p}`;an(d.location)&&r("location",He(d.location.location_id),i(d.location),a,p,`${l}.location`);for(let f of vn(d.actors))an(f)&&r("actor",He(f.actor_id),i(f),a,p,`${l}.actors`);for(let f of vn(d.props))an(f)&&r("prop",He(f.prop_id),i(f),a,p,`${l}.props`);vn(d.actions).forEach((f,u)=>{if(!an(f)||!an(f.speaker))return;let m=He(f.speaker.actor_id);m&&r("actor",m,i(f.speaker),a,p,`${l}#${u+1}.speaker`)})}}let s=c=>{c.episode_count=c.episodeIds.size,c.scene_count=c.sceneIds.size;for(let a of c.states)a.episode_count=a.episodeIds.size,a.scene_count=a.sceneIds.size,a.frequency_flag=a.state_id==="default"?null:a.scene_count===0?"unused":a.scene_count===1?"singleton":null;return{kind:c.kind,id:c.id,name:c.name,aliases:c.aliases,description:c.description,importance:c.importance,format_key:c.format_key,alias_format_keys:c.alias_format_keys,reference_count:c.reference_count,episode_count:c.episode_count,scene_count:c.scene_count,references:c.references,states:c.states.map(a=>({address:a.address,state_id:a.state_id,state_name:a.state_name,description:a.description,format_key:a.format_key,reference_count:a.reference_count,episode_count:a.episode_count,scene_count:a.scene_count,references:a.references,frequency_flag:a.frequency_flag}))}};return{title:He(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var V=Ft,Xf=["id",V(38),V(13),V(90),V(40),V(34),V(6),V(82),V(35),V(62)];function bd(){let e=["yxnZzxrFAwrZ","DgL0Bgv8","5l6l5AAc44co5P6x5PYj57kU44cp5zkm44co5P6xioACIEEYRUoaJ+wpQUAyR+AGVow8J+s4JEwqJo+8Jos9HUs4JEIdVEwpQUAmIEwqJEENSoEBUos8Vow6PUwqIow5TUoaGUw/HEMHU+E7VowqIos6UUEjQEwfS+EZU+oaGEwjP+AdHEI6Q+s7VEoaGEwKLUIYJoApJ+I/SooaGEIHJos4UUI9QoI/UEoaGEwVUEEzVEw9KUwXNUoaGEwhUUEoSos9JEE9RUwsJoI3QoMBHUI/NUE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NldNGRNJGihPGzpLHBFLIiBLJlRVViXoioAyR+IVPEwiHUwmUUI1Hos6P+AvSow5TUwgS+wUMUwfTUs4RsbbioIHJoEAHoI1Hos6P+EXU+wEI+oaGG","CMv2Awv3","5Qoa5P+L5zcm5lIa5lIQ54MP55cg5zYW54k55OIw5zcm5lIa5lU25yw35l2t6ygt5yw35PIV5zcM5zUG5zcn56EW44cb5yMn5zco57Ya44cb5B2s5BgE5O+p6l+W44cb566a56EW44cb566a57Mb5l2t44cb6l2S5B2v5BEU5BYc5OIw6kEc5A+F6kEs5BQM5lIn5zcm6icm6yEn5Asn55M76k6W44cc5yY65yIg5zcm5lIa5zYW54k555Qe5lIn5zcm5zcn56EW5lIo5zcm5lIa5BU6562r5lIT55Qe5lIn5zcm54US56Ul56M66zE077Ym5lMF5yY65yIg5zcm5lIa5lU25yw35l2t6ygt5yw35lIo5zcm57g75l2g5A6E6zMf5lIn5zcm55Qe5AsA5lU26ygt5yw344cc","yxnZzxqGyxvKAxqGCMvZCg9UC2uGBxvZDcbIzsbHiePtt04GB2jQzwn0","CMvJB21Tzw5KyxrPB24","AgLNAa","zw1PDf9HC3nLDf9HDwrPDa","Bg93","ywn0Aw9U","C3rHDgvFAwrZ","zMLSDgvY","qvntrvrFqvvesvrFu05bufnit1rFvJe","zM9YBwf0x2TLEsdLJ6RMIPJLJ6dNQBRNMB3JGihMOiFNGRNJGihLPkFLSi/LHPNJGihLHAJLJyROP5lNRyNMOlZLVi/LT67LVilVViZMMk/LJ6ZLM57OR4hMJA7OGiZKUi3MMk/LKiZKUidLRP7KVzpNMOtMNidNU4JNU5pORRRJGii","AxnbCNjHEq","zxbPC29Kzxm","zgvZy3jPChrPB24","CMvWBgfJzq","BwvKAxvT","BMfTzq","u19dt0Xvtu5tFa","CMvMCW","5l2G5Q2J5zYO5A+55lIa6yoO5BEY57Up5A6m5OIq6kEJ5P6q55Qe5A6m5Pw05yMN5PYS6l+B6kgm5ywO5Bga6lwe5lQN5lIa6iE05OcN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s44cb566a57Mb5l2t77YB5ywO5zcn44cb566a56EW44cb5PI156EW44cb56EW6lct44cb6igm5l2n44cb5PEN5zcn44cb5yYw5zcn44cb6k+r5zcn44cb6z+Z6k+r77YB5yIg6k+n5BEU5BYc44cb6l275B6U6zsz5yIR5A2x44cb6l2S5B2v6k+V5BEU77YB5zcn56EW6zMe5BIM6lQR5lU944cb5Oof57UQ44cb5A+555M95OIw54Q25Ocb6k+05PIo77YB5yMn5PYF6lQR5lU95PYQ5PIo44cb5zco5PYF5y+i5lUL55YF5zcn6yEn5PAW55M76k6W44cc","5zYO5zcm5lIa5lIQ5lQ654MP44cb5zYW54k55OIw6ygt5yw35yAf6yoO77Ym5Qoa5P+L5PIV5zcM5zUG5O+p6l+W5PA55BYp44cb6AkC6iMY57ks5BQM44cb5O6Q6l6E6k+M55wL5OIw6kEc5A+F6kEs5BQM5lIn5zcm77Ym5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return bd=function(){return e},bd()}var em=[V(5),V(38),V(40),V(34),V(6),V(11),V(82),V(35),V(62)],$x=[V(41),V(20),V(14)+Xf[V(45)](V(68))+V(61),V(77)+em[V(45)](V(68))+V(79),V(58),V(32),"",V(75),V(83),V(2),"",V(91),V(84),V(53),"",V(92),V(56),"",V(60),V(22),V(74),"",V(7),V(52),V(9),V(8),V(67),V(43)][V(45)](`
|
|
244
|
-
`),Dx=new Set([V(80),V(55),V(10),V(86),V(57),V(70),V(65)]),Gx=new Set([V(85),V(78),V(21)]),Jx=new Set([V(25),V(37),V(27)]);function Ht(e){let t=V,n=e[t(93)]();return n?n[t(36)](/\\/g,"\\\\")[t(36)](/\r\n?|\n/g,"\\n")[t(36)](/\|/g,"\\|")[t(36)](/;/g,"\\;"):"-"}function Ad(e){let t=V;return e[t(18)]>0?e[t(69)](Ht)[t(45)](";"):"-"}function Bx(e){let t=V,n=[t(31),t(1)+Ht(e[t(42)]),t(46)+Xf[t(45)]("|"),t(39)+em[t(45)]("|")],o=(i,r)=>{let s=t;n[s(71)]("["+i+":"+r[s(18)]+"]");for(let c of r)if(s(88)!==s(88)){_0x4c5672[s(71)](["A",_0x3346d3(_0x10ff10.id),_0x491f28(_0x2e3418[s(38)]),_0x43a7a6(_0x21c903[s(13)]),_0x59e3d3(_0x33921a[s(90)]),_0x5b4072(_0x3f99c5[s(19)]),_0x1e2ca7(_0x46d1f3[s(3)]),_0x7f6b22(_0xcfe569[s(64)]),_0x376ad7(_0x21b2b4[s(82)]),_0x4dc2db(_0xcd97ac[s(35)]),_0x390c6b(_0x4f88f5[s(4)])][s(45)]("|"));for(let a of _0xef23b5[s(17)])_0x5593cc[s(71)](["S",_0x265c62(a[s(5)]),_0x1ae902(a[s(49)]),_0xabc48e(a[s(19)]),_0x4a1d6b(a[s(3)]),_0x514694(a[s(64)]),a[s(15)]??"-",_0x5aa3d6(a[s(82)]),_0x32748e(a[s(35)]),_0x3d8f50(a[s(4)])][s(45)]("|"))}else{n[s(71)](["A",Ht(c.id),Ht(c[s(38)]),Ad(c[s(13)]),Ht(c[s(90)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),Ht(c[s(82)]),Ht(c[s(35)]),Ad(c[s(4)])][s(45)]("|"));for(let a of c[s(17)])n[s(71)](["S",Ht(a[s(5)]),Ht(a[s(49)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),a[s(15)]??"-",Ht(a[s(82)]),Ht(a[s(35)]),Ad(a[s(4)])][s(45)]("|"))}};return o(t(47),e[t(47)]),o(t(81),e[t(81)]),o(t(54),e[t(54)]),n[t(45)](`
|
|
245
|
-
`)}function Ft(e,t){e=e-0;let n=bd(),o=n[e];if(Ft.qyTtRy===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};Ft.uxwRFZ=i,Ft.OXUPnC={},Ft.qyTtRy=!0}let r=n[0];Ft.TDHWfX!==r&&(Ft.OXUPnC={},Ft.TDHWfX=r);let s=Ft.OXUPnC[e];return s===void 0?(o=Ft.uxwRFZ(o),Ft.OXUPnC[e]=o):o=s,o}var Zf=e=>typeof e===V(48)&&e!==null&&!Array[V(33)](e),tm=e=>Array[V(33)](e)?e:[],Ro=e=>typeof e===V(63)?e[V(93)]():"",kd=e=>[...new Set(tm(e)[V(69)](Ro)[V(30)](Boolean))];function Kx(e,t){let n=V;if(!Zf(e))throw new Error(n(23));let o=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(69)](s=>s.id)),i=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(59)](s=>s[n(17)][n(69)](c=>c[n(5)]))),r=[];for(let s of tm(e[n(73)])){if(!Zf(s))continue;let c=Ro(s[n(50)]),a=Ro(s[n(28)]),d=Ro(s[n(76)]);if(!Dx[n(44)](c)||!Gx[n(44)](a)||!Jx[n(44)](d))continue;let p=kd(s[n(0)])[n(30)](m=>o[n(44)](m)),l=kd(s[n(29)])[n(30)](m=>i[n(44)](m));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=Ro(s[n(51)]),u=f&&(o[n(44)](f)||i[n(44)](f))?f:null;r[n(71)]({type:c,asset_ids:p,state_ids:l,names:kd(s[n(87)]),evidence:Ro(s[n(16)]),recommendation:Ro(s[n(24)]),suggested_survivor:u,action:a,confidence:d})}return r}async function nm(e,t,n){let o=V,i=await e[o(12)](o(66),{system:$x,user:Bx(t),tool:{name:o(26),description:o(89),inputSchema:Uf},...n?{signal:n}:{}});return Kx(i[o(72)],t)}var om="1",jx=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===om&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function zx(e,t){return{audit_version:om,script_hash:e,created_at:new Date().toISOString(),summary:{issues:t.length,high:t.filter(n=>n.confidence==="high").length,medium:t.filter(n=>n.confidence==="medium").length,low:t.filter(n=>n.confidence==="low").length},issues:t}}async function Od(e,t,n){let o=Ce(e),i=Wf(e),r=await nm(t,i,n);return zx(o,r)}async function Hx(e){let t=Ce(e.script);if(!e.force&&e.exists())try{let o=e.read();if(jx(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await Od(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function im(e,t,n,o={}){return Hx({script:t,executor:n,read:()=>e.readJson("asset-audit.json"),write:i=>e.writeJson("asset-audit.json",i),exists:()=>e.has("asset-audit.json"),...o.force?{force:!0}:{},...o.signal?{signal:o.signal}:{}})}var Fx={duplicate_actor:"duplicate actor",duplicate_location:"duplicate location",duplicate_prop:"duplicate prop",duplicate_state:"duplicate state",suspicious_singleton_state:"suspicious singleton state",unused_state:"unused state",needs_human_review:"asset needs human review"};function vd(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${Fx[e.type]} [${t}]: ${n}`}function rm(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${vd(t)}; action=${t.action}; confidence=${t.confidence}`}))}var Ts=class{constructor(t,n=()=>Date.now()){this.flush=t;this.now=n;this.t={startedMs:this.now(),endedMs:null,phases:[],serial:null},this.flush(this.t)}flush;now;t;phaseStart(t){this.t.phases.push({name:t,startedMs:this.now(),endedMs:null}),this.flush(this.t)}phaseEnd(t){for(let n=this.t.phases.length-1;n>=0;n--){let o=this.t.phases[n];if(o.name===t&&o.endedMs===null){o.endedMs=this.now(),this.flush(this.t);return}}}serialStart(t,n){this.t.serial={totalWindows:t,totalEpisodes:n,windows:[]},this.flush(this.t)}windowDone(t,n,o,i){this.t.serial||(this.t.serial={totalWindows:0,totalEpisodes:0,windows:[]}),this.t.serial.windows.push({start:t,end:n,ms:o,cached:i}),this.flush(this.t)}finish(){this.t.endedMs=this.now(),this.flush(this.t)}};function sm(e,t){let n=(e.endedMs??t)-e.startedMs,o=e.phases.map(r=>({name:r.name,ms:(r.endedMs??t)-r.startedMs,running:r.endedMs===null})),i=null;if(e.serial){let r=e.serial.windows,s=r.filter(p=>!p.cached),c=s.length?s.reduce((p,l)=>p+l.ms,0)/s.length:null,a=r.reduce((p,l)=>p+(l.end-l.start+1),0),d=Math.max(0,e.serial.totalWindows-r.length);i={doneWindows:r.length,totalWindows:e.serial.totalWindows,doneEpisodes:a,totalEpisodes:e.serial.totalEpisodes,avgWindowMs:c!=null?Math.round(c):null,etaMs:c!=null?Math.round(c*d):null}}return{elapsedMs:n,done:e.endedMs!==null,phases:o,serial:i}}import*as cm from"node:crypto";function Nd(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function Qx(e,t){if(t.status==="reused"){e.reused+=1;return}e.calls+=1,t.status==="succeeded"?e.succeeded+=1:e.failed+=1,e.attempts+=t.attempts,e.durationMs+=t.durationMs,e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cachedInputTokens+=t.cachedInputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.totalTokens=e.inputTokens+e.outputTokens}function Cs(e){let t=Nd();for(let n of e)Qx(t,n);return t}var dr=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function dm(e){let t=new Map;for(let n of e){let o=dr(n),i=t.get(o)??{identity:{provider:n.provider,protocol:n.protocol,model:n.model},profiles:new Set,fingerprints:new Set,records:[]};i.profiles.add(n.profile),i.fingerprints.add(n.fingerprint),i.records.push(n),t.set(o,i)}return[...t.values()].map(n=>({...n.identity,profiles:[...n.profiles].sort(),fingerprints:[...n.fingerprints].sort(),totals:Cs(n.records)})).sort((n,o)=>dr(n).localeCompare(dr(o)))}function Rd(e){let t=new Map;for(let n of e){let o=t.get(n.task)??[];o.push(n),t.set(n.task,o)}return[...t.entries()].map(([n,o])=>({task:n,totals:Cs(o),byModel:dm(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function am(e){return dm(e).map(t=>{let n=e.filter(o=>dr(o)===dr(t));return{...t,byTask:Rd(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function Yx(e){let t=e.updatedAt,n=new Map;for(let r of e.episodes)n.set(r.episode,r.runs);let o=[...n.entries()].map(([r,s])=>{let c=new Set(s.flatMap(d=>d.recordIds)),a=e.records.filter(d=>c.has(d.id));return{episode:r,totals:Cs(a),byTask:Rd(a),byModel:am(a),durationMs:s.reduce((d,p)=>d+p.durationMs,0),runs:s}}).sort((r,s)=>r.episode-s.episode),i=Cs(e.records);return{...e,updatedAt:t,totals:i,byTask:Rd(e.records),byModel:am(e.records),episodes:o,timing:{totalDurationMs:e.runs.reduce((r,s)=>r+s.durationMs,0),modelDurationMs:i.durationMs,episodeDurationMs:o.reduce((r,s)=>r+s.durationMs,0)}}}function qx(e){return{version:2,createdAt:e,updatedAt:e,totals:Nd(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function cr(e){return new Date(e).toISOString()}var ai=class{constructor(t,n,o=()=>Date.now()){this.store=t;this.executor=n;this.now=o;this.startedAtMs=this.now(),this.cursor=n.usageEvents().length;let i=cr(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):qx(i),this.report.version!==2)throw new Error("workspace/usage.json uses an incompatible schema; rerun ingest with --force to rebuild the workspace.");for(let r of this.report.runs)r.status==="running"&&(r.status="interrupted",r.endedAt=this.report.updatedAt,r.durationMs=Math.max(0,Date.parse(this.report.updatedAt)-Date.parse(r.startedAt)));this.report.runs.push({id:this.runId,status:"running",startedAt:i,endedAt:null,durationMs:0}),this.write(this.startedAtMs)}store;executor;now;runId=cm.randomUUID();startedAtMs;cursor;report;flush(t){let n=t.endedAtMs??this.now(),o=t.startedAtMs??n,i=this.executor.usageEvents(),s=i.slice(this.cursor).map(c=>this.toRecord(c,t.scope));if(this.cursor=i.length,this.report.records.push(...s),t.scope.kind==="episode"){let c=t.scope.episode,a=this.report.episodes.find(p=>p.episode===c),d=a?.runs??[];d.push({runId:this.runId,status:t.status??"succeeded",startedAt:cr(o),endedAt:cr(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),a||this.report.episodes.push({episode:c,totals:Nd(),byTask:[],byModel:[],durationMs:0,runs:d})}this.write(n)}finish(t){let n=this.now();this.executor.usageEvents().length>this.cursor&&this.flush({scope:{kind:"run"},status:t==="succeeded"?"succeeded":"failed",endedAtMs:n});let o=this.report.runs.find(i=>i.id===this.runId);o&&(o.status=t,o.endedAt=cr(n),o.durationMs=Math.max(0,n-this.startedAtMs)),this.write(n)}toRecord(t,n){return{...t,id:`${this.runId}:${t.sequence}`,runId:this.runId,scope:n}}write(t){let n=this.report.runs.find(o=>o.id===this.runId);n?.status==="running"&&(n.durationMs=Math.max(0,t-this.startedAtMs)),this.report.updatedAt=cr(t),this.report=Yx(this.report),this.store.writeJson("usage.json",this.report)}};var Ld="12",Ps=e=>String(e).padStart(3,"0"),pm=e=>e.map(t=>JSON.stringify(t)).join(`
|
|
246
|
-
`)+`
|
|
247
|
-
`;function Wx(e,t,n){if(e.has("manifest.json")){let o=e.readJson("manifest.json");if(o.source?.sha256&&o.source.sha256!==t)throw new x("This workspace was built from a different source. --force cannot switch sources.",{exitCode:b,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh --workspace-path for the new source.",data:{actual:["workspace source differs from --source-path"]}});if(!n&&o.pipeline_version&&o.pipeline_version!==Ld)throw new x("This workspace was created by an older text-ingest pipeline.",{exitCode:b,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Rerun `scriptctl ingest --force` with the same source to rebuild its checkpoints.",data:{actual:[`workspace pipeline ${o.pipeline_version}; current ${Ld}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])Md.rmSync(e.path(o),{recursive:!0,force:!0});for(let o of["body.json","script.initial.json","script.json","validation.json","asset-audit.json","notes.json","issues.json","provisional_assets.json","usage.json","v4_identity_map.json"])Md.rmSync(e.path(o),{force:!0})}}async function lm(e){let t=Wn(e.sourcePath);if(t.kind!=="text")throw new x("runTextIngest received a non-text source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});let n=await xf(t.path,t.ext),o=Se(n),i=new At(e.workspacePath);i.ensure(),Wx(i,o,e.force??!1);let r=new Ts(a=>i.writeJson("timings.json",a)),s=new ai(i,e.executor),c="failed";try{let a=Date.now(),d=0;if(!e.force&&i.has("pass1/body_start.json"))d=i.readJson("pass1/body_start.json").line??0,e.executor.recordReuse("ingest.body-start");else{let L=await bf(e.executor,n,e.signal);d=L.line,i.writeJson("pass1/body_start.json",L)}let p=n.split(`
|
|
248
|
-
`),l=d>0?p.slice(d).join(`
|
|
249
|
-
`):n,f=d>0?p.slice(0,d).join(`
|
|
250
|
-
`).trim().slice(0,6e3):"",u=ef(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(L=>({index:L.index,core_line_start:L.core_line_start,core_line_end:L.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:Ld,updated:new Date().toISOString(),source:{path:ci.resolve(t.path),sha256:o,kind:"text",ext:t.ext},chunks:u.length}),s.flush({scope:{kind:"phase",phase:"prepare"},status:"succeeded",startedAtMs:a});let m=0;r.phaseStart("normalize");let g=await Of(u,e.concurrency??30,async L=>{let oe=`pass2/chunk_${Ps(L.index)}.json`,he=`pass2/chunk_${Ps(L.index)}.error.json`;if(i.has(oe)&&!e.force){let We=fd(i.readJson(oe),L);return i.clearError(he),m++,e.executor.recordReuse("ingest.text-normalize"),We}let{raw:rt,records:qt}=await If(e.executor,L,e.signal);return i.writeText(oe,rt),i.writeText(`pass2/chunk_${Ps(L.index)}.jsonl`,pm(qt)),i.clearError(he),qt}),h=g.filter(L=>!L.ok);for(let L of h){let oe=L.error instanceof Error?L.error.message:String(L.error);i.writeJson(`pass2/chunk_${Ps(L.index)}.error.json`,{chunk:L.index,error:oe})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:h.length?"failed":"succeeded"}),h.length>0)throw new x(`${h.length}/${u.length} chunk(s) failed normalization.`,{exitCode:b,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:h.map(L=>`chunk ${L.index}`)}});r.phaseEnd("normalize");let w,y,E;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?ir(i.readText("pass3/script.jsonl")).length:0,E=i.has("notes.json")?i.readJson("notes.json").length:0,m++;else{let L=[];for(let qt of g)qt.ok&&L.push(...qt.value);i.writeText("pass3/script.jsonl",pm(L));let oe=ir(i.readText("pass3/script.jsonl")),he=Zx(t.path),rt=Xu(oe,{title:he});i.writeJson("notes.json",rt.notes),w=rt.script,i.writeJson("body.json",w),y=L.length,E=rt.notes.length}let S=L=>String(L).padStart(3,"0"),_=(L,oe)=>`serial/win_${S(L)}_${S(oe)}.json`,A={readUpdate:(L,oe)=>i.has(_(L,oe))?i.readText(_(L,oe)):void 0,writeStep:(L,oe,he,rt)=>{i.writeText(`serial/context_${S(L)}.md`,he),i.writeText(_(L,oe),rt)},readArc:(L,oe)=>{let he=`serial/arc_${S(L)}_${S(oe)}.md`;return i.has(he)?i.readText(he):void 0},writeArc:(L,oe,he)=>{i.writeText(`serial/arc_${S(L)}_${S(oe)}.md`,he)},readNameFix:(L,oe)=>{let he=`serial/fix_${S(L)}_${S(oe)}.json`;return i.has(he)?i.readText(he):void 0},writeNameFix:(L,oe,he)=>i.writeText(`serial/fix_${S(L)}_${S(oe)}.json`,he)};r.phaseStart("serial");let k=await Yf(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:L=>{L.index===0&&r.serialStart(L.total,L.totalEpisodes),r.windowDone(L.startEp,L.endEp,L.ms,L.cached);let oe=L.startEp===L.endEp?{kind:"episode",episode:L.startEp}:{kind:"episode-range",startEpisode:L.startEp,endEpisode:L.endEp},he=Date.now();s.flush({scope:oe,status:L.cached?"reused":"succeeded",startedAtMs:he-L.ms,endedAtMs:he})},...e.signal?{signal:e.signal}:{}}),D=k.doc;m+=k.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:R,idMap:I}=ks(D);i.writeJson("id_map.json",I);let M=at(R);if(!M.ok)throw i.writeJson("validation.json",M),new x("Intermediate script failed validation before v4 identity assignment.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:M.errors.slice(0,5).map(L=>`${L.path}: ${L.message}`)}});let $=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,U=ii(It(D),$,k.identityKeys),v=U.script,j=Ue(v),Z=[],De=Date.now(),B="failed";try{if(j.ok){let L=await im(i,v,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});Z=rm(L.report)}B="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:B,startedAtMs:De})}let be={...j,warnings:[...j.warnings,...Is(v),...Z]};if(i.writeJson("pass5/script.json",v),i.writeJson("v4_identity_map.json",U.identityMap),i.writeJson("validation.json",be),!be.ok)throw new x("Final script.json failed v4 validation.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:be.errors.slice(0,5).map(L=>`${L.path}: ${L.message}`)}});i.writeJson("script.json",v),r.phaseEnd("govern"),r.finish();let Qe=v;return c="succeeded",{workspacePath:i.root,chunks:u.length,reused:m,records:y,notes:E,assets:{actors:Qe.actors?.length??0,locations:Qe.locations?.length??0,props:Qe.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:be.ok,errors:be.errors.length,warnings:be.warnings.length}}}finally{s.finish(c)}}function Zx(e){return ci.basename(e,ci.extname(e))}import*as Yt from"node:fs";import*as yi from"node:path";function Xx(e,t){return e.episode!==t.episode?`episode ${e.episode} was replaced by episode ${t.episode}`:e.ext!==t.ext||e.mime!==t.mime?`episode ${e.episode} changed media type`:e.sha256!==t.sha256?`episode ${e.episode} content changed`:null}function um(e,t){if(t.length<e.length)return{kind:"incompatible",reason:`source removed ${e.length-t.length} previously accepted episode(s)`};for(let o=0;o<e.length;o+=1){let i=Xx(e[o],t[o]);if(i)return{kind:"incompatible",reason:i}}let n=t.slice(e.length);return n.length===0?{kind:"unchanged",appended:[]}:{kind:"append",appended:n}}function Vs(e){for(let t=0;t<e.length;t+=1){let n=t+1,o=e[t].episode;if(o!==n)return`expected episode ${n}, found episode ${o}`}return null}function di(e){let t=typeof e=="string"?e.trim().replace(/\.\d+$/,""):"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})$/);if(!n)return t;let o=Number(n[1]??0),i=Number(n[2]),r=Number(n[3]);if(![o,i,r].every(Number.isSafeInteger))return t;let s=o*3600+i*60+r,c=Math.floor(s/3600),a=Math.floor(s%3600/60),d=s%60;return c>0?`${c}:${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`:`${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`}function pi(e,t){if(!e)return e;let n=e.match(/^(\w+):(.+)$/);return n?`${n[1]}:${t.get(n[2])??n[2]}`:t.get(e)??e}var fm=e=>String(e).padStart(3,"0"),eS={\u5185:"interior",\u5916:"exterior"},tS={act:"action",dlg:"dialogue",think:"inner_thought"},Ud={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function nS(e){let t=e.match(/^(\w+):(.+)$/);if(t&&Ud[t[1]]){let n=t[2].trim();return n?{kind:Ud[t[1]],label:n}:{kind:Ud[t[1]]}}return lt(e)?{kind:"group",label:e.trim()}:{name:e}}function mm(e,t){let n=0,o=e.map((i,r)=>{let s=`video:episode:${i.episode}`,c=new Map;return{identity_key:s,episode_id:`ep_${fm(r+1)}`,scenes:i.scenes.map(a=>{let d=a.timeRange?.trim()?`time:${a.timeRange.trim()}`:`index:${a.index}`,p=(c.get(d)??0)+1;c.set(d,p);let l=`${s}:scene:${d}:${p}`,f={},u=eS[(a.environment.space??"").trim()],m=ei(a.environment.time);u&&(f.space=u),m&&(f.time=m);let g=[],h=A=>{g.some(k=>k.name===A)||g.push({name:A})};for(let A of a.characters)A.name&&!lt(A.name)&&(A.states.length===0?g.push({name:A.name}):g.push(...A.states.map(k=>({name:A.name,state:k}))));let w=new Map,y=a.anchors.map(A=>{let k=di(A.ts),D=k?`time:${k}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,R=(w.get(D)??0)+1;w.set(D,R);let I={identity_key:`${l}:action:${D}:${R}`,type:tS[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let $=nS(A.speaker);I.speaker=$,"name"in $&&h($.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let M=di(A.ts);return M&&(I.extend={timestamp:M}),I}),E=(a.location??"").trim(),S=[],_=new Set;for(let A of a.props??[]){if(!A)continue;let k=A.normalize("NFC").replace(/\s+/g," ").trim();!k||_.has(k)||(_.add(k),S.push({name:A}))}return{identity_key:l,scene_id:`scn_${fm(++n)}`,...f.space||f.time?{environment:f}:{},location:E?{name:E}:null,actors:g,props:S,actions:y}})}});return{title:t,episodes:o}}var oS=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function li(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var ge=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),pr=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function iS(e,t){let n=ge(t);return e.find(o=>ge(o.name)===n||ge(o.identitySeed)===n||o.aliases.some(i=>ge(i)===n))}var rS=3,sS=12e3;function No(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var aS=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function $s(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:oS();for(let i of aS){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])No(o.persistent_marks,i);return o}function Td(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>sn(s.name)===sn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function gm(e,t,n,o=!1){let i=(s,c)=>{let a=(c??"").trim();return a&&(o||!s)?a:s};for(let s of t.add_recognition_anchors??[])No(e.recognitionAnchors,s);e.identityProfile=$s(e.identityProfile,t.identity_profile_patch,o);let r=i(e.appearance,t.appearance);r&&(e.appearance=r),e.role=i(e.role,t.role)??e.role;for(let s of t.add_aliases??[])No(e.aliases,s);for(let s of t.add_states??[])Td(e.states,s,o);e.lastEpisode=n}function wm(e,t,n){let o=r=>iS(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&<(s))continue;let c=o(s);if(c){gm(c,{add_recognition_anchors:r.recognition_anchors,identity_profile_patch:r.identity_profile,appearance:r.appearance,role:r.role,add_aliases:r.aliases,add_states:r.states},n);continue}let a=[];for(let p of r.states??[])Td(a,p,!1);let d=[];for(let p of r.aliases??[])No(d,p);e.registry.push({identitySeed:s,name:s,kind:r.kind,status:r.status,importance:r.importance,recognitionAnchors:[...new Set((r.recognition_anchors??[]).map(p=>p.trim()).filter(Boolean))],...r.identity_profile?{identityProfile:$s(void 0,r.identity_profile,!0)}:{},...r.appearance?{appearance:r.appearance.trim()}:{},role:(r.role??"").trim(),aliases:d,states:a,firstEpisode:n,lastEpisode:n})}for(let r of t.registry_delta.enrich){let s=o(r.name);s&&gm(s,r,n,!0)}for(let r of t.registry_delta.canonicalize){let s=o(r.from_name),c=r.canonical_name.trim();if(!s||!c||ge(c)===ge(s.name))continue;let a=o(c);if(a&&a!==s){let d=s.firstEpisode<a.firstEpisode?s:a,p=d===s?a:s,l=d.states.map(m=>({...m})),f=new Set([...s.aliases,...a.aliases,s.identitySeed,a.identitySeed,s.name,a.name,r.from_name].map(m=>m.trim()).filter(Boolean));d.name=c,d.status="canonical",d.importance=s.importance==="featured"||a.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let m of[...s.recognitionAnchors,...a.recognitionAnchors])No(d.recognitionAnchors,m);let u=$s(void 0,s.identityProfile,!0);d.identityProfile=$s(u,a.identityProfile,!0),(a.appearance||s.appearance)&&(d.appearance=a.appearance||s.appearance),d.role=a.role||s.role,d.states=[];for(let m of[...l,...p.states])Td(d.states,m,!1);d.aliases=[...f].filter(m=>ge(m)!==ge(c)),d.firstEpisode=Math.min(s.firstEpisode,a.firstEpisode),d.lastEpisode=Math.max(s.lastEpisode,a.lastEpisode,n),e.registry.splice(e.registry.indexOf(p),1);continue}No(s.aliases,s.name),No(s.aliases,r.from_name),s.name=c,s.status="canonical",s.aliases=s.aliases.filter(d=>ge(d)!==ge(c)),s.lastEpisode=n}let i=0;for(let r of t.open_threads.opened){let s=r.text.trim();s&&e.openThreads.push({id:`t${n}_${++i}`,text:s,sinceEpisode:n})}for(let r of t.open_threads.closed){let s=r.ref.trim();s&&(e.openThreads=e.openThreads.filter(c=>c.id!==s&&c.text!==s))}return e.digests.push({episode:n,synopsis:(t.synopsis??"").trim()}),e.lastEpisode=n,e}function _m(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function cS(e,t){let n=[],o=e.status==="provisional"?"\xB7\u5F85\u5B9A \u26A0":`\xB7${e.importance}`;n.push(`### ${e.name} ${o}`),e.role&&n.push(`- \u4F5C\u7528: ${pr(e.role,t?40:200)}`),e.recognitionAnchors.length&&n.push(`- \u8BC6\u522B\u951A\u70B9: ${e.recognitionAnchors.join("\uFF1B")}`);let i=e.identityProfile;if(i){let r=[i.apparent_gender,i.apparent_age].filter(Boolean).join("\uFF0C");r&&n.push(`- \u5E74\u9F84\u6027\u522B: ${r}`),i.face_shape&&n.push(`- \u8138\u578B\u4E0B\u988C: ${i.face_shape}`),i.brows_eyes&&n.push(`- \u7709\u773C: ${i.brows_eyes}`),i.nose&&n.push(`- \u9F3B\u90E8: ${i.nose}`),i.mouth&&n.push(`- \u5507\u5F62\u5634\u89D2: ${i.mouth}`),i.skin_features&&n.push(`- \u80A4\u8272\u9762\u90E8: ${i.skin_features}`),i.hair&&n.push(`- \u53D1\u578B: ${i.hair}`),i.build&&n.push(`- \u4F53\u6001: ${i.build}`),i.persistent_marks.length&&n.push(`- \u56FA\u5B9A\u6807\u8BB0: ${i.persistent_marks.join("\uFF1B")}`),i.voice&&n.push(`- \u58F0\u7EBF: ${i.voice}`)}return e.aliases.length&&n.push(`- \u66FE\u7528\u79F0\u547C: ${e.aliases.join("\u3001")}`),e.states.length&&n.push(`- \u5DF2\u77E5\u9020\u578B: ${e.states.map(r=>{let s=pr(r.description,t?30:90);return s?`${r.name}\uFF08${s}\uFF09`:r.name}).join(" / ")}`),n.push(`- \u51FA\u73B0: ep ${e.firstEpisode}\u2013${e.lastEpisode}`),e.status==="provisional"&&n.push(`- \u8EAB\u4EFD\u672A\u786E\u8BA4\uFF1A\u672C\u96C6\u82E5\u51FA\u73B0\u4E66\u9762\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u7528 canonicalize \u4ECE\u300C${e.name}\u300D\u5347\u7EA7\u89C4\u8303\u540D`),n}function hm(e,t){let n=pr(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${pr(i.description,t?20:60)}\uFF09`:i.name).join(" / ");return`- ${e.name} \xB7${e.importance}${n?`\uFF1A${n}`:""}${o?`\uFF1B\u72B6\u6001\uFF1A${o}`:""}`}function ym(e,t,n){let o=[];o.push(`# \u5DF2\u77E5\u8BBE\u5B9A\uFF08\u89E3\u6790\u7B2C ${e.lastEpisode+1} \u96C6\u65F6\u5BF9\u7167\u672C\u8868\uFF09`,""),o.push("\u8BA4\u5F97\u51FA\u7684\u4EBA/\u7269\u6CBF\u7528\u5176**\u89C4\u8303\u540D**\uFF0C\u522B\u81EA\u5DF1\u65B0\u8D77\u540D\uFF1B\u4EBA\u7269\u4F18\u5148\u6BD4\u5BF9\u8BC6\u522B\u951A\u70B9\u4E0E\u7ED3\u6784\u5316\u8EAB\u4EFD\u753B\u50CF\uFF0C\u670D\u88C5\u53EA\u4F5C\u5F31\u8F85\u52A9\u3002","");let i=e.registry.filter(a=>a.kind==="actor"),r=e.registry.filter(a=>a.kind==="location"),s=e.registry.filter(a=>a.kind==="prop");if(i.length){o.push("## \u4EBA\u7269","");for(let a of i)o.push(...cS(a,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let a of r)o.push(hm(a,n));for(let a of s)o.push(hm(a,n));o.push("")}let c=e.digests.filter(a=>a.episode>e.lastEpisode-t);if(c.length){o.push("## \u5267\u60C5\u8FDB\u5C55","");for(let a of[...c].sort((d,p)=>d.episode-p.episode))o.push(a.outcome==="skipped"?`\u7B2C${a.episode}\u96C6\u5DF2\u4EBA\u5DE5\u8DF3\u8FC7\uFF0C\u5267\u60C5\u672A\u77E5\u3002`:`\u7B2C${a.episode}\u96C6\uFF1A${n?pr(a.synopsis,40):a.synopsis}`);o.push("")}if(e.openThreads.length){o.push("## \u672A\u95ED\u5408\u7EBF\u7D22\uFF08\u82E5\u672C\u96C6\u4EA4\u4EE3\u4E86\uFF0C\u7528 open_threads.closed \u5F15\u7528\u5176 [id] \u5173\u95ED\uFF09","");for(let a of e.openThreads)o.push(`- [${a.id}] ${a.text}`);o.push("")}return o.join(`
|
|
251
|
-
`)}function Em(e){for(let t=rS;t>=1;t--){let n=ym(e,t,!1);if(n.length<=sS)return n}return ym(e,1,!0)}function lr(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])ge(o)!==ge(n.name)&&t.set(o,n.name);return t}function dS(e){let t=e.identityProfile,n=[];if(t){let o=[t.apparent_gender,t.apparent_age].filter(Boolean).join("\uFF0C");o&&n.push(`\u5916\u89C2\u5E74\u9F84\u4E0E\u6027\u522B\uFF1A${o}`),t.face_shape&&n.push(`\u8138\u578B\u4E0B\u988C\uFF1A${t.face_shape}`),t.brows_eyes&&n.push(`\u7709\u773C\uFF1A${t.brows_eyes}`),t.nose&&n.push(`\u9F3B\u90E8\uFF1A${t.nose}`),t.mouth&&n.push(`\u5507\u5F62\u53E3\u5468\uFF1A${t.mouth}`),t.skin_features&&n.push(`\u80A4\u8272\u9762\u90E8\uFF1A${t.skin_features}`),t.hair&&n.push(`\u5934\u53D1\uFF1A${t.hair}`),t.build&&n.push(`\u9AA8\u67B6\u4F53\u578B\uFF1A${t.build}`),t.persistent_marks.length&&n.push(`\u56FA\u5B9A\u6807\u8BB0\uFF1A${t.persistent_marks.join("\u3001")}`),t.voice&&n.push(`\u58F0\u7EBF\uFF1A${t.voice}`)}return e.recognitionAnchors.length&&n.push(`\u8BC6\u522B\u951A\u70B9\uFF1A${e.recognitionAnchors.join("\uFF1B")}`),e.role&&n.push(`\u89D2\u8272\u8BED\u5883\uFF1A${e.role}`),n.map(o=>o.replace(/[。;]+$/,"")).join("\uFF1B")}function xm(e,t){let n=new Map,o=new Map,i=(s,c)=>{let a=ge(s),d=c.trim();!d||ge(d)===a||(o.has(a)||o.set(a,new Set),o.get(a).add(d))};for(let s of t){n.set(ge(s.name),s.importance);for(let c of s.aliases)n.set(ge(c),s.importance);n.set(ge(s.identitySeed),s.importance);for(let c of new Set([s.identitySeed,...s.aliases]))i(s.name,c)}let r=(s,c)=>{for(let a of s??[]){let d=String(a[c]??""),p=[d,...a.aliases??[]],l;for(let m of p)if(l=t.find(g=>ge(g.name)===ge(m)||ge(g.identitySeed)===ge(m)||g.aliases.some(h=>ge(h)===ge(m))),l)break;a.importance=l?.importance??n.get(ge(d))??"featured";let f=o.get(ge(d));if(f?.size&&(a.aliases=[...new Set([...a.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?dS(l):[l.appearance,l.role].map(m=>(m?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(a.description=`${u}\u3002`);for(let m of a.states??[]){let g=l.states.find(h=>sn(h.name)===sn(m.state_name));g?.description?m.description=g.description:m.state_name==="default"&&l.kind!=="actor"&&l.appearance&&(m.description=l.appearance)}}};return r(e.actors,"actor_name"),r(e.locations,"location_name"),r(e.props,"prop_name"),e}function Sm(e,t){let n=e.scenes.map((o,i)=>{let r={};o.environment?.space&&(r.space=o.environment.space),o.environment?.time&&(r.time=o.environment.time);let s=(o.anchors??[]).map(c=>({kind:c.kind,...c.speaker?{speaker:c.speaker}:{},...c.parenthetical?{parenthetical:c.parenthetical}:{},...c.ts?{ts:c.ts}:{},content:c.content??""}));return{index:i+1,environment:r,...o.timeRange?{timeRange:o.timeRange}:{},...o.location?{location:o.location}:{},characters:(o.characters??[]).filter(c=>c.name).map(c=>({name:c.name,states:[...c.states]})),props:(o.props??[]).filter(Boolean),anchors:s}});return{episode:t,synopsis:(e.synopsis??"").trim(),scenes:n,actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}var pS=60,lS=6,uS=[-1e3,0,1e3],bm=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,Cd=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,Pd=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,Im=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,Om=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,vm=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,Rm=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function to(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function Nm(e){let t=e.trim().match(/^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(!t)return null;let n=Number(t[1]??0),o=Number(t[2]),i=Number(t[3]);if(o>=60&&t[1]!==void 0||i>=60)return null;let r=String(t[4]??"").padEnd(3,"0");return((n*60+o)*60+i)*1e3+Number(r||0)}function Mm(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function Lm(e,t="clock"){return t==="legacy_centiseconds"?Mm(e):Nm(e)}function Vd(e,t){return e===null?!1:t===void 0||e<=t}function fS(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(Um)).filter(Boolean),o=n.filter(r=>Vd(Nm(r),t)).length;return n.filter(r=>Vd(Mm(r),t)).length>o?"legacy_centiseconds":"clock"}function Am(e){let t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=e%1e3;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}.${String(o).padStart(3,"0")}`}function Um(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function mS(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(to).filter(Boolean));for(let[o,i]of t)to(i)===to(e.actor_name)&&n.add(to(o));return[...n].sort((o,i)=>i.length-o.length)}function Tm(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function Cm(e,t,n){return t.filter(o=>Tm(e,n.get(o.actor_id)??[])>=0).length}function gS({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let c=e.type==="action"||e.type==="transition",a=to(c?e.content:"parenthetical"in e?e.parenthetical??"":""),d=Tm(a,i),p=d>=0&&d<=12,l=d>=0,u=e.type==="dialogue"&&"speaker"in e&&"actor_id"in e.speaker&&e.speaker.actor_id===t.actor_id&&!Rm.test(a),m=n===1&&(c&&a.length>0||u&&a.length>0&&(Pd.test(a)||Im.test(a)));if(!l&&!u&&!m)return null;let g=p||u?"target_anchor":"scene_fallback",h=u?250:p?65:l?50:45,w=u?250:p?65:l?50:45;n===1&&(h+=20,w+=20);let y=to(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&a.includes(y)&&(h+=35),bm.test(a)&&(h+=30),Cd.test(a)?(h+=25,w+=15):Pd.test(a)&&(h+=15,w+=5),Im.test(a)&&(w+=30,Cd.test(a)||(h-=20)),Om.test(a)&&(h-=70,w-=70),vm.test(a)&&(h-=40),Cm(a,o,r)>=2&&(h-=15,w-=15),{stateScore:h,identityScore:w,selection:g}}function hS(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?to(e.parenthetical??""):"";if(!o&&Rm.test(i))return null;let r=to(o?e.content:i),s=o?0:-40;return s-=Cm(r,t,n)*20,bm.test(r)&&(s+=10),Cd.test(r)?s+=10:Pd.test(r)&&(s+=5),Om.test(r)&&(s-=20),vm.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function ur(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function Pm(e,t,n,o,i){let r=new Map;for(let a of e){let d=`${a.episode}:${a.milliseconds}`,p=r.get(d);(!p||ur(a,t,n)>ur(p,t,n))&&r.set(d,a)}let s=[...r.values()].sort((a,d)=>ur(d,t,n)-ur(a,t,n)||a.episode-d.episode||a.milliseconds-d.milliseconds).filter(a=>i===null||ur(a,t,n)>=i),c=[];for(let a of s)if(!c.some(p=>p.episode===a.episode&&p.sceneId===a.sceneId&&Math.abs(p.milliseconds-a.milliseconds)<3e3)&&(c.push(a),c.length>=o))break;return c}function yS(e,t,n){return Pm(e,t,n,1,null)[0]??null}function km(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Ds(e,t,n,o,i){let r=new Map(o.map(h=>[h.episode,h])),s=lr(n.registry),c=new Map(t.actors.map(h=>[h.actor_id,h])),a=new Map(t.actors.map(h=>[h.actor_id,mS(h,s)])),d=new Map,p=new Map,l=new Map,f=new Map;for(let h=0;h<t.episodes.length;h+=1){let w=t.episodes[h],y=h+1,E=r.get(y);if(!E)continue;let S=fS(w,E.duration_ms);for(let _=0;_<w.scenes.length;_+=1){let A=w.scenes[_],k=A.actors.map(D=>c.get(D.actor_id)).filter(D=>!!D);for(let D of A.actors){d.set(D.actor_id,(d.get(D.actor_id)??0)+1);let R=c.get(D.actor_id);if(!R)continue;let I=a.get(R.actor_id)??[R.actor_name],M=[],$=D.state_ids.length===1?D.state_ids[0]:null,U=$?R.states.find(v=>v.state_id===$):null;for(let v of A.actions){let j=Um(v),Z=Lm(j,S);if(!Vd(Z,E.duration_ms))continue;let De=gS({action:v,actor:R,actorCount:k.length,allActors:k,surfaces:I,surfacesByActor:a,stateName:U?.state_name??"default"}),B=De??(U?hS(v,k,a):null);if(!B)continue;let be={actorId:R.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:Am(Z),milliseconds:Z,durationMs:E.duration_ms,stateScore:B.stateScore,identityScore:B.identityScore,selection:B.selection,sourcePath:E.path,sourceSha256:E.sha256};if(M.push(be),De){let Qe=`${y}:${Z}`,L=f.get(Qe)??new Set;L.add(R.actor_id),f.set(Qe,L)}}if(M.length>0){let v=p.get(R.actor_id)??[];if(v.push(...M),p.set(R.actor_id,v),U){let j=`${R.actor_id}:${U.state_id}`,Z=l.get(j)??[];Z.push(...M),l.set(j,Z)}}}}}let u=(h,w)=>{let y=c.get(h),E=c.get(w),S=y?.importance==="background"?1:0,_=E?.importance==="background"?1:0;return S-_||(d.get(w)??0)-(d.get(h)??0)||(y?.actor_name??h).localeCompare(E?.actor_name??w,"zh-CN")},m=[...l.entries()].flatMap(([h,w])=>{let[y,E]=h.split(":"),S=y?c.get(y):void 0,_=S?.states.find(R=>R.state_id===E),A=yS(w,"stateScore",f);if(!S||!_||!A)return[];let k=`state:${S.actor_id}:${_.state_id}`,D=uS.map(R=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),M=Math.min(I,Math.max(0,A.milliseconds+R)),$=Am(M);return{evidence_id:`${k}:${A.episode}:${$}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:$,offset_ms:R,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${S.actor_id}/${_.state_id}/ep_${String(A.episode).padStart(3,"0")}_${km($)}.jpg`,frame_status:"pending"}}).filter((R,I,M)=>M.findIndex($=>$.timestamp===R.timestamp)===I);return[{evidence_id:k,asset_kind:"actor",actor_id:S.actor_id,actor_name:S.actor_name,state_id:_.state_id,state_name:_.state_name,samples:D}]}).sort((h,w)=>u(h.actor_id,w.actor_id)||h.state_name.localeCompare(w.state_name,"zh-CN")),g=[...p.entries()].flatMap(([h,w])=>{let y=c.get(h),E=Pm(w,"identityScore",f,lS,pS);if(!y||E.length===0)return[];let S=`identity:${y.actor_id}`;return[{evidence_id:S,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:E.map(_=>({evidence_id:`${S}:${_.episode}:${_.timestamp}`,episode:_.episode,episode_id:_.episodeId,scene_id:_.sceneId,timestamp:_.timestamp,offset_ms:0,selection:_.selection,source_sha256:_.sourceSha256,source_path:_.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(_.episode).padStart(3,"0")}_${km(_.timestamp)}.jpg`,frame_status:"pending"}))}]}).sort((h,w)=>u(h.actor_id,w.actor_id));return{version:2,source_sha256:i,items:m,identities:g}}function Vm(e){return Lm(e)}import*as ui from"node:path";function Dm(e){return ui.extname(e).toLowerCase()}function wS(e){return nd[Dm(e)]??"application/octet-stream"}function _S(e){let t=ui.basename(e,ui.extname(e)),n=t.match(/第\s*0*(\d+)\s*[集话回]/u)??t.match(/(?:^|[._\-\s])(?:ep(?:isode)?|e)\s*[._\-\s]*0*(\d+)(?=$|[._\-\s])/iu);if(n)return Number(n[1]);let o=t.match(/\d+/);return o?Number(o[0]):null}function $m(e,t){return new x(e,{exitCode:b,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function $d(e,t){return{episode:t,path:e,ext:Dm(e),mime:wS(e)}}function Gs(e){if(e.kind==="text")throw new x("discoverEpisodes received a text source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[$d(e.path,1)];let t=e.files,n=t.map(_S),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>$d(r,s+1));if(o.length!==t.length){let r=t.filter((s,c)=>n[c]===null).map(s=>ui.basename(s));throw $m("Some episode files carry a number and some do not.",[`unnumbered: ${r.join(", ")}`])}let i=new Set;for(let r of o){if(i.has(r))throw $m("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>$d(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as Gm from"node:fs";import*as Jm from"node:path";function Bm(e,t=[],n){let o=new Map(t.map(r=>[r.episode,r])),i=n?Date.parse(n):Number.NaN;return e.map(r=>{let s=Jm.resolve(r.path),c=Gm.statSync(s),a=c.size,d=Math.trunc(c.mtimeMs),p=o.get(r.episode),l=p&&p.size_bytes===a&&p.mtime_ms===d,f=p&&p.size_bytes===void 0&&p.mtime_ms===void 0&&p.path===s&&Number.isFinite(i)&&c.mtimeMs<=i,u=p&&p.ext===r.ext&&p.mime===r.mime&&(l||f)?p.sha256:ga(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:a,mtime_ms:d}})}function Js(e){return Se(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as ES}from"node:child_process";import*as ot from"node:fs";import*as Km from"node:path";var xS=20*1024*1024,SS="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function IS(e,t){return["-y","-loglevel","error","-i",e,"-vf",SS,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function AS(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=ES("ffmpeg",IS(e,t),{stdio:["ignore","ignore","pipe"]}),s="";r.stderr?.on("data",a=>{s+=String(a)});let c=()=>{r.kill("SIGKILL")};n?.addEventListener("abort",c,{once:!0}),r.on("error",a=>{n?.removeEventListener("abort",c),i(a)}),r.on("close",a=>{n?.removeEventListener("abort",c),a===0?o():i(new Error(`ffmpeg exited ${a}: ${s.trim().slice(0,300)}`))})})}async function jm(e,t,n,o){if(ot.existsSync(t)&&(ot.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=ot.statSync(e).size}catch{}if(i>0&&i<=xS)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(ot.mkdirSync(Km.dirname(t),{recursive:!0}),ot.rmSync(r,{force:!0}),await AS(e,r,o),!ot.existsSync(r)||ot.statSync(r).size===0)throw new Error("ffmpeg produced no output");return ot.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{ot.rmSync(r,{force:!0}),ot.rmSync(t,{force:!0})}catch{}if(o?.aborted)throw s instanceof Error?s:new Error(String(s));let c=s instanceof Error?s.message:String(s);return{path:e,mime:n,transcoded:!1,note:`transcode failed, uploading original (${c})`}}}import{spawn as kS}from"node:child_process";import*as Ve from"node:fs";import*as zm from"node:path";var bS="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",OS=4;function vS(e){let t=Vm(e);return t===null?null:(t/1e3).toFixed(3)}var RS=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=vS(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!Ve.existsSync(e)||Ve.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}Ve.mkdirSync(zm.dirname(n),{recursive:!0});let r=`${n}.part`;return Ve.rmSync(r,{force:!0}),new Promise((s,c)=>{let a=kS("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",bS,"-q:v","3","-f","image2",r],{stdio:["ignore","ignore","pipe"]});a.stderr?.resume();let d=()=>{a.kill("SIGKILL")};o?.addEventListener("abort",d,{once:!0}),a.on("error",()=>{o?.removeEventListener("abort",d),Ve.rmSync(r,{force:!0}),o?.aborted?c(new Error("aborted")):s({ok:!1,error:"frame extractor unavailable"})}),a.on("close",p=>{if(o?.removeEventListener("abort",d),o?.aborted){Ve.rmSync(r,{force:!0}),c(new Error("aborted"));return}if(p===0&&Ve.existsSync(r)&&Ve.statSync(r).size>0){Ve.renameSync(r,n),s({ok:!0});return}Ve.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function NS(e){let{source_path:t,...n}=e;return n}async function Bs(e,t,n,o=RS,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(m=>m.samples),...(t.identities??[]).flatMap(m=>m.samples)],c=new Map,a=0,d=async()=>{for(;;){let m=a;if(a+=1,m>=s.length)return;if(n?.aborted)throw new Error("aborted");let g=s[m],h=e.path(g.frame_path),w;r&&Ve.existsSync(h)&&Ve.statSync(h).size>0?w={ok:!0}:(Ve.rmSync(h,{force:!0}),w=await o(g.source_path,g.timestamp,h,n)),c.set(g,NS({...g,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(OS,s.length)},()=>d()));let p=m=>m.map(g=>c.get(g)),l=t.items.map(m=>({...m,samples:p(m.samples)})),f=(t.identities??[]).map(m=>({...m,samples:p(m.samples)})),u={version:2,generated_at:new Date().toISOString(),source_sha256:t.source_sha256,items:l,...f.length>0?{identities:f}:{}};if(e.has("evidence/state-evidence.json"))try{let m=e.readJson("evidence/state-evidence.json"),g=h=>JSON.stringify({version:h.version,source_sha256:h.source_sha256,items:h.items,identities:h.identities??[]});if(g(m)===g(u))return m}catch{}return e.writeJson("evidence/state-evidence.json",u),u}import*as Hm from"node:fs";import*as Fm from"node:path";import MS from"proper-lockfile";async function fi(e,t){let n=Fm.resolve(e);Hm.mkdirSync(n,{recursive:!0});let o=null;try{o=await MS.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new x("The ingest workspace is busy.",{exitCode:fe,errorCode:"INGEST_WORKSPACE_BUSY",hint:"Wait for the other ingest or skip command to finish, then retry.",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}var pe=Qt,LS=pe(60);function US(e,t){let n=pe,o=t[n(106)]()?n(86)+t+`
|
|
252
|
-
`:n(110);return n(47)+e+n(36)+o}function Dd(e,t){let n=pe;return new x(e,{exitCode:fe,errorCode:n(119),hint:n(113),data:{actual:t}})}var Gd=e=>{let t=pe;return typeof e===t(32)?e[t(33)](/\u0000/g,""):Array[t(70)](e)?e[t(65)](Gd):it(e)?Object[t(101)](Object[t(18)](e)[t(65)](([n,o])=>[n,Gd(o)])):e},it=e=>typeof e===pe(46)&&e!==null&&!Array[pe(70)](e);function Jd(){let e=["C2v0","CM9Szq","Aw5JBhvKzxm","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","C3rYAw5NAwz5","Bg9JyxrPB24","ywLzwxG","CMvJB2DUAxrPB25Fyw5JAg9YCW","zw5YAwnO","AwrLBNrPDhLFChjVzMLSzq","z2vUzxjHDgu","BMv3x2vUDgL0AwvZ","yw5JAg9YCW","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","B3bLBMvK","DgHPBMS","CMvNAxn0CNLFzgvSDge","zgvZy3jPChrPB24","zw50CMLLCW","y2fUB25Py2fSAxPL","tefztLm","z2v0","y2HHCMfJDgvYCW","BgvUz3rO","DgLTzxn0yw1Wx21PC3nPBMC","y2fUB25Py2fS","DgLTzq","ywrK","B3bLBL90AhjLywrZ","CgfYC2u","BwLTzq","zMLSDgvY","C3rYAw5N","CMvWBgfJzq","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","DMfSDwvZ","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos4JEIMGEI+K+whUUINO+MhIUoaGEwjJEIOGoAiLIbnyxjRzg93BIdKU6pNOihLNzFJGijZy2vUzxmG6ycq5zY66kAg55Uw5ywO6zUg77YB5Q+p5zY65ywi54US56Ul5A6m5OIq6ycq6zwCihnOB3rZ77Ym5yAn54US56Ul5A6m5OIqihzVAwnLC+oaGNnOB3rZiow/HEMHU+IMHUEBLUAVJ+ASOEwiH+MvNowsJowpR+EHRUIUPoEAHoArHow9Ss/OOAJMVjtLJ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vJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","ywXPyxnLCW","AxnbCNjHEq","rvHms2W","oIbZzxjPywWGB3v0Chv0ihbYB2r1y2vKig5VihnJzw5LCW","ywrKx2fSAwfZzxm","Aw1WB3j0yw5Jzq","cGRKUiRMRkhOVPpLH7RMNiKG","ChjVChm","DuH1qwG","ywn0","tKzd","C29YDa","zMfJzv9ZAgfWzq","AgfZ","BM9Zzq","y29UDgvUDa","BMfTzq","pt09pt09pt09psdLT7lNN6xORR7LRPRVViJLIldKUiRKUidPM4BKUlRMRAlVViZOP4tOJipLKi3KU6xMRAtKUlRLH4BVViKGpt09pt09pt09pqO","C2TPBL9Mzwf0DxjLCW","uLPSD0u","zxzPzgvUy2u","xsaO","DMLZDwfS","yNvPBgq","C2HVDhm","zxbPC29Kzsa","CgvYC2LZDgvUDf9TyxjRCW","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViNVViZKUi3LVPFNVlRLPlhJGihNLzNNQBRMIjBLOASGBNvSBo+8M+I/LowBNUwUJoAvTcbku09o77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","ChjVDMLZAw9UywW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","ywrKx3n0yxrLCW","rxbPC29Kzsa","zNjVBuvUDhjPzxm","C3LUB3bZAxm","ue9tsvrjvKvFsu5gsu5jvfK","weLmzNa","rMHHqK0","DhjPBq","AgfPCG","zMvHDhvYzwq","y2XVC2vK","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","y2fTzxjH","yNjVD3nFzxLLCW","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","ChvZAa","A2v5CW","CMvM","CgfYzw50Agv0AwnHBa","BgvUz3rOoIa","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","AxngAw5PDgu","DM9Py2vZ","oIbZzxjPywWGB3v0Chv0ihDHCYbUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","Dgv4Da","zNjVBv9Uyw1L","C3rHDgvZ","Dg9ju09tDhjPBMC","C2nLBMvZ","Bw91DgG","su5hrvnux1zjrevpx1rjtuvtvefnuf9nsvntsu5h","C2nLBMvZwW"];return Jd=function(){return e},Jd()}var W=e=>typeof e===pe(32)?e[pe(106)]():"",Fe=e=>Array[pe(70)](e)?e:[],Wm=e=>{let t=pe,n=W(e);return n?n[t(59)](/[((//,,、]/)[0][t(106)]():""},TS=e=>[...new Set(Fe(e)[pe(65)](Wm)[pe(31)](Boolean))],Qm=e=>{let t=pe,n=[];for(let o of Fe(e))if(t(20)===t(20)){if(!it(o))continue;let i=Wm(o[t(85)]);if(!i)continue;let r=W(o[t(17)]),s=n[t(58)](c=>c[t(85)]===i);s?!s[t(17)]&&r&&(s[t(17)]=r):n[t(114)]({name:i,description:r})}else throw _0xea1873(t(94)+_0x26d9eb+t(122)+_0x40ae4d[t(40)]+")",[_0x54b3bb[t(42)](0,200)]);return n},CS=[pe(37),pe(56),pe(81),pe(112),pe(83),pe(128),pe(87),pe(107),pe(92),pe(52)],Ym=e=>{let t=pe;if(!it(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:Fe(e[t(95)])[t(65)](W)[t(31)](Boolean),voice:""};for(let o of CS)n[o]=W(e[o]);return n},qm=e=>{let t=pe;if(!e)return Number[t(103)];let n=e[t(59)](":")[t(65)](Number);return n[t(61)](o=>!Number[t(120)](o))?Number[t(103)]:n[t(23)]===2?n[0]*60+n[1]:n[t(23)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(103)]},PS=(e,t)=>{let n=pe;return e?t?e[n(33)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function Qt(e,t){e=e-0;let n=Jd(),o=n[e];if(Qt.yxMOYo===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};Qt.DlFVxD=i,Qt.iMIPil={},Qt.yxMOYo=!0}let r=n[0];Qt.ISLRJj!==r&&(Qt.iMIPil={},Qt.ISLRJj=r);let s=Qt.iMIPil[e];return s===void 0?(o=Qt.DlFVxD(o),Qt.iMIPil[e]=o):o=s,o}function VS(e){let t=pe,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!it(e))return n;n[t(102)]=W(e[t(102)]);for(let r of Fe(e[t(127)])){if(!it(r))continue;let s={},c=W(r[t(41)]);c&&(s[t(41)]=c);let a=ei(r[t(26)]);a&&(s[t(26)]=a);let d=new Map;for(let h of Fe(r[t(22)])){if(t(67)!==t(67))throw new _0x25b22d(t(100)+_0x39f21e+": "+_0x1bf283[t(23)]+t(13),{exitCode:_0x26902a,errorCode:t(129),hint:t(68),data:{actual:_0x36fc5d}});{if(!it(h))continue;let w=W(h[t(85)]);if(!w||lt(w))continue;let y=d[t(21)](w)??{name:w,states:[]};for(let E of TS(h[t(125)]))if(t(71)===t(71))y[t(125)][t(2)](E)||y[t(125)][t(114)](E);else{if(!_0x279b30)return _0x499743[t(103)];let S=_0x3e9bd8[t(59)](":")[t(65)](_0xbf8c);return S[t(61)](_=>!_0x2242ca[t(120)](_))?_0x4255ff[t(103)]:S[t(23)]===2?S[0]*60+S[1]:S[t(23)]===3?S[0]*3600+S[1]*60+S[2]:_0x3f6179[t(103)]}d[t(0)](w,y)}}let p=[],l=new Set;for(let h of Fe(r[t(76)])[t(65)](W)[t(31)](Boolean)){let w=h[t(63)](t(79))[t(33)](/\s+/g," ")[t(106)]();!w||l[t(82)](w)||(l[t(27)](w),p[t(114)](h[t(106)]()))}let f=[];for(let h of Fe(r[t(93)])){if(!it(h))continue;let w=PS(W(h[t(111)]),W(h[t(91)]));if(!w)continue;let y={kind:t(78),content:w},E=di(h.ts);E&&(y.ts=E),f[t(114)](y)}for(let h of Fe(r[t(121)])){if(!it(h))continue;let w=W(h[t(55)]);if(w!==t(48)&&w!==t(15))continue;let y=W(h[t(84)]);if(!y)continue;let E={kind:w,content:y},S=W(h[t(49)]);S&&(E[t(49)]=S);let _=W(h[t(117)]);_&&(E[t(117)]=_);let A=di(h.ts);A&&(E.ts=A),f[t(114)](E)}f[t(80)]((h,w)=>{let y=t,E=qm(h.ts)-qm(w.ts);return E!==0?E:h[y(55)]===y(78)&&w[y(55)]!==y(78)?-1:h[y(55)]!==y(78)&&w[y(55)]===y(78)?1:0});let u={environment:s,characters:[...d[t(35)]()],props:p,anchors:f},m=W(r[t(57)]);m&&(u[t(57)]=m);let g=W(r[t(5)]);g&&(u[t(5)]=g),n[t(127)][t(114)](u)}let o=it(e[t(16)])?e[t(16)]:{};for(let r of Fe(o[t(11)])){if(!it(r))continue;let s=W(r[t(85)]),c=W(r[t(55)]);if(!s||c!==t(62)&&c!==t(5)&&c!==t(45)||c===t(62)&<(s))continue;let a={name:s,kind:c,status:W(r[t(39)])===t(97)?t(97):t(25),importance:W(r[t(74)])===t(53)?t(53):t(108)},d=Fe(r[t(7)])[t(65)](W)[t(31)](Boolean);d[t(23)]&&(a[t(7)]=d);let p=Ym(r[t(9)]);p&&(a[t(9)]=p);let l=W(r[t(43)]);l&&(a[t(43)]=l);let f=W(r[t(1)]);f&&(a[t(1)]=f);let u=Qm(r[t(125)]);u[t(23)]&&(a[t(125)]=u);let m=Fe(r[t(69)])[t(65)](W)[t(31)](Boolean);m[t(23)]&&(a[t(69)]=m),n[t(16)][t(11)][t(114)](a)}for(let r of Fe(o[t(8)]))if(t(6)===t(6)){if(!it(r))continue;let s=W(r[t(85)]);if(!s)continue;let c={name:s},a=Fe(r[t(3)])[t(65)](W)[t(31)](Boolean);a[t(23)]&&(c[t(3)]=a);let d=Ym(r[t(34)]);d&&(c[t(34)]=d);let p=W(r[t(43)]);p&&(c[t(43)]=p);let l=W(r[t(1)]);l&&(c[t(1)]=l);let f=Fe(r[t(73)])[t(65)](W)[t(31)](Boolean);f[t(23)]&&(c[t(73)]=f);let u=Qm(r[t(99)]);u[t(23)]&&(c[t(99)]=u),Object[t(115)](c)[t(23)]>1&&n[t(16)][t(8)][t(114)](c)}else return _0x150727?_0x422014?_0x1f4862[t(33)](/[。!?;]+$/,"")+"\u3002"+_0x2651c7:_0x44d23d:_0x1c02e9;for(let r of Fe(o[t(19)])){if(!it(r))continue;let s=W(r[t(124)]),c=W(r[t(50)]);s&&c&&n[t(16)][t(19)][t(114)]({from_name:s,canonical_name:c,evidence:W(r[t(89)])})}let i=it(e[t(28)])?e[t(28)]:{};for(let r of Fe(i[t(14)])){if(!it(r))continue;let s=W(r[t(123)]);s&&n[t(28)][t(14)][t(114)]({text:s})}for(let r of Fe(i[t(109)])){if(!it(r))continue;let s=W(r[t(116)]);s&&n[t(28)][t(109)][t(114)]({ref:s})}return n}async function Zm(e,t,n,o,i,r,s,c){let a=pe,d="";for(let p=0;;p++)if(a(77)===a(88))_0x29fde1[a(125)][a(2)](_0xa46e54)||_0x28a8c2[a(125)][a(114)](_0x480bab);else{let l=await e[a(10)]({media:t,system:LS,user:US(n,o+d),fps:i,responseJsonSchema:Vf,...s?{localPath:s[a(64)],localMime:s[a(30)]}:{},...r?{signal:r}:{}}),f=l[a(123)][a(106)]();if(f[a(23)]<40)throw Dd(a(94)+n+a(98)+l[a(40)]+")",[a(118)+f[a(23)]]);let u;try{a(104)!==a(104)?_0x5dc535[a(114)]({name:_0x101a20,description:_0x8301e3}):u=JSON[a(29)](f)}catch{throw Dd(a(94)+n+a(122)+l[a(40)]+")",[f[a(42)](0,200)])}let m=Gd(u),g=VS(m);if(g[a(127)][a(23)]===0)throw Dd(a(94)+n+a(72),[f[a(42)](0,200)]);let h=g[a(127)][a(66)]((y,E)=>y[a(12)][a(66)]((S,_)=>S.ts?[]:[a(130)+E+a(51)+_+a(90)+S[a(55)]+")"]));if(h[a(23)]>0){if(c?.({event:a(24),at:new Date()[a(126)](),episode:n,attempt:p+1,missing_count:h[a(23)],missing_paths:h,retries_exhausted:p===3}),p===3){if(a(44)!==a(105))throw new x(a(100)+n+": "+h[a(23)]+a(13),{exitCode:fe,errorCode:a(129),hint:a(68),data:{actual:h}});{let y=_0x414037[a(106)]()?a(86)+_0x336d80+`
|
|
253
|
-
`:a(110);return a(47)+_0x1bbdb7+a(36)+y}}d=a(75)+h[a(23)]+a(38)+h[a(54)]("\u3001")+a(96);continue}return{md:JSON[a(4)](m,null,2),output:g}}}function Ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $S(e){switch(e.errorCode){case"LLM_CREDENTIAL_MISSING":return{failure_type:"authentication",failure_code:"authentication_failed"};case"LLM_CONFIG_INVALID":return{failure_type:"provider",failure_code:"request_rejected"};case"INGEST_VIDEO_INLINE_TOO_LARGE":return{failure_type:"media",failure_code:"media_too_large"};case"INGEST_VIDEO_SERIAL_FAILED":return{failure_type:"pipeline",failure_code:"serial_parse_failed"};case"INGEST_VIDEO_TIMESTAMP_MISSING":return{failure_type:"validation",failure_code:"script_validation_failed"};case"INGEST_SOURCE_MISMATCH":return{failure_type:"pipeline",failure_code:"source_mismatch"};case"INGEST_PIPELINE_MISMATCH":return{failure_type:"pipeline",failure_code:"pipeline_mismatch"};case"INGEST_VALIDATION_FAILED":return{failure_type:"validation",failure_code:"script_validation_failed"};default:return{failure_type:"unknown",failure_code:"unknown"}}}function DS(e){if(e instanceof P)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof x){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED";return{failure:_t($S(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:_t({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function eg(e,t,n){let o=DS(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function tg(e){return e.retryable?"Inspect the episode error sidecar and rerun `scriptctl ingest` to resume from this episode.":e.failure_type==="policy"?"Inspect the provider policy reason in the episode error sidecar; rerunning the same source is unlikely to help.":e.failure_type==="authentication"||e.failure_type==="authorization"?"Fix the provider credential or permission reported in the episode error sidecar before rerunning.":"Inspect the typed episode error sidecar and resolve the terminal failure before rerunning."}function Xm(e,t){return typeof e=="string"&&t.some(n=>n===e)}function mi(e){return typeof e=="string"?e:void 0}function GS(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Ks(n)||typeof n.category!="string"||typeof n.probability!="string"||typeof n.blocked!="boolean")return;t.push({category:n.category,probability:n.probability,blocked:n.blocked})}return t}function JS(e){let t=e.provider_source,n=e.provider_reason;return{provider:mi(e.provider),model:mi(e.model),operation:mi(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:mi(e.system_code),provider_source:Xm(t,["prompt","candidate"])?t:void 0,provider_reason:Xm(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:mi(e.provider_reason_raw),finish_message:mi(e.finish_message),safety_ratings:GS(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function fr(e){if(!Ks(e))return null;let t=Rp(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:_t(t,{...JS(e),retryable:e.retryable,message:e.message})}function mr(e){if(!Ks(e)||e.schema_version!==1)return null;let t=e.unit;if(!Ks(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=fr(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=fr(i);if(!r)return null;o.push(r)}return{schema_version:1,unit:{kind:"episode",episode:t.episode},phase:e.phase,occurred_at:e.occurred_at,failure:n,attempts:o}}function js(e){return new x("The video skip ledger is invalid.",{exitCode:b,errorCode:"INGEST_SKIP_LEDGER_INVALID",hint:"Repair or remove skipped.json, then retry.",data:{actual:[e]}})}function BS(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Number.isInteger(t.episode)||Number(t.episode)<=0||typeof t.skipped_at!="string"||typeof t.reason!="string"||t.reason.trim().length===0||typeof t.source_sha256!="string"||t.source_sha256.length===0||!Array.isArray(t.attempts))return null;let n=fr(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=fr(i);if(!r)return null;o.push(r)}return{episode:Number(t.episode),skipped_at:t.skipped_at,reason:t.reason,source_sha256:t.source_sha256,failure:n,attempts:o}}function Bd(e){if(!e.has("skipped.json"))return{schema_version:1,episodes:[]};let t=e.readJson("skipped.json");if(typeof t!="object"||t===null||Array.isArray(t))throw js("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw js("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=BS(r);if(!s)throw js("one or more episode records are malformed");if(i.has(s.episode))throw js(`episode ${s.episode} appears more than once`);i.add(s.episode),o.push(s)}return o.sort((r,s)=>r.episode-s.episode),{schema_version:1,episodes:o}}function ng(e,t){e.writeJson("skipped.json",t)}function zs(e,t){let n=new Map(t.map(o=>[o.episode,o.sha256]));for(let o of e){let i=n.get(o.episode);if(i!==o.source_sha256)throw new x("The video skip ledger no longer matches the source.",{exitCode:b,errorCode:"INGEST_SKIP_SOURCE_MISMATCH",hint:"Restore the source episode recorded by this workspace, or rebuild the same source with --force.",data:{actual:[`episode=${o.episode}`,`ledger_sha256=${o.source_sha256}`,`source_sha256=${i??"<missing>"}`]}})}}function KS(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function Hs(e,t,n,o){let i=new Set(o.map(s=>s.episode)),r=[];for(let s of t){if(s.episode>n)break;let c=`ep/ep_${String(s.episode).padStart(3,"0")}.json`;e.has(c)?r.push(e.readJson(c)):i.has(s.episode)&&r.push(KS(s.episode))}return r}function gr(e,t,n){for(let i of n)i.episode<=t.lastEpisode&&e.clearError(`ep/ep_${String(i.episode).padStart(3,"0")}.error.json`);let o=new Map(n.map(i=>[i.episode,i]));for(;;){let i=t.lastEpisode+1;if(!o.has(i))break;_m(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function og(e,t){for(let n of t){let o=e.episodes[n.episode-1];o&&(o.extend={scriptctl:{ingest:{outcome:"skipped",source_episode:n.episode}}})}}var hr="19",jS=new Set([hr]),gi=e=>String(e).padStart(3,"0"),Kd=2;function rg(e){try{return Yt.statSync(e).size}catch{return 0}}function zS(e,t){let n=rg(e);if(!(n<Oc))throw new x(`Episode ${t} is too large for inline base64 video input.`,{exitCode:b,errorCode:"INGEST_VIDEO_INLINE_TOO_LARGE",hint:"Use --upload-mode file-api, or provide a source that transcodes below the Gemini inline limit.",data:{expected:[`video smaller than ${Oc} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function ig(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
|
|
254
|
-
`;Yt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function sg(e){return new x("This workspace's accepted video sequence no longer matches the source.",{exitCode:b,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the accepted episode prefix, or choose a fresh --workspace-path for a different source.",data:{actual:[e]}})}function jd(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!jS.has(t.pipeline_version))throw new x("This workspace uses an incompatible video-ingest pipeline.",{exitCode:b,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh --workspace-path and run ingest again.",data:{actual:[`workspace pipeline ${t.pipeline_version??"(missing)"}; current ${hr}`]}});return e.readJson("manifest.json")}function zd(e,t){if(t.pipeline_version===hr)return t;let n={...t,pipeline_version:hr,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function HS(e,t,n){if(e&&e.source.kind!==t)throw sg(`source kind changed from ${e.source.kind} to ${t}`)}function FS(e,t,n,o){if(t){let i=um(t.episodes,n);if(i.kind==="incompatible")throw sg(i.reason)}if(o){Yt.rmSync(e.path("ep"),{recursive:!0,force:!0}),Yt.rmSync(e.path("cache"),{recursive:!0,force:!0}),Yt.rmSync(e.path("evidence"),{recursive:!0,force:!0});for(let i of["context.json","script.initial.json","script.json","validation.json","asset-audit.json","id_map.json","timing.jsonl","usage.json","v4_identity_map.json","skipped.json"])Yt.rmSync(e.path(i),{force:!0})}}function QS(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=pi(i.name,t)??i.name;for(let i of o.scenes){for(let c of i.characters)c.name=pi(c.name,t)??c.name;i.location&&(i.location=pi(i.location,t)??i.location);let r=[],s=new Set;for(let c of i.props){let a=(pi(c,t)??c).trim();if(!a)continue;let d=a.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();s.has(d)||(s.add(d),r.push(a))}i.props=r;for(let c of i.anchors)c.speaker=pi(c.speaker,t)}return o})}function YS(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
|
|
255
|
-
`);return`${e}
|
|
256
|
-
|
|
257
|
-
========== \u4E0A\u4E00\u6B21\u8F93\u51FA\u7684\u6574\u5408\u6821\u9A8C\u53CD\u9988 ==========
|
|
258
|
-
\u4E0A\u4E00\u6B21\u5BF9\u672C\u96C6\u7684\u7ED3\u6784\u5316\u8F93\u51FA\u6CA1\u6709\u5199\u5165 checkpoint\uFF0C\u56E0\u4E3A\u4E0E\u65E2\u6709\u5267\u672C\u5408\u5E76\u540E\u8FDD\u53CD\u4E86\u4EE5\u4E0B\u7EA6\u675F\uFF1A
|
|
259
|
-
${n}
|
|
260
|
-
\u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574 JSON\u3002\u4FDD\u6301\u539F\u7247\u4E8B\u5B9E\u3001\u5BF9\u767D\u3001\u955C\u5934\u4E0E\u5DF2\u77E5\u4EBA\u7269\u4E0D\u53D8\uFF0C\u53EA\u4FEE\u6B63\u5BFC\u81F4\u6821\u9A8C\u5931\u8D25\u7684\u4EBA\u7269\u547D\u540D\u3001\u8D44\u4EA7\u7ED1\u5B9A\u6216 registry_delta\u3002\u4EBA\u7269\u89C4\u8303\u540D\u4E0D\u5F97\u7528\u62EC\u53F7\u5907\u6CE8\u533A\u5206\u89D2\u8272\uFF1B\u89D2\u8272\u804C\u80FD\u5199\u5165 role\uFF0C\u4E0D\u540C\u4EBA\u7269\u4F7F\u7528\u5F52\u4E00\u540E\u4ECD\u552F\u4E00\u7684\u89C4\u8303\u540D\u3002`}var hi=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function qS(e,t){let n=lr(t),o=p=>n.get(p)??p,i=new Map;for(let p of t){let l=o(p.name),u=t.find(g=>g.kind===p.kind&&hi(g.name)===hi(l))??p,m=`${p.kind}:${hi(l)}`;i.has(m)||i.set(m,`video:${u.kind}:${u.firstEpisode}:${hi(u.identitySeed)}`)}let r={},s={},c={},a={},d={actor:r,location:s,prop:c};for(let p of e){let l=p.names[0]??p.provisional_id,f=i.get(`${p.kind}:${hi(l)}`)??`video:${p.kind}:source:${hi(l)}`;d[p.kind][p.provisional_id]=f,a[p.provisional_id]=Object.fromEntries(p.states.map(u=>[u.id,`${f}:state:${sn(u.name)}`]))}return{actor:r,location:s,prop:c,state:a}}function ag(e,t,n,o,i=[]){let r=lr(t.registry),s=QS(e,r),c=mm(s,n),{script:a,assets:d,identityKeys:p}=xs(c);xm(a,t.registry);let l=Ms(a),{script:f,idMap:u}=ks(l),m=at(f);if(!m.ok)return{initial:a,final:f,idMap:u,validation:m,identityMap:o};let g=ii(It(l),o,{...qS(d,t.registry),...p}),h=g.script;og(h,i);let w=Ue(h),y=[...h.actors.map((S,_)=>({asset:S,path:`$.actors[${_}]`})),...h.locations.map((S,_)=>({asset:S,path:`$.locations[${_}]`})),...h.props.map((S,_)=>({asset:S,path:`$.props[${_}]`}))].flatMap(({asset:S,path:_})=>[...S.description.trim()?[]:[{code:"video_asset_description_missing",path:`${_}.description`,message:"video asset needs a source-grounded description"}],...S.states.flatMap((A,k)=>A.description.trim()?[]:[{code:"video_state_description_missing",path:`${_}.states[${k}].description`,message:"video asset state needs a source-grounded visual description"}])]),E={...w,warnings:[...w.warnings,...Is(h),...y,...i.map(S=>({code:"episode_skipped",path:`$.episodes[${S.episode-1}]`,message:`Episode ${S.episode} was manually skipped: ${S.reason}`}))]};return{initial:a,final:h,idMap:u,validation:E,identityMap:g.identityMap}}function Fs(e,t,n,o,i,r){let s=ag(Hs(e,t,n.lastEpisode,r),n,o,i,r.filter(l=>l.episode<=n.lastEpisode)),{initial:c,final:a,idMap:d,validation:p}=s;if(e.writeJson("script.initial.json",c),e.writeJson("id_map.json",d),e.writeJson("validation.json",p),e.writeJson("v4_identity_map.json",s.identityMap),!p.ok)throw new x("Final script.json failed validation.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:p.errors.slice(0,5).map(l=>`${l.path}: ${l.message}`)}});return e.writeJson("script.json",a),s}async function WS(e,t,n,o,i,r,s){return Bs(e,Ds(t,n,o,i,r),s)}async function ZS(e){let t=Wn(e.sourcePath);if(t.kind==="text")throw new x("runVideoIngest received a text source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...Gs(t)].sort((h,w)=>h.episode-w.episode),o=Vs(n);if(o)throw new x("Video episodes must form one continuous sequence starting at episode 1.",{exitCode:b,errorCode:"INGEST_VIDEO_SEQUENCE",hint:"Add or rename files so the discovered episode numbers are 1..N with no gaps.",data:{actual:[o]}});let i=e.fps??3,r=e.force??!1,s=e.step??!1,c=e.uploadMode??"file-api",a=e.signal,d=new At(e.workspacePath);d.ensure();let p=jd(d),l=yi.resolve(t.path);HS(p,t.kind,l);let f=Bm(n,p?.episodes??[],p?.updated);FS(d,p,f,r);let u={version:2,pipeline_version:hr,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:Js(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let m=new ai(d,e.executor),g="failed";try{let h=null,w=Qs(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):li(),E={schema_version:1,episodes:u.skips??[]};zs(E.episodes,f),r||gr(d,y,E.episodes);let S=new Set(E.episodes.map(B=>B.episode)),_=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):oi(),A=0,k=0;for(let B of n){let be=`ep/ep_${gi(B.episode)}.json`;if(!r&&S.has(B.episode)&&B.episode<=y.lastEpisode)continue;if(!r&&d.has(be)&&B.episode<=y.lastEpisode){A++,e.executor.recordReuse("ingest.video-serial");let gt=Date.now();m.flush({scope:{kind:"episode",episode:B.episode},status:"reused",startedAtMs:gt,endedAtMs:gt});continue}if(s&&k>=1)break;let Qe=Em(y);d.writeText(`ep/ep_${gi(B.episode)}.context.md`,Qe);let L,oe,he,rt,qt=Date.now(),We={episode:B.episode,uploadMode:c,status:"succeeded",totalMs:0},Rr="transcode";try{let gt=Date.now(),st=await jm(B.path,d.path(`cache/ep_${gi(B.episode)}.mp4`),B.mime,a);We.transcodeMs=Date.now()-gt,We.uploadBytes=rg(st.path),We.transcoded=st.transcoded,st.note&&(We.note=st.note),c==="base64"&&zS(st.path,B.episode),Rr="upload",h??=e.executor.videoPort("ingest.video-serial");let ca=Date.now(),Mn=await h.prepare(st.path,st.mime,c,a);We.uploadMs=Date.now()-ca;try{Rr="generate";let da=Date.now(),ph=Hs(d,n,y.lastEpisode,E.episodes),pa=Qe;for(let Nr=1;Nr<=Kd;Nr++){let Mr;try{Mr=await Zm(h,Mn,B.episode,pa,i,a,{path:st.path,mime:st.mime},Ut=>Yt.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(Ut)+`
|
|
261
|
-
`))}catch(Ut){if(!(Ut instanceof x)||Ut.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||Nr===Kd)throw Ut;pa=`${Qe}
|
|
262
|
-
|
|
263
|
-
\u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${Ut.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408 schema \u7684\u5B8C\u6574 JSON\uFF0Cscenes \u81F3\u5C11\u5305\u542B\u4E00\u4E2A\u5B9E\u9645\u573A\u666F\uFF1B\u4E0D\u8981\u53EA\u5199\u6897\u6982\u6216\u8BBE\u5B9A\u589E\u91CF\u3002`;continue}let Ap=Sm(Mr.output,B.episode),la=structuredClone(y);wm(la,Mr.output,B.episode);let Lr=ag([...ph,Ap],la,w,_,E.episodes.filter(Ut=>Ut.episode<=B.episode));if(Lr.validation.ok){L=Mr.md,oe=Ap,he=la,rt=Lr;break}if(Rr="validation",Nr===Kd)throw new x("Final script.json failed validation after model correction.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Rerun ingest to continue with the next configured model route.",data:{actual:Lr.validation.errors.slice(0,8).map(Ut=>`${Ut.path}: ${Ut.message}`)}});pa=YS(Qe,Lr.validation.errors)}We.generateMs=Date.now()-da}finally{await h.release(Mn,a).catch(()=>{}),st.transcoded&&Yt.rmSync(st.path,{force:!0})}}catch(gt){let st=Date.now();We.status="failed",We.totalMs=st-qt,ig(d,We),m.flush({scope:{kind:"episode",episode:B.episode},status:"failed",startedAtMs:qt,endedAtMs:st,stages:We});let ca=gt instanceof x&>.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":Rr,Mn=eg(gt,B.episode,ca),da=Un(Mn.failure);throw d.writeJson(`ep/ep_${gi(B.episode)}.error.json`,Mn),d.writeJson("manifest.json",{...u,updated:Mn.occurred_at,current_error:Mn}),gt instanceof x&&(gt.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||gt.errorCode==="INGEST_VALIDATION_FAILED"||gt.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?gt:new x(`Episode ${B.episode} failed serial parse; later episodes depend on its context.`,{exitCode:b,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:tg(Mn.failure),data:{actual:[da]}})}y=he,k+=1,d.writeText(`ep/ep_${gi(B.episode)}.md`,L),d.writeJson(be,oe),d.writeJson("context.json",y),d.clearError(`ep/ep_${gi(B.episode)}.error.json`);let Ip=Date.now();We.totalMs=Ip-qt,ig(d,We),m.flush({scope:{kind:"episode",episode:B.episode},status:"succeeded",startedAtMs:qt,endedAtMs:Ip,stages:We}),_=rt.identityMap,d.writeJson("v4_identity_map.json",_),d.writeJson("script.json",rt.final)}let D=Math.min(y.lastEpisode,n.length),R=n.length-D,I=R===0,M=I?null:n[D]?.episode??null,$=Fs(d,n.slice(0,D),y,w,_,E.episodes),{final:U,validation:v}=$,j=I?await WS(d,Hs(d,n,y.lastEpisode,E.episodes),U,y,f,u.source.sha256,a):{items:[]},Z=j.items.flatMap(B=>B.samples),De=U;return g="succeeded",{workspacePath:d.root,episodes:n.length,processed:k,reused:A,skipped:E.episodes.length,skippedEpisodes:E.episodes.map(B=>B.episode),completed:D,remaining:R,complete:I,nextEpisode:M,uploadMode:c,assets:{actors:De.actors?.length??0,locations:De.locations?.length??0,props:De.props?.length??0},evidence:{states:j.items.length,samples:Z.length,ready:Z.filter(B=>B.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:v.ok,errors:v.errors.length,warnings:v.warnings.length}}}finally{m.finish(g)}}async function cg(e){return fi(e.workspacePath,()=>ZS(e))}function Qs(e){return yi.basename(e,yi.extname(e))||""}var yr=e=>e==null?"":String(e),dg=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},XS=["video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","step"];function Mo(e,t){return new x(e,{exitCode:b,errorCode:"INGEST_VIDEO_OPTION_INVALID",hint:"Use these options only with a video file or video episode directory.",data:{actual:t}})}function Ys(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function wi(e,t,n){if(!Ys(e,t))return;let o=yr(e[t]).trim();if(!o)throw Mo(`${n} requires a non-empty value.`,[n]);return o}function eI(e){let t=wi(e,"upload_mode","--upload-mode")??"file-api";if(t!=="file-api"&&t!=="base64")throw Mo("Video upload mode must be file-api or base64.",[`--upload-mode ${t}`]);return t}function tI(e){let t=wi(e,"video_provider","--video-provider");if(t!==void 0&&t!=="gemini"&&t!=="doubao")throw Mo("Video provider must be gemini or doubao.",["--video-provider gemini|doubao"]);let n=Ys(e,"provider_api_key"),o=Ys(e,"provider_api_key_env");if(n&&o)throw Mo("Provider API key options are mutually exclusive.",["--provider-api-key","--provider-api-key-env"]);let i=wi(e,"provider_base_url","--provider-base-url"),r=wi(e,"provider_api_key","--provider-api-key"),s=wi(e,"provider_api_key_env","--provider-api-key-env"),c=wi(e,"provider_model","--provider-model");if(s!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw Mo("Provider API key environment variable name is invalid.",[s]);let a;if(r!==void 0?a={kind:"literal",value:r}:s!==void 0&&(a={kind:"env",name:s}),!(!t&&!i&&!a&&!c))return{...t?{provider:t}:{},...i?{baseUrl:i}:{},...a?{apiKey:a}:{},...c?{model:c}:{}}}async function lg(e,t=kn){let n=yr(e.source_path).trim();if(!n)throw new x("ingest needs a source file or directory.",{exitCode:b,errorCode:"INGEST_NO_SOURCE",hint:"Pass a txt/md/docx file or a video file/directory: scriptctl ingest --source-path <path>.",data:{expected:["--source-path <file|dir>"]}});let o=pg.resolve(yr(e.workspace_path||"workspace")),i=Wn(n),r=XS.filter(d=>{let p=e[d];return typeof p=="boolean"?p:Ys(e,d)});if(i.kind==="text"&&r.length>0)throw Mo("Video ingest options cannot be used with a text source.",r.map(d=>`--${d.replace(/_/g,"-")}`));if(i.kind!=="text"){let d=eI(e),p=tI(e);if(p?.provider==="doubao"&&d!=="file-api")throw Mo("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let l=p?{videoProvider:p}:void 0,f=t.createExecutor(yr(e.llm_config).trim()||void 0,l),u=f.route("ingest.video-serial"),m=await cg({sourcePath:n,workspacePath:o,executor:f,fps:dg(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:d}),g=[`workspace: ${m.workspacePath}`,`${m.completed}/${m.episodes} episodes complete (${m.processed} processed / ${m.reused} reused / ${m.remaining} remaining) \u2192 ${m.scriptPath}`,...m.skipped>0?[`skipped: ${m.skippedEpisodes.join(", ")}`]:[],`assets: ${m.assets.actors} actors / ${m.assets.locations} locations / ${m.assets.props} props`],h=[...f.usageEvents()].reverse().find(w=>w.task==="ingest.video-serial"&&w.status==="succeeded")??u;return[{text:g.join(`
|
|
264
|
-
`),data:{workspace:m.workspacePath,script_path:m.scriptPath,episodes:m.episodes,processed:m.processed,reused:m.reused,parsed:m.completed-m.skipped,skipped:m.skipped,skipped_episodes:m.skippedEpisodes,has_skips:m.skipped>0,completed:m.completed,remaining:m.remaining,complete:m.complete,next_episode:m.nextEpisode,upload_mode:m.uploadMode,route:{protocol:h.protocol,provider:h.provider,base_url:h.baseUrl,model:h.model},assets:m.assets}},J]}let s=t.createExecutor(yr(e.llm_config).trim()||void 0),c=await lm({sourcePath:n,workspacePath:o,executor:s,concurrency:dg(e.concurrency,30),force:!!e.force});return[{text:[`workspace: ${c.workspacePath}`,`${c.records} records, ${c.chunks} chunks \u2192 ${c.scriptPath}`,`assets: ${c.assets.actors} actors / ${c.assets.locations} locations / ${c.assets.props} props`].join(`
|
|
265
|
-
`),data:{workspace:c.workspacePath,script_path:c.scriptPath,records:c.records,chunks:c.chunks,assets:c.assets}},J]}import*as Mt from"node:fs";import*as Lt from"node:path";var nI=e=>e==null?"":String(e);function oI(e){try{let t=JSON.parse(Mt.readFileSync(Lt.join(e,"timings.json"),"utf-8"));return sm(t,Date.now())}catch{return null}}function qs(e,t,n){let o=Lt.join(e,t),i;try{i=Mt.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var iI=(e,t,n)=>qs(e,t,n).length,Yd=(e,t)=>Mt.existsSync(Lt.join(e,t));function rI(e){try{return JSON.parse(Mt.readFileSync(Lt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function sI(e){try{let t=JSON.parse(Mt.readFileSync(Lt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function Hd(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],..._t({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function aI(e,t,n){try{let o=JSON.parse(Mt.readFileSync(Lt.join(e,t,`${n}.error.json`),"utf-8")),i=mr(o);return i?{pass:t,unit:n,phase:i.phase,attempts:i.attempts,...i.failure}:typeof o=="object"&&o!==null&&"error"in o&&typeof o.error=="string"?Hd(t,n,o.error):Hd(t,n,"Error sidecar has an unsupported schema.")}catch{return Hd(t,n,"Error sidecar is unreadable.")}}function cI(e,t,n=new Set){return qs(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>aI(e,t,o))}function dI(e,t,n){let o=mr(e.current_error);if(!o)return[];let i=`ep_${String(o.unit.episode).padStart(3,"0")}`;return o.unit.episode<=t||n.has(i)?[]:[{pass:"ep",unit:i,phase:o.phase,attempts:o.attempts,...o.failure}]}function Fd(e){let t={};for(let o of e)t[o.failure_type]=(t[o.failure_type]??0)+1;let n=e.filter(o=>o.retryable).length;return{total:e.length,retryable:n,terminal:e.length-n,by_type:t}}function pI(e){try{let t=JSON.parse(Mt.readFileSync(Lt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function lI(e){try{let t=JSON.parse(Mt.readFileSync(Lt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function uI(e,t){try{let n=JSON.parse(Mt.readFileSync(Lt.join(e,"context.json"),"utf-8"));return typeof n.lastEpisode=="number"&&Number.isInteger(n.lastEpisode)?Math.min(Math.max(n.lastEpisode,0),t):0}catch{return 0}}function fI(e,t){let n=t.chunks??0,o={total:n,done:qs(e,"pass2",".json").filter(a=>/^chunk_\d+\.json$/.test(a)).length,failed:iI(e,"pass2",".error.json")},i=pI(e),r=qs(e,"serial",".json").reduce((a,d)=>{let p=d.match(/^win_(\d+)_(\d+)\.json$/);return p?a+(Number(p[2])-Number(p[1])+1):a},0),s={total:i,done:r,failed:0};return{passes:[{name:"normalize",done:n>0&&o.done>=n&&o.failed===0,unit:o},{name:"assemble",done:Yd(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:Yd(e,"script.json")}],units:o}}function mI(e,t,n,o,i){let r=t.episodes?.length??0,s=o-n.filter(d=>d.episode<=o).length,c={total:r,done:o,failed:i};return{passes:[{name:"serial",done:r>0&&c.done>=r&&c.failed===0,unit:c},{name:"finalize",done:o>=r&&lI(e)===o}],units:c,parsed:s}}function wr(e){let t=Lt.resolve(e),n=rI(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:Fd([]),errors:[],updated:null,timings:null};let o=n.source?.kind==="text"?"text":"video",i=n.episodes?.length??0,r=o==="video"?uI(t,i):0,s=o==="video"&&r<i,c=o==="video"?n.skips??[]:[],a=new Set(c.map(_=>`ep_${String(_.episode).padStart(3,"0")}`)),d=o==="video"&&r<i?dI(n,r,a):[],p=o==="video"?mI(t,n,c,r,d.length):null,{passes:l,units:f}=o==="text"?fI(t,n):p,u=o==="text"?cI(t,"pass2"):d;if(s){let _=c.filter(A=>A.episode<=r);return{workspace:t,exists:!0,kind:o,state:u.length>0?"failed":"incomplete",phase:"serial",passes:l,units:f,script:r>0,validation:null,failure_summary:Fd(u),errors:u,updated:n.updated??null,timings:null,completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:_.length,skipped_episodes:c.map(A=>A.episode),has_skips:c.length>0,skips:c.map(A=>({episode:A.episode,skipped_at:A.skipped_at,reason:A.reason,failure_type:A.failure.failure_type,failure_code:A.failure.failure_code}))}}let m=Yd(t,"script.json"),g=sI(t);g&&!g.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],..._t({failure_type:"validation",failure_code:"script_validation_failed"},{retryable:!1,message:`Script validation failed with ${g.errors} error(s).`})});let h,w=l.length>0&&l.every(_=>_.done);(o==="text"||w)&&m&&g?.ok?h="ready":u.length>0||g&&!g.ok?h="failed":h="incomplete";let y=l.find(_=>!_.done),E=h==="ready"?"done":y?y.name:"done",S=o==="video"?{completed:f.done,remaining:Math.max(0,f.total-f.done),complete:f.total>0&&f.done>=f.total&&f.failed===0,next_episode:f.done>=f.total?null:f.done+1,parsed:p?.parsed??0,skipped:c.filter(_=>_.episode<=f.done).length,skipped_episodes:c.map(_=>_.episode),has_skips:c.length>0,skips:c.map(_=>({episode:_.episode,skipped_at:_.skipped_at,reason:_.reason,failure_type:_.failure.failure_type,failure_code:_.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:h,phase:E,passes:l,units:f,script:m,validation:g,failure_summary:Fd(u),errors:u,updated:n.updated??null,timings:oI(t),...S}}function gI(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function hI(e){if(!e.exists)return[`no ingest workspace at ${e.workspace}`];let t=`${e.kind} ingest: ${e.state} (phase=${e.phase})`,n=e.passes.map(i=>`${i.name} ${i.unit?gI(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(yI(e.timings)),e.validation&&o.push(`validation: ${e.validation.ok?"ok":`${e.validation.errors} errors`}, ${e.validation.warnings} warnings`),e.has_skips&&o.push(`skipped episodes: ${e.skipped_episodes?.join(", ")}`),e.state==="failed"){for(let i of e.errors.slice(0,3))o.push(`${i.unit}: ${i.failure_type}/${i.failure_code} \xB7 ${i.retryable?"retryable":"terminal"}`);e.failure_summary.retryable>0&&o.push("rerun `scriptctl ingest` to resume retryable failures"),(e.failure_summary.by_type.policy??0)>0&&o.push("provider policy blocked the source; rerunning the same source is unlikely to help"),((e.failure_summary.by_type.authentication??0)>0||(e.failure_summary.by_type.authorization??0)>0)&&o.push("check provider credentials and permissions before rerunning")}return o}function Qd(e){let t=Math.round(e/1e3);return t>=60?`${Math.floor(t/60)}m${String(t%60).padStart(2,"0")}s`:`${t}s`}function yI(e){let t=[`elapsed ${Qd(e.elapsedMs)}${e.done?"":" (running)"}`],n=e.serial;return n&&(t.push(`serial ${n.doneWindows}/${n.totalWindows} windows (${n.doneEpisodes}/${n.totalEpisodes} eps)`),n.avgWindowMs!=null&&t.push(`~${Qd(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${Qd(n.etaMs)}`)),t.join(" \xB7 ")}function ug(e){let t=nI(e.workspace_path||"workspace"),n=wr(t);return[{text:hI(n).join(`
|
|
266
|
-
`),data:{status:n}},J]}import*as Ws from"node:path";function cn(e,t,n,o){return new x(e,{exitCode:b,errorCode:t,hint:n,data:{actual:o}})}function wI(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw cn("--episode must be a positive integer.","INGEST_SKIP_EPISODE_INVALID","Pass the current next_episode from `scriptctl ingest status`.",[String(e)]);return t}async function _I(e,t,n){let o=new At(e);if(!o.has("manifest.json"))throw cn("The ingest workspace does not exist.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first, then retry the failed episode or skip it.",[e]);if(o.readJson("manifest.json").source?.kind==="text")throw cn("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=jd(o);if(!r)throw cn("The video ingest manifest is missing.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first.",[e]);let s=r.episodes.find(w=>w.episode===t);if(!s)throw cn("The requested episode is not in the video source.","INGEST_SKIP_EPISODE_NOT_FOUND","Pass an episode listed in manifest.json.",[`episode=${t}`]);let c=Bd(o);zs(c.episodes,r.episodes);let a=o.has("context.json")?o.readJson("context.json"):li();if(c.episodes.find(w=>w.episode===t)){let w=zd(o,r);a=gr(o,a,c.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):oi();return Fs(o,w.episodes,a,Qs(w.source.path),y,c.episodes),!1}let p=a.lastEpisode+1;if(t!==p)throw cn("Only the next unresolved video episode can be skipped.","INGEST_SKIP_NOT_NEXT","Read status.next_episode and skip exactly that episode.",[`requested=${t}`,`next_episode=${p}`]);let l=`ep/ep_${String(t).padStart(3,"0")}`;if(o.has(`${l}.json`))throw cn("A parsed episode cannot be skipped.","INGEST_SKIP_ALREADY_PARSED","Continue ingest from the next unresolved episode.",[`episode=${t}`]);if(!o.has(`${l}.error.json`))throw cn("The episode has no recorded ingest failure.","INGEST_SKIP_FAILURE_REQUIRED","Run ingest for this episode first; a typed error sidecar is required before manual skip.",[`episode=${t}`]);let f=mr(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw cn("The episode error sidecar is invalid.","INGEST_SKIP_FAILURE_INVALID","Regenerate the typed failure by rerunning video ingest.",[`${l}.error.json`]);let u={episode:t,skipped_at:new Date().toISOString(),reason:n,source_sha256:s.sha256,failure:f.failure,attempts:f.attempts},m=zd(o,r),g=[...c.episodes,u];o.writeJson("manifest.json",{...m,updated:u.skipped_at,current_error:void 0,skips:g}),ng(o,{schema_version:1,episodes:g}),a=gr(o,a,g);let h=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):oi();return Fs(o,m.episodes,a,Qs(m.source.path),h,[...c.episodes,u]),!0}async function fg(e){let t=Ws.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=wI(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw cn("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await fi(t,()=>_I(t,n,o)),r=wr(t),s=Bd(new At(t)).episodes.map(c=>c.episode);return[{text:i?`Episode ${n} skipped; ingest can continue at episode ${r.next_episode??"end"}.`:`Episode ${n} was already skipped; no changes made.`,data:{workspace:t,episode:n,changed:i,skipped_episodes:s,complete:r.complete??!1,next_episode:r.next_episode??null,script_path:Ws.join(t,"script.json")}},J]}import*as Xs from"node:fs";import*as Lo from"node:path";import{spawnSync as EI}from"node:child_process";function Zs(e,t,n,o){return new x(e,{exitCode:b,errorCode:t,hint:n,data:{actual:o}})}function xI(e){let t=Gs(Wn(e)),n=Vs(t);if(n)throw Zs("Video episode files are not a continuous 1..N sequence.","EVIDENCE_VIDEO_SEQUENCE_INVALID","Rename the linked videos so every script episode has one matching numbered file.",[n]);return t.map(o=>{let i=Lo.resolve(o.path),r=Xs.statSync(i),s=r.size,c=Math.trunc(r.mtimeMs),a=EI("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",i],{encoding:"utf-8"}),d=Number(a.stdout.trim()),p=a.status===0&&Number.isFinite(d)&&d>0?Math.round(d*1e3):void 0;return{episode:o.episode,path:i,ext:o.ext,mime:o.mime,sha256:Se(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:c})),size_bytes:s,mtime_ms:c,duration_ms:p}})}async function SI(e){let t=Lo.resolve(e.scriptPath),n=Lo.resolve(e.sourcePath),o=Lo.resolve(e.workspacePath),i=Dr(JSON.parse(Xs.readFileSync(t,"utf-8"))),r=xI(n);if(r.length!==i.episodes.length)throw Zs("The linked video count does not match the script episode count.","EVIDENCE_VIDEO_EPISODE_COUNT_MISMATCH","Bind the complete source-video folder for this script, then retry.",[`script=${i.episodes.length}`,`videos=${r.length}`]);let s=Js(r),c=Ds([],i,li(),r,s),a=await fi(o,async()=>{let p=new At(o);return p.ensure(),Bs(p,c,e.signal,e.extractor,{reuseExistingFrames:e.force!==!0})}),d=[...a.items.flatMap(p=>p.samples),...(a.identities??[]).flatMap(p=>p.samples)];return{output:Lo.join(o,"evidence","state-evidence.json"),states:a.items.length,identities:a.identities?.length??0,samples:d.length,ready:d.filter(p=>p.frame_status==="ready").length,unavailable:d.filter(p=>p.frame_status==="unavailable").length,sourceSha256:s}}async function mg(e){let t=xe(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw Zs("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw Zs("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await SI({scriptPath:t,sourcePath:n,workspacePath:o,force:e.force===!0});return[{text:`Generated ${i.ready}/${i.samples} original-video reference frames for ${i.states} actor states.`,data:{output:i.output,states:i.states,identities:i.identities,samples:i.samples,ready:i.ready,unavailable:i.unavailable,source_sha256:i.sourceSha256}},J]}import*as _i from"node:fs";import*as ea from"node:path";var mt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rn=e=>Array.isArray(e),$e=e=>typeof e=="string"?e:"",II={interior:"\u5185",exterior:"\u5916"},AI={day:"\u65E5",night:"\u591C"},kI=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},bI=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function qd(e,t,n){let o=new Map;if(Rn(e))for(let i of e)mt(i)&&typeof i[t]=="string"&&o.set(i[t],$e(i[n]));return o}function OI(e,t){let n=new Map;if(Rn(e))for(let o of e){if(!mt(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of Rn(o.states)?o.states:[])mt(r)&&typeof r.state_id=="string"&&i.set(r.state_id,$e(r.state_name));n.set(o[t],i)}return n}function vI(e,t){return mt(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${$e(e.label)}`:""}`:"":""}function RI(e){let t=qd(e.actors,"actor_id","actor_name"),n=qd(e.locations,"location_id","location_name"),o=qd(e.props,"prop_id","prop_name"),i=OI(e.actors,"actor_id"),r=(Rn(e.episodes)?e.episodes:[]).filter(mt).map(c=>({episode:kI($e(c.episode_id)),synopsis:$e(c.synopsis),scenes:(Rn(c.scenes)?c.scenes:[]).filter(mt).map(a=>{let d=mt(a.location)?n.get($e(a.location.location_id))??$e(a.location.location_id):"",p=[],l={};for(let m of Rn(a.actors)?a.actors:[]){if(!mt(m)||typeof m.actor_id!="string")continue;let g=t.get(m.actor_id)??m.actor_id;if(p.includes(g)||p.push(g),typeof m.state_id=="string"){let w=(i.get(m.actor_id)?.get(m.state_id)??"")||(m.state_id!=="default"?m.state_id:"");w&&(l[g]=w)}}let f=[];for(let m of Rn(a.props)?a.props:[])if(mt(m)&&typeof m.prop_id=="string"){let g=o.get(m.prop_id)??m.prop_id;f.includes(g)||f.push(g)}let u=mt(a.environment)?a.environment:{};return{scene_num:bI($e(a.scene_id)),location_name:d,environment:{space:II[$e(u.space)]??$e(u.space),time:AI[$e(u.time)]??$e(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(Rn(a.actions)?a.actions:[]).filter(mt).map(m=>({type:$e(m.type),content:$e(m.content),speaker:vI(m.speaker,t),emotion:typeof m.emotion=="string"?m.emotion:void 0,extend:mt(m.extend)&&typeof m.extend.timestamp=="string"?{timestamp:m.extend.timestamp}:void 0}))}})})),s=(Rn(e.actors)?e.actors:[]).filter(mt).map(c=>({asset_name:$e(c.actor_name),description:$e(c.description),extend:{}}));return{title:$e(e.title),actors:s,episodes:r}}function gg(e){if(!mt(e))throw new Error("review renderer expects a script object");let t=RI(e),n=JSON.stringify(t),o=$e(t.title);return`<!DOCTYPE html>
|
|
267
|
-
<html lang="zh">
|
|
268
|
-
<head>
|
|
269
|
-
<meta charset="utf-8">
|
|
270
|
-
<title>\u5267\u672C\u5BA1\u9605\u5668 \xB7 ${o}</title>
|
|
271
|
-
<style>
|
|
272
|
-
* { box-sizing: border-box; }
|
|
273
|
-
html, body { margin: 0; height: 100%; font: 14px/1.6 -apple-system, "PingFang SC", system-ui, sans-serif; color: #1a1a1a; }
|
|
274
|
-
body { display: flex; flex-direction: column; height: 100vh; background: #f5f5f7; }
|
|
275
|
-
header { display: flex; align-items: center; gap: 12px; padding: 8px 14px; background: #fff; border-bottom: 1px solid #ddd; flex: none; }
|
|
276
|
-
header h1 { font-size: 15px; margin: 0; font-weight: 600; }
|
|
277
|
-
header select, header .nav { font-size: 13px; padding: 4px 8px; border: 1px solid #ccc; border-radius: 6px; background: #fff; cursor: pointer; }
|
|
278
|
-
header .spacer { flex: 1; }
|
|
279
|
-
header .hint { color: #888; font-size: 12px; }
|
|
280
|
-
main { flex: 1; display: flex; min-height: 0; }
|
|
281
|
-
.left { width: 42%; min-width: 320px; max-width: 620px; background: #000; display: flex; flex-direction: column; align-items: center; justify-content: flex-start; position: relative; }
|
|
282
|
-
.left video { width: 100%; height: auto; max-height: 72vh; background: #000; }
|
|
283
|
-
.vbar { color: #ccc; font-size: 12px; padding: 6px 10px; width: 100%; display: flex; gap: 12px; align-items: center; background: #111; }
|
|
284
|
-
.vbar b { color: #fff; font-variant-numeric: tabular-nums; }
|
|
285
|
-
.right { flex: 1; overflow-y: auto; padding: 10px 4px 40vh 4px; background: #fafafa; }
|
|
286
|
-
.syn { background: #fff7e6; border: 1px solid #ffe0a3; border-radius: 8px; padding: 10px 12px; margin: 8px 10px 14px; color: #5b4a1f; font-size: 13px; }
|
|
287
|
-
.scene { margin: 0 10px 14px; border: 1px solid #e5e5e5; border-radius: 8px; overflow: hidden; background: #fff; }
|
|
288
|
-
.scene-head { background: #eef2f7; padding: 6px 12px; font-size: 12px; color: #445; display: flex; gap: 14px; flex-wrap: wrap; }
|
|
289
|
-
.scene-head .loc { font-weight: 600; color: #223; }
|
|
290
|
-
.rows { }
|
|
291
|
-
.row { display: flex; gap: 10px; padding: 5px 12px; border-top: 1px solid #f0f0f0; cursor: pointer; align-items: baseline; }
|
|
292
|
-
.row:hover { background: #eef6ff; }
|
|
293
|
-
.row.active { background: #d8ecff; }
|
|
294
|
-
.row .ts { flex: none; width: 46px; color: #3a7; font-variant-numeric: tabular-nums; font-size: 12px; }
|
|
295
|
-
.row .kind { flex: none; width: 58px; font-size: 12px; }
|
|
296
|
-
.row .kind.act { color: #999; }
|
|
297
|
-
.row .kind.dlg { color: #c60; font-weight: 600; }
|
|
298
|
-
.row .kind.think { color: #96c; font-style: italic; }
|
|
299
|
-
.row .body { flex: 1; }
|
|
300
|
-
.row .spk { color: #c60; font-weight: 600; margin-right: 4px; }
|
|
301
|
-
.row .emo { color: #a8a; font-size: 12px; margin-left: 4px; }
|
|
302
|
-
.row .body .subtitle { color: #b00; } /* \u753B\u9762\u5B57\u5E55\u5F15\u8FF0\uFF0C\u7EA2\u8272\u6807\u51FA */
|
|
303
|
-
/* ===== Tab ===== */
|
|
304
|
-
header .tabs { display: flex; gap: 4px; }
|
|
305
|
-
header .tab { font-size: 13px; padding: 5px 14px; border: 1px solid #ccc; border-radius: 6px; background: #fff; cursor: pointer; color: #555; }
|
|
306
|
-
header .tab.active { background: #1a6dff; color: #fff; border-color: #1a6dff; font-weight: 600; }
|
|
307
|
-
header .ep-ctl { display: flex; gap: 8px; align-items: center; }
|
|
308
|
-
/* ===== \u8D44\u4EA7\u603B\u89C8 ===== */
|
|
309
|
-
.assets { flex: 1; overflow-y: auto; padding: 16px 18px 30vh; background: #f5f5f7; }
|
|
310
|
-
.asset-sec { margin: 0 0 26px; }
|
|
311
|
-
.asset-sec > h2 { font-size: 15px; margin: 4px 0 12px; color: #223; display: flex; align-items: center; gap: 8px; }
|
|
312
|
-
.asset-sec > h2 .cnt { font-size: 12px; font-weight: 400; color: #888; background: #ececf0; padding: 1px 8px; border-radius: 10px; }
|
|
313
|
-
.acard { background: #fff; border: 1px solid #e3e3e6; border-radius: 10px; padding: 14px 16px; margin-bottom: 12px; }
|
|
314
|
-
.acard .ah { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
|
|
315
|
-
.acard .ah .nm { font-size: 17px; font-weight: 700; color: #1a1a1a; }
|
|
316
|
-
.acard .ah .id { font-size: 12px; color: #aaa; font-variant-numeric: tabular-nums; }
|
|
317
|
-
.acard .ah .meta { margin-left: auto; font-size: 12px; color: #888; display: flex; gap: 6px; }
|
|
318
|
-
.acard .ah .meta .tag { background: #f0f0f3; border-radius: 6px; padding: 1px 8px; }
|
|
319
|
-
.acard .desc { font-size: 13px; color: #555; margin: 7px 0 4px; }
|
|
320
|
-
.acard .anchor { font-size: 12px; color: #999; margin-bottom: 8px; }
|
|
321
|
-
/* \u72B6\u6001\xD7\u96C6 \u77E9\u9635 */
|
|
322
|
-
.mtx { overflow-x: auto; margin-top: 8px; border: 1px solid #eee; border-radius: 8px; }
|
|
323
|
-
table.tl { border-collapse: collapse; font-size: 12px; width: 100%; }
|
|
324
|
-
table.tl th, table.tl td { border: 1px solid #eee; padding: 5px 7px; text-align: center; white-space: nowrap; }
|
|
325
|
-
table.tl thead th { background: #f7f7f9; color: #556; font-weight: 600; position: sticky; top: 0; }
|
|
326
|
-
table.tl .stname { text-align: left; font-weight: 600; color: #333; background: #fafafa; position: sticky; left: 0; min-width: 130px; max-width: 220px; white-space: normal; }
|
|
327
|
-
table.tl .stname.unmk { color: #999; font-weight: 400; }
|
|
328
|
-
table.tl .stname .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
|
|
329
|
-
table.tl .stname .sc { color: #aaa; font-weight: 400; font-size: 11px; margin-left: 4px; }
|
|
330
|
-
table.tl td.cell { color: #ccc; }
|
|
331
|
-
table.tl td.hit { background: #fff0f0; }
|
|
332
|
-
table.tl td.hit.unmk { background: #f2f2f2; }
|
|
333
|
-
.scc { display: inline-block; min-width: 20px; margin: 1px; padding: 1px 6px; border-radius: 6px; font-variant-numeric: tabular-nums; cursor: pointer; }
|
|
334
|
-
.scc.on { background: #f4c9c9; color: #7a1f1f; border: 1px solid #e8a9a9; }
|
|
335
|
-
.scc.on.unmk { background: #dcdcdc; color: #555; border-color: #c9c9c9; }
|
|
336
|
-
.scc.on:hover { filter: brightness(0.94); }
|
|
337
|
-
</style>
|
|
338
|
-
</head>
|
|
339
|
-
<body>
|
|
340
|
-
<header>
|
|
341
|
-
<h1>${o||"\u5267\u672C\u5BA1\u9605\u5668"}</h1>
|
|
342
|
-
<div class="tabs">
|
|
343
|
-
<button class="tab active" id="tab-script">\u5267\u672C\u5BA1\u9605</button>
|
|
344
|
-
<button class="tab" id="tab-assets">\u8D44\u4EA7\u603B\u89C8</button>
|
|
345
|
-
</div>
|
|
346
|
-
<span class="ep-ctl">
|
|
347
|
-
<select id="epsel"></select>
|
|
348
|
-
<button class="nav" id="prev">\u25C0 \u4E0A\u4E00\u96C6</button>
|
|
349
|
-
<button class="nav" id="next">\u4E0B\u4E00\u96C6 \u25B6</button>
|
|
350
|
-
</span>
|
|
351
|
-
<span class="spacer"></span>
|
|
352
|
-
<span class="hint" id="hint">\u70B9\u4EFB\u610F\u5267\u672C\u884C \u2192 \u89C6\u9891\u8DF3\u5230\u8BE5\u65F6\u95F4\u6233</span>
|
|
353
|
-
</header>
|
|
354
|
-
<main id="view-script">
|
|
355
|
-
<div class="left">
|
|
356
|
-
<video id="vid" controls preload="metadata"></video>
|
|
357
|
-
<div class="vbar"><span>\u5F53\u524D <b id="cur">00:00</b></span><span id="epinfo"></span></div>
|
|
358
|
-
</div>
|
|
359
|
-
<div class="right" id="right"></div>
|
|
360
|
-
</main>
|
|
361
|
-
<div id="view-assets" class="assets" style="display:none"></div>
|
|
362
|
-
<script>
|
|
363
|
-
const SCRIPT = ${n};
|
|
364
|
-
const eps = SCRIPT.episodes.slice().sort((a,b)=>a.episode-b.episode);
|
|
365
|
-
const vid = document.getElementById('vid');
|
|
366
|
-
const right = document.getElementById('right');
|
|
367
|
-
const epsel = document.getElementById('epsel');
|
|
368
|
-
const cur = document.getElementById('cur');
|
|
369
|
-
const epinfo = document.getElementById('epinfo');
|
|
370
|
-
let curEp = eps.length?eps[0].episode:1;
|
|
371
|
-
|
|
372
|
-
function pad(n){return String(n).padStart(2,'0');}
|
|
373
|
-
function fmt(sec){sec=Math.max(0,sec|0);return pad(sec/60|0)+':'+pad(sec%60);}
|
|
374
|
-
function tsToSec(ts){if(!ts)return null;const m=String(ts).match(/(?:(\\d{1,2}):)?(\\d{1,2}):(\\d{2}(?:\\.\\d{1,3})?)/);return m?(+(m[1]||0))*3600+(+m[2])*60+(+m[3]):null;}
|
|
375
|
-
function epId(n){return 'ep_'+String(n).padStart(3,'0');}
|
|
376
|
-
function actKind(t){return t==='dialogue'?'dlg':t==='inner_thought'?'think':'act';}
|
|
377
|
-
function actTs(a){return a && a.extend ? a.extend.timestamp : undefined;}
|
|
378
|
-
|
|
379
|
-
function renderBody(content){
|
|
380
|
-
const esc = content.replace(/&/g,'&').replace(/</g,'<');
|
|
381
|
-
return esc.replace(/(\u753B\u9762(?:\u5B57\u5E55|\u6587\u5B57)[:\uFF1A][^\u3002\uFF01\uFF1F\\n]*)/g,'<span class="subtitle">$1</span>');
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
for(const e of eps){
|
|
385
|
-
const o=document.createElement('option');
|
|
386
|
-
o.value=e.episode; o.textContent='\u7B2C '+e.episode+' \u96C6';
|
|
387
|
-
epsel.appendChild(o);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function loadEp(n, targetScene){
|
|
391
|
-
curEp=n;
|
|
392
|
-
epsel.value=n;
|
|
393
|
-
vid.src='src/'+epId(n)+'.mp4';
|
|
394
|
-
const ep=eps.find(e=>e.episode===n);
|
|
395
|
-
if(!ep)return;
|
|
396
|
-
epinfo.textContent='\u7B2C'+n+'\u96C6 \xB7 '+ep.scenes.length+'\u573A';
|
|
397
|
-
right.innerHTML='';
|
|
398
|
-
if(ep.synopsis){const s=document.createElement('div');s.className='syn';s.textContent='\u6897\u6982\uFF1A'+ep.synopsis;right.appendChild(s);}
|
|
399
|
-
for(const sc of ep.scenes){
|
|
400
|
-
const box=document.createElement('div');box.className='scene';
|
|
401
|
-
box.dataset.scene=sc.scene_num;
|
|
402
|
-
const head=document.createElement('div');head.className='scene-head';
|
|
403
|
-
const env=(sc.environment&&(sc.environment.space||'')+' '+(sc.environment.time||''))||'';
|
|
404
|
-
const chNames=sc.actor_names||[]; const chSt=sc.actor_states||{};
|
|
405
|
-
head.innerHTML='<span class="loc">\u573A\u666F'+sc.scene_num+' \xB7 '+(sc.location_name||'')+'</span>'+
|
|
406
|
-
'<span>'+env+'</span>'+
|
|
407
|
-
(chNames.length?'<span>\u89D2\u8272: '+chNames.map(nm=>nm+(chSt[nm]?'('+chSt[nm]+')':'')).join('\u3001')+'</span>':'');
|
|
408
|
-
box.appendChild(head);
|
|
409
|
-
const rows=document.createElement('div');rows.className='rows';
|
|
410
|
-
for(const a of sc.actions){
|
|
411
|
-
const ts=actTs(a); const kd=actKind(a.type); const sec=tsToSec(ts);
|
|
412
|
-
const row=document.createElement('div');row.className='row';row.dataset.sec=sec==null?'':sec;
|
|
413
|
-
const spk=a.speaker?'<span class="spk">'+a.speaker+'</span>':'';
|
|
414
|
-
const emo=a.emotion?'<span class="emo">['+a.emotion+']</span>':'';
|
|
415
|
-
row.innerHTML='<span class="ts">'+(ts||'')+'</span>'+
|
|
416
|
-
'<span class="kind '+kd+'">'+kd+'</span>'+
|
|
417
|
-
'<span class="body">'+spk+renderBody(a.content)+emo+'</span>';
|
|
418
|
-
if(sec!=null)row.addEventListener('click',()=>{vid.currentTime=sec;vid.play();});
|
|
419
|
-
rows.appendChild(row);
|
|
420
|
-
}
|
|
421
|
-
box.appendChild(rows);right.appendChild(box);
|
|
422
|
-
}
|
|
423
|
-
if(targetScene){
|
|
424
|
-
const tb=right.querySelector('.scene[data-scene="'+targetScene+'"]');
|
|
425
|
-
if(tb){tb.scrollIntoView({block:'start'}); tb.style.outline='2px solid #1a6dff'; setTimeout(()=>tb.style.outline='',1600);}
|
|
426
|
-
} else { right.scrollTop=0; }
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
vid.addEventListener('timeupdate',()=>{
|
|
430
|
-
cur.textContent=fmt(vid.currentTime);
|
|
431
|
-
const t=vid.currentTime;
|
|
432
|
-
const rows=[...right.querySelectorAll('.row')].filter(r=>r.dataset.sec!=='');
|
|
433
|
-
let active=null;
|
|
434
|
-
for(const r of rows){ if(+r.dataset.sec<=t+0.25) active=r; else break; }
|
|
435
|
-
right.querySelectorAll('.row.active').forEach(r=>r.classList.remove('active'));
|
|
436
|
-
if(active){active.classList.add('active');}
|
|
437
|
-
});
|
|
438
|
-
|
|
439
|
-
epsel.addEventListener('change',()=>loadEp(+epsel.value));
|
|
440
|
-
document.getElementById('prev').addEventListener('click',()=>{const i=eps.findIndex(e=>e.episode===curEp);if(i>0)loadEp(eps[i-1].episode);});
|
|
441
|
-
document.getElementById('next').addEventListener('click',()=>{const i=eps.findIndex(e=>e.episode===curEp);if(i<eps.length-1)loadEp(eps[i+1].episode);});
|
|
442
|
-
|
|
443
|
-
if(eps.length)loadEp(curEp);
|
|
444
|
-
|
|
445
|
-
// ===================== \u8D44\u4EA7\u603B\u89C8 =====================
|
|
446
|
-
const allEps = eps.map(e=>e.episode).sort((a,b)=>a-b);
|
|
447
|
-
const actorMeta = {};
|
|
448
|
-
for(const a of (SCRIPT.actors||[])){
|
|
449
|
-
const ext=a.extend||{};
|
|
450
|
-
actorMeta[a.asset_name]={role:a.description||'',anchor:ext.anchor||''};
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
function aggAssets(){
|
|
454
|
-
const person={}, loc={}, prop={};
|
|
455
|
-
const addP=(nm,st,n,idx)=>{(person[nm]=person[nm]||{});(person[nm][st]=person[nm][st]||new Map()).set(n+':'+idx,{n,idx});};
|
|
456
|
-
const addX=(bag,nm,n,idx)=>{(bag[nm]=bag[nm]||new Map()).set(n+':'+idx,{n,idx});};
|
|
457
|
-
for(const ep of eps){ const n=ep.episode;
|
|
458
|
-
for(const sc of ep.scenes){ const idx=sc.scene_num;
|
|
459
|
-
const names=sc.actor_names||[]; const st=sc.actor_states||{};
|
|
460
|
-
for(const nm of names) addP(nm, st[nm]||'\u672A\u6807\u6CE8', n, idx);
|
|
461
|
-
if(sc.location_name) addX(loc, sc.location_name, n, idx);
|
|
462
|
-
for(const p of (sc.prop_names||[])) addX(prop, p, n, idx);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
return {person,loc,prop};
|
|
466
|
-
}
|
|
467
|
-
const AG = aggAssets();
|
|
468
|
-
|
|
469
|
-
function epsOf(occMaps){ const s=new Set(); for(const m of occMaps) for(const {n} of m.values()) s.add(n); return [...s].sort((a,b)=>a-b); }
|
|
470
|
-
function sceneChips(occMap, unmk){
|
|
471
|
-
const byEp={}; for(const {n,idx} of occMap.values()){(byEp[n]=byEp[n]||[]).push(idx);}
|
|
472
|
-
return byEp;
|
|
473
|
-
}
|
|
474
|
-
function chipEl(n, idx, unmk){
|
|
475
|
-
const c=document.createElement('span'); c.className='scc on'+(unmk?' unmk':''); c.textContent=idx;
|
|
476
|
-
c.title='\u7B2C'+n+'\u96C6 \xB7 \u573A'+idx+' \u2192 \u8DF3\u8F6C';
|
|
477
|
-
c.addEventListener('click',(e)=>{e.stopPropagation();gotoScene(n,idx);});
|
|
478
|
-
return c;
|
|
479
|
-
}
|
|
480
|
-
function gotoScene(n, idx){ switchTab('script'); loadEp(n, idx); }
|
|
481
|
-
|
|
482
|
-
function personCard(name){
|
|
483
|
-
const states=AG.person[name]; const stKeys=Object.keys(states);
|
|
484
|
-
const involved=epsOf(Object.values(states));
|
|
485
|
-
const card=document.createElement('div'); card.className='acard';
|
|
486
|
-
const meta=actorMeta[name]||{};
|
|
487
|
-
const totalScenes=new Set(); for(const m of Object.values(states)) for(const k of m.keys()) totalScenes.add(k);
|
|
488
|
-
const head=document.createElement('div'); head.className='ah';
|
|
489
|
-
head.innerHTML='<span class="nm">'+esc(name)+'</span>'+
|
|
490
|
-
'<span class="meta"><span class="tag">'+totalScenes.size+' \u573A</span><span class="tag">'+involved.length+' \u96C6</span><span class="tag">'+stKeys.length+' \u72B6\u6001</span></span>';
|
|
491
|
-
card.appendChild(head);
|
|
492
|
-
if(meta.role){const d=document.createElement('div');d.className='desc';d.textContent=meta.role;card.appendChild(d);}
|
|
493
|
-
if(meta.anchor){const d=document.createElement('div');d.className='anchor';d.textContent='\u951A\u70B9\uFF1A'+meta.anchor;card.appendChild(d);}
|
|
494
|
-
const wrap=document.createElement('div'); wrap.className='mtx';
|
|
495
|
-
const tb=document.createElement('table'); tb.className='tl';
|
|
496
|
-
let thead='<thead><tr><th class="stname">\u72B6\u6001\uFF3C\u96C6</th>';
|
|
497
|
-
for(const n of involved) thead+='<th>'+n+'</th>';
|
|
498
|
-
thead+='</tr></thead>';
|
|
499
|
-
const ordered=stKeys.filter(s=>s!=='\u672A\u6807\u6CE8').sort((a,b)=>states[b].size-states[a].size);
|
|
500
|
-
if(states['\u672A\u6807\u6CE8']) ordered.push('\u672A\u6807\u6CE8');
|
|
501
|
-
const tbody=document.createElement('tbody');
|
|
502
|
-
for(const st of ordered){
|
|
503
|
-
const unmk=st==='\u672A\u6807\u6CE8';
|
|
504
|
-
const byEp=sceneChips(states[st], unmk);
|
|
505
|
-
const tr=document.createElement('tr');
|
|
506
|
-
const th=document.createElement('td'); th.className='stname'+(unmk?' unmk':'');
|
|
507
|
-
th.innerHTML='<span class="dot" style="background:'+(unmk?'#bbb':'#d9534f')+'"></span>'+esc(st)+'<span class="sc">'+states[st].size+'</span>';
|
|
508
|
-
tr.appendChild(th);
|
|
509
|
-
for(const n of involved){
|
|
510
|
-
const td=document.createElement('td'); td.className='cell'+(byEp[n]?' hit'+(unmk?' unmk':''):'');
|
|
511
|
-
if(byEp[n]){ for(const idx of byEp[n].sort((a,b)=>a-b)) td.appendChild(chipEl(n,idx,unmk)); }
|
|
512
|
-
tr.appendChild(td);
|
|
513
|
-
}
|
|
514
|
-
tbody.appendChild(tr);
|
|
515
|
-
}
|
|
516
|
-
tb.innerHTML=thead; tb.appendChild(tbody);
|
|
517
|
-
wrap.appendChild(tb); card.appendChild(wrap);
|
|
518
|
-
return card;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
function occCard(name, occMap){
|
|
522
|
-
const involved=epsOf([occMap]);
|
|
523
|
-
const card=document.createElement('div'); card.className='acard';
|
|
524
|
-
const head=document.createElement('div'); head.className='ah';
|
|
525
|
-
head.innerHTML='<span class="nm">'+esc(name)+'</span>'+
|
|
526
|
-
'<span class="meta"><span class="tag">'+occMap.size+' \u573A</span><span class="tag">'+involved.length+' \u96C6</span></span>';
|
|
527
|
-
card.appendChild(head);
|
|
528
|
-
const wrap=document.createElement('div'); wrap.className='mtx';
|
|
529
|
-
const tb=document.createElement('table'); tb.className='tl';
|
|
530
|
-
let thead='<thead><tr><th class="stname">\u51FA\u73B0\uFF3C\u96C6</th>';
|
|
531
|
-
for(const n of involved) thead+='<th>'+n+'</th>'; thead+='</tr></thead>';
|
|
532
|
-
const byEp=sceneChips(occMap,false);
|
|
533
|
-
const tbody=document.createElement('tbody'); const tr=document.createElement('tr');
|
|
534
|
-
const th=document.createElement('td'); th.className='stname';
|
|
535
|
-
th.innerHTML='<span class="dot" style="background:#5b8def"></span>\u51FA\u73B0';
|
|
536
|
-
tr.appendChild(th);
|
|
537
|
-
for(const n of involved){ const td=document.createElement('td'); td.className='cell'+(byEp[n]?' hit':'');
|
|
538
|
-
if(byEp[n]){ for(const idx of byEp[n].sort((a,b)=>a-b)) td.appendChild(chipEl(n,idx,false)); } tr.appendChild(td);}
|
|
539
|
-
tbody.appendChild(tr); tb.innerHTML=thead; tb.appendChild(tbody);
|
|
540
|
-
wrap.appendChild(tb); card.appendChild(wrap);
|
|
541
|
-
return card;
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
function esc(s){return String(s).replace(/&/g,'&').replace(/</g,'<');}
|
|
545
|
-
|
|
546
|
-
let assetsRendered=false;
|
|
547
|
-
function renderAssets(){
|
|
548
|
-
if(assetsRendered) return; assetsRendered=true;
|
|
549
|
-
const root=document.getElementById('view-assets');
|
|
550
|
-
const persons=Object.keys(AG.person).sort((a,b)=>{
|
|
551
|
-
const ea=new Set(),eb=new Set();
|
|
552
|
-
for(const m of Object.values(AG.person[a])) for(const {n} of m.values()) ea.add(n);
|
|
553
|
-
for(const m of Object.values(AG.person[b])) for(const {n} of m.values()) eb.add(n);
|
|
554
|
-
return eb.size-ea.size;
|
|
555
|
-
});
|
|
556
|
-
const secP=document.createElement('div'); secP.className='asset-sec';
|
|
557
|
-
secP.innerHTML='<h2>\u4EBA\u7269 <span class="cnt">'+persons.length+'</span></h2>';
|
|
558
|
-
for(const nm of persons) secP.appendChild(personCard(nm));
|
|
559
|
-
root.appendChild(secP);
|
|
560
|
-
const locs=Object.keys(AG.loc).sort((a,b)=>AG.loc[b].size-AG.loc[a].size);
|
|
561
|
-
const secL=document.createElement('div'); secL.className='asset-sec';
|
|
562
|
-
secL.innerHTML='<h2>\u573A\u666F <span class="cnt">'+locs.length+'</span></h2>';
|
|
563
|
-
for(const nm of locs) secL.appendChild(occCard(nm,AG.loc[nm]));
|
|
564
|
-
root.appendChild(secL);
|
|
565
|
-
const props=Object.keys(AG.prop).sort((a,b)=>AG.prop[b].size-AG.prop[a].size);
|
|
566
|
-
const secD=document.createElement('div'); secD.className='asset-sec';
|
|
567
|
-
secD.innerHTML='<h2>\u9053\u5177 <span class="cnt">'+props.length+'</span></h2>';
|
|
568
|
-
for(const nm of props) secD.appendChild(occCard(nm,AG.prop[nm]));
|
|
569
|
-
root.appendChild(secD);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
const tabScript=document.getElementById('tab-script'), tabAssets=document.getElementById('tab-assets');
|
|
573
|
-
const viewScript=document.getElementById('view-script'), viewAssets=document.getElementById('view-assets');
|
|
574
|
-
const epCtl=document.querySelector('.ep-ctl'), hint=document.getElementById('hint');
|
|
575
|
-
function switchTab(which){
|
|
576
|
-
const asset=which==='assets';
|
|
577
|
-
tabScript.classList.toggle('active',!asset); tabAssets.classList.toggle('active',asset);
|
|
578
|
-
viewScript.style.display=asset?'none':'flex'; viewAssets.style.display=asset?'block':'none';
|
|
579
|
-
epCtl.style.display=asset?'none':'flex';
|
|
580
|
-
hint.textContent=asset?'\u70B9\u573A\u53F7 \u2192 \u8DF3\u56DE\u5267\u672C\u5BA1\u9605\u5BF9\u5E94\u96C6/\u573A':'\u70B9\u4EFB\u610F\u5267\u672C\u884C \u2192 \u89C6\u9891\u8DF3\u5230\u8BE5\u65F6\u95F4\u6233';
|
|
581
|
-
if(asset) renderAssets();
|
|
582
|
-
}
|
|
583
|
-
tabScript.addEventListener('click',()=>switchTab('script'));
|
|
584
|
-
tabAssets.addEventListener('click',()=>switchTab('assets'));
|
|
585
|
-
</script>
|
|
586
|
-
</body>
|
|
587
|
-
</html>`}import*as hg from"node:http";import*as no from"node:fs";import*as dn from"node:path";import{spawn as NI}from"node:child_process";var MI=e=>e==null?"":String(e);function LI(e){let t=r=>{try{let s=no.statSync(dn.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let c=[];try{c=no.readdirSync(dn.join(e,r))}catch{return[]}return c.filter(s).sort().map(a=>t(`${r}/${a}`)).filter(a=>!!a)},o=r=>r.filter(s=>!!s),i=r=>n("ep",s=>s.endsWith(r)&&!s.endsWith(".error.json"));return{\u7ED3\u679C:o([t("script.json"),t("validation.json"),t("asset-audit.json"),t("usage.json"),t("review.html"),t("timings.json")]),\u4E0A\u4E0B\u6587:n("serial",r=>r.startsWith("context_")&&r.endsWith(".md")),\u6BCF\u7A97\u66F4\u65B0:n("serial",r=>r.startsWith("win_")&&r.endsWith(".json")),\u7BC7\u7AE0\u6897\u6982:n("serial",r=>r.startsWith("arc_")&&r.endsWith(".md")),\u524D\u6BB5:n("pass2",r=>/^chunk_\d+\.json$/.test(r)),\u8F6C\u5F55:i(".md").filter(r=>!r.rel.endsWith(".context.md")),\u9001\u6A21\u4E0A\u4E0B\u6587:i(".context.md"),\u89E3\u6790:i(".json"),\u82B1\u540D\u518C:o([t("context.json")]),\u8BA1\u65F6:o([t("timing.jsonl")]),\u4E2D\u95F4\u4EA7\u7269:o([t("script.initial.json"),t("provisional_assets.json"),t("notes.json"),t("id_map.json"),t("manifest.json")])}}function UI(e){let t="";try{t=no.readFileSync(dn.join(e,"timing.jsonl"),"utf-8")}catch{return{episodes:[],totalMs:0}}let n=[],o=0;for(let i of t.split(/\r?\n/)){let r=i.trim();if(r)try{let s=JSON.parse(r);if(typeof s.episode!="number")continue;let c={episode:s.episode};typeof s.transcodeMs=="number"&&(c.transcodeMs=s.transcodeMs,o+=s.transcodeMs),typeof s.uploadMs=="number"&&(c.uploadMs=s.uploadMs,o+=s.uploadMs),typeof s.generateMs=="number"&&(c.generateMs=s.generateMs,o+=s.generateMs),typeof s.uploadMB=="string"&&(c.uploadMB=s.uploadMB),typeof s.transcoded=="boolean"&&(c.transcoded=s.transcoded),n.push(c)}catch{}}return{episodes:n,totalMs:o}}function TI(e){try{return JSON.parse(no.readFileSync(dn.join(e,"usage.json"),"utf-8"))}catch{return null}}function CI(e,t){let n=dn.resolve(e,t);if(n!==e&&!n.startsWith(e+dn.sep))return{ok:!1};try{return{ok:!0,text:no.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function _r(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function yg(e){let t=dn.resolve(MI(e.workspace_path||"workspace")),n=Number(e.port)||0,o=hg.createServer((s,c)=>{let a=new URL(s.url??"/","http://localhost");if(a.pathname==="/")return _r(c,200,"text/html; charset=utf-8",PI);if(a.pathname==="/api/state"){let d=wr(t);return _r(c,200,"application/json",JSON.stringify({root:t,status:d,groups:LI(t),timing:UI(t),usage:TI(t)}))}if(a.pathname==="/api/file"){let d=a.searchParams.get("path")??"",p=CI(t,d);return p.ok?_r(c,200,"text/plain; charset=utf-8",p.text):_r(c,404,"text/plain","not found")}_r(c,404,"text/plain","not found")}),r=`http://127.0.0.1:${await new Promise((s,c)=>{o.once("error",c),o.listen(n,"127.0.0.1",()=>s(o.address().port))})}/`;if(process.stderr.write(`Ingest monitor: ${r}
|
|
588
|
-
Workspace: ${t}
|
|
589
|
-
Press Ctrl-C to stop.
|
|
590
|
-
`),process.platform==="darwin"&&process.stderr.isTTY)try{NI("open",[r],{detached:!0,stdio:"ignore"}).unref()}catch{}return process.once("SIGINT",()=>o.close()),process.once("SIGTERM",()=>o.close()),[{text:r,data:{url:r,workspace:t}},J]}var PI=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
591
|
-
<title>scriptctl ingest \u76D1\u542C</title>
|
|
592
|
-
<style>
|
|
593
|
-
:root{--bg:#f6f7f9;--panel:#ffffff;--panel2:#f0f2f5;--line:#e3e6ea;--fg:#1f2430;--dim:#6b7280;--acc:#2563eb;--ok:#16a34a;--warn:#d97706;--err:#dc2626}
|
|
594
|
-
*{box-sizing:border-box}body{margin:0;font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;background:var(--bg);color:var(--fg);height:100vh;display:grid;grid-template-rows:auto auto 1fr}
|
|
595
|
-
header{padding:12px 16px;background:var(--panel);border-bottom:1px solid var(--line);display:flex;gap:16px;align-items:center;flex-wrap:wrap}
|
|
596
|
-
header .title{font-weight:700;font-size:15px}
|
|
597
|
-
.now{font-size:14px}.now b{color:var(--acc)}
|
|
598
|
-
.state{padding:3px 12px;border-radius:20px;font-weight:600;font-size:12px}
|
|
599
|
-
.state.ready{background:#e7f6ee;color:var(--ok)}.state.incomplete{background:#e8f0fe;color:var(--acc)}.state.failed{background:#fde8e8;color:var(--err)}.state.empty{background:var(--panel2);color:var(--dim)}
|
|
600
|
-
.dim{color:var(--dim)}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
601
|
-
/* overall bar + stage stepper */
|
|
602
|
-
.progress{background:var(--panel);border-bottom:1px solid var(--line);padding:12px 16px}
|
|
603
|
-
.ovwrap{display:flex;align-items:center;gap:10px;margin-bottom:12px}
|
|
604
|
-
.ovtrack{flex:1;height:10px;background:var(--panel2);border-radius:6px;overflow:hidden}
|
|
605
|
-
.ovtrack i{display:block;height:100%;background:linear-gradient(90deg,#3b82f6,#2563eb);border-radius:6px;transition:width .4s}
|
|
606
|
-
.ovpct{font-weight:700;min-width:44px;text-align:right}
|
|
607
|
-
.stages{display:flex;align-items:stretch;gap:0}
|
|
608
|
-
.stage{flex:1;padding:8px 12px;border:1px solid var(--line);background:var(--panel);border-radius:8px;margin-right:8px}
|
|
609
|
-
.stage:last-child{margin-right:0}
|
|
610
|
-
.stage-h{display:flex;align-items:center;gap:7px;font-weight:600}
|
|
611
|
-
.stage .dot{width:9px;height:9px;border-radius:50%;background:#cbd2dc;flex:none}
|
|
612
|
-
.stage .cnt{margin-left:auto;font-size:12px;color:var(--dim)}
|
|
613
|
-
.stage .track{height:6px;background:var(--panel2);border-radius:4px;margin-top:8px;overflow:hidden}
|
|
614
|
-
.stage .track i{display:block;height:100%;width:0;border-radius:4px;transition:width .4s}
|
|
615
|
-
.stage.wait{opacity:.7}
|
|
616
|
-
.stage.done{border-color:#bfe6cd}.stage.done .dot{background:var(--ok)}.stage.done .track i{background:var(--ok)}.stage.done .stage-h b{color:var(--ok)}
|
|
617
|
-
.stage.run{border-color:#bcd3fb;box-shadow:0 0 0 2px #e8f0fe}.stage.run .dot{background:var(--acc);animation:pulse 1.2s infinite}.stage.run .track i{background:var(--acc)}
|
|
618
|
-
.stage.fail{border-color:#f3bcbc}.stage.fail .dot{background:var(--err)}.stage.fail .track i{background:var(--err)}
|
|
619
|
-
@keyframes pulse{50%{opacity:.35}}
|
|
620
|
-
main{display:grid;grid-template-columns:280px 1fr;min-height:0}
|
|
621
|
-
aside{background:var(--panel);border-right:1px solid var(--line);overflow:auto;padding:8px}
|
|
622
|
-
.grp{margin:8px 4px 2px;color:var(--dim);font-size:11px;font-weight:700;letter-spacing:.04em}
|
|
623
|
-
.f{padding:4px 8px;border-radius:6px;cursor:pointer;display:flex;justify-content:space-between;gap:8px;white-space:nowrap;overflow:hidden}
|
|
624
|
-
.f:hover{background:var(--panel2)}.f.sel{background:#e8f0fe;color:var(--acc);font-weight:600}
|
|
625
|
-
.f .sz{color:var(--dim);font-size:11px}
|
|
626
|
-
section{overflow:auto;background:var(--panel)}
|
|
627
|
-
.toolbar{position:sticky;top:0;background:var(--panel2);border-bottom:1px solid var(--line);padding:6px 12px;display:flex;gap:14px;align-items:center;font-size:12px}
|
|
628
|
-
label{cursor:pointer;user-select:none}.empty{color:var(--dim);padding:34px;text-align:center}
|
|
629
|
-
#view{padding:14px 18px;white-space:pre-wrap;word-break:break-word;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12.5px}
|
|
630
|
-
#view h1,#view h2{margin:14px 0 4px}#view h1{color:var(--acc);font-size:15px}#view h2{color:var(--warn);font-size:13px}
|
|
631
|
-
#view .b{color:var(--dim)}
|
|
632
|
-
/* per-episode timing table (video only) */
|
|
633
|
-
.timing{padding:8px 16px 4px;background:var(--panel);border-bottom:1px solid var(--line);overflow:auto;max-height:132px}
|
|
634
|
-
table.tm{border-collapse:collapse;font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
635
|
-
table.tm th,table.tm td{padding:2px 10px 2px 0;text-align:right}table.tm th:first-child,table.tm td:first-child{text-align:left}
|
|
636
|
-
table.tm th{color:var(--dim);font-weight:600;border-bottom:1px solid var(--line)}
|
|
637
|
-
table.tm td.slow{color:var(--warn)}
|
|
638
|
-
</style></head><body>
|
|
639
|
-
<header>
|
|
640
|
-
<span class="title">scriptctl ingest</span>
|
|
641
|
-
<span id="stateBadge" class="state empty">\u2014</span>
|
|
642
|
-
<span class="now">\u5F53\u524D\uFF1A<b id="curState">\u2014</b></span>
|
|
643
|
-
<span class="now">\u8017\u65F6 <b id="elapsed">\u2014</b></span>
|
|
644
|
-
<span class="dim" id="eta"></span>
|
|
645
|
-
<span class="now" id="tokWrap" style="display:none">Token <b id="tokTotal">\u2014</b> <span class="dim" id="tokIO"></span></span>
|
|
646
|
-
<span class="dim mono" id="root" style="margin-left:auto"></span>
|
|
647
|
-
<span class="dim" id="tick"></span>
|
|
648
|
-
</header>
|
|
649
|
-
<div class="progress">
|
|
650
|
-
<div class="ovwrap"><span class="dim">\u603B\u8FDB\u5EA6</span><div class="ovtrack"><i id="ovBar"></i></div><span class="ovpct" id="ovPct">0%</span></div>
|
|
651
|
-
<div class="stages" id="stages"></div>
|
|
652
|
-
</div>
|
|
653
|
-
<div class="timing" id="timingWrap" style="display:none"><table class="tm" id="tmTable"></table></div>
|
|
654
|
-
<div class="timing" id="usageWrap" style="display:none"><table class="tm" id="usageTable"></table></div>
|
|
655
|
-
<main>
|
|
656
|
-
<aside id="side"></aside>
|
|
657
|
-
<section>
|
|
658
|
-
<div class="toolbar">
|
|
659
|
-
<span id="cur" class="mono dim">\u672A\u9009\u62E9\u6587\u4EF6</span>
|
|
660
|
-
<label style="margin-left:auto"><input type="checkbox" id="follow" checked> \u8DDF\u968F\u6700\u65B0\u96C6</label>
|
|
661
|
-
</div>
|
|
662
|
-
<div id="view"><div class="empty">\u5DE6\u4FA7\u9009\u62E9\u6587\u4EF6\uFF0C\u6216\u7B49\u5F85 ingest \u4EA7\u51FA\u2026</div></div>
|
|
663
|
-
</section>
|
|
664
|
-
</main>
|
|
665
|
-
<script>
|
|
666
|
-
var NAMES={normalize:'\u89C4\u8303\u5316',assemble:'\u88C5\u914D',serial:'\u4E32\u884C\u89E3\u6790',govern:'\u6CBB\u7406\u6210\u7A3F',finalize:'\u6CBB\u7406\u6210\u7A3F',transcribe:'\u8F6C\u5199',roster:'\u89D2\u8272\u5408\u5E76',correct:'\u6821\u6B63',speaker:'\u53D1\u58F0\u6E90'};
|
|
667
|
-
var cur=null, follow=true, lastLatest=null;
|
|
668
|
-
var timing=null, timingAt=0; // last status.timings + client time it arrived (avoids clock skew)
|
|
669
|
-
function $(s){return document.querySelector(s)}
|
|
670
|
-
function fmtDur(ms){if(ms==null)return '\u2014';var s=Math.round(ms/1000);return s>=60?(Math.floor(s/60)+'m'+('0'+(s%60)).slice(-2)+'s'):s+'s'}
|
|
671
|
-
// per-episode timing table (video only; hidden when there is no timing.jsonl)
|
|
672
|
-
function fmtTok(n){if(n==null)return '\u2014';if(n>=1e6)return (n/1e6).toFixed(2)+'M';if(n>=1e3)return (n/1e3).toFixed(1)+'k';return ''+n}
|
|
673
|
-
var TASKNAMES={'ingest.body-start':'\u6B63\u6587\u5B9A\u4F4D','ingest.text-normalize':'\u89C4\u8303\u5316','ingest.serial-govern':'\u4E32\u884C\u6CBB\u7406','ingest.name-fix':'\u547D\u540D\u4FEE\u590D','ingest.episode-assets':'\u5206\u96C6\u8D44\u4EA7','ingest.asset-curate':'\u8D44\u4EA7\u7504\u9009','ingest.asset-govern':'\u8D44\u4EA7\u603B\u89C8','ingest.arc-summary':'\u7BC7\u7AE0\u6897\u6982','ingest.state-reconcile':'\u72B6\u6001\u5F52\u5E76','ingest.asset-audit':'\u8D44\u4EA7\u5BA1\u8BA1','ingest.mention-resolve':'\u6307\u79F0\u6D88\u89E3','ingest.video-serial':'\u89C6\u9891\u4E32\u884C'};
|
|
674
|
-
// Token accounting table + header badge. Hidden until usage.json exists.
|
|
675
|
-
function renderUsage(u){
|
|
676
|
-
if(!u||!u.totals){$('#usageWrap').style.display='none';$('#tokWrap').style.display='none';return}
|
|
677
|
-
var t=u.totals;
|
|
678
|
-
$('#tokWrap').style.display='';
|
|
679
|
-
$('#tokTotal').textContent=fmtTok(t.totalTokens);
|
|
680
|
-
var cacheHit=(t.cachedInputTokens||0),cacheNew=(t.cacheCreationTokens||0);
|
|
681
|
-
var cacheStr=(cacheHit||cacheNew)?' \xB7 \u7F13\u5B58\u547D\u4E2D '+fmtTok(cacheHit)+(cacheNew?'/\u5EFA '+fmtTok(cacheNew):''):'';
|
|
682
|
-
$('#tokIO').textContent='(\u5165 '+fmtTok(t.inputTokens)+' / \u51FA '+fmtTok(t.outputTokens)+cacheStr+' \xB7 '+t.calls+'\u6B21'+(t.reused?' \xB7 \u590D\u7528'+t.reused:'')+')';
|
|
683
|
-
var rows=[];
|
|
684
|
-
(u.byTask||[]).forEach(function(task){
|
|
685
|
-
(task.byModel||[]).forEach(function(model){
|
|
686
|
-
var r=model.totals||{};
|
|
687
|
-
if(r.calls>0||r.reused>0||r.inputTokens>0||r.outputTokens>0)rows.push({task:task.task,model:model.model,provider:model.provider,totals:r});
|
|
688
|
-
});
|
|
689
|
-
});
|
|
690
|
-
if(!rows.length){$('#usageWrap').style.display='none';return}
|
|
691
|
-
rows.sort(function(a,b){return (b.totals.totalTokens||0)-(a.totals.totalTokens||0)});
|
|
692
|
-
$('#usageWrap').style.display='block';
|
|
693
|
-
var h=['<tr><th>\u4EFB\u52A1</th><th>\u6A21\u578B</th><th>\u8C03\u7528</th><th>\u5931\u8D25</th><th>\u590D\u7528</th><th>\u5165token</th><th title="\u7F13\u5B58\u547D\u4E2D/\u65B0\u5EFA\uFF0C\u5747\u4E3A\u5165token\u7684\u5B50\u96C6">\u7F13\u5B58(\u547D\u4E2D/\u5EFA)</th><th>\u51FAtoken</th><th>\u5408\u8BA1</th></tr>'];
|
|
694
|
-
rows.forEach(function(row){
|
|
695
|
-
var r=row.totals,ch=r.cachedInputTokens||0,cn=r.cacheCreationTokens||0;
|
|
696
|
-
h.push('<tr><td>'+(TASKNAMES[row.task]||row.task)+'</td><td class="mono">'+row.provider+'/'+row.model+'</td><td>'+r.calls+'</td><td>'+(r.failed||0)+'</td><td>'+(r.reused||0)+'</td><td>'+fmtTok(r.inputTokens)+'</td><td class="dim">'+(ch||cn?fmtTok(ch)+'/'+fmtTok(cn):'\u2014')+'</td><td>'+fmtTok(r.outputTokens)+'</td><td>'+fmtTok(r.totalTokens)+'</td></tr>');
|
|
697
|
-
});
|
|
698
|
-
h.push('<tr><td class="dim">\u5408\u8BA1</td><td></td><td class="dim">'+t.calls+'</td><td class="dim">'+t.failed+'</td><td class="dim">'+t.reused+'</td><td class="dim">'+fmtTok(t.inputTokens)+'</td><td class="dim">'+(t.cachedInputTokens||t.cacheCreationTokens?fmtTok(t.cachedInputTokens||0)+'/'+fmtTok(t.cacheCreationTokens||0):'\u2014')+'</td><td class="dim">'+fmtTok(t.outputTokens)+'</td><td class="dim">'+fmtTok(t.totalTokens)+'</td></tr>');
|
|
699
|
-
$('#usageTable').innerHTML=h.join('');
|
|
700
|
-
}
|
|
701
|
-
function renderEpTiming(tm){
|
|
702
|
-
if(!tm||!tm.episodes||!tm.episodes.length){$('#timingWrap').style.display='none';return}
|
|
703
|
-
$('#timingWrap').style.display='block';
|
|
704
|
-
var rows=['<tr><th>\u96C6</th><th>\u8F6C\u7801</th><th>\u5927\u5C0F</th><th>\u4E0A\u4F20</th><th>\u89E3\u6790</th></tr>'];
|
|
705
|
-
tm.episodes.forEach(function(e){
|
|
706
|
-
var slow=e.generateMs>60000?' class="slow"':'';
|
|
707
|
-
rows.push('<tr><td>ep'+('00'+e.episode).slice(-3)+'</td><td>'+fmtDur(e.transcodeMs)+(e.transcoded===false?'*':'')+'</td><td>'+(e.uploadMB||'?')+'M</td><td>'+fmtDur(e.uploadMs)+'</td><td'+slow+'>'+fmtDur(e.generateMs)+'</td></tr>');
|
|
708
|
-
});
|
|
709
|
-
rows.push('<tr><td class="dim">\u7D2F\u8BA1</td><td></td><td></td><td></td><td class="dim">'+fmtDur(tm.totalMs)+'</td></tr>');
|
|
710
|
-
$('#tmTable').innerHTML=rows.join('');
|
|
711
|
-
}
|
|
712
|
-
// tick the total elapsed locally between polls; serial ETA/rate from the summary
|
|
713
|
-
function renderTiming(){
|
|
714
|
-
if(!timing){$('#elapsed').textContent='\u2014';$('#eta').textContent='';return}
|
|
715
|
-
var live=timing.elapsedMs+(timing.done?0:(Date.now()-timingAt));
|
|
716
|
-
$('#elapsed').textContent=fmtDur(live)+(timing.done?'':' \u2026');
|
|
717
|
-
var ser=timing.serial,eta='';
|
|
718
|
-
if(ser){
|
|
719
|
-
eta='\u4E32\u884C '+ser.doneWindows+'/'+ser.totalWindows+' \u7A97\u53E3';
|
|
720
|
-
if(ser.avgWindowMs!=null)eta+=' \xB7 ~'+fmtDur(ser.avgWindowMs)+'/\u7A97';
|
|
721
|
-
if(ser.etaMs!=null&&!timing.done)eta+=' \xB7 \u9884\u8BA1\u5269\u4F59 '+fmtDur(ser.etaMs);
|
|
722
|
-
}
|
|
723
|
-
$('#eta').textContent=eta;
|
|
724
|
-
}
|
|
725
|
-
$('#follow').onchange=function(e){follow=e.target.checked};
|
|
726
|
-
function esc(s){return s.replace(/[&<>]/g,function(c){return{'&':'&','<':'<','>':'>'}[c]})}
|
|
727
|
-
function renderContent(rel,text){
|
|
728
|
-
if(rel.endsWith('.jsonl')){$('#view').textContent=text.split('\\n').map(function(l){try{return JSON.stringify(JSON.parse(l))}catch(e){return l}}).join('\\n');return}
|
|
729
|
-
if(rel.endsWith('.json')){try{text=JSON.stringify(JSON.parse(text),null,2)}catch(e){}$('#view').textContent=text;return}
|
|
730
|
-
if(rel.endsWith('.md')){
|
|
731
|
-
$('#view').innerHTML=text.split('\\n').map(function(l){
|
|
732
|
-
if(l.indexOf('## ')===0)return '<h2>'+esc(l.slice(3))+'</h2>';
|
|
733
|
-
if(l.indexOf('# ')===0)return '<h1>'+esc(l.slice(2))+'</h1>';
|
|
734
|
-
if(l.indexOf(' ')===0||l.indexOf('- ')===0||l.indexOf('> ')===0)return '<span class="b">'+esc(l)+'</span>';
|
|
735
|
-
return esc(l)||' ';
|
|
736
|
-
}).join('\\n');return}
|
|
737
|
-
$('#view').textContent=text;
|
|
738
|
-
}
|
|
739
|
-
function loadFile(rel){
|
|
740
|
-
cur=rel;$('#cur').textContent=rel;
|
|
741
|
-
var fs=document.querySelectorAll('.f');for(var i=0;i<fs.length;i++)fs[i].classList.toggle('sel',fs[i].dataset.rel===rel);
|
|
742
|
-
fetch('/api/file?path='+encodeURIComponent(rel)).then(function(r){return r.text()}).then(function(t){renderContent(rel,t)}).catch(function(){});
|
|
743
|
-
}
|
|
744
|
-
function frac(p){return p.unit&&p.unit.total?p.unit.done/p.unit.total:(p.done?1:0)}
|
|
745
|
-
function poll(){
|
|
746
|
-
fetch('/api/state').then(function(r){return r.json()}).then(function(d){
|
|
747
|
-
var s=d.status,passes=s.passes||[];
|
|
748
|
-
$('#root').textContent=d.root;
|
|
749
|
-
$('#stateBadge').className='state '+s.state;
|
|
750
|
-
$('#stateBadge').textContent={ready:'\u5DF2\u5B8C\u6210',incomplete:'\u8FDB\u884C\u4E2D',failed:'\u5931\u8D25',empty:'\u7A7A'}[s.state]||s.state;
|
|
751
|
-
// overall progress = mean of per-stage fractions
|
|
752
|
-
var sum=0;passes.forEach(function(p){sum+=frac(p)});
|
|
753
|
-
var pct=passes.length?Math.round(100*sum/passes.length):0;
|
|
754
|
-
$('#ovBar').style.width=pct+'%';$('#ovPct').textContent=pct+'%';
|
|
755
|
-
// current stage
|
|
756
|
-
var curP=null;for(var i=0;i<passes.length;i++){if(!passes[i].done){curP=passes[i];break}}
|
|
757
|
-
$('#curState').textContent=s.state==='ready'?'\u5DF2\u5B8C\u6210 \u2713':(curP?(NAMES[curP.name]||curP.name)+(curP.unit?' \xB7 '+curP.unit.done+'/'+curP.unit.total:''):'\u2014');
|
|
758
|
-
// per-phase durations from timings (real wall-clock)
|
|
759
|
-
var ph={};((s.timings&&s.timings.phases)||[]).forEach(function(x){ph[x.name]=x});
|
|
760
|
-
// staged stepper with per-stage bars + real durations
|
|
761
|
-
$('#stages').innerHTML=passes.map(function(p){
|
|
762
|
-
var st=p.done?'done':(p.unit&&p.unit.failed?'fail':(p.unit&&p.unit.done>0||p===curP?'run':'wait'));
|
|
763
|
-
var cnt=p.unit?(p.unit.done+'/'+p.unit.total+(p.unit.failed?' \u2717'+p.unit.failed:'')):(p.done?'\u2713':'\u2014');
|
|
764
|
-
var d=ph[p.name]?('<span class="cnt">'+fmtDur(ph[p.name].ms)+(ph[p.name].running?' \u2026':'')+'</span>'):'';
|
|
765
|
-
return '<div class="stage '+st+'"><div class="stage-h"><span class="dot"></span><b>'+(NAMES[p.name]||p.name)+'</b><span class="cnt">'+cnt+'</span></div><div class="track"><i style="width:'+Math.round(frac(p)*100)+'%"></i></div>'+(d?'<div class="dim" style="margin-top:4px">'+d+'</div>':'')+'</div>';
|
|
766
|
-
}).join('');
|
|
767
|
-
timing=s.timings||null;timingAt=Date.now();renderTiming();
|
|
768
|
-
renderEpTiming(d.timing);
|
|
769
|
-
renderUsage(d.usage);
|
|
770
|
-
// sidebar
|
|
771
|
-
var html='',latest=null;
|
|
772
|
-
Object.keys(d.groups).forEach(function(grp){
|
|
773
|
-
var files=d.groups[grp];if(!files.length)return;html+='<div class="grp">'+grp+'</div>';
|
|
774
|
-
files.forEach(function(f){
|
|
775
|
-
html+='<div class="f" data-rel="'+f.rel+'"><span>'+f.rel.split('/').pop()+'</span><span class="sz">'+(f.size>1024?(f.size/1024).toFixed(0)+'k':f.size)+'</span></div>';
|
|
776
|
-
if(grp==='\u6BCF\u7A97\u66F4\u65B0'||grp==='\u4E0A\u4E0B\u6587'||grp==='\u8F6C\u5F55'||grp==='\u89E3\u6790')latest=f.rel;
|
|
777
|
-
});
|
|
778
|
-
});
|
|
779
|
-
$('#side').innerHTML=html;
|
|
780
|
-
var els=document.querySelectorAll('.f');
|
|
781
|
-
for(var j=0;j<els.length;j++){(function(el){el.onclick=function(){follow=false;$('#follow').checked=false;loadFile(el.dataset.rel)};if(el.dataset.rel===cur)el.classList.add('sel')})(els[j])}
|
|
782
|
-
$('#tick').textContent='\u25CF '+new Date().toLocaleTimeString();
|
|
783
|
-
if(follow&&latest&&latest!==lastLatest){lastLatest=latest;loadFile(latest)}
|
|
784
|
-
else if(cur){loadFile(cur)}
|
|
785
|
-
}).catch(function(){$('#tick').textContent='\u25CF \u79BB\u7EBF'});
|
|
786
|
-
}
|
|
787
|
-
poll();setInterval(poll,1500);setInterval(renderTiming,1000);
|
|
788
|
-
</script></body></html>`;var VI=e=>e==null?"":String(e),$I=e=>String(e).padStart(3,"0");function DI(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");_i.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=ea.join(n,`ep_${$I(o.episode)}.mp4`);try{_i.rmSync(i,{force:!0}),_i.symlinkSync(o.path,i)}catch{}}}async function wg(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new x("`view --watch` runs a local web server and opens a browser; it is local-only and unavailable in the sandbox.",{exitCode:b,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return yg(e)}let t=VI(e.workspace_path||"workspace"),n=new At(ea.resolve(t));if(!n.has("script.json"))throw new x("workspace has no script.json to render.",{exitCode:b,errorCode:"VIEW_NO_SCRIPT",hint:"Run `scriptctl ingest --source-path <src> --workspace-path <dir>` first.",data:{actual:[n.path("script.json")]}});DI(n);let o=gg(n.readJson("script.json"));n.writeText("review.html",o);let i=n.path("review.html");return[{text:i,data:{output:i}},J]}import*as Uo from"node:path";import GI from"fast-json-patch";var{compare:_g}=GI;var Eg="/api/anime/workbench/v2/script/project-groups",JI="/api/anime/workbench/projectGroup/updateProjectGroupInfo",BI=5e3,xg=8*1024*1024;function KI(e){let t=e.trim().replace(/\/+$/,"");for(let n of["/api/anime/workbench","/api/sandbox"])if(t.endsWith(n)){t=t.slice(0,-n.length);break}return t.replace(/\/+$/,"")}function Sg(e){return encodeURIComponent(String(e))}function jI(e,t,n){if(t===404&&n.includes("/imports"))return new de("backend lacks episode import API",{status:t,payload:e});let o=null;try{o=e?JSON.parse(e):null}catch{o=null}if(o&&typeof o=="object"){let i=o,r=String(i.msg??i.message??`HTTP ${t}`);return new de(r,{status:t,code:i.code??null,payload:i})}return new de(e||`HTTP ${t}`,{status:t,payload:e})}function Ig(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=xg))throw new de(`script ${e} body too large: ${n} bytes (limit ${xg})`)}async function Ag(e,t,n,o,i,r={}){let s=r.body===void 0?void 0:JSON.stringify(r.body),c={Accept:"application/json","X-Access-Key":t};s!==void 0&&(c["Content-Type"]="application/json; charset=utf-8");let a=new AbortController,d=setTimeout(()=>a.abort(),n),p,l;try{let g=await fetch(`${e}${i}`,{method:o,headers:c,body:s,signal:a.signal});p=g.status,l=await g.text()}catch(g){if(g instanceof Error&&g.name==="AbortError")throw new de("Gateway request timed out");let h=g instanceof Error?g.message:String(g);throw new de(`Gateway request failed: ${h}`)}finally{clearTimeout(d)}if(p>=400)throw jI(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new de("Gateway response is not valid JSON",{status:p,payload:l})}if(f===null)return null;if(typeof f!="object")return f;let u=f,m=u.code;if(m!=null&&String(m)!=="200"){let g=String(u.msg??u.message??"script-output API failed");if(r.allowMissing&&typeof g=="string"&&g.includes("\u5267\u672C\u4E0D\u5B58\u5728"))return null;throw new de(g,{status:p,code:m,payload:u})}return"data"in u?u.data:u}var Wd=class e{gatewayBase;projectGroupNo;accessKey;timeoutMs;constructor(t){this.gatewayBase=t.gatewayBase,this.projectGroupNo=t.projectGroupNo,this.accessKey=t.accessKey,this.timeoutMs=t.timeoutMs??3e5}static fromEnv(t){let n=(t??process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();if(!n)throw new de("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=KI(process.env.AWB_BASE_URL||"");if(!o)throw new de("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new de("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${Eg}/${Sg(this.projectGroupNo)}`}async getScript(){return await this.request("GET",this.projectPrefix,{allowMissing:!0})}async getRevision(){return await this.request("GET",`${this.projectPrefix}/revision`,{allowMissing:!0})}async getSnapshot(){return await this.request("GET",`${this.projectPrefix}/snapshot`,{allowMissing:!0})}async publishPatch(t){return await this.request("PATCH",`${this.projectPrefix}/publish`,{body:{baseRevision:t.baseRevision,patch:_g(t.old,t.edited),validation:t.validation}})}async replaceScript(t){let n={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",script:t.script};return Ig("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=_g(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return Ig("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${Eg}/${Sg(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await Ag(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,BI),"POST",JI,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return Ag(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function Zd(e){return Wd.fromEnv(e)}var Er=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=co(t.script),this.baseline=structuredClone(t.script),this.baselineHash=Ce(t.script),this.scriptPath=t.scriptPath??null,this.client=t.client??null,this.projectGroupNo=t.projectGroupNo??null,this.revision=t.revision??null}get remote(){return this.client!==null}get artifactLabel(){return this.remote?`script-output/${this.projectGroupNo}@revision/${this.revision??0}`:this.scriptPath??""}};function oo(e,t){let n=t.message||"script-output API failed",o=String(t.code)==="9002"||n.includes("\u7248\u672C\u51B2\u7A81"),i=n.includes("\u5267\u672C\u4E0D\u5B58\u5728"),r=o?"Script has been updated by another revision; keep local work and merge before retrying.":i?"Script not found on the gateway.":"Gateway request failed.";return new x(r,{exitCode:t.status!==null&&t.status>=500?fe:b,errorCode:o?"REVISION_CONFLICT":i?"SCRIPT_NOT_FOUND":"SCRIPT_API_FAILED",hint:o?"Keep the local file, inspect the latest remote snapshot, and merge before publishing again.":i?"Run `scriptctl publish` to publish a script first.":"Run `scriptctl doctor` to verify gateway configuration; retry if it was transient.",data:{expected:["successful script-output gateway request"],actual:[n,`status: ${t.status??"<unknown>"}`]}})}async function xr(e){let t=O(e.workspace_path||"workspace"),n=xe(e);if(!ro(n))throw new x("Local script file not found.",{exitCode:b,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[n]}});let o;try{o=ki(n)}catch(i){throw new x("script JSON invalid.",{exitCode:b,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!X(o))throw new x("script root invalid.",{exitCode:G,errorCode:"SCRIPT_ROOT_INVALID",hint:"Use a valid script document object.",data:{expected:["script root object"],actual:[Array.isArray(o)?"array":typeof o]}});return new Er({workspace:t,scriptPath:n,script:o})}function Sr(e,t={}){let n=Xd(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function zI(e,t){let{ok:n,errors:o,warnings:i}=t,r=[...o.map(d=>({severity:"error",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}})),...i.map(d=>({severity:"warning",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}}))],s=ee(e.episodes),c=0,a=0;for(let d of s)for(let p of ee(d.scenes))c+=1,a+=ee(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:ee(e.actors).length,locations:ee(e.locations).length,props:ee(e.props).length,episodes:s.length,scenes:c,actions:a}}}function Xd(e){return zI(e,Ti(e))}function HI(e){if(e.path)return O(e.path);let t=[];return e.episode!==null&&e.episode!==void 0&&t.push(O(e.episode)),e.scene!==null&&e.scene!==void 0&&t.push(O(e.scene)),e.action_index!==null&&e.action_index!==void 0&&t.push(`action[${e.action_index}]`),t.length>0?t.join("/"):null}function FI(e){let t=O(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function QI(e){let t=ee(e.issues),n=e.passed?"valid":"invalid",o={passed:!!e.passed,hasBlocking:!!e.has_blocking,stats:e.stats??{},issueCount:t.length},i=[];for(let r of t){if(!X(r))continue;let s={...r};for(let c of["severity","code","path","summary","repair_hint"])delete s[c];i.push({severity:FI(r.severity),code:O(r.code||"SCRIPT_VALIDATION_ISSUE"),path:HI(r),summary:O(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function ep(e,t,n){if(!e.remote||e.client===null)return;let o=Number(n??e.revision??0);if(o<=0)return;let[i,r,s]=QI(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(c){throw c instanceof de?oo("SCRIPT API BLOCKED: Validation sync failed",c):c}}async function tp(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return kt(e.scriptPath,e.baselineHash),Je(e.scriptPath,e.script),[null,!1]}async function kg(e,t=kn){let n=await xr(e),o=t.createExecutor(O(e.llm_config).trim()||void 0),i=await Od(n.script,o);n.scriptPath&&kt(n.scriptPath,n.baselineHash);let r=n.scriptPath?Uo.dirname(n.scriptPath):Uo.resolve(n.workspace),s=Uo.resolve(O(e.output).trim()||Uo.join(r,"asset-audit.json"));Je(s,i);let c=i.issues.length>0,a=i.issues.map(vd);return[{text:[`${i.summary.issues} issues; confidence high=${i.summary.high} medium=${i.summary.medium} low=${i.summary.low}`,...a,`output: ${s}`,...c?["Inspect each finding, repair confirmed duplicates, then rerun `scriptctl audit-assets` and `scriptctl validate`."]:[]].join(`
|
|
789
|
-
`),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},c?Ln:J]}function bg(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function io(e){let t=X(e.location)?e.location:null;return{actors:hn(e.actors)?e.actors:[],props:hn(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function Cg(e,t,n){let o=!!t.passed,i=[`created: blank script (Script v${e.version})`,`validation: ${o?"passed":"needs repair"}`];return e.remote&&(i.push(`revision: ${e.revision}`),n!==null&&i.push(`idempotent: ${String(n).toLowerCase()}`)),{text:i.join(`
|
|
790
|
-
`),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function Pg(e){let t=O(e.workspace_path||"workspace"),n=!!e.force,o=O(e.title).trim(),i=bg(o),r=xe(e);if(ro(r)&&!n)throw new x("A script already exists at the target.",{exitCode:b,errorCode:"SCRIPT_EXISTS",hint:"Edit the existing script with the atomic verbs, or pass --force to overwrite with a blank scaffold.",data:{expected:["a non-existent target, or --force to overwrite"],actual:[r]}});Je(r,i);let s=new Er({workspace:t,scriptPath:r,script:i}),c=Sr(s),a=!!c.passed;return[Cg(s,c,null),a?J:Ln]}import*as xi from"node:fs";import*as Co from"node:path";function cA(e){let t={};for(let n of e.episodes)for(let o of n.scenes){let i=`${n.episode_id}/${o.scene_id}`;o.actions.forEach((r,s)=>{let c=`${i}#${s}`;t[c]=c})}return t}function To(e){return X(e)&&Object.values(e).every(t=>typeof t=="string")}function dA(e){return X(e)&&Object.values(e).every(To)}function pA(e){return X(e)&&e.version===3&&To(e.actor)&&To(e.location)&&To(e.prop)&&dA(e.state)&&To(e.episode)&&To(e.scene)&&To(e.action)}function lA(e){if(e!==void 0){if(pA(e.identityMap))return e.identityMap;throw new x("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function Vg(e,t){let n=It(e),o=ii(n,lA(t),{action:cA(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var uA=[{sourceVersion:3,targetVersion:4,migrate:Vg}];function fA(e){return X(e)&&$n(e.source_version)&&$n(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function $g(e){if(!Array.isArray(e))throw new x("Migration manifest steps must be an array.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!fA(t))throw new x("Migration manifest contains an invalid step artifact.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"});return{sourceVersion:t.source_version,targetVersion:t.target_version,identityMap:t.identity_map}})}function mA(e,t){return uA.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function gA(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function Dg(e,t,n=[]){let o=co(e);if(t<o)throw new x("A migration target must be newer than the source script.",{exitCode:b,errorCode:"MIGRATE_TARGET_OLDER",data:{expected:[String(o)],actual:[String(t)]}});let i=jr(e),r=o,s=[];for(;r<t;){let c=mA(r,t);if(c===void 0)throw new x(`No migration path exists from Script v${r} to Script v${t}.`,{exitCode:b,errorCode:"MIGRATE_PATH_UNSUPPORTED",data:{actual:[String(r),String(t)]}});let a=c.migrate(i,gA(n,c));i=a.script,r=c.targetVersion,s.push(a.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function Ir(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function hA(e,t){let n=Ir(e,t);return/^\d+$/.test(n)?Number(n):null}function yA(e){let t=hA(e,"to");if($n(t))return t;throw new x("A supported migration target version is required.",{exitCode:G,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:Va.map(String),actual:[Ir(e,"to")||"<empty>"]}})}function wA(e){let t=Co.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function _A(e,t,n){let o=[e,t,n].map(i=>Co.resolve(i));if(o[0]===o[1])throw new x("The migration destination must differ from the source.",{exitCode:G,errorCode:"MIGRATE_SAME_PATH",hint:"Choose a separate --output path. The source file stays unchanged.",data:{actual:[e]}});if(o[0]===o[2]||o[1]===o[2])throw new x("The migration manifest needs its own file path.",{exitCode:G,errorCode:"MIGRATE_MANIFEST_PATH",hint:"Choose a --manifest path separate from the source and output files.",data:{actual:[n]}})}function Gg(e,t){if(!t&&xi.existsSync(e))throw new x("Migration destination already exists.",{exitCode:G,errorCode:"MIGRATE_OUTPUT_EXISTS",hint:"Choose a new path, or pass --force to replace the migration artifact.",data:{actual:[e]}})}function EA(e){let t;try{t=xi.readFileSync(e,"utf8")}catch(n){throw new x("Cannot read the source script.",{exitCode:G,errorCode:"MIGRATE_SOURCE_READ_FAILED",hint:"Pass an existing JSON file with --script-path.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}try{return{raw:t,value:JSON.parse(t)}}catch(n){throw new x("The source script is not valid JSON.",{exitCode:G,errorCode:"MIGRATE_SOURCE_JSON_INVALID",hint:"Repair the JSON syntax, then rerun migrate.",data:{actual:[n instanceof Error?n.message:String(n)]}})}}function xA(e,t){if(!t||!xi.existsSync(e))return;let n;try{n=JSON.parse(xi.readFileSync(e,"utf8"))}catch(o){throw new x("Cannot reuse the existing migration manifest.",{exitCode:G,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e,o instanceof Error?o.message:String(o)]}})}if(!X(n)||n.version!==1||!$n(n.source_version)||!$n(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new x("Cannot reuse the existing migration manifest.",{exitCode:G,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e]}});return{version:1,source_version:n.source_version,target_version:n.target_version,source_path:n.source_path,source_sha256:n.source_sha256,steps:$g(n.steps)}}async function Jg(e){let t=Ir(e,"script_path"),n=Ir(e,"output");if(!t||!n)throw new x("Migration paths are required.",{exitCode:G,errorCode:"MIGRATE_PATH_MISSING",hint:"Pass --script-path <source.json> and --output <target.json>.",data:{expected:["--script-path <source.json>","--output <target.json>"]}});let o=Co.resolve(t),i=Co.resolve(n),r=Co.resolve(Ir(e,"manifest")||wA(i)),s=yA(e),c=!!e.force;return _A(o,i,r),Gr(i,async()=>{Gg(i,c),Gg(r,c);let a=EA(o),d=co(a.value);if(s<=d)throw new x("The migration target must be newer than the source script.",{exitCode:G,errorCode:"MIGRATE_TARGET_NOT_NEWER",data:{expected:[`>${d}`],actual:[String(s)]}});let p=Ti(a.value),l=xA(r,c),f=Dg(a.value,s,l?.steps),u=Ti(f.script),m={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:Se(a.raw),steps:f.steps};Je(r,{...m,steps:m.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),Je(i,f.script);let g={op:"script.migrate",changed:!0,source_script_path:o,script_path:i,manifest_path:r,source_version:f.sourceVersion,target_version:f.targetVersion,source_validation:{ok:p.ok,errors:p.errors.length,warnings:p.warnings.length},validation:{ok:u.ok,errors:u.errors.length,warnings:u.warnings.length,issues:u.errors.slice(0,100)}};return[{text:u.ok?[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,"validation: ok"].join(`
|
|
791
|
-
`):[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,`validation: ${u.errors.length} errors; repair before production use`].join(`
|
|
792
|
-
`),data:g},u.ok?J:Ln]})}import*as Si from"node:path";import*as Kg from"node:path";function Bg(e,t){let n=Se(t);return Kg.join(e,`${n}.json`)}function Ar(e){return{read(t){let n=Bg(e,t);return ro(n)?ki(n):null},write(t){ma(Bg(e,t.key),t)}}}function dp(){return{read(){return null},write(){}}}function pp(e){if(Array.isArray(e))return`[${e.map(t=>pp(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${pp(t[n])}`).join(",")}}`}return JSON.stringify(e)}function lp(e){return Se(pp(e))}function up(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function SA(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
|
|
793
|
-
|
|
794
|
-
`)}function zg(e,t){return{system:SA(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function IA(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=zg(e,t),i=n.executor.route(e.taskId);return{request:o,payload:{step:"extract",kind:"llm",taskId:e.taskId,version:e.version??"",routeFingerprint:i.fingerprint,system:o.system,user:o.user,salt:n.checkpointSalt}}}return{payload:{step:"extract",kind:"fn",version:e.version??"",parcel:t,salt:n.checkpointSalt}}}function na(e){return{kind:"root",children:e}}function hp(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function kr(e){return{kind:"parcel",data:e}}function Or(e){return{kind:"llm",...e}}var fp=class e{constructor(t,n=[]){this.input=t;this.steps=n}input;steps;split(t){return new e(this.input,[...this.steps,{kind:"split",spec:t}])}extract(t){return new e(this.input,[...this.steps,{kind:"extract",task:t}])}reduce(t,n){let o=typeof n=="function"?{run:n}:n;return new e(this.input,[...this.steps,{kind:"reduce",scope:t,task:o}])}plan(){return{input:this.input,steps:[...this.steps]}}async run(t={}){return await RA(this.input,this.steps,t)}};function oa(e){return new fp(e)}async function AA(e,t,n){if(e.length===0)return[];let o=new Array(e.length),i=0,r=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:r},async()=>{for(;;){let s=i++;if(s>=e.length)break;o[s]=await n(e[s],s)}})),o}function kA(e,t){let n=t.partition(e);return na(n.map(o=>{let i=t.chunk(o).map(r=>kr(r));return hp(t.scope,i,o)}))}function mp(e,t=[]){if(e.kind==="parcel")return[{parcel:e.data,path:t}];let n=(e.kind==="root",e.children),o=[];for(let i=0;i<n.length;i++){let r=n[i],s=r.kind==="scope"?[...t,`${r.scope}:${i}`]:[...t,`parcel:${i}`];o.push(...mp(r,s))}return o}function br(e,t){return e?.(t),t}async function bA(e,t){return br(e.validate,await e.run({parcel:t}))}async function OA(e,t,n){if(!n.executor)throw new Error("loom llm task requires run({ executor })");return n.executor.generateText(e.taskId,{system:t.system,user:t.user,signal:n.signal})}function jg(e,t,n){return br(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function Hg(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,kr(i)}let o=e.children.map(i=>Hg(i,t,n));return e.kind==="root"?na(o):hp(e.scope,o,e.data)}function vA(e){return e.children.every(t=>t.kind==="parcel")}async function Fg(e,t,n,o,i){if(e.kind==="parcel")return e;let r=[];for(let w=0;w<e.children.length;w++){let y=e.children[w];r.push(await Fg(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?na(r):hp(e.scope,r,e.data),c=t==="root"&&s.kind==="root",a=s.kind==="scope"&&s.scope===t;if(!c&&!a||!vA(s))return s;let d=s.children.map(w=>w.data),p=s.kind==="scope"?s.data:null,l=s.kind==="scope"?s.scope:"root",f=n.version??"",u=`reduce:${t}:${i.join("/")}:${lp({items:d,scopeData:p,version:f,salt:o.checkpointSalt})}`,m=lp({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),g=await gp(o.checkpoint,u,m);if(g.hit)return o.report.reused+=1,kr(br(n.validate,g.value));let h=br(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(up(u,m,h)),kr(h)}async function gp(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function RA(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??dp(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let c of t){if(c.kind==="split"){i=kA(r,c.spec),r=i;continue}if(i||(i=na([kr(r)])),c.kind==="extract"){let a=mp(i),d=await AA(a,o.concurrency,async p=>{let l=IA(c.task,p.parcel,o),f=lp(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(c.task.kind==="llm"){let h=await gp(o.checkpoint,u,f);if(h.hit)return o.report.reused+=1,o.executor?.recordReuse(c.task.taskId),jg(c.task,p.parcel,h.value);let w=l.request??zg(c.task,p.parcel),y=await OA(c.task,w,o),E=jg(c.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(up(u,f,y)),E}let m=await gp(o.checkpoint,u,f);if(m.hit)return o.report.reused+=1,br(c.task.validate,m.value);let g=await bA(c.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(up(u,f,g)),g});i=Hg(i,d,{index:0}),r=i;continue}i=await Fg(i,c.scope,c.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=mp(i);if(s.length!==1)throw new Error(`loom plan ended with ${s.length} result(s); reduce to root before run completes`);return{value:s[0].parcel,report:o.report}}var qg={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},NA="\u4ECE\u5F53\u524D\u5267\u672C\u7247\u6BB5\u4E2D\u63D0\u53D6\u5267\u60C5\u6897\u6982\u548C\u5173\u952E\u4E8B\u4EF6\u3002\u53EA\u57FA\u4E8E\u5F53\u524D\u7247\u6BB5\uFF0C\u4E0D\u8981\u63A8\u6D4B\u540E\u7EED\u3002",MA=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u7247\u6BB5\u6897\u6982","<\u5982\u679C\u5F53\u524D\u96C6\u53EA\u6709\u4E00\u4E2A\u7247\u6BB5\uFF0C\u5199 200-300 \u5B57\uFF1B\u5982\u679C\u5F53\u524D\u96C6\u88AB\u5207\u6210\u591A\u4E2A\u7247\u6BB5\uFF0C\u5199 80-150 \u5B57\u3002\u6309\u53D1\u751F\u987A\u5E8F\u6982\u62EC\uFF0C\u53EA\u5199\u5F53\u524D\u7247\u6BB5\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>","","## \u4EBA\u7269\u53D8\u5316","- <\u4EBA\u7269\u540D> | <\u53D8\u5316>","","## \u7ED3\u5C3E\u94A9\u5B50","<\u6709\u5219\u5199\u4E00\u53E5\uFF1B\u6CA1\u6709\u5219\u7559\u7A7A>"].join(`
|
|
795
|
-
`),LA="\u628A\u540C\u4E00\u96C6\u7684\u591A\u4E2A\u7247\u6BB5\u6897\u6982\u5408\u5E76\u4E3A\u4E00\u96C6\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u7247\u6BB5\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",UA=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5206\u96C6\u6897\u6982","<200-300 \u5B57\uFF0C\u6309\u5267\u60C5\u53D1\u751F\u987A\u5E8F\u5199\u6210\u8FDE\u8D2F\u6BB5\u843D\u3002>","","## \u5355\u53E5\u6897\u6982","<30-50 \u5B57\uFF0C\u6982\u62EC\u672C\u96C6\u4E3B\u7EBF\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>"].join(`
|
|
796
|
-
`),TA="\u628A\u4E00\u7EC4\u8FDE\u7EED\u5206\u96C6\u6897\u6982\u538B\u7F29\u4E3A\u9636\u6BB5\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5206\u96C6\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",CA=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u9636\u6BB5\u6897\u6982","<400-600 \u5B57\uFF0C\u6982\u62EC\u8FD9\u4E00\u9636\u6BB5\u7684\u4E3B\u7EBF\u63A8\u8FDB\u3002>","","## \u5173\u952E\u8F6C\u6298","- <\u8F6C\u62981>","- <\u8F6C\u62982>","","## \u672A\u89E3\u51B3\u60AC\u5FF5","- <\u60AC\u5FF51>"].join(`
|
|
797
|
-
`),PA="\u6839\u636E\u5206\u96C6\u7D22\u5F15\u548C\u9636\u6BB5\u6897\u6982\u751F\u6210\u5168\u5267\u603B\u89C8\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5185\u5BB9\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3001\u4EBA\u7269\u6216\u5173\u7CFB\u3002",VA=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5168\u6587\u6897\u6982","<800-1200 \u5B57\uFF0C\u8986\u76D6\u5168\u5267\u4E3B\u7EBF\u3001\u5173\u952E\u5173\u7CFB\u3001\u4E3B\u8981\u51B2\u7A81\u548C\u7ED3\u5C40\u8D70\u5411\u3002>","","## \u4E3B\u9898","<\u4E00\u53E5\u8BDD\u6216\u4E00\u4E2A\u77ED\u8BED>","","## \u4E00\u53E5\u8BDD","<\u4E00\u53E5\u5B8C\u6574 logline>","","## \u98CE\u683C","<\u7C7B\u578B / \u6C14\u8D28 / \u53D9\u4E8B\u98CE\u683C>","","## \u4E3B\u8981\u4EBA\u7269","- <\u540D\u5B57> | <\u89D2\u8272\u5B9A\u4F4D>"].join(`
|
|
798
|
-
`);function $A(e,t,n){let o=O(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=e5(o,n),r=O(t.title).trim(),s=[],c=O(e.title).trim();c&&s.push(`\u5267\u540D\uFF1A${c}`),s.push(`\u96C6\u6570\uFF1A\u7B2C${i}\u96C6`),r&&s.push(`\u6807\u9898\uFF1A${r}`),s.push("");for(let a of ee(t.scenes)){s.push(ZA(e,a));for(let d of ee(a.actions)){let p=XA(e,d);p&&s.push(p)}s.push("")}return{episodeIndex:n,episodeId:o,episodeNo:i,title:r,existingSynopsis:O(t.synopsis).trim(),text:s.join(`
|
|
799
|
-
`).trim()}}function DA(e,t=qg){let n=e.text.split(/\r?\n/),o=n.flatMap(c=>YA(c,t.episodeChunkTargetChars));if(e.text.length<=t.episodeInputMaxChars&&o.length===n.length)return[{episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:1,partCount:1,text:e.text,sourceHash:Se(e.text)}];let i=[],r=[],s=0;for(let c of o){let a=c.length+(r.length>0?1:0);r.length>0&&s+a>t.episodeChunkTargetChars&&(i.push(r.join(`
|
|
800
|
-
`).trim()),r=[],s=0);let d=c.length+(r.length>0?1:0);r.push(c),s+=d}return r.length>0&&i.push(r.join(`
|
|
801
|
-
`).trim()),i.map((c,a)=>({episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:a+1,partCount:i.length,text:c,sourceHash:Se(c)}))}function GA(e,t){let n=ra(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:Nn(n,"\u7247\u6BB5\u6897\u6982"),events:Ii(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:n5(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function JA(e,t){let n=d5(t.scope,"episode"),o=[...e].sort((i,r)=>i.part-r.part);return{episodeIndex:n.episodeIndex,episodeId:n.episodeId,episodeNo:n.episodeNo,title:n.title,synopsis:o.map(i=>i.synopsis).filter(i=>i.trim()).join(`
|
|
802
|
-
`),oneLine:l5(o.map(i=>i.synopsis)),events:_p(o.flatMap(i=>i.events))}}function BA(e,t){let n=ra(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:Nn(n,"\u5206\u96C6\u6897\u6982"),oneLine:Nn(n,"\u5355\u53E5\u6897\u6982"),events:Ii(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function KA(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.episodeNo,endEpisodeNo:s.episodeNo,text:s5(i)})}return n}function jA(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.startEpisodeNo,endEpisodeNo:s.endEpisodeNo,text:a5(i)})}return n}function zA(e,t){let n=ra(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:Nn(n,"\u9636\u6BB5\u6897\u6982"),turns:Ii(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:Ii(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function HA(e){let t=[...e].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo),n=t[0],o=t[t.length-1];if(!n||!o)throw new Error("arc reduce requires at least one item");return{index:n.index,startEpisodeNo:n.startEpisodeNo,endEpisodeNo:o.endEpisodeNo,synopsis:t.map(i=>`\u7B2C${i.startEpisodeNo}-${i.endEpisodeNo}\u96C6\uFF1A${i.synopsis}`).join(`
|
|
803
|
-
`),turns:_p(t.flatMap(i=>i.turns)),openQuestions:_p(t.flatMap(i=>i.openQuestions))}}function yp(e,t){let n=["\u5206\u96C6\u7D22\u5F15\uFF1A"];for(let o of[...e].sort((i,r)=>i.episodeNo-r.episodeNo))n.push(`\u7B2C${o.episodeNo}\u96C6\uFF1A${o.oneLine||o.synopsis}`);n.push("","\u9636\u6BB5\u6897\u6982\uFF1A");for(let o of[...t].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo))n.push(`\u7B2C${o.startEpisodeNo}-${o.endEpisodeNo}\u96C6\uFF1A${o.synopsis}`);return n.join(`
|
|
804
|
-
`)}function FA(e){let t=ra(e);return{synopsis:Nn(t,"\u5168\u6587\u6897\u6982"),theme:Nn(t,"\u4E3B\u9898"),logline:Nn(t,"\u4E00\u53E5\u8BDD"),style:Nn(t,"\u98CE\u683C"),mainCharacters:o5(Nn(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function QA(e){let t=e.config??qg,n=ee(e.script.episodes);if(n.length===0)throw new x("No episodes found in script.",{exitCode:G,errorCode:"SCRIPT_EPISODES_MISSING",hint:"Create or parse episodes before generating synopsis.",data:{expected:["script.episodes[] with at least one episode"],actual:["episodes: 0"]}});let o=n.map((u,m)=>$A(e.script,u,m)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await oa(e.script).split({scope:"episode",partition:()=>i,chunk:u=>DA(u,t)}).extract(Or({taskId:"synopsis.chunk",instruction:NA,format:MA,input:({parcel:u})=>i5(u),parse:({text:u,parcel:m})=>GA(u,m)})).reduce("episode",JA).extract(Or({taskId:"synopsis.episode",instruction:LA,format:UA,input:({parcel:u})=>r5(u),parse:({text:u,parcel:m})=>BA(u,m)})).reduce("root",u=>[...u].sort((m,g)=>m.episodeNo-g.episodeNo)).run({concurrency:e.concurrency,checkpoint:Ar(Si.join(e.checkpointDir,"episode")),checkpointSalt:e.checkpointSalt,executor:e.executor}),s=Array.isArray(r)?r:r.value,c=new Map(s.map(u=>[u.episodeIndex,u])),a=o.map(u=>c.get(u.episodeIndex)??{episodeIndex:u.episodeIndex,episodeId:u.episodeId,episodeNo:u.episodeNo,title:u.title,synopsis:u.existingSynopsis,oneLine:u5(u.existingSynopsis),events:[]}),d=a.filter(u=>!u.synopsis.trim()).map(u=>u.episodeId);if(d.length>0)throw new x("Some episode synopses are still missing.",{exitCode:fe,errorCode:"EPISODE_SYNOPSIS_MISSING",hint:"Use --overwrite to regenerate, or manually set missing episode synopses.",data:{expected:["every episode has synopsis"],actual:d}});let p=e.overwrite||m5(e.script),l=p?await qA({episodes:a,executor:e.executor,checkpointDir:Si.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await WA({episodes:a,arcs:l.value,executor:e.executor,checkpointDir:Si.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:g5(e.script),report:{reused:0,ran:0}};return{episodeBriefs:a,overview:f.value,overviewGenerated:p,report:{reused:(Array.isArray(r)?0:r.report.reused)+l.report.reused+f.report.reused,ran:(Array.isArray(r)?0:r.report.ran)+l.report.ran+f.report.ran}}}async function Wg(e,t=kn){let n=f5(e.concurrency,kp,"--concurrency"),o=!!e.overwrite,i=!!e.apply,r=!!e.dry_run;if(i&&r)throw new x("--apply and --dry-run are mutually exclusive.",{exitCode:G,errorCode:"SYNOPSIS_GENERATE_FLAG_CONFLICT",hint:"Pick one mode and retry.",data:{expected:["at most one of --apply / --dry-run"],actual:["--apply","--dry-run"]}});let s=O(e.workspace_path||"workspace"),c=await xr(e),a=t.createExecutor(O(e.llm_config).trim()||void 0),d=O(e.checkpoint).trim()||Si.join(vp(s),"loom","synopsis-generate"),p=await QA({script:c.script,executor:a,checkpointDir:d,concurrency:n,overwrite:o}),l=new Set,f=ee(c.script.episodes);for(let A of p.episodeBriefs){let k=f[A.episodeIndex];k&&(o||!O(k.synopsis).trim())&&O(k.synopsis)!==A.synopsis&&(k.synopsis=A.synopsis,l.add(A.episodeId))}let u=!1;if(u=ia(c.script,"synopsis",p.overview.synopsis,o)||u,u=ia(c.script,"theme",p.overview.theme,o)||u,u=ia(c.script,"logline",p.overview.logline,o)||u,u=ia(c.script,"style",p.overview.style,o)||u,o||ee(c.script.main_characters).length===0){let A=p.overview.mainCharacters.map(k=>({name:k.name,role:k.role}));JSON.stringify(c.script.main_characters??[])!==JSON.stringify(A)&&(c.script.main_characters=A,u=!0)}let m=l.size>0||u,g=Sr(c),h=!!g.passed,w=[`${p.episodeBriefs.length} episodes; ${l.size} synopses ${i?"written":"would change"}; overview ${p.overviewGenerated?"generated":"reused"}; validation ${h?i?"passed":"would pass":i?"needs repair":"would need repair"}${i?"":"; dry-run, no write"}`,`loom: ran=${p.report.ran}, reused=${p.report.reused}`,`llm config: ${a.configSource}; routes: ${a.usage().length}`],y,E;i&&m&&([y,E]=await tp(c,e,"synopsis.generate"),await ep(c,g,y),c.remote&&w.push(`revision ${y}; idempotent ${String(E).toLowerCase()}`));let S=ac(ee(g.issues));return i||w.push("Run again with --apply to write the generated synopsis fields."),[{text:[...w,...S].join(`
|
|
805
|
-
`),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&m,revision:y,idempotent:E,validation:g,issues:S,script_path:c.artifactLabel,episode_synopses:p.episodeBriefs.map(A=>({episode_id:A.episodeId,title:A.title,synopsis:A.synopsis,one_line:A.oneLine})),config_source:a.configSource,llm_routes:a.usage()}},J]}function YA(e,t){if(e.length<=t)return[e];let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function qA(e){let t=KA(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await oa(t).split({scope:"arc",partition:c=>c,chunk:c=>[c]}).extract(Or({taskId:"synopsis.arc",instruction:TA,format:CA,input:({parcel:c})=>c5(c),parse:({text:c,parcel:a})=>zA(c,a)})).reduce("arc",c=>p5(c,"arc")).reduce("root",c=>[...c].sort((a,d)=>a.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:Ar(Si.join(e.checkpointDir,`level-${n}`)),checkpointSalt:e.checkpointSalt,executor:e.executor});o.reused+=i.report.reused,o.ran+=i.report.ran;let r=i.value;if(yp(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=jA(r,e.config.arcEpisodeCount),n+=1}}async function WA(e){let t=e.arcs;for(;yp(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[HA(t)];let n=await oa({episodes:e.episodes,arcs:t}).extract(Or({taskId:"synopsis.script-overview",instruction:PA,format:VA,input:({parcel:o})=>yp(o.episodes,o.arcs),parse:({text:o})=>FA(o)})).run({concurrency:1,checkpoint:Ar(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function ZA(e,t){let n=X(t.environment)?t.environment:{},o=O(n.space).trim(),i=O(n.time).trim(),r=io(t),s=ee(r.locations).map(p=>wp(e,"locations","location_id","location_name",O(p.location_id))).filter(p=>p),c=ee(r.actors).map(p=>wp(e,"actors","actor_id","actor_name",O(p.actor_id))).filter(p=>p),a=s.join("\u3001")||"-";return`[\u573A\u666F] ${[o,i].filter(p=>p).join(" ")||"-"}\uFF5C${a}\uFF5C\u51FA\u573A\uFF1A${c.join("\u3001")||"-"}`}function XA(e,t){let n=O(t.type).trim();if(n==="dialogue"){let i=Qg(e,t),r=O(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=Qg(e,t),r=O(t.content).trim();return r?`[\u5FC3\u58F0] ${i?`${i}\uFF1A`:""}${r}`:""}let o=O(t.content).trim();return o?`[\u52A8\u4F5C] ${o}`:""}function Qg(e,t){let n=t.speaker;if(!X(n))return"";let o=O(n.actor_id).trim();if(o)return wp(e,"actors","actor_id","actor_name",o)||o;let i=O(n.kind).trim();return i?O(n.label).trim()||i:""}function wp(e,t,n,o,i){let r=ee(e[t]).find(s=>O(s[n])===i);return r?O(r[o]).trim():""}function e5(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function ra(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
|
|
806
|
-
`).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=t5(r);if(s){if(n===s.name&&s.inline){o.push(r);continue}i(),n=s.name,s.inline&&o.push(s.inline);continue}n&&o.push(r)}return i(),t}var Yg=new Set(["\u7247\u6BB5\u6897\u6982","\u5173\u952E\u4E8B\u4EF6","\u4EBA\u7269\u53D8\u5316","\u7ED3\u5C3E\u94A9\u5B50","\u5206\u96C6\u6897\u6982","\u5355\u53E5\u6897\u6982","\u9636\u6BB5\u6897\u6982","\u5173\u952E\u8F6C\u6298","\u672A\u89E3\u51B3\u60AC\u5FF5","\u5168\u6587\u6897\u6982","\u4E3B\u9898","\u4E00\u53E5\u8BDD","\u98CE\u683C","\u4E3B\u8981\u4EBA\u7269"]);function t5(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=n[1].trim();return Yg.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=(o>=0?t.slice(0,o):t).trim();return Yg.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}function Nn(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function Ii(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function n5(e){return Ii(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function o5(e){return Ii(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function i5(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),`\u5F53\u524D\u7247\u6BB5\uFF1A${e.part}/${e.partCount}`,"","\u8FD9\u662F\u5F53\u524D\u4EFB\u52A1\u7684\u539F\u6587\uFF1A",e.text].join(`
|
|
807
|
-
`)}function r5(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),"","\u7247\u6BB5\u6897\u6982\uFF1A",e.synopsis,"","\u7247\u6BB5\u5173\u952E\u4E8B\u4EF6\uFF1A",...e.events.map(t=>`- ${t}`)].join(`
|
|
808
|
-
`)}function s5(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.episodeNo}\u96C6 ${n.title||""}`.trim()),t.push(`\u5355\u53E5\uFF1A${n.oneLine}`),t.push(`\u6897\u6982\uFF1A${n.synopsis}`),n.events.length>0){t.push("\u5173\u952E\u4E8B\u4EF6\uFF1A");for(let o of n.events)t.push(`- ${o}`)}t.push("")}return t.join(`
|
|
809
|
-
`).trim()}function a5(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.startEpisodeNo}-${n.endEpisodeNo}\u96C6`),t.push(`\u9636\u6BB5\u6897\u6982\uFF1A${n.synopsis}`),n.turns.length>0){t.push("\u5173\u952E\u8F6C\u6298\uFF1A");for(let o of n.turns)t.push(`- ${o}`)}if(n.openQuestions.length>0){t.push("\u672A\u89E3\u51B3\u60AC\u5FF5\uFF1A");for(let o of n.openQuestions)t.push(`- ${o}`)}t.push("")}return t.join(`
|
|
810
|
-
`).trim()}function c5(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
|
|
811
|
-
`)}function d5(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function p5(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function l5(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function _p(e){let t=new Set,n=[];for(let o of e.map(i=>i.trim()).filter(i=>i.length>0))t.has(o)||(t.add(o),n.push(o));return n}function u5(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function f5(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new x(`${n} must be a positive integer.`,{exitCode:G,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[O(e)]}});return Math.floor(o)}function ia(e,t,n,o){return!o&&O(e[t]).trim()||O(e[t])===n?!1:(e[t]=n,!0)}function m5(e){return!O(e.synopsis).trim()||!O(e.theme).trim()||!O(e.logline).trim()||!O(e.style).trim()||ee(e.main_characters).length===0}function g5(e){return{synopsis:O(e.synopsis).trim(),theme:O(e.theme).trim(),logline:O(e.logline).trim(),style:O(e.style).trim(),mainCharacters:ee(e.main_characters).map(t=>({name:O(t.name).trim(),role:O(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as vr from"node:fs";var Xg=3;function Ep(e){return O(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function xp(e){try{return Zd(e)}catch(t){throw t instanceof de?oo("SCRIPT API BLOCKED: gateway not configured",t):t}}function eh(e,t){let n=Ep(e);if(n&&n!==t.projectGroupNo)throw Zg(t,`configured projectGroupNo=${n}`);let o=xp(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw Zg(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function Zg(e,t){return new x("The configured remote does not match this working copy.",{exitCode:b,errorCode:"WORKING_COPY_REMOTE_MISMATCH",hint:"Restore the checkout environment for this working copy, or checkout another file.",data:{expected:[`projectGroupNo=${e.projectGroupNo}`,`apiBaseUrl=${e.apiBaseUrl}`],actual:[t]}})}function Sp(e){let t;try{t=JSON.parse(vr.readFileSync(e,"utf-8"))}catch(n){throw new x("The local script is missing or invalid JSON.",{exitCode:b,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON before continuing.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}if(!X(t))throw new x("The script root must be a JSON object.",{exitCode:b,errorCode:"SCRIPT_ROOT_INVALID",hint:"Replace the file with a valid Script v3 JSON object.",data:{actual:[e,Array.isArray(t)?"array":typeof t]}});return t}function th(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function sa(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function nh(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new x("The gateway returned an invalid snapshot revision.",{exitCode:fe,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function oh(e,t){return new x("The publish outcome could not be confirmed after retrying.",{exitCode:fe,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Run publish again; it will inspect the latest snapshot before sending another patch.",data:{actual:[...t,`baseRevision=${e}`]}})}async function h5(e,t,n,o,i,r){let s=[];for(let c=1;c<=Xg;c+=1){let a;try{a=await e.getSnapshot()}catch(p){if(p instanceof de&&sa(p)){s.push(`snapshot attempt ${c}: ${p.message}`);continue}throw p instanceof de?oo("PUBLISH BLOCKED: snapshot query failed",p):p}if(a===null||!X(a.script))throw new x("The managed working copy no longer has a remote script.",{exitCode:b,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Publish a new unmanaged file to create the remote script, or restore the remote project.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`]}});let d=nh(a);if(Ce(a.script)===o&&a.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:c,recovered:d!==i.baseRevision};kt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:a.script,edited:n,validation:r}),l=X(p)?Number(p.revision):Number.NaN;if(Number.isInteger(l)&&l>d)return{revision:l,patchedFromRevision:d,attempts:c,recovered:c>1};s.push(`patch attempt ${c}: invalid response ${JSON.stringify(p)}`)}catch(p){if(p instanceof de&&(th(p)||sa(p))){s.push(`patch attempt ${c}: ${p.message}`);continue}throw p instanceof de?oo("PUBLISH BLOCKED: patch failed",p):p}}throw oh(i.baseRevision,s)}async function y5(e,t,n,o,i){let r=[];for(let s=1;s<=Xg;s+=1){let c;try{c=await e.getSnapshot()}catch(a){if(a instanceof de&&sa(a)){r.push(`snapshot attempt ${s}: ${a.message}`);continue}throw a instanceof de?oo("PUBLISH BLOCKED: snapshot query failed",a):a}if(c!==null){let a=nh(c);if(X(c.script)&&Ce(c.script)===o&&c.validationStatus==="valid")return{revision:a,patchedFromRevision:0,attempts:s,recovered:!0};throw new x("An unmanaged local script cannot replace an existing remote script.",{exitCode:b,errorCode:"REMOTE_SCRIPT_EXISTS",hint:"Checkout the remote script, apply the local changes to that managed working copy, then publish.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`,`revision=${a}`]}})}kt(t,o);try{let a=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=X(a)?Number(a.revision):Number.NaN;if(Number.isInteger(d)&&d>0)return{revision:d,patchedFromRevision:0,attempts:s,recovered:s>1};r.push(`patch attempt ${s}: invalid response ${JSON.stringify(a)}`)}catch(a){if(a instanceof de&&(th(a)||sa(a))){r.push(`patch attempt ${s}: ${a.message}`);continue}throw a instanceof de?oo("PUBLISH BLOCKED: patch failed",a):a}}throw oh(0,r)}async function ih(e){let t=xe(e),n=!!e.discard_local,o=Ui(t),i=Br(t),r=vr.existsSync(t),s=Mi(t);if(r&&i===null&&!n)throw new x("The target is an unmanaged local script.",{exitCode:b,errorCode:"LOCAL_TARGET_EXISTS",hint:`Run \`scriptctl checkout --script-path ${t} --discard-local\` only if the local file may be discarded.`,data:{actual:[t]}});if(r&&i!==null&&!n&&Ce(Sp(t))!==i.baseContentHash)throw new x("The working copy has unpublished local changes.",{exitCode:b,errorCode:"WORKING_COPY_DIRTY",hint:"Publish the local changes, or pass --discard-local to replace them with the remote snapshot.",data:{actual:[t,`baseRevision=${i.baseRevision}`]}});let c=i!==null&&!n?eh(e,i):xp(Ep(e)||null),a;try{a=await c.getSnapshot()}catch(l){throw l instanceof de?oo("CHECKOUT BLOCKED: snapshot query failed",l):l}if(a===null||!X(a.script))throw new x("No remote script_v2 snapshot exists for this project.",{exitCode:b,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Use the ingest/create workflow and publish the first script instead of checkout.",data:{actual:[`projectGroupNo=${c.projectGroupNo}`]}});Li(t,s);let d=Ce(a.script);return Je(t,a.script),Kr(t,{schemaVersion:1,projectGroupNo:c.projectGroupNo,apiBaseUrl:c.gatewayBase,baseRevision:Number(a.revision),baseContentHash:d}),[{text:n&&r?`Discarded the local file and checked out revision ${a.revision} to ${t}`:`Checked out revision ${a.revision} to ${t}`,data:{changed:!0,script_path:t,metadata_path:o.metadataPath,managed:!0,dirty:!1,discarded_local:n&&r,project_group_no:c.projectGroupNo,base_revision:Number(a.revision)}},J]}function rh(e){let t=xe(e),n=vr.existsSync(t),o=Br(t),i=n&&o!==null?Ce(Sp(t))!==o.baseContentHash:null;return[{text:o===null?`${t}: unmanaged local script`:`${t}: ${i?"dirty":"clean"} at revision ${o.baseRevision}`,data:{script_path:t,exists:n,managed:o!==null,dirty:i,...o===null?{}:{project_group_no:o.projectGroupNo,api_base_url:o.apiBaseUrl,base_revision:o.baseRevision}}},J]}async function sh(e){let t=xe(e),n=Sp(t),o=Ce(n),i=Br(t);if(i!==null&&i.baseContentHash===o)return[{text:`No local changes; revision remains ${i.baseRevision}`,data:{changed:!1,published:!1,reason:"NO_CHANGES",revision:i.baseRevision,script_path:t}},J];let r=Xd(n);if(!r.passed)throw new x("The local script does not pass its declared Script version validation.",{exitCode:b,errorCode:"PUBLISH_VALIDATION_FAILED",hint:`Run \`scriptctl validate --script-path ${t}\`, repair the issues, then publish again.`,data:{actual:r.issues.slice(0,5).map(p=>`${p.path??"<root>"}: ${p.summary}`)}});let s=jr(n).episodes.length,c={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=eh(e,i),l=await h5(p,t,n,o,i,c);return Kr(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await xc(p,s),[{text:`Published local content over revision ${l.patchedFromRevision} \u2192 ${l.revision}`,data:{changed:!0,published:!0,created:!1,transport:"patch",script_path:t,project_group_no:p.projectGroupNo,base_revision:l.patchedFromRevision,revision:l.revision,attempts:l.attempts,recovered:l.recovered}},J]}let a=xp(Ep(e)||null),d=await y5(a,t,n,o,c);return Kr(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await xc(a,s),[{text:`Published revision ${d.patchedFromRevision} \u2192 ${d.revision}`,data:{changed:!0,published:!0,created:!0,transport:"patch",script_path:t,project_group_no:a.projectGroupNo,base_revision:d.patchedFromRevision,revision:d.revision,attempts:d.attempts,recovered:d.recovered}},J]}function ah(e,t,n){e.command("migrate").description("Create a newer Script schema copy through the registered migration chain").requiredOption("-p, --script-path <path>","Source Script JSON file").requiredOption("-o, --output <file>","Destination Script JSON file").requiredOption("--to <version>","Target Script version").option("--manifest <file>","Migration manifest output").option("--force","Replace existing migration artifacts").addHelpText("after",`
|
|
812
|
-
Example:
|
|
813
|
-
scriptctl migrate -p ./old-script.json -o ./script-v4.json --to 4
|
|
814
|
-
`).action(Y(Jg,t));let o=e.command("ingest").description("Convert source files into a Script v4 workspace").option("-s, --source-path <path>","Source file or directory").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls").option("--fps <n>","Video sampling rate").option("--upload-mode <mode>","Video transport: file-api (default) or base64").option("--video-provider <provider>","Video provider: gemini or doubao (explicit selection disables fallback)").option("--provider-base-url <url>","Selected video provider service root").option("--provider-api-key <key>","Provider API key (visible in process arguments; prefer --provider-api-key-env)").option("--provider-api-key-env <name>","Environment variable containing the provider API key").option("--provider-model <model>","Selected video provider model (Doubao defaults to ARK_MODEL)").option("--step","Process only the next unfinished video episode").option("--force","Rebuild completed stages").addHelpText("after",`
|
|
815
|
-
Example:
|
|
816
|
-
scriptctl ingest --source-path ./draft.md --workspace-path ./workspace
|
|
817
|
-
`).action(Y(r=>lg(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(Y(ug,t)),o.command("skip").description("Manually accept the next failed video episode as empty").option("-w, --workspace-path <path>","Workspace directory").requiredOption("--episode <n>","Failed episode number").requiredOption("--reason <text>","Why this episode is being skipped").addHelpText("after",`
|
|
818
|
-
Example:
|
|
819
|
-
scriptctl ingest skip -w ./workspace --episode 7 --reason "provider policy block"
|
|
820
|
-
`).action(Y(fg,t)),e.command("evidence").description("Generate local original-video reference frames from final Script v4 timestamps").option("-p, --script-path <path>","Final Script v4 JSON file").requiredOption("-s, --source-path <path>","Linked source-video file or episode directory").requiredOption("-w, --workspace-path <path>","Project workspace directory").option("--force","Re-extract frames even when deterministic output files already exist").addHelpText("after",`
|
|
821
|
-
Example:
|
|
822
|
-
scriptctl evidence -p ./script.json -s /Volumes/NAS/videos -w ./workspace --force
|
|
823
|
-
`).action(Y(mg,t)),e.command("view").description("Render or serve the workspace review page").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--watch","Serve and refresh the review page").option("--port <n>","HTTP server port").action(Y(wg,t)),uc(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(Y(ih,t)),se(e.command("status"),"read").description("Show local working-copy state").action(Y(rh,t)),uc(e.command("publish")).description("Validate and publish the local working copy").action(Y(sh,t)),se(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(Y(Pg,t)),se(e.command("audit-assets"),"read").description("Audit asset consistency with an LLM").option("--llm-config <path>","LLM configuration file").option("-o, --output <path>","Audit JSON output file").action(Y(r=>kg(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());se(i.command("generate")).description("Generate synopsis fields with an LLM").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls","30").option("--checkpoint <dir>","Checkpoint directory").option("--overwrite","Regenerate existing synopsis fields").option("--apply","Write generated fields").option("-n, --dry-run","Generate a preview without writing").action(Y(r=>Wg(r,n),t))}function E5(e,t=kn){let n=new w5("scriptctl").description("Read, edit, ingest, and publish structured scripts").usage("<command> [options]").exitOverride().allowExcessArguments(!1).allowUnknownOption(!1).showHelpAfterError(!1).configureOutput({writeOut:o=>process.stdout.write(o),writeErr:()=>{}}).option("-j, --json","Output structured JSON").option("--format <format>","Output format (addr)").version(Qo(),"-v, --version","Show the scriptctl version");return ah(n,e,t),qu(n,e),Gl(n,e),Eu(n,e),hu(n,e),n}function aa(e,t){let n=t.split("=",1)[0],o=e;for(;o;){let i=o.options.find(r=>r.short===n||r.long===n);if(i)return i;o=o.parent}}function dh(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<2)return{recognized:!1,json:!1,hasAttachedValue:!1};let n=!1;for(let o=1;o<t.length;o+=1){let i=aa(e,`-${t[o]}`);if(!i?.short)return{recognized:!1,json:!1,hasAttachedValue:!1};if(i.short==="-j"&&(n=!0),i.required||i.optional)return{recognized:!0,json:n,valueOption:i,hasAttachedValue:o<t.length-1}}return{recognized:!0,json:n,hasAttachedValue:!1}}function x5(e,t){return t==="--"?!0:t.startsWith("--")?aa(e,t)!==void 0:dh(e,t).recognized}function ch(e,t,n){return n===void 0||n==="--"?!1:t.required?!x5(e,n):t.optional&&!n.startsWith("-")}function S5(e,t){let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];if(i==="--")break;if(i.startsWith("--")){if(i==="--json")return!0;let s=aa(n,i);s&&!i.includes("=")&&ch(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=dh(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&ch(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function I5(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let a=aa(n,s);a&&!s.includes("=")&&(a.required||a.optional)&&(r+=1);continue}let c=n.commands.find(a=>a.name()===s);if(!c)break;n=c}let o=[],i=n;for(;i&&i.parent;)o.unshift(i.name()),i=i.parent;return["scriptctl",...o,"--help"].join(" ")}function A5(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function wG(e=null,t=kn){Hl();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:J},i=E5(o,t);if(o.jsonMode=S5(i,n),n.length===0)return i.outputHelp(),J;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof _5)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?J:Bi(new x(A5(r),{exitCode:G,errorCode:"USAGE_ERROR",hint:`Run '${I5(i,n)}'.`}),o.jsonMode);if(r instanceof x)return Bi(r,o.jsonMode);if(r instanceof P)return Bi(new x(Un(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return Bi(new x(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{E5 as a,wG as b};
|