galbook 0.0.0-stage → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/galbook/SKILL.md +44 -0
- package/LICENSE +21 -0
- package/README.en.md +114 -0
- package/README.md +133 -3
- package/bin/galbook.js +53 -0
- package/cordis.patch.yml +30 -0
- package/dsh-plugin/README.md +49 -0
- package/dsh-plugin/install.py +190 -0
- package/galbook/__init__.py +15 -0
- package/galbook/__main__.py +138 -0
- package/galbook/build.py +89 -0
- package/galbook/cli.py +29 -0
- package/galbook/demo/fog-harbor/assets/cg_dawn_together.svg +1 -0
- package/galbook/demo/fog-harbor/assets/cg_old_letter.svg +1 -0
- package/galbook/demo/fog-harbor/assets/cg_ship.svg +1 -0
- package/galbook/demo/fog-harbor/assets/harbor_night.svg +1 -0
- package/galbook/demo/fog-harbor/assets/lamp_room.svg +1 -0
- package/galbook/demo/fog-harbor/assets/lamp_room_dawn.svg +1 -0
- package/galbook/demo/fog-harbor/assets/path_tide.svg +1 -0
- package/galbook/demo/fog-harbor/assets/shio_normal.svg +1 -0
- package/galbook/demo/fog-harbor/assets/shio_smile.svg +1 -0
- package/galbook/demo/fog-harbor/assets/shio_surprised.svg +1 -0
- package/galbook/demo/fog-harbor/assets/warehouse.svg +1 -0
- package/galbook/demo/fog-harbor/story.gal +97 -0
- package/galbook/demo/fog-harbor-en/assets/cg_dawn_together.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/cg_old_letter.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/cg_ship.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/harbor_night.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/lamp_room.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/lamp_room_dawn.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/path_tide.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/shio_normal.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/shio_smile.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/shio_surprised.svg +1 -0
- package/galbook/demo/fog-harbor-en/assets/warehouse.svg +1 -0
- package/galbook/demo/fog-harbor-en/story.gal +97 -0
- package/galbook/demo_boot.py +63 -0
- package/galbook/engine.py +325 -0
- package/galbook/expr.py +107 -0
- package/galbook/i18n.py +85 -0
- package/galbook/importers/__init__.py +106 -0
- package/galbook/importers/common.py +94 -0
- package/galbook/importers/galscript.py +218 -0
- package/galbook/importers/kag.py +326 -0
- package/galbook/importers/legacy.py +122 -0
- package/galbook/importers/nscripter.py +314 -0
- package/galbook/importers/qlie.py +498 -0
- package/galbook/importers/renpy.py +333 -0
- package/galbook/importers/textdump.py +128 -0
- package/galbook/ir.py +266 -0
- package/galbook/mcp_server.py +102 -0
- package/galbook/play.py +374 -0
- package/galbook/server.py +199 -0
- package/galbook/static/play.html +151 -0
- package/galbook/store.py +160 -0
- package/galbook/tools.py +99 -0
- package/galbook/web.py +316 -0
- package/icon.svg +21 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +58 -6
package/galbook/play.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""对外的「玩」操作:new / next / choose / save / load / saves / rewind / log / status / profile / click。
|
|
2
|
+
web.py 和命令行都调这里。每个操作在 agent 自己的锁里完成。"""
|
|
3
|
+
import copy
|
|
4
|
+
import os
|
|
5
|
+
import random
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
from . import engine
|
|
9
|
+
from .expr import evaluate, assign, ExprError
|
|
10
|
+
from .ir import load_story, StoryError
|
|
11
|
+
from .importers import legacy
|
|
12
|
+
from .store import Store, StoreError
|
|
13
|
+
|
|
14
|
+
READONLY = ("status", "saves", "log", "profile", "gallery")
|
|
15
|
+
ACTIONS = ("new", "next", "choose", "save", "load", "saves", "rewind", "log", "status", "profile", "persona", "gallery", "click")
|
|
16
|
+
SLUG_OK = lambda s: bool(s) and "/" not in s and "\\" not in s and not s.startswith(".")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Library(object):
|
|
20
|
+
def __init__(self, books_dir, data_dir, demo=None):
|
|
21
|
+
self.books_dir = books_dir
|
|
22
|
+
self.store = Store(data_dir)
|
|
23
|
+
# 装完就能玩:books 不存在或空的时候,自动装自带演示书(npm 包场景)
|
|
24
|
+
# 关掉:demo=False,或环境变量 GALBOOK_NO_DEMO=1(命令行 --no-demo 就是设这个)
|
|
25
|
+
if demo is None:
|
|
26
|
+
from .demo_boot import demo_enabled
|
|
27
|
+
demo = demo_enabled()
|
|
28
|
+
try:
|
|
29
|
+
if not demo:
|
|
30
|
+
raise StopIteration
|
|
31
|
+
import sys as _sys
|
|
32
|
+
from .demo_boot import empty, ensure_demo_books
|
|
33
|
+
if empty(books_dir):
|
|
34
|
+
n = ensure_demo_books(books_dir)
|
|
35
|
+
if n:
|
|
36
|
+
# 只能写 stderr:MCP 走 stdio 时 stdout 是协议通道
|
|
37
|
+
print("(books 目录是空的,已自动装入 %d 本演示书;不想要:--no-demo 或 GALBOOK_NO_DEMO=1)" % n,
|
|
38
|
+
file=_sys.stderr)
|
|
39
|
+
except (Exception, StopIteration):
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
# ---- 书 ----
|
|
43
|
+
def books(self):
|
|
44
|
+
out = []
|
|
45
|
+
if not os.path.isdir(self.books_dir):
|
|
46
|
+
return out
|
|
47
|
+
for slug in sorted(os.listdir(self.books_dir)):
|
|
48
|
+
try:
|
|
49
|
+
st = self.story(slug)
|
|
50
|
+
except Exception as e: # noqa
|
|
51
|
+
if os.path.isfile(os.path.join(self.books_dir, slug, "book.json")):
|
|
52
|
+
out.append({"slug": slug, "playable": False, "error": str(e)[:200]})
|
|
53
|
+
continue
|
|
54
|
+
out.append({"slug": slug, "title": st.title or slug, "mode": st.mode, "engine": st.meta.get("engine", ""),
|
|
55
|
+
"scenes": len(st.scenes), "routes": [r.get("title") for r in st.routes],
|
|
56
|
+
"players": len(self.store.agents(slug)),
|
|
57
|
+
"problem_count": len(st.problems), "problems": st.problems[:20],
|
|
58
|
+
"choices": st.op_counts.get("choice", 0), "jumps": st.op_counts.get("jump", 0),
|
|
59
|
+
"warnings": st.warnings})
|
|
60
|
+
return out
|
|
61
|
+
|
|
62
|
+
def story(self, slug):
|
|
63
|
+
if not SLUG_OK(slug):
|
|
64
|
+
raise StoryError("书名不合法: %r" % slug)
|
|
65
|
+
d = os.path.join(self.books_dir, slug)
|
|
66
|
+
if os.path.isfile(os.path.join(d, "story", "story.json")):
|
|
67
|
+
return load_story(os.path.join(d, "story"))
|
|
68
|
+
if os.path.isfile(os.path.join(d, "book.json")):
|
|
69
|
+
return legacy.load(d)
|
|
70
|
+
raise StoryError("没有这本书: %s" % slug)
|
|
71
|
+
|
|
72
|
+
# ---- 玩 ----
|
|
73
|
+
def act(self, slug, agent, action, **kw):
|
|
74
|
+
story = self.story(slug)
|
|
75
|
+
fn = getattr(self, "_a_" + action, None)
|
|
76
|
+
if fn is None:
|
|
77
|
+
raise engine.PlayError("不认识的操作 %r(可用:%s)" % (action, " ".join(ACTIONS)))
|
|
78
|
+
with self.store.session(slug, agent, readonly=action in READONLY) as S:
|
|
79
|
+
r = fn(story, S, **kw)
|
|
80
|
+
r.setdefault("book", slug)
|
|
81
|
+
r.setdefault("agent", agent)
|
|
82
|
+
return r
|
|
83
|
+
|
|
84
|
+
def _need_run(self, S):
|
|
85
|
+
if not S.run:
|
|
86
|
+
raise engine.PlayError("还没开始。先 new(新游戏)或 load(读档)")
|
|
87
|
+
return S.run
|
|
88
|
+
|
|
89
|
+
def _a_new(self, story, S, h="fold", mode="normal", hints="0", lang=None, **_):
|
|
90
|
+
st = engine.new_state(story, h=h, mode=mode, hints=hints, lang=lang or S.profile.get("lang") or "zh")
|
|
91
|
+
S.set_run(st)
|
|
92
|
+
S.profile["stats"]["games"] = S.profile["stats"].get("games", 0) + 1
|
|
93
|
+
r = engine.advance(story, st, S.profile["s"], S.profile["seen"], n=0)
|
|
94
|
+
S.profile["stats"]["lines"] = S.profile["stats"].get("lines", 0) + len(r["lines"])
|
|
95
|
+
self._decorate(story, S, st, r)
|
|
96
|
+
return {"ok": True, "msg": "新游戏开始(第 %d 周目)" % S.profile["stats"]["games"], "state": r,
|
|
97
|
+
"opts": st["opts"], "system_vars": S.profile["s"]}
|
|
98
|
+
|
|
99
|
+
def _a_next(self, story, S, n=20, skip_read=False, **_):
|
|
100
|
+
st = self._need_run(S)
|
|
101
|
+
if st.get("ended"):
|
|
102
|
+
# 已经结束:幂等返回,不再吐一遍同样的结尾(灵犀实测反馈)
|
|
103
|
+
return {"ok": True, "no_new": True, "msg": "已经结束了,没有新内容(想换条路:rewind / load / new)",
|
|
104
|
+
"state": {"lines": [], "ended": st["ended"]}}
|
|
105
|
+
n = max(1, min(int(n or 20), 200))
|
|
106
|
+
before_end = st.get("ended")
|
|
107
|
+
st.pop("_click", None) # 上一批的「可点」只在那一批有效(原作的点击也只在那一句上)
|
|
108
|
+
r = self._advance_clicks(story, S, st, n, bool(skip_read))
|
|
109
|
+
S.touch_run()
|
|
110
|
+
S.profile["stats"]["lines"] = S.profile["stats"].get("lines", 0) + len(r["lines"])
|
|
111
|
+
if r.get("choice") and not (st.get("_autosaved_at") == [st["scene"], st["pc"], st["turn"]]):
|
|
112
|
+
st["_autosaved_at"] = [st["scene"], st["pc"], st["turn"]]
|
|
113
|
+
S.save_slot("auto", self._meta(story, st, "到选项自动存"))
|
|
114
|
+
if r.get("cg_seen"):
|
|
115
|
+
got = S.profile.setdefault("cg", [])
|
|
116
|
+
got.extend(c for c in dict.fromkeys(r["cg_seen"]) if c not in got)
|
|
117
|
+
self._decorate(story, S, st, r)
|
|
118
|
+
if st.get("ended") and not before_end:
|
|
119
|
+
e = st["ended"]
|
|
120
|
+
S.profile["stats"].setdefault("endings", []).append({"kind": e.get("kind"), "name": e.get("name"),
|
|
121
|
+
"t": time.time(), "turn": st.get("turn")})
|
|
122
|
+
return {"ok": True, "state": r, "opts": st.get("opts")}
|
|
123
|
+
|
|
124
|
+
# ---- 点击(特殊机制:比如某句台词时点时钟,才会出现隐藏选项)----
|
|
125
|
+
@staticmethod
|
|
126
|
+
def _click_of(story, ln):
|
|
127
|
+
try:
|
|
128
|
+
return story.scene(ln["scene"]).ops[ln["pc"]].get("click")
|
|
129
|
+
except Exception: # noqa
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
def _advance_clicks(self, story, S, st, n, skip_read):
|
|
133
|
+
"""和 engine.advance 一样推进;剧本里没有 click 时零开销。
|
|
134
|
+
有 click 的句子且条件成立:那一行带上 mark=◇,并把「刚读完那一句」的状态存进 st["_click"],
|
|
135
|
+
之后 do=click 就回到那一刻再点。返回的内容和不带 click 时完全一样(不提前停、不解释)。"""
|
|
136
|
+
sysv, seen = S.profile["s"], S.profile["seen"]
|
|
137
|
+
if not has_clicks(story):
|
|
138
|
+
return engine.advance(story, st, sysv, seen, n=n, skip_read=skip_read)
|
|
139
|
+
st0, sv0 = copy.deepcopy(st), copy.deepcopy(sysv)
|
|
140
|
+
r = engine.advance(story, st, sysv, seen, n=n, skip_read=skip_read)
|
|
141
|
+
cand = [j for j, ln in enumerate(r["lines"]) if not ln.get("folded") and self._click_of(story, ln)]
|
|
142
|
+
if not cand:
|
|
143
|
+
return r
|
|
144
|
+
# 有候选:从推进前的状态逐段重放,在每个候选句停一下,按「那一刻」的变量判断能不能点
|
|
145
|
+
st.clear(); st.update(st0)
|
|
146
|
+
sysv.clear(); sysv.update(sv0)
|
|
147
|
+
parts, done = [], 0
|
|
148
|
+
for j in cand:
|
|
149
|
+
seg = engine.advance(story, st, sysv, seen, n=j + 1 - done, skip_read=skip_read)
|
|
150
|
+
parts.append(seg)
|
|
151
|
+
done += len(seg["lines"])
|
|
152
|
+
if done != j + 1 or seg.get("choice") or seg.get("ended"):
|
|
153
|
+
break # 重放和第一次不一致(不该发生):不标记,照常往下
|
|
154
|
+
ln = seg["lines"][-1]
|
|
155
|
+
ck = self._click_of(story, ln)
|
|
156
|
+
try:
|
|
157
|
+
ok = evaluate(ck.get("if"), st["f"], sysv)
|
|
158
|
+
except ExprError:
|
|
159
|
+
ok = False
|
|
160
|
+
if ok:
|
|
161
|
+
ln["mark"] = "◇"
|
|
162
|
+
snap = {k: v for k, v in st.items() if k != "_click"}
|
|
163
|
+
st["_click"] = {"scene": ln["scene"], "pc": ln["pc"], "state": copy.deepcopy(snap),
|
|
164
|
+
"s": copy.deepcopy(sysv)}
|
|
165
|
+
if done < n and not (parts and (parts[-1].get("choice") or parts[-1].get("ended"))):
|
|
166
|
+
parts.append(engine.advance(story, st, sysv, seen, n=n - done, skip_read=skip_read))
|
|
167
|
+
out = dict(parts[-1])
|
|
168
|
+
out["lines"] = [ln for p in parts for ln in p["lines"]]
|
|
169
|
+
out["skipped"] = sum(p.get("skipped", 0) for p in parts)
|
|
170
|
+
for k in ("cg_seen", "events", "warnings"):
|
|
171
|
+
v = [x for p in parts for x in (p.get(k) or [])]
|
|
172
|
+
if v:
|
|
173
|
+
out[k] = v
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
def _a_click(self, story, S, **_):
|
|
177
|
+
st = self._need_run(S)
|
|
178
|
+
c = st.get("_click")
|
|
179
|
+
if not c:
|
|
180
|
+
return {"ok": True, "msg": "点了一下,什么也没发生。", "clicked": False}
|
|
181
|
+
ck = (story.scene(c["scene"]).ops[c["pc"]].get("click") or {}) if c["scene"] in story.scenes else {}
|
|
182
|
+
new = c["state"]
|
|
183
|
+
sysv = S.profile["s"]
|
|
184
|
+
sysv.clear(); sysv.update(c.get("s") or {})
|
|
185
|
+
if ck.get("set"):
|
|
186
|
+
try:
|
|
187
|
+
assign(ck["set"], new["f"], sysv)
|
|
188
|
+
except ExprError as e:
|
|
189
|
+
raise engine.PlayError("点击效果执行失败:%s" % e)
|
|
190
|
+
cid = str(ck.get("id") or "%s#%s" % (c["scene"], c["pc"]))
|
|
191
|
+
new["f"]["click_" + cid] = 1 # 存档里记下:这一局在这里点过
|
|
192
|
+
found = S.profile.setdefault("clicks", []) # 跨周目记下:发现过哪些
|
|
193
|
+
if cid not in found:
|
|
194
|
+
found.append(cid)
|
|
195
|
+
g = ck.get("goto") or {}
|
|
196
|
+
if g:
|
|
197
|
+
new["scene"], new["pc"] = story.resolve(g.get("scene"), g.get("label"), c["scene"])
|
|
198
|
+
new.pop("pending", None)
|
|
199
|
+
S.set_run(new)
|
|
200
|
+
S.profile["stats"]["clicks"] = S.profile["stats"].get("clicks", 0) + 1
|
|
201
|
+
return {"ok": True, "msg": "点了一下。", "clicked": True, "where": engine.where(story, new)}
|
|
202
|
+
|
|
203
|
+
def _a_choose(self, story, S, i=None, reason="", **_):
|
|
204
|
+
st = self._need_run(S)
|
|
205
|
+
st.pop("_click", None)
|
|
206
|
+
p = st.get("pending")
|
|
207
|
+
if p and str(i).lower() == "random":
|
|
208
|
+
i = random.choice(p["options"])["i"]
|
|
209
|
+
reason = reason or "(随机)"
|
|
210
|
+
key = None
|
|
211
|
+
if p:
|
|
212
|
+
o = next((o for o in p["options"] if str(o["i"]) == str(i)), None)
|
|
213
|
+
if o is not None:
|
|
214
|
+
key = "%s:%s:%s" % (p["scene"], p["pc"], o["k"])
|
|
215
|
+
c = engine.choose(story, st, S.profile["s"], i, reason or "")
|
|
216
|
+
if key:
|
|
217
|
+
picked = S.profile.setdefault("picked", [])
|
|
218
|
+
if key not in picked:
|
|
219
|
+
picked.append(key)
|
|
220
|
+
S.touch_run()
|
|
221
|
+
S.profile["stats"]["choices"] = S.profile["stats"].get("choices", 0) + 1
|
|
222
|
+
if reason:
|
|
223
|
+
S.profile["stats"]["reasons"] = S.profile["stats"].get("reasons", 0) + 1
|
|
224
|
+
return {"ok": True, "chosen": c, "where": engine.where(story, st)}
|
|
225
|
+
|
|
226
|
+
def _a_save(self, story, S, slot="quick", note="", **_):
|
|
227
|
+
st = self._need_run(S)
|
|
228
|
+
self._ironman(S, "手动存档")
|
|
229
|
+
S.save_slot(slot, self._meta(story, st, note))
|
|
230
|
+
S.profile["stats"]["saves"] = S.profile["stats"].get("saves", 0) + 1
|
|
231
|
+
return {"ok": True, "msg": "已存到 %s" % slot, "where": engine.where(story, st)}
|
|
232
|
+
|
|
233
|
+
def _ironman(self, S, what):
|
|
234
|
+
if S.run and (S.run.get("opts") or {}).get("mode") == "ironman":
|
|
235
|
+
raise engine.PlayError("铁人模式这一局不能%s(选了就认;想重来就 new)" % what)
|
|
236
|
+
|
|
237
|
+
def _a_load(self, story, S, slot="quick", **_):
|
|
238
|
+
self._ironman(S, "读档")
|
|
239
|
+
d = S.load_slot(slot)
|
|
240
|
+
st = d["state"]
|
|
241
|
+
if st.get("scene") not in story.scenes:
|
|
242
|
+
raise engine.PlayError("这个存档指向的场景 %r 在当前剧本里没有了(剧本重建过?)" % st.get("scene"))
|
|
243
|
+
if st.get("pending"):
|
|
244
|
+
st["pending"]["shown_at"] = time.time()
|
|
245
|
+
S.set_run(st)
|
|
246
|
+
S.profile["stats"]["loads"] = S.profile["stats"].get("loads", 0) + 1
|
|
247
|
+
r = engine.advance(story, st, S.profile["s"], S.profile["seen"], n=0)
|
|
248
|
+
self._decorate(story, S, st, r)
|
|
249
|
+
return {"ok": True, "msg": "读档 %s" % slot, "meta": d.get("meta"), "state": r, "opts": st.get("opts"),
|
|
250
|
+
"recent": [dict(who=x["who"], text=x["text"]) for x in st.get("log", [])[-5:]]}
|
|
251
|
+
|
|
252
|
+
def _a_saves(self, story, S, **_):
|
|
253
|
+
return {"ok": True, "saves": S.slots()}
|
|
254
|
+
|
|
255
|
+
def _a_rewind(self, story, S, steps=1, **_):
|
|
256
|
+
st = self._need_run(S)
|
|
257
|
+
self._ironman(S, "回溯")
|
|
258
|
+
new = engine.rewind(st, steps)
|
|
259
|
+
S.set_run(new)
|
|
260
|
+
S.profile["stats"]["rewinds"] = S.profile["stats"].get("rewinds", 0) + 1
|
|
261
|
+
r = engine.advance(story, new, S.profile["s"], S.profile["seen"], n=0)
|
|
262
|
+
self._decorate(story, S, new, r)
|
|
263
|
+
return {"ok": True, "msg": "回到选项点", "state": r, "opts": new.get("opts")}
|
|
264
|
+
|
|
265
|
+
def _a_log(self, story, S, n=30, **_):
|
|
266
|
+
st = self._need_run(S)
|
|
267
|
+
n = max(1, min(int(n or 30), 300))
|
|
268
|
+
return {"ok": True, "log": st.get("log", [])[-n:], "choices": st.get("choices", [])}
|
|
269
|
+
|
|
270
|
+
def _a_status(self, story, S, **_):
|
|
271
|
+
st = S.run
|
|
272
|
+
r = {"ok": True, "title": story.title, "mode": story.mode, "started": bool(st),
|
|
273
|
+
"routes": [r.get("title") for r in story.routes], "stats": S.profile["stats"],
|
|
274
|
+
"system_vars": S.profile["s"], "saves": [x["slot"] for x in S.slots()]}
|
|
275
|
+
if st:
|
|
276
|
+
r["state"] = engine.peek(story, st)
|
|
277
|
+
self._decorate(story, S, st, r["state"])
|
|
278
|
+
r["opts"] = st.get("opts")
|
|
279
|
+
r["choices_made"] = st.get("choices", [])[-10:]
|
|
280
|
+
return r
|
|
281
|
+
|
|
282
|
+
def _a_profile(self, story, S, **_):
|
|
283
|
+
seen = S.profile.get("seen", {})
|
|
284
|
+
total = sum(sc.says for sc in story.scenes.values()) or 1
|
|
285
|
+
got = sum(min(b - a + 1, 10 ** 9) for rs in seen.values() for a, b in rs)
|
|
286
|
+
return {"ok": True, "stats": S.profile["stats"], "system_vars": S.profile["s"],
|
|
287
|
+
"read_ratio": round(min(1.0, got / total), 4), "seen_scenes": len(seen),
|
|
288
|
+
"humanlike": humanlike(S.profile, S.run)}
|
|
289
|
+
|
|
290
|
+
def _a_persona(self, story, S, text=None, **_):
|
|
291
|
+
"""人设:每个 agent 自己的性格/口味,选项时会提醒(让不同 agent 走出不同的路)。text 为空 = 只看。"""
|
|
292
|
+
if text is not None:
|
|
293
|
+
S.profile["persona"] = str(text).strip()[:600]
|
|
294
|
+
return {"ok": True, "msg": "人设已记下" if S.profile["persona"] else "人设已清空", "persona": S.profile["persona"]}
|
|
295
|
+
return {"ok": True, "persona": S.profile.get("persona", "")}
|
|
296
|
+
|
|
297
|
+
def _a_gallery(self, story, S, **_):
|
|
298
|
+
"""收集进度:结局、路线、CG、已读。"""
|
|
299
|
+
st = S.profile.get("stats", {})
|
|
300
|
+
got_end = list(dict.fromkeys(e.get("name", "") for e in st.get("endings", []) if e.get("kind") == "ending"))
|
|
301
|
+
seen = S.profile.get("seen", {})
|
|
302
|
+
routes = [r.get("title") for r in story.routes]
|
|
303
|
+
seen_routes = sorted({story.scenes[s].route for s in seen if s in story.scenes and story.scenes[s].route})
|
|
304
|
+
total = sum(sc.says for sc in story.scenes.values()) or 1
|
|
305
|
+
got = sum(b - a + 1 for rs in seen.values() for a, b in rs)
|
|
306
|
+
cg_all = story.cg_total()
|
|
307
|
+
return {"ok": True, "endings": got_end, "endings_total": story.endings_total(),
|
|
308
|
+
"routes": routes, "routes_seen": seen_routes,
|
|
309
|
+
"cg_seen": len(S.profile.get("cg", [])), "cg_total": cg_all,
|
|
310
|
+
"read_ratio": round(min(1.0, got / total), 4), "games": st.get("games", 0)}
|
|
311
|
+
|
|
312
|
+
def _decorate(self, story, S, st, r):
|
|
313
|
+
"""给选项加标记(hints 打开时)和人设提醒。"""
|
|
314
|
+
c = r.get("choice")
|
|
315
|
+
if not c:
|
|
316
|
+
return
|
|
317
|
+
if (st.get("opts") or {}).get("hints") and st.get("pending"):
|
|
318
|
+
picked = set(S.profile.get("picked", []))
|
|
319
|
+
seen = S.profile.get("seen", {})
|
|
320
|
+
p = st["pending"]
|
|
321
|
+
op = story.scene(p["scene"]).ops[p["pc"]]
|
|
322
|
+
for o, po in zip(c["options"], p["options"]):
|
|
323
|
+
marks = []
|
|
324
|
+
if "%s:%s:%s" % (p["scene"], p["pc"], po["k"]) in picked:
|
|
325
|
+
marks.append("picked")
|
|
326
|
+
g = (op["options"][po["k"]].get("goto") or {})
|
|
327
|
+
try:
|
|
328
|
+
tsid, tpc = story.resolve(g.get("scene"), g.get("label"), p["scene"]) if g else (p["scene"], p["pc"] + 1)
|
|
329
|
+
fs = story.first_say(tsid, tpc)
|
|
330
|
+
if fs and not engine.seen_has(seen, fs[0], fs[1]):
|
|
331
|
+
marks.append("new")
|
|
332
|
+
except Exception: # noqa
|
|
333
|
+
pass
|
|
334
|
+
if marks:
|
|
335
|
+
o["marks"] = marks
|
|
336
|
+
if S.profile.get("persona"):
|
|
337
|
+
c["persona"] = S.profile["persona"]
|
|
338
|
+
|
|
339
|
+
def _meta(self, story, st, note):
|
|
340
|
+
sc = story.scenes.get(st.get("scene"))
|
|
341
|
+
last = (st.get("log") or [{}])[-1]
|
|
342
|
+
return {"title": sc.title if sc else "", "turn": st.get("turn"), "note": (note or "")[:120],
|
|
343
|
+
"preview": ((last.get("who") + ":") if last.get("who") else "") + engine.plain(last.get("text", ""))[:60],
|
|
344
|
+
"pending": bool(st.get("pending"))}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def has_clicks(story):
|
|
348
|
+
"""剧本里有没有可点的句子(say 上带 click 字段);结果缓存在 story 上。"""
|
|
349
|
+
v = getattr(story, "_gb_has_clicks", None)
|
|
350
|
+
if v is None:
|
|
351
|
+
v = any(op.get("click") for sc in story.scenes.values() for op in sc.ops)
|
|
352
|
+
try:
|
|
353
|
+
story._gb_has_clicks = v
|
|
354
|
+
except AttributeError:
|
|
355
|
+
pass
|
|
356
|
+
return v
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def humanlike(profile, run):
|
|
360
|
+
"""「像不像人」的几个可量化指标(不打分,给人看趋势)。"""
|
|
361
|
+
st = profile.get("stats", {})
|
|
362
|
+
ch = (run or {}).get("choices") or []
|
|
363
|
+
thinks = [c["think_s"] for c in ch if c.get("think_s") is not None and not c.get("auto")]
|
|
364
|
+
with_reason = [c for c in ch if (c.get("reason") or "").strip() and not c.get("auto")]
|
|
365
|
+
picks = [c["i"] for c in ch if not c.get("auto")]
|
|
366
|
+
return {
|
|
367
|
+
"choices_this_game": len([c for c in ch if not c.get("auto")]),
|
|
368
|
+
"reason_rate": round(len(with_reason) / len(picks), 2) if picks else None,
|
|
369
|
+
"median_think_s": sorted(thinks)[len(thinks) // 2] if thinks else None,
|
|
370
|
+
"always_first_option": (all(i == 1 for i in picks) and len(picks) >= 3) if picks else None,
|
|
371
|
+
"lines_per_choice": round(st.get("lines", 0) / max(1, st.get("choices", 0)), 1),
|
|
372
|
+
"saves": st.get("saves", 0), "loads": st.get("loads", 0), "rewinds": st.get("rewinds", 0),
|
|
373
|
+
"endings_seen": len({(e.get("name")) for e in st.get("endings", [])}),
|
|
374
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""独立服务:python3 -m galbook serve --books ./books --data ./play-data [--host 127.0.0.1] [--port 8765]
|
|
2
|
+
|
|
3
|
+
/play/... 见 web.py(JSON / 纯文本 / 页面)
|
|
4
|
+
/b/<书>/assets/... 书里的图片(只开放 assets/ 下面,剧本文件不外露,免得剧透/外泄)
|
|
5
|
+
/ 跳到 /play/
|
|
6
|
+
POST /mcp MCP(Streamable HTTP,JSON 响应):?book=默认书&agent=默认名,或请求头 X-Galplay-Agent
|
|
7
|
+
|
|
8
|
+
公开部署时的访问控制(可选):
|
|
9
|
+
--token XXX 所有 /play/api 和 /play/t 请求都要带 ?token=XXX 或 Authorization: Bearer XXX
|
|
10
|
+
--tokens tokens.json {"令牌": "agent 名" | "*"}:每个令牌只能用自己的 agent 名玩(防冒名),"*" 是管理员
|
|
11
|
+
--cors 加 Access-Control-Allow-Origin: *(给浏览器里的别的前端调用)
|
|
12
|
+
默认只听 127.0.0.1。要给局域网/公网用,请自己加 --host 并配令牌、放在反向代理后面。"""
|
|
13
|
+
import argparse
|
|
14
|
+
import hmac
|
|
15
|
+
import json
|
|
16
|
+
import mimetypes
|
|
17
|
+
import os
|
|
18
|
+
import posixpath
|
|
19
|
+
import sys
|
|
20
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
21
|
+
from urllib.parse import unquote, parse_qs
|
|
22
|
+
|
|
23
|
+
from . import VERSION
|
|
24
|
+
from .web import App
|
|
25
|
+
from . import mcp_server
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Auth(object):
|
|
29
|
+
def __init__(self, token=None, tokens=None):
|
|
30
|
+
self.token = token
|
|
31
|
+
self.tokens = dict(tokens or {})
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def on(self):
|
|
35
|
+
return bool(self.token or self.tokens)
|
|
36
|
+
|
|
37
|
+
def check(self, presented, agent):
|
|
38
|
+
"""返回 None = 通过,否则返回原因。"""
|
|
39
|
+
if not self.on:
|
|
40
|
+
return None
|
|
41
|
+
if not presented:
|
|
42
|
+
return "需要令牌(?token= 或 Authorization: Bearer)/ token required"
|
|
43
|
+
if self.token and hmac.compare_digest(presented, self.token):
|
|
44
|
+
return None
|
|
45
|
+
for tok, who in self.tokens.items():
|
|
46
|
+
if hmac.compare_digest(presented, tok):
|
|
47
|
+
if who == "*" or agent is None or agent == who:
|
|
48
|
+
return None
|
|
49
|
+
return "这个令牌只能用名字 %s / this token can only play as %s" % (who, who)
|
|
50
|
+
return "令牌不对 / bad token"
|
|
51
|
+
|
|
52
|
+
def bound(self, presented):
|
|
53
|
+
"""令牌绑定的 agent 名(管理员 / 共享口令返回 None)。"""
|
|
54
|
+
for tok, who in self.tokens.items():
|
|
55
|
+
if presented and hmac.compare_digest(presented, tok):
|
|
56
|
+
return None if who == "*" else who
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_handler(app, books_dir, auth, cors=False, quiet=False, lang="zh"):
|
|
61
|
+
class H(BaseHTTPRequestHandler):
|
|
62
|
+
server_version = "galbook/" + VERSION
|
|
63
|
+
|
|
64
|
+
def log_message(self, fmt, *a):
|
|
65
|
+
if not quiet:
|
|
66
|
+
sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % a))
|
|
67
|
+
|
|
68
|
+
def _send(self, code, body, ctype, extra=None):
|
|
69
|
+
self.send_response(code)
|
|
70
|
+
self.send_header("Content-Type", ctype)
|
|
71
|
+
self.send_header("Content-Length", str(len(body)))
|
|
72
|
+
self.send_header("Cache-Control", "no-store")
|
|
73
|
+
if cors:
|
|
74
|
+
self.send_header("Access-Control-Allow-Origin", "*")
|
|
75
|
+
self.send_header("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Galplay-Agent, Mcp-Session-Id")
|
|
76
|
+
for k, v in (extra or {}).items():
|
|
77
|
+
self.send_header(k, v)
|
|
78
|
+
self.end_headers()
|
|
79
|
+
if self.command != "HEAD":
|
|
80
|
+
self.wfile.write(body)
|
|
81
|
+
|
|
82
|
+
def do_OPTIONS(self):
|
|
83
|
+
self._send(204, b"", "text/plain")
|
|
84
|
+
|
|
85
|
+
def _play(self, method):
|
|
86
|
+
path, _, query = self.path.partition("?")
|
|
87
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
88
|
+
if n > 65536:
|
|
89
|
+
return self._send(413, b"too large", "text/plain")
|
|
90
|
+
body = self.rfile.read(n) if n > 0 else b""
|
|
91
|
+
parts = [unquote(p) for p in path.split("/") if p]
|
|
92
|
+
needs = len(parts) >= 3 and parts[1] in ("api", "t") and not (parts[1] == "api" and parts[2] == "books")
|
|
93
|
+
if needs and auth.on:
|
|
94
|
+
agent = parts[3] if len(parts) >= 4 and not (parts[1] == "api" and parts[-1] == "players") else None
|
|
95
|
+
q = parse_qs(query)
|
|
96
|
+
tok = (self.headers.get("Authorization") or "").replace("Bearer ", "", 1).strip() or (q.get("token") or [""])[-1]
|
|
97
|
+
why = auth.check(tok, agent)
|
|
98
|
+
if why:
|
|
99
|
+
return self._send(403 if why.startswith("这个令牌只能") else 401, json.dumps({"ok": False, "error": why}, ensure_ascii=False).encode(), "application/json; charset=utf-8")
|
|
100
|
+
r = app.handle(method, path, query, body)
|
|
101
|
+
if r is None:
|
|
102
|
+
return self._send(404, b"not found", "text/plain")
|
|
103
|
+
code, ctype, data = r
|
|
104
|
+
return self._send(code, data, ctype)
|
|
105
|
+
|
|
106
|
+
def _mcp(self):
|
|
107
|
+
path, _, query = self.path.partition("?")
|
|
108
|
+
q = parse_qs(query)
|
|
109
|
+
n = int(self.headers.get("Content-Length") or 0)
|
|
110
|
+
if n > 262144:
|
|
111
|
+
return self._send(413, b"too large", "text/plain")
|
|
112
|
+
body = self.rfile.read(n) if n > 0 else b""
|
|
113
|
+
force = None
|
|
114
|
+
if auth.on:
|
|
115
|
+
tok = (self.headers.get("Authorization") or "").replace("Bearer ", "", 1).strip() or (q.get("token") or [""])[-1]
|
|
116
|
+
why = auth.check(tok, None)
|
|
117
|
+
if why:
|
|
118
|
+
return self._send(401, json.dumps({"error": why}, ensure_ascii=False).encode(), "application/json; charset=utf-8")
|
|
119
|
+
force = auth.bound(tok)
|
|
120
|
+
try:
|
|
121
|
+
req = json.loads(body.decode("utf-8") or "null")
|
|
122
|
+
except ValueError:
|
|
123
|
+
return self._send(400, json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}).encode(),
|
|
124
|
+
"application/json")
|
|
125
|
+
book = (q.get("book") or [None])[-1]
|
|
126
|
+
agent = self.headers.get("X-Galplay-Agent") or (q.get("agent") or [None])[-1]
|
|
127
|
+
lg = (q.get("lang") or [lang])[-1]
|
|
128
|
+
reqs = req if isinstance(req, list) else [req]
|
|
129
|
+
out = [r for r in (mcp_server.handle(app.lib, x, book, agent, lg, force) for x in reqs) if r is not None]
|
|
130
|
+
if not out:
|
|
131
|
+
return self._send(202, b"", "text/plain")
|
|
132
|
+
res = out if isinstance(req, list) else out[0]
|
|
133
|
+
return self._send(200, json.dumps(res, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
|
|
134
|
+
|
|
135
|
+
def do_POST(self):
|
|
136
|
+
if self.path.split("?", 1)[0] == "/mcp":
|
|
137
|
+
return self._mcp()
|
|
138
|
+
if self.path.startswith("/play"):
|
|
139
|
+
return self._play("POST")
|
|
140
|
+
return self._send(404, b"not found", "text/plain")
|
|
141
|
+
|
|
142
|
+
def do_GET(self):
|
|
143
|
+
path = self.path.split("?", 1)[0]
|
|
144
|
+
if path == "/mcp": # 不提供服务端推送流
|
|
145
|
+
return self._send(405, b"method not allowed", "text/plain", {"Allow": "POST"})
|
|
146
|
+
if path == "/":
|
|
147
|
+
return self._send(302, b"", "text/plain", {"Location": "/play/"})
|
|
148
|
+
if path == "/play" or path.startswith("/play/"):
|
|
149
|
+
return self._play("GET")
|
|
150
|
+
if path.startswith("/b/"):
|
|
151
|
+
rest = unquote(path[3:])
|
|
152
|
+
slug, _, sub = rest.partition("/")
|
|
153
|
+
sub = posixpath.normpath("/" + sub).lstrip("/")
|
|
154
|
+
if not slug or slug.startswith(".") or "/" in slug or not sub.startswith("assets/"):
|
|
155
|
+
return self._send(403, b"forbidden", "text/plain")
|
|
156
|
+
base = os.path.realpath(os.path.join(books_dir, slug))
|
|
157
|
+
target = os.path.realpath(os.path.join(base, sub))
|
|
158
|
+
if not target.startswith(base + os.sep) or not os.path.isfile(target):
|
|
159
|
+
return self._send(404, b"not found", "text/plain")
|
|
160
|
+
with open(target, "rb") as f:
|
|
161
|
+
data = f.read()
|
|
162
|
+
return self._send(200, data, mimetypes.guess_type(target)[0] or "application/octet-stream")
|
|
163
|
+
return self._send(404, b"not found", "text/plain")
|
|
164
|
+
|
|
165
|
+
do_HEAD = do_GET
|
|
166
|
+
return H
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def main(argv=None):
|
|
170
|
+
ap = argparse.ArgumentParser(prog="galbook serve", description="galbook 独立服务")
|
|
171
|
+
ap.add_argument("--books", default="books")
|
|
172
|
+
ap.add_argument("--data", default="play-data")
|
|
173
|
+
ap.add_argument("--host", default=os.environ.get("GALBOOK_HOST", "127.0.0.1"))
|
|
174
|
+
ap.add_argument("--port", type=int, default=int(os.environ.get("GALBOOK_PORT", "8765")))
|
|
175
|
+
ap.add_argument("--token", default=os.environ.get("GALBOOK_TOKEN"))
|
|
176
|
+
ap.add_argument("--tokens", help="JSON 文件:{令牌: agent名 或 *}")
|
|
177
|
+
ap.add_argument("--lang", default="zh", choices=("zh", "en"))
|
|
178
|
+
ap.add_argument("--cors", action="store_true")
|
|
179
|
+
ap.add_argument("--quiet", action="store_true")
|
|
180
|
+
ap.add_argument("--no-demo", action="store_true", help="books 为空时不自动装演示书(同 GALBOOK_NO_DEMO=1)")
|
|
181
|
+
a = ap.parse_args(argv)
|
|
182
|
+
if a.no_demo:
|
|
183
|
+
os.environ["GALBOOK_NO_DEMO"] = "1"
|
|
184
|
+
tokens = json.load(open(a.tokens, encoding="utf-8")) if a.tokens else None
|
|
185
|
+
os.makedirs(a.books, exist_ok=True)
|
|
186
|
+
app = App(a.books, a.data, default_lang=a.lang)
|
|
187
|
+
srv = ThreadingHTTPServer((a.host, a.port), make_handler(app, a.books, Auth(a.token, tokens), a.cors, a.quiet, a.lang))
|
|
188
|
+
srv.daemon_threads = True
|
|
189
|
+
print("galbook %s serving http://%s:%d/play/ books=%s data=%s auth=%s" % (
|
|
190
|
+
VERSION, a.host, a.port, os.path.abspath(a.books), os.path.abspath(a.data), "on" if (a.token or tokens) else "off"), flush=True)
|
|
191
|
+
try:
|
|
192
|
+
srv.serve_forever()
|
|
193
|
+
except KeyboardInterrupt:
|
|
194
|
+
pass
|
|
195
|
+
return 0
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
if __name__ == "__main__":
|
|
199
|
+
sys.exit(main())
|