@myclaw163/clawclaw-cli 0.7.6 → 0.7.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/docs/desktop-event-push.md +37 -3
  2. package/docs/runtime/README.md +1 -0
  3. package/docs/runtime/official-perception-modules.md +346 -0
  4. package/package.json +1 -1
  5. package/src/commands/game/index.ts +1 -1
  6. package/src/lib/service-status.test.ts +56 -0
  7. package/src/lib/service-status.ts +111 -0
  8. package/src/pipeline/event-format.test.ts +26 -0
  9. package/src/pipeline/event-format.ts +22 -1
  10. package/src/pipeline/event-hints.test.ts +18 -3
  11. package/src/pipeline/event-hints.ts +11 -0
  12. package/src/pipeline/game-sync-event-normalization.test.ts +54 -1
  13. package/src/pipeline/game-sync-event-normalization.ts +39 -6
  14. package/src/pipeline/player-projection.test.ts +19 -2
  15. package/src/pipeline/player-projection.ts +17 -2
  16. package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
  17. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  18. package/src/runtime/clawclaw/owner.ts +6 -0
  19. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +24 -0
  20. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +29 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +39 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +71 -0
  23. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
  24. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
  25. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
  26. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
  27. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
  28. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
  29. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
  30. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
  31. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
  32. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
  33. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
  34. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
  35. package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
  36. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +214 -1
  37. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +109 -21
  38. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  39. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
  40. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
  41. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
  42. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
  43. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
  44. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
  45. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
  46. package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
  47. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  48. package/src/sdk/perception-plugin/index.ts +14 -0
  49. package/src/sdk/resource-metadata.test.ts +40 -0
  50. package/src/sdk/resource-metadata.ts +63 -0
  51. package/src/sdk/strategy-plugin/index.ts +14 -0
@@ -44,11 +44,30 @@ CCL 每次先查询 `/api/v1/queue/status`;仅当结果为 `in_room` 时,再
44
44
  CCL 连接成功后先发送:
45
45
 
46
46
  ```json
47
- {"schema":"ccl.desktop-events.v1","type":"hello","connection_id":"<uuid>","token":"<nonce>","pid":1234}
47
+ {
48
+ "schema": "ccl.desktop-events.v1",
49
+ "type": "hello",
50
+ "connection_id": "<uuid>",
51
+ "token": "<nonce>",
52
+ "pid": 1234,
53
+ "active_resources": {
54
+ "locale": "zh-CN",
55
+ "strategy": null,
56
+ "perceptions": [
57
+ {
58
+ "id": "visual.visibility",
59
+ "name": "视野变化",
60
+ "description": "感知其他玩家进入、离开或短暂离开后重新出现在视野中。"
61
+ }
62
+ ]
63
+ }
64
+ }
48
65
  ```
49
66
 
50
67
  Desktop 必须校验 `schema`、`connection_id` 和启动时约定的 `token`。
51
68
 
69
+ `active_resources` 是连接建立时的当前资源快照:`strategy` 仅表示已经激活执行的策略,尚未选定时为 `null`;`perceptions` 包含本次 Runtime 已启用的全部感知模块。当前 CCL 固定发送 `zh-CN` 文案。名称和描述来自策略或感知模块自己的 manifest;Desktop IPC 和 Mailbox 不维护模块文案映射。manifest 可继续增加其他 locale,传输结构无需变化。
70
+
52
71
  ## 什么时候发送事件
53
72
 
54
73
  CCL 在以下条件全部满足时发送一个 `mailbox_batch`:
@@ -79,6 +98,21 @@ CCL 在以下条件全部满足时发送一个 `mailbox_batch`:
79
98
  "connection_id": "<uuid>",
80
99
  "seq": 1,
81
100
  "delivery_id": "<stable-delivery-id>",
101
+ "active_resources": {
102
+ "locale": "zh-CN",
103
+ "strategy": {
104
+ "id": "task-only",
105
+ "name": "纯任务",
106
+ "description": "专心做任务。紧急任务出现时优先处理,其次按顺序完成普通任务,如果是蟹,则蟹的伪装任务也会做。没有尸体报告和战斗行为。"
107
+ },
108
+ "perceptions": [
109
+ {
110
+ "id": "visual.motion",
111
+ "name": "玩家移动",
112
+ "description": "感知自己和可见玩家的连续移动片段及显著方向变化。"
113
+ }
114
+ ]
115
+ },
82
116
  "payload": {
83
117
  "schema": "clawclaw.channel-events.v1",
84
118
  "state": {},
@@ -87,7 +121,7 @@ CCL 在以下条件全部满足时发送一个 `mailbox_batch`:
87
121
  }
88
122
  ```
89
123
 
90
- `payload.state` 是当前 Ready View 的紧凑状态,`payload.events` 是本批完整 Agent 事件。
124
+ `payload.state` 是当前 Ready View 的紧凑状态,`payload.events` 是本批完整 Agent 事件。`active_resources` 是这一交付批次创建时的资源快照,Desktop 可据此更新策略和感知窗口;它不属于 `payload` 内的 Agent Mailbox 内容。
91
125
 
92
126
  ## 什么时候不发送
93
127
 
@@ -117,4 +151,4 @@ Desktop 将批次可靠放入自己的输入队列后返回:
117
151
 
118
152
  `connection_id`、`seq` 和 `delivery_id` 必须与当前批次完全一致,否则 ACK 被忽略。CCL 只有收到正确 ACK 后才把事件标记为已交付。
119
153
 
120
- ACK 超时或连接中断时,CCL 会重连并重发未确认批次;重试保持相同 `delivery_id`。Desktop 应按 `delivery_id` 幂等入队,避免“已入队但 ACK 丢失”导致重复唤醒。
154
+ ACK 超时或连接中断时,CCL 会重连并重发未确认批次;重试保持相同 `delivery_id`,并保留该交付首次创建时的 `active_resources` 快照。Desktop 应按 `delivery_id` 幂等入队,避免“已入队但 ACK 丢失”导致重复唤醒。
@@ -18,6 +18,7 @@
18
18
  ### 插件与开发工具
19
19
 
20
20
  - [Strategy Plugin、执行线程与 Action 边界](./strategy-runtime.md):策略怎样消费本轮输入、调用 capability 和热更新参数。
21
+ - [ClawClaw 官方感知模块](./official-perception-modules.md):当前 7 个内置模块分别观察什么、产生哪些 `visual.*` Event,以及默认启用和投递边界。
21
22
  - [自定义感知开发指南](../自定义感知.md):第三方感知模块能读取什么、输出什么以及怎样切片。
22
23
  - [Perception 离线复放](./perception-replay.md):怎样实时查看感知 Event,并把 State/Event 与观战录像对齐。
23
24
 
@@ -0,0 +1,346 @@
1
+ # ClawClaw 官方感知模块
2
+
3
+ 当前 `npm-publish-public` 的 ClawClaw Runtime 内置 7 个官方感知模块。它们都由同一个 `ClawclawPerceptionPlugin` 调度,把当前玩家可见的坐标 State 转成彼此独立的 `visual.*` Canonical Event;模块本身不直接唤醒 Agent,也不拼接跨模块叙事。
4
+
5
+ ## 模块清单
6
+
7
+ | 模块 ID | 观察对象 | 负责判断 | 产出的 Event |
8
+ |---|---|---|---|
9
+ | `visual.visibility` | 其他可见玩家 | 玩家进入视野、离开视野、短时间离开后重新出现 | `visual.player_entered`、`visual.player_left`、`visual.player_reappeared` |
10
+ | `visual.motion` | 自己和其他可见玩家 | 持续移动片段,以及有意义的移动方向变化 | `visual.player_moved`、`visual.player_motion_changed` |
11
+ | `visual.stop` | 自己和其他可见玩家 | 稳定停留,以及停留后确认恢复移动 | `visual.player_stopped`、`visual.player_resumed` |
12
+ | `visual.spatial` | 自己和其他可见玩家 | 已验证的房间切换,以及同一房间内粗粒度方位变化 | `visual.player_area_changed`、`visual.player_position_changed` |
13
+ | `visual.route` | 自己和其他可见玩家 | 路线转弯、折返,以及连续多次局部变向 | `visual.player_turned`、`visual.player_reversed`、`visual.player_wandering` |
14
+ | `visual.co_movement` | 同时可见的玩家对 | 两名玩家近距离、同方向稳定移动,以及这种关系结束 | `visual.players_moving_together`、`visual.players_stopped_moving_together` |
15
+ | `visual.follow` | 同时可见的玩家对 | 带有明确前后位置的稳定跟随关系,以及这种关系结束 | `visual.following`、`visual.following_ended` |
16
+
17
+ 7 个官方模块的 manifest 都声明为 `parallel_analysis`:无状态分析可以在线程池并行执行,模块私有状态和 Event 仍按帧顺序在主线程提交。
18
+
19
+ `visual.co_movement` 只陈述“两人一起移动”,`visual.follow` 进一步陈述谁跟随谁。两者是独立事实;同一段观察同时满足条件时,可以各自产生 Event,不应把其中一个当成另一个的别名。
20
+
21
+ ## 输出示例(真实日志)
22
+
23
+ 以下示例来自真实 Runtime 导出的 `event-ledger/events.jsonl`。其中 15 种 Event 来自 2026-08-03 的同一局,`visual.player_reappeared` 来自 2026-07-30 的另一局;日志本身以座位号表示玩家,不包含账号信息。为突出模块输出,这里只保留 `type` 和解码后的 `payload_json`,省略 Canonical Ledger 外层的 `commit_seq`、`event_id`、session/segment、投递类别和时间戳。
24
+
25
+ ### `visual.visibility`
26
+
27
+ ```json
28
+ [
29
+ {
30
+ "type": "visual.player_entered",
31
+ "payload": {
32
+ "from_tick": 140,
33
+ "to_tick": 140,
34
+ "actors": [1],
35
+ "text": "0:14,1号从左侧进入视野,位于5号走廊中部。",
36
+ "data": {
37
+ "player_id": "seat:1",
38
+ "side": "左",
39
+ "place": "5号走廊中部"
40
+ }
41
+ }
42
+ },
43
+ {
44
+ "type": "visual.player_left",
45
+ "payload": {
46
+ "from_tick": 311,
47
+ "to_tick": 311,
48
+ "actors": [1],
49
+ "text": "0:31,1号从右侧离开你的视野。",
50
+ "data": {
51
+ "player_id": "seat:1",
52
+ "side": "右",
53
+ "last_place": "自助餐厅下侧"
54
+ }
55
+ }
56
+ },
57
+ {
58
+ "type": "visual.player_reappeared",
59
+ "payload": {
60
+ "from_tick": 782,
61
+ "to_tick": 782,
62
+ "actors": [9],
63
+ "text": "1:18,9号重新出现在视野中,位于休闲会所中部。",
64
+ "data": {
65
+ "player_id": "seat:9",
66
+ "side": "左",
67
+ "place": "休闲会所中部"
68
+ }
69
+ }
70
+ }
71
+ ]
72
+ ```
73
+
74
+ ### `visual.motion`
75
+
76
+ ```json
77
+ [
78
+ {
79
+ "type": "visual.player_moved",
80
+ "payload": {
81
+ "from_tick": 123,
82
+ "to_tick": 141,
83
+ "actors": [6],
84
+ "status": "ongoing",
85
+ "text": "0:12-0:14,你从情报室中部移动到5号走廊右侧,目前仍在移动。",
86
+ "data": {
87
+ "player_id": "seat:6",
88
+ "direction": "左下",
89
+ "from_place": "情报室中部",
90
+ "to_place": "5号走廊右侧",
91
+ "path_length_px": 216
92
+ }
93
+ }
94
+ },
95
+ {
96
+ "type": "visual.player_motion_changed",
97
+ "payload": {
98
+ "from_tick": 291,
99
+ "to_tick": 291,
100
+ "actors": [6],
101
+ "text": "0:29,你由向左下移动改为向左移动。",
102
+ "data": {
103
+ "player_id": "seat:6",
104
+ "from_direction": "左下",
105
+ "to_direction": "左"
106
+ }
107
+ }
108
+ }
109
+ ]
110
+ ```
111
+
112
+ `visual.player_moved` 是一个带 tick 范围的移动片段。片段尚未结束时会带 `status: "ongoing"`;关闭或查询边界下也可能出现 `closed` 等状态,而不是每个坐标点各发一个 Event。
113
+
114
+ ### `visual.stop`
115
+
116
+ ```json
117
+ [
118
+ {
119
+ "type": "visual.player_stopped",
120
+ "payload": {
121
+ "from_tick": 140,
122
+ "to_tick": 150,
123
+ "actors": [1],
124
+ "text": "0:14-0:15,1号在5号走廊中部停留了1秒。",
125
+ "data": {
126
+ "player_id": "seat:1",
127
+ "place": "5号走廊中部",
128
+ "duration_secs": 1
129
+ }
130
+ }
131
+ },
132
+ {
133
+ "type": "visual.player_resumed",
134
+ "payload": {
135
+ "from_tick": 186,
136
+ "to_tick": 188,
137
+ "actors": [1],
138
+ "text": "0:18,1号在5号走廊中部停留了4.6秒后继续移动。",
139
+ "data": {
140
+ "player_id": "seat:1",
141
+ "from_place": "5号走廊中部",
142
+ "stop_duration_secs": 4.6,
143
+ "movement_confirmation_secs": 0.2
144
+ }
145
+ }
146
+ }
147
+ ]
148
+ ```
149
+
150
+ ### `visual.spatial`
151
+
152
+ ```json
153
+ [
154
+ {
155
+ "type": "visual.player_area_changed",
156
+ "payload": {
157
+ "from_tick": 137,
158
+ "to_tick": 137,
159
+ "actors": [6],
160
+ "text": "0:13,你从情报室进入5号走廊。",
161
+ "data": {
162
+ "player_id": "seat:6",
163
+ "from_area": "情报室",
164
+ "to_area": "5号走廊",
165
+ "map_transition_verified": true
166
+ }
167
+ }
168
+ },
169
+ {
170
+ "type": "visual.player_position_changed",
171
+ "payload": {
172
+ "from_tick": 245,
173
+ "to_tick": 245,
174
+ "actors": [1],
175
+ "text": "0:24,1号从中央厨房右侧移动到中央厨房中部。",
176
+ "data": {
177
+ "player_id": "seat:1",
178
+ "area": "中央厨房",
179
+ "from_side": "右侧",
180
+ "to_side": "中部"
181
+ }
182
+ }
183
+ }
184
+ ]
185
+ ```
186
+
187
+ `map_transition_verified: true` 表示空间模型确认了这次房间切换;没有该证据时,文本只会陈述区域值发生变化,不会虚构房间连通关系。
188
+
189
+ ### `visual.route`
190
+
191
+ ```json
192
+ [
193
+ {
194
+ "type": "visual.player_turned",
195
+ "payload": {
196
+ "from_tick": 298,
197
+ "to_tick": 298,
198
+ "actors": [2],
199
+ "text": "0:29,2号转向并改为向左上移动。",
200
+ "data": {
201
+ "player_id": "seat:2",
202
+ "direction": "左上"
203
+ }
204
+ }
205
+ },
206
+ {
207
+ "type": "visual.player_reversed",
208
+ "payload": {
209
+ "from_tick": 639,
210
+ "to_tick": 639,
211
+ "actors": [3],
212
+ "text": "1:03,3号折返并改为向左下移动。",
213
+ "data": {
214
+ "player_id": "seat:3",
215
+ "direction": "左下"
216
+ }
217
+ }
218
+ },
219
+ {
220
+ "type": "visual.player_wandering",
221
+ "payload": {
222
+ "from_tick": 625,
223
+ "to_tick": 644,
224
+ "actors": [3],
225
+ "text": "1:02-1:04,3号在附近多次转向或折返。",
226
+ "data": {
227
+ "player_id": "seat:3",
228
+ "reversal_count": 1,
229
+ "path_length_px": 211,
230
+ "net_distance_px": 72
231
+ }
232
+ }
233
+ }
234
+ ]
235
+ ```
236
+
237
+ ### `visual.co_movement`
238
+
239
+ ```json
240
+ [
241
+ {
242
+ "type": "visual.players_moving_together",
243
+ "payload": {
244
+ "from_tick": 297,
245
+ "to_tick": 309,
246
+ "actors": [6, 2],
247
+ "text": "0:29-0:30,你和2号近距离同方向移动。",
248
+ "data": {
249
+ "player_ids": ["seat:6", "seat:2"],
250
+ "average_distance_px": 29
251
+ }
252
+ }
253
+ },
254
+ {
255
+ "type": "visual.players_stopped_moving_together",
256
+ "payload": {
257
+ "from_tick": 343,
258
+ "to_tick": 343,
259
+ "actors": [6, 2],
260
+ "text": "0:34,你和2号不再保持同方向共同移动。",
261
+ "data": {
262
+ "player_ids": ["seat:6", "seat:2"],
263
+ "reason": "movement_diverged"
264
+ }
265
+ }
266
+ }
267
+ ]
268
+ ```
269
+
270
+ ### `visual.follow`
271
+
272
+ ```json
273
+ [
274
+ {
275
+ "type": "visual.following",
276
+ "payload": {
277
+ "from_tick": 297,
278
+ "to_tick": 309,
279
+ "actors": [2, 6],
280
+ "text": "0:29-0:30,2号疑似跟在你后方约1个身位同方向移动。",
281
+ "data": {
282
+ "follower_id": "seat:2",
283
+ "leader_id": "seat:6",
284
+ "confidence": "medium",
285
+ "average_distance_px": 29,
286
+ "body_lengths": 1
287
+ }
288
+ }
289
+ },
290
+ {
291
+ "type": "visual.following_ended",
292
+ "payload": {
293
+ "from_tick": 343,
294
+ "to_tick": 343,
295
+ "actors": [2, 6],
296
+ "text": "0:34,2号不再保持跟在你后方。",
297
+ "data": {
298
+ "follower_id": "seat:2",
299
+ "leader_id": "seat:6",
300
+ "reason": "formation_lost"
301
+ }
302
+ }
303
+ }
304
+ ]
305
+ ```
306
+
307
+ 这组真实日志也展示了两个关系模块的独立性:相同的 tick 297–309 同时产生了 `players_moving_together` 和 `following`,但两者的 `actors` 语义不同。共同移动只列参与者;跟随严格按 `[follower, leader]` 排列,并在 `data` 中给出方向角色。
308
+
309
+ ## 观察边界
310
+
311
+ 官方模块只使用 CCL 从当前 Agent State 投影出的视觉输入:自己 `you`、`visible_players`、`visible_corpses` 及其当前坐标和已知房间。当前 7 个模块只分析玩家;官方注册表里暂时没有尸体专用模块。
312
+
313
+ 这些模块遵守以下边界:
314
+
315
+ - 只把自由移动阶段(`wandering`)的连续视觉帧用于移动、路线和关系判断;阶段切换或轨迹中断会结束或重建模块私有基线。
316
+ - 同一个 game tick 的多份 State 是修订,不是多次独立观察。模块按最终修订提交,避免用中间坐标制造虚假移动或关系变化。
317
+ - 不可见玩家不会被继续追踪。输入未明确给出完整可见集合时,缺席只表示未知,不能据此生成 `player_left`。
318
+ - 模块只报告有证据的视觉事实,不推断目的地、阵营、身份、意图、任务完成、击杀或其他不可见信息。
319
+ - 各模块分别维护状态并分别产出 Event。Event 可以用玩家 ID 和 tick 范围关联,但 Perception 不把多个模块的结果组装成一段自然语言轨迹。
320
+
321
+ ## 默认启用和投递
322
+
323
+ 7 个官方模块默认全部启用。查看当前工作区实际存在的官方/自定义模块及禁用状态:
324
+
325
+ ```bash
326
+ ccl perception --list
327
+ ```
328
+
329
+ 模块开关写入 `<workspace>/user-data/gameplay.json`,并在下一次 Runtime 启动时生效:
330
+
331
+ ```bash
332
+ ccl perception --disable visual.follow
333
+ ccl perception --enable visual.follow
334
+ ```
335
+
336
+ 是否运行模块和 Event 如何投递是两件事。未单独配置的 `visual.*` Event 默认是 `events_only`,会进入 `ccl events`,但不会主动唤醒 Monitor。可以在 `<workspace>/config.json` 的 `events.delivery` 中按 Event type 改成:
337
+
338
+ - `monitor_and_events`:进入 Monitor 和 `ccl events`;
339
+ - `events_only`:只进入 `ccl events`;
340
+ - `internal_only`:只保存在 Canonical Event Ledger。
341
+
342
+ 完整配置规则见 [Workspace、更新与自定义 TTS](../configuration.md),第三方模块接口见 [自定义感知开发指南](../自定义感知.md),复放和逐帧核对方法见 [Perception 离线复放](./perception-replay.md)。
343
+
344
+ ## 实现真值
345
+
346
+ 本文的官方清单对应 `src/runtime/clawclaw/plugins/perception/official-module-ids.ts` 和 `official-modules.ts` 的闭合注册表。判断某个模块是否已经成为官方运行时能力时,以该注册表、模块 manifest 和 `ccl perception --list` 为准;仅存在设计稿、测试辅助模块或 Event Catalog 条目,不代表它已被官方默认装载。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.7.6",
3
+ "version": "0.7.8",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -166,7 +166,7 @@ async function runOwner(
166
166
  ? { desktopEvents: options.desktopEvents }
167
167
  : { notificationHost: notifications }),
168
168
  });
169
- if (completion.reason === 'error') process.exitCode = 1;
169
+ if (completion.reason === 'error' || completion.reason === 'maintenance') process.exitCode = 1;
170
170
  } catch (error) {
171
171
  try {
172
172
  await notifications.reportBootstrapFailure(
@@ -0,0 +1,56 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { ApiError } from './http-transport.js';
3
+ import { jsonTransportResponse } from '../short-command/transport-response.js';
4
+ import {
5
+ isServiceMaintenanceApiError,
6
+ parseServerServiceStatus,
7
+ serverServiceStatusFromApiError,
8
+ serverServiceStatusFromEnvelope,
9
+ } from './service-status.js';
10
+
11
+ const maintenance = {
12
+ starts_at: '2026-08-05T01:00:00+00:00',
13
+ ends_at: '2026-08-05T03:00:00+00:00',
14
+ };
15
+
16
+ describe('service status contract', () => {
17
+ it('extracts upcoming maintenance from a successful Lobby envelope', () => {
18
+ expect(serverServiceStatusFromEnvelope({
19
+ success: true,
20
+ data: { status: 'queued' },
21
+ server: { service_status: 'maintenance_upcoming', maintenance },
22
+ })).toEqual({ service_status: 'maintenance_upcoming', maintenance });
23
+ });
24
+
25
+ it('extracts active maintenance and Retry-After from an ApiError', () => {
26
+ const payload = {
27
+ success: false,
28
+ error: { code: 'SERVICE_MAINTENANCE', message: 'Service is under maintenance' },
29
+ server: { service_status: 'maintenance_active', maintenance },
30
+ };
31
+ const response = jsonTransportResponse(payload, {
32
+ method: 'GET',
33
+ path: '/api/v1/queue/status',
34
+ status: 503,
35
+ headers: { 'content-type': 'application/json', 'retry-after': '7200' },
36
+ });
37
+ const error = new ApiError(503, response.body.rawText, 'GET', response.path, response);
38
+
39
+ expect(serverServiceStatusFromApiError(error)).toEqual({
40
+ service_status: 'maintenance_active',
41
+ maintenance,
42
+ retry_after_seconds: 7200,
43
+ });
44
+ expect(isServiceMaintenanceApiError(error)).toBe(true);
45
+ });
46
+
47
+ it('rejects unrelated 503 responses and malformed status values', () => {
48
+ const response = jsonTransportResponse({ error: { code: 'UPSTREAM_UNAVAILABLE' } }, {
49
+ status: 503,
50
+ });
51
+ const error = new ApiError(503, response.body.rawText, 'GET', '/api/v1/queue/status', response);
52
+
53
+ expect(serverServiceStatusFromApiError(error)).toBeUndefined();
54
+ expect(parseServerServiceStatus({ service_status: 'paused' })).toBeUndefined();
55
+ });
56
+ });
@@ -0,0 +1,111 @@
1
+ import { ApiError } from './http-transport.js';
2
+
3
+ export type ServiceStatus = 'available' | 'maintenance_upcoming' | 'maintenance_active';
4
+
5
+ export interface MaintenanceWindow {
6
+ starts_at: string;
7
+ ends_at: string;
8
+ }
9
+
10
+ export interface ServerServiceStatus {
11
+ service_status: ServiceStatus;
12
+ maintenance?: MaintenanceWindow;
13
+ retry_after_seconds?: number;
14
+ }
15
+
16
+ function objectValue(value: unknown): Record<string, unknown> | undefined {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
18
+ ? value as Record<string, unknown>
19
+ : undefined;
20
+ }
21
+
22
+ function serviceStatusValue(value: unknown): ServiceStatus | undefined {
23
+ return value === 'available'
24
+ || value === 'maintenance_upcoming'
25
+ || value === 'maintenance_active'
26
+ ? value
27
+ : undefined;
28
+ }
29
+
30
+ function maintenanceWindow(value: unknown): MaintenanceWindow | undefined {
31
+ const root = objectValue(value);
32
+ if (!root) return undefined;
33
+ const startsAt = typeof root.starts_at === 'string' ? root.starts_at : undefined;
34
+ const endsAt = typeof root.ends_at === 'string' ? root.ends_at : undefined;
35
+ return startsAt && endsAt ? { starts_at: startsAt, ends_at: endsAt } : undefined;
36
+ }
37
+
38
+ function retryAfterSeconds(value: unknown): number | undefined {
39
+ if (typeof value !== 'string' && typeof value !== 'number') return undefined;
40
+ const parsed = Number(value);
41
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
42
+ }
43
+
44
+ /** Parse the public server-status shape itself, without assigning transport behavior. */
45
+ export function parseServerServiceStatus(value: unknown): ServerServiceStatus | undefined {
46
+ const root = objectValue(value);
47
+ if (!root) return undefined;
48
+ const status = serviceStatusValue(root.service_status);
49
+ if (!status) return undefined;
50
+ const maintenance = maintenanceWindow(root.maintenance);
51
+ return {
52
+ service_status: status,
53
+ ...(maintenance ? { maintenance } : {}),
54
+ };
55
+ }
56
+
57
+ /** Extract the optional top-level `server` metadata added to successful Lobby responses. */
58
+ export function serverServiceStatusFromEnvelope(value: unknown): ServerServiceStatus | undefined {
59
+ return parseServerServiceStatus(objectValue(value)?.server);
60
+ }
61
+
62
+ /** Extract an active-maintenance fact from the structured Lobby 503 response. */
63
+ export function serverServiceStatusFromApiError(error: unknown): ServerServiceStatus | undefined {
64
+ if (!(error instanceof ApiError)) return undefined;
65
+ let root: Record<string, unknown> | undefined;
66
+ if (error.response?.body.kind === 'json') {
67
+ root = objectValue(error.response.body.value);
68
+ }
69
+ if (!root) {
70
+ try {
71
+ root = objectValue(JSON.parse(error.body));
72
+ } catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ const errorValue = objectValue(root?.error);
77
+ const status = parseServerServiceStatus(root?.server);
78
+ if (
79
+ errorValue?.code !== 'SERVICE_MAINTENANCE'
80
+ && status?.service_status !== 'maintenance_active'
81
+ ) return undefined;
82
+ if (!status) return undefined;
83
+ const retryAfter = retryAfterSeconds(error.response?.headers['retry-after']);
84
+ return {
85
+ ...status,
86
+ ...(retryAfter === undefined ? {} : { retry_after_seconds: retryAfter }),
87
+ };
88
+ }
89
+
90
+ export function isServiceMaintenanceApiError(error: unknown): boolean {
91
+ return serverServiceStatusFromApiError(error)?.service_status === 'maintenance_active';
92
+ }
93
+
94
+ export function serviceStatusEvent(status: ServerServiceStatus): Record<string, unknown> {
95
+ return {
96
+ type: 'service_status',
97
+ service_status: status.service_status,
98
+ ...(status.maintenance ? { maintenance: structuredClone(status.maintenance) } : {}),
99
+ ...(status.retry_after_seconds === undefined
100
+ ? {}
101
+ : { retry_after_seconds: status.retry_after_seconds }),
102
+ };
103
+ }
104
+
105
+ export function serviceStatusSignature(status: ServerServiceStatus): string {
106
+ return JSON.stringify([
107
+ status.service_status,
108
+ status.maintenance?.starts_at ?? null,
109
+ status.maintenance?.ends_at ?? null,
110
+ ]);
111
+ }
@@ -3,6 +3,19 @@ import { compactEventFields, compactStateForEvents, formatEventMessage, shortSta
3
3
  import { BACKEND_EVENT_HINT_FORMATTERS } from './event-hints.js';
4
4
 
5
5
  describe('event-format', () => {
6
+ it('formats upcoming and active maintenance as explicit service messages', () => {
7
+ const maintenance = {
8
+ starts_at: '2026-08-05T01:00:00+00:00',
9
+ ends_at: '2026-08-05T03:00:00+00:00',
10
+ };
11
+ expect(formatEventMessage({
12
+ type: 'service_status', service_status: 'maintenance_upcoming', maintenance,
13
+ })).toContain('当前请求仍可继续');
14
+ expect(formatEventMessage({
15
+ type: 'service_status', service_status: 'maintenance_active', maintenance,
16
+ })).toContain('新的匹配和房间操作已停止');
17
+ });
18
+
6
19
  it('formats killed as a short message and keeps direct compaction separate from presentation ownership', () => {
7
20
  const event = {
8
21
  type: 'killed',
@@ -24,6 +37,19 @@ describe('event-format', () => {
24
37
  expect(JSON.stringify(formatted)).not.toContain('Your hands are off the board');
25
38
  });
26
39
 
40
+ it('formats a system killer without a fake player seat', () => {
41
+ const message = formatEventMessage({
42
+ type: 'killed',
43
+ tick: 41,
44
+ room: '制氧舱',
45
+ killer_kind: 'system',
46
+ killer_name: 'Shrimp God',
47
+ });
48
+
49
+ expect(message).toContain('被Shrimp God击杀');
50
+ expect(message).not.toContain('?号Shrimp God');
51
+ });
52
+
27
53
  it('keeps meeting_briefing details aligned with the compact monitor payload', () => {
28
54
  const formatted = compactEventFields({
29
55
  type: 'meeting_briefing',