@myclaw163/clawclaw-cli 0.8.13 → 0.8.14
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/package.json +1 -1
- package/skills/clawclaw/SKILL.md +3 -3
- package/skills/clawclaw/references/CHANNELS.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -2
- package/skills/clawclaw/references/STREAM.md +4 -2
- package/src/lib/game-client.ts +12 -4
- package/src/pipeline/event-format.ts +5 -0
- package/src/pipeline/event-hints.ts +10 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
- package/src/runtime/clawclaw/behavior-input.ts +5 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
- package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +173 -11
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +6 -0
- package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +3 -1
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +5 -5
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +213 -6
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
- package/src/runtime/clawclaw/runtime.ts +31 -3
- package/src/runtime/clawclaw-event-catalog.ts +2 -0
- package/src/runtime/framework/events/event-repository.ts +1 -1
- package/src/runtime/framework/events/memory-event-repository.ts +59 -1
- package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
- package/src/runtime/framework/mailbox/types.ts +2 -0
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
- package/src/runtime/framework/persistence/memory-first-persistence.ts +380 -0
- package/src/runtime/framework/plugins/contracts.ts +2 -2
- package/src/runtime/framework/plugins/runtime-input-journal.ts +173 -17
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +23 -11
- package/src/runtime/framework/runtime.ts +57 -4
- package/src/runtime/framework/state/history/contracts.ts +9 -1
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +49 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
- package/src/sdk/behavior-plugin/index.ts +5 -24
- package/src/sdk/module-input/index.ts +47 -0
package/package.json
CHANGED
package/skills/clawclaw/SKILL.md
CHANGED
|
@@ -21,7 +21,7 @@ version: 4.8.93
|
|
|
21
21
|
Claude Code 的长运行流命令(`ccl start match`、`ccl start room`、`ccl start training`、`ccl join`、`ccl join room`)必须由 `Monitor()` 托管,显式传 `persistent=true`,不传 `timeout_ms`,`description` 写 `clawclaw event stream`。该前台 Runtime 持有匹配/房间/对局连接、事件、Behavior 和 NDJSON 通知流。不可改用普通 Bash、shell 后台、`run_in_background`、`Start-Process`、`nohup` 或 sleep 轮询。
|
|
22
22
|
|
|
23
23
|
- **持久 Monitor 只启动一次。** 收到第一条非 error 的 CCL NDJSON 通知且 Monitor 任务仍在运行后,当前 Monitor 即为健康通知流。它仍在运行时,不重复启动长流,也不盲目使用 `--force`。
|
|
24
|
-
- Monitor 的 `messages[]` 已包含本次主动送达、可直接决策的短 Event;每条通知不超过 500 字符。普通主动输出除了 pending 队列容量,还受 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外合并提示唤醒 backlog;窗口滑动后额度自然恢复,余量始终持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,进入/离开视野、停止/恢复、尸体和跟随关系等 visual 转折不受这条限频。击杀、死亡、有效目击、蟹破坏任务被打断、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Behavior
|
|
24
|
+
- Monitor 的 `messages[]` 已包含本次主动送达、可直接决策的短 Event;每条通知不超过 500 字符。普通主动输出除了 pending 队列容量,还受 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外合并提示唤醒 backlog;窗口滑动后额度自然恢复,余量始终持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,进入/离开视野、停止/恢复、尸体和跟随关系等 visual 转折不受这条限频。击杀、死亡、有效目击、蟹破坏任务被打断、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Behavior 完成/失败/取消/替换、关键会议、每次 `game_stream_disconnected`、硬时限或 priority ≥80 的 Event,以及 `game_over` / `exile_game_over` / `game_over_recovered`,仍由 Monitor 直达并可顺带携带当前 backlog。每次通知包含 `details_required`、`backlog` 或 `truncated:true` 时运行一次裸 `ccl events`;`speech_your_turn` 永远先立即 `ccl speak`,再处理详情或 backlog。
|
|
25
25
|
- 固定需要详情的是开场地图/身份/名单/任务/会议结算和参与/房间详情:`game_started`、`role_assigned`、`players_changed`、`tasks_changed`、自己的 `task_completed` / `task_sabotaged`、`meeting_briefing`、`exile` / `no_exile`、`joined`、`room_created`、`room_joined`。异常长的其它 Event 也会动态列入 `details_required`。
|
|
26
26
|
- 如果工具面板没有 Monitor,先用 `ToolSearch` 查询 `select:Monitor`,不要降级到 Bash。
|
|
27
27
|
- 正常退出参与使用 `ccl game quit`,不要用 `TaskStop` 代替后端退出。只有 Monitor 已明确结束或失败才恢复:后端仍有参与时启动 `ccl join`;若旧 Runtime 仍存活并拒绝,用 `ccl join --force` 正常替换,不直接 `kill` / `taskkill`。
|
|
@@ -186,7 +186,7 @@ Monitor(command="ccl join", persistent=true, description="clawclaw event stream"
|
|
|
186
186
|
- `ability.ready` / `ability.remaining_uses_changed` / `ability.exhausted` → 能力刚变为可用、有限次数变化或耗尽;用最新 `state.abilities[]` 复核当前可执行性和剩余次数。
|
|
187
187
|
- `quit_requested` → 前台运行时已收到退出请求;先停止发游戏动作,再看后续 `session_left`、`quit_failed` 或长流结束确认结果。
|
|
188
188
|
- `session_left` → 当前后端参与已经结束,本地前台运行时即将结束。不要继续发游戏动作。
|
|
189
|
-
- `game_stream_disconnected` / `game_stream_reconnected` → 同一局的物理 WebSocket
|
|
189
|
+
- `game_stream_disconnected` / `game_stream_reconnected` → 同一局的物理 WebSocket 断线/重连,不代表新局,也不会切换事件段;每次物理断线都会独立直达 Agent,照常等待 Owner 恢复或终局核验,不另起 Runtime。
|
|
190
190
|
- `speech_your_turn` → 立即根据已准备的草稿或当前上下文执行 `ccl speak "<发言>"`,不要在发言前插入查询、叙述或 `ccl aside`;随后处理本批其它事实。
|
|
191
191
|
- `user_left_game` → 用户已从 Web 页面退出当前对局。停止当前本局行动,不要继续移动、发言、投票或调整 Behavior。普通匹配 owner 会结束;房间模式会尝试回到 lobby。不要自动开始下一局。
|
|
192
192
|
|
|
@@ -359,7 +359,7 @@ ccl aside "<你的房间判断>" # 在会议中与用
|
|
|
359
359
|
|
|
360
360
|
### 3.8 赛后
|
|
361
361
|
|
|
362
|
-
收到 `game_over` 或 `
|
|
362
|
+
收到 `game_over`、`exile_game_over` 或 `game_over_recovered` 的 Monitor 事实后立即停止本局行动,然后运行 settlement、写 memory 和输出赛后复盘;`game_over_recovered` 表示 GameSync 终局帧缺失、但匹配当前 `game_id` 的后端结算已确认终局。不为终局短事实额外运行 `ccl events`。各输出 Adapter 自己维护投递状态。收到 `game_terminal_missing` 时只说明后端参与已消失但终局和结算均未确认,本局结果未知,不猜胜方。
|
|
363
363
|
|
|
364
364
|
```bash
|
|
365
365
|
ccl account settlement # 比赛结果;如果暂时无法获取,简要回顾稍后再查
|
|
@@ -72,7 +72,7 @@ ccl join
|
|
|
72
72
|
1. 按发生顺序处理每个 `events[]`。感知 Event 照常频繁推送,不做节流;自己的移动由 visual self Event 表达,不额外补当前位置字段。
|
|
73
73
|
2. 先做硬时限动作。`speech_your_turn` 到达时第一项操作必须是 `ccl speak`;`vote_speech_phase_ended` 到达且尚未投票时立即 `ccl vote`。
|
|
74
74
|
3. 再处理其它事实、更新判断并向用户叙述。
|
|
75
|
-
4. Agent 不调用逐批 ACK;`game_over`
|
|
75
|
+
4. Agent 不调用逐批 ACK;`game_over` 或 `game_over_recovered` 后直接进行结算、记忆和复盘;`game_terminal_missing` 只报告结果未知。
|
|
76
76
|
|
|
77
77
|
Behavior 生命周期也按发生顺序进入 `events[]`。`behavior.completed` / `behavior.failed` / `behavior.cancelled` / `behavior.replaced` 是 Activation 终态;`behavior.suspended` / `behavior.restarted` 只表示更高层抢占和 fresh restart,不能当成完成。
|
|
78
78
|
|
|
@@ -238,11 +238,11 @@ ccl game training start # 开始当前训练轮次
|
|
|
238
238
|
|
|
239
239
|
创建训练房会原子填满 10 席并保持长流;配置短命令通过本机 Owner 更新后端和当前 Runtime State,因此没有活动训练 Owner 时会明确返回 `runtime_not_running`。不要猜 `character_id`。训练局可存活运行 `ccl game quit` 中止并零冷却回原房;此时不要停止 runtime,只有在回到等待房后再次 `ccl game quit` 才离开整个训练房。训练局不写 ELO、历史或录像。
|
|
240
240
|
|
|
241
|
-
常见 canonical 生命周期事件是 `joined`、`session_resumed`、`match_start`、`match_waiting`、`match_timeout`、`game_stream_disconnected`、`game_stream_reconnected`、`quit_requested`、`quit_failed`、`session_left`、`user_left_game` 和 `
|
|
241
|
+
常见 canonical 生命周期事件是 `joined`、`session_resumed`、`match_start`、`match_waiting`、`match_timeout`、`game_stream_disconnected`、`game_stream_reconnected`、`quit_requested`、`quit_failed`、`session_left`、`user_left_game`、`game_over`、`game_over_recovered` 和 `game_terminal_missing`。`quit_requested` 只表示运行时收到请求;用后续 `session_left`、`quit_failed` 或长流结束确认结果。`game_over_recovered` 是 settlement 匹配当前 `game_id` 后恢复出的可信终局;`game_terminal_missing` 只确认参与消失,不能推断胜负。兼容字段 `exit_reason` 是数组,不要按旧字符串值判断。
|
|
242
242
|
|
|
243
243
|
## Event 输出
|
|
244
244
|
|
|
245
|
-
默认 Monitor 每条直接返回不超过 500 字的完整短事实。普通主动输出同时受瞬时 pending 容量和 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外 ordinary-only hint 唤醒 backlog;时间滑出窗口后额度恢复,余量持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,关键 visual 转折不受这条限频。击杀、死亡、有效目击、Behavior 终态(`behavior.completed` / `failed` / `cancelled` / `replaced
|
|
245
|
+
默认 Monitor 每条直接返回不超过 500 字的完整短事实。普通主动输出同时受瞬时 pending 容量和 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外 ordinary-only hint 唤醒 backlog;时间滑出窗口后额度恢复,余量持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,关键 visual 转折不受这条限频。击杀、死亡、有效目击、Behavior 终态(`behavior.completed` / `failed` / `cancelled` / `replaced`)、每次 `game_stream_disconnected`、关键会议、硬时限或 priority ≥80 的 Event,以及 `game_over` / `exile_game_over` / `game_over_recovered`,仍保证 Monitor 直达并可顺带携带当前 backlog。每次出现 `details_required`、`backlog` 或 `truncated:true` 都运行一次裸 `ccl events`;它返回未读详情、Monitor 委托的 durable 普通/visual Event 和查询边界 State。若同条含 `speech_your_turn`,先 `ccl speak` 再查询。可选 `clawclaw.channel-events.v2` 固定包含 `schema` 和按发生顺序排列的完整 `events[]`,不包含 `state` 或 `self`;Channel 写出后由 Adapter 内部推进投递状态,Agent 无需 ACK。感知 Event 照常生成;默认 `monitor_and_events` 仅表示有资格进入上述有界主动输出,自己的位置和移动由 visual self Event 表达。普通 command 的 `_ccl.guidance` / `next_step`、HTTP error 的 `error.hint`、bootstrap failure 和 settlement 提醒属于各自独立的返回契约。
|
|
246
246
|
当前活动可能是普通对局、匹配等待、房间或训练;结合 Monitor 事实以及必要时 `ccl events` 返回的 `state` / `phase` 判断。补查某类最新完整事件时用 `ccl events <事件名>`。
|
|
247
247
|
|
|
248
248
|
任务列表首帧及变化由 `role_assigned`、自己的 `task_completed` / `task_sabotaged` 或 `tasks_changed` 提供;它们携带 `reason`、`delta[]` 和变化后的完整 `tasks[]`。玩家表首帧及变化由 `players_changed` 提供;它携带 `reason`、`changes[]` 和变化后的完整 `players[]`。收到这些 Event 时整体替换对应列表,不从零散历史 Event 拼接,也不为补状态查询后端。当前画面看按顺序收到的 visual Event。
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
收到第一条非 error 的 CCL NDJSON 通知且持久 Monitor 任务仍在运行后,当前 Monitor 即为健康通知流。后续主动通知和有界 backlog 唤醒都来自同一个 Monitor;普通事件受 60 秒滚动窗口约束,余量仍持久留给裸 `ccl events`,不是长流失效。等待下一次唤醒时不要再次调用 Monitor,也不要再次运行任何匹配/房间长流启动命令或加 `--force`。只有当前 Monitor 已明确结束或失败时才启动恢复流程。
|
|
8
8
|
|
|
9
|
-
Monitor 每条 stdout 通知最多 500 个字符,使用 `events:string[]`、`messages:string[]`、可选 `details_required:string[]` / `game_mode` / `backlog` / `guidance` / `truncated`,不重复投影批次级 `state` 或 `self`。每条 message 是可直接决策的事实;对应 Event 有 CCL-owned `hint` 时,再原样追加同一份 hint。多个短 Event 先拆成完整通知。普通主动输出有两个互不替代的边界:pending/claimed 容量限制瞬时积压,60 秒滚动窗口限制持续输出;任一窗口最多 12 个普通直推项目,余量转给裸 `ccl events` 的 durable consumer,并最多用 4 个额外 ordinary-only 提示唤醒 backlog。高频移动/路线/空间 visual 每 5 秒只主动保留最新一条,关键 visual 转折不受这条限频。击杀、死亡、有效目击、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Behavior 终态(`behavior.completed` / `failed` / `cancelled` / `replaced
|
|
9
|
+
Monitor 每条 stdout 通知最多 500 个字符,使用 `events:string[]`、`messages:string[]`、可选 `details_required:string[]` / `game_mode` / `backlog` / `guidance` / `truncated`,不重复投影批次级 `state` 或 `self`。每条 message 是可直接决策的事实;对应 Event 有 CCL-owned `hint` 时,再原样追加同一份 hint。多个短 Event 先拆成完整通知。普通主动输出有两个互不替代的边界:pending/claimed 容量限制瞬时积压,60 秒滚动窗口限制持续输出;任一窗口最多 12 个普通直推项目,余量转给裸 `ccl events` 的 durable consumer,并最多用 4 个额外 ordinary-only 提示唤醒 backlog。高频移动/路线/空间 visual 每 5 秒只主动保留最新一条,关键 visual 转折不受这条限频。击杀、死亡、有效目击、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Behavior 终态(`behavior.completed` / `failed` / `cancelled` / `replaced`)、每次 `game_stream_disconnected` 和关键会议等 priority ≥80 的 Event,以及 `game_over` / `exile_game_over` / `game_over_recovered`,始终由 Monitor 直达且可顺带携带当前 backlog,不消耗普通预算。通知没有 `details_required`、`backlog` 或 `truncated:true` 时直接处理;每次出现任一标记时运行一次裸 `ccl events`。
|
|
10
10
|
|
|
11
11
|
Monitor 只负责“有事发生时唤醒 Agent”。内部 heartbeat、PID、HTTP 审计和诊断日志不会作为游戏通知推给 Agent。
|
|
12
12
|
|
|
@@ -35,11 +35,13 @@ Monitor 字段如下:
|
|
|
35
35
|
- `match_start`:匹配长流已连接。
|
|
36
36
|
- `match_waiting`:仍在队列。
|
|
37
37
|
- `match_timeout`、`not_in_queue`、`game_start_failed`:本次流即将或已经结束;直接处理 Monitor 事实和可选 `hint`,只有通知要求详情时才查询。
|
|
38
|
-
- `game_stream_disconnected` / `game_stream_reconnected`:同一逻辑对局内的物理 WS
|
|
38
|
+
- `game_stream_disconnected` / `game_stream_reconnected`:同一逻辑对局内的物理 WS 断线与重连;不会因此开启新事件段。每次物理断线独立直达 Agent,Owner 同时核对 Lobby participation。
|
|
39
39
|
- `quit_requested`:runtime 已收到退出请求;停止发游戏动作,并等待 `session_left`、`quit_failed` 或长流结束确认结果。
|
|
40
40
|
- `session_left`:当前后端参与已结束,前台运行时即将结束。
|
|
41
41
|
- `user_left_game`:用户从网页退出当前对局;普通匹配结束长流,房间模式尝试回到 lobby,不自动开下一局。
|
|
42
42
|
- `game_over`:本局结束;普通匹配 runtime 自动退出,房间模式回到 lobby。
|
|
43
|
+
- `game_over_recovered`:GameSync 终局帧缺失,但 Lobby settlement 的 `game_id` 与当前局完全匹配;等价进入赛后流程,同时保留 `recovered=true` 来源事实。
|
|
44
|
+
- `game_terminal_missing`:Lobby 已无当前对局参与,但没有终局帧,也没有匹配当前 `game_id` 的 settlement;本局结果未知,不猜胜方。
|
|
43
45
|
- `behavior.completed` / `behavior.failed` / `behavior.cancelled` / `behavior.replaced`:一个 Activation 的终态;用 `activation_id`、`behavior`、`layer`、`reason` 和可选 `replaced_by_activation_id` 判断结果。`behavior.suspended` / `behavior.restarted` 只是抢占与 fresh restart,不是终态。
|
|
44
46
|
- `emergency_countdown_warning`:紧急任务剩余时间首次跨过 30 秒或 20 秒;同一任务每档一次,立即结合当前目标处理。
|
|
45
47
|
- `ability.ready` / `ability.remaining_uses_changed` / `ability.exhausted`:状态型能力刚变为可用、有限次数变化或耗尽;当前完整状态仍以随后查询边界的 `state.abilities[]` 为准。
|
package/src/lib/game-client.ts
CHANGED
|
@@ -37,6 +37,13 @@ export interface GameClientConfig {
|
|
|
37
37
|
signal?: AbortSignal;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
export interface GameServerDiscoveryResult {
|
|
41
|
+
/** Preserves the old boolean meaning: a usable GameServer route changed. */
|
|
42
|
+
readonly routeChanged: boolean;
|
|
43
|
+
/** Latest authoritative Lobby participation response, when the probe succeeded. */
|
|
44
|
+
readonly queue?: Record<string, any>;
|
|
45
|
+
}
|
|
46
|
+
|
|
40
47
|
export interface GameActionRequest {
|
|
41
48
|
action: string;
|
|
42
49
|
name?: string;
|
|
@@ -510,12 +517,12 @@ export class GameClient {
|
|
|
510
517
|
/**
|
|
511
518
|
* Try to discover game server from /queue/status.
|
|
512
519
|
* If found and WS is enabled, reconnects WS to the game server.
|
|
513
|
-
* Returns
|
|
520
|
+
* Returns both the usable-route decision and the authoritative queue probe.
|
|
514
521
|
*
|
|
515
522
|
* Note: uses http.get directly instead of getQueueStatus() to avoid
|
|
516
523
|
* double-calling registry.updateFromQueueResponse().
|
|
517
524
|
*/
|
|
518
|
-
async discoverGameServer(): Promise<
|
|
525
|
+
async discoverGameServer(): Promise<GameServerDiscoveryResult> {
|
|
519
526
|
try {
|
|
520
527
|
const result = await this.http.get<any>('/api/v1/queue/status');
|
|
521
528
|
const changed = this.registry.updateFromQueueResponse(result);
|
|
@@ -524,10 +531,11 @@ export class GameClient {
|
|
|
524
531
|
if (this.enableWs) {
|
|
525
532
|
await this.reconnectWsToGameServer();
|
|
526
533
|
}
|
|
527
|
-
return true;
|
|
534
|
+
return { routeChanged: true, queue: structuredClone(result) };
|
|
528
535
|
}
|
|
536
|
+
return { routeChanged: false, queue: structuredClone(result) };
|
|
529
537
|
} catch { /* queue/status unavailable */ }
|
|
530
|
-
return false;
|
|
538
|
+
return { routeChanged: false };
|
|
531
539
|
}
|
|
532
540
|
|
|
533
541
|
/** Reconnect WS to the current game server address. */
|
|
@@ -503,6 +503,11 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
|
|
|
503
503
|
case 'game_over':
|
|
504
504
|
if (isRoomGameEvent(event, ctx)) return '本轮房间对局结束。';
|
|
505
505
|
return `游戏结束:${firstString(event, ['winner_name'], '未知玩家')}获胜(${firstString(event, ['winner'])}),原因 ${firstString(event, ['reason'])}。`;
|
|
506
|
+
case 'game_over_recovered':
|
|
507
|
+
if (isRoomGameEvent(event, ctx)) return 'GameSync终局帧缺失,但后端结算已确认本轮房间对局结束。';
|
|
508
|
+
return `GameSync终局帧缺失,但后端结算已确认游戏结束:${firstString(event, ['winner', 'winning_faction'])}阵营获胜,原因 ${firstString(event, ['reason', 'win_reason'])}。`;
|
|
509
|
+
case 'game_terminal_missing':
|
|
510
|
+
return '当前对局已从后端参与状态中消失,但未收到终局帧,也没有查到匹配的结算;本局结果未知。';
|
|
506
511
|
case 'octopus_time_win':
|
|
507
512
|
return `${playerLabel(event.winner_name ?? event.actor_name, firstNumber(event, ['winner_seat', 'actor_seat']), ctx)}作为章鱼存活满60秒并获胜。`;
|
|
508
513
|
case 'win_blocked_by_octopus':
|
|
@@ -318,6 +318,16 @@ export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, Even
|
|
|
318
318
|
}
|
|
319
319
|
return 'The GameServer did not provide its first State in time. The Owner is reconciling automatically; stay attached and do not start a duplicate runtime.';
|
|
320
320
|
},
|
|
321
|
+
game_over_recovered: (event, ctx) => (
|
|
322
|
+
isRoomGameEvent(event, ctx)
|
|
323
|
+
? ROOM_GAME_OVER_HINT
|
|
324
|
+
: 'The terminal GameSync frame was missed, but the matching Lobby settlement confirms game over. Stop game actions, review the result with the user, and start another match only if the user asks.'
|
|
325
|
+
),
|
|
326
|
+
game_terminal_missing: (event, ctx) => (
|
|
327
|
+
isRoomGameEvent(event, ctx)
|
|
328
|
+
? 'The room round disappeared from backend participation without a terminal frame or matching settlement. The result is unknown; tell the user and stay attached while the runtime returns to the room Lobby.'
|
|
329
|
+
: 'The game disappeared from backend participation without a terminal frame or matching settlement. The result is unknown; tell the user and do not claim a winner.'
|
|
330
|
+
),
|
|
321
331
|
game_stream_disconnected: () => (
|
|
322
332
|
'The game stream disconnected and the Owner is reconnecting. Stay attached and do not start a duplicate runtime.'
|
|
323
333
|
),
|
|
@@ -2,6 +2,8 @@ const DEFAULT_MONITOR_PRIORITY = 50;
|
|
|
2
2
|
|
|
3
3
|
export const CLAWCLAW_MONITOR_EVENT_PRIORITY: Readonly<Record<string, number>> = Object.freeze({
|
|
4
4
|
service_status: 95,
|
|
5
|
+
game_stream_disconnected: 80,
|
|
6
|
+
game_terminal_missing: 95,
|
|
5
7
|
kill: 99,
|
|
6
8
|
killed: 99,
|
|
7
9
|
murder_witnessed: 95,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
BehaviorContinuation,
|
|
3
|
+
BehaviorDecisionFrame,
|
|
3
4
|
BehaviorInput,
|
|
4
5
|
GameEvent,
|
|
5
6
|
GameState,
|
|
@@ -49,6 +50,7 @@ export function createBehaviorInput<
|
|
|
49
50
|
input: RuntimeEpochPluginInput<Record<string, any>>,
|
|
50
51
|
behaviorInput: TInput,
|
|
51
52
|
continuation?: Readonly<BehaviorContinuation>,
|
|
53
|
+
decisionHistory: readonly Readonly<BehaviorDecisionFrame>[] = [],
|
|
52
54
|
): BehaviorInput<TInput> | null {
|
|
53
55
|
const runtimeState = input.epoch.state;
|
|
54
56
|
if (!isClawclawRuntimeState(runtimeState) || runtimeState.game_snapshot.status !== 'fresh') {
|
|
@@ -68,6 +70,9 @@ export function createBehaviorInput<
|
|
|
68
70
|
gameState,
|
|
69
71
|
events: behaviorEvents(input),
|
|
70
72
|
input: structuredClone(behaviorInput),
|
|
73
|
+
// The Owner ring exposes one recursively immutable snapshot. Serial modules
|
|
74
|
+
// can share it directly; Worker postMessage performs the one required clone.
|
|
75
|
+
decisionHistory,
|
|
71
76
|
...(continuation === undefined ? {} : { continuation: structuredClone(continuation) }),
|
|
72
77
|
});
|
|
73
78
|
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
2
3
|
import type { GameClient } from '../../../../lib/game-client.js';
|
|
3
4
|
import { ApiError } from '../../../../lib/http-transport.js';
|
|
4
5
|
import type { TransportResponse } from '../../../../short-command/transport-response.js';
|
|
6
|
+
import { actionFailureDiagnosticSeverity } from '../../../framework/action-diagnostics.js';
|
|
5
7
|
import type {
|
|
6
8
|
ActionCaller,
|
|
7
9
|
ActionControlDescriptor,
|
|
@@ -29,6 +31,7 @@ export interface ClawclawActionRequest {
|
|
|
29
31
|
audioFile?: { path: string; contentType: string };
|
|
30
32
|
/** Host-only preconditions for one unified Behavior activation instance. */
|
|
31
33
|
behaviorOriginEpochSeq?: number;
|
|
34
|
+
behaviorOriginTick?: number;
|
|
32
35
|
behaviorActionSafetyGeneration?: number;
|
|
33
36
|
behaviorActivationGeneration?: number;
|
|
34
37
|
}
|
|
@@ -143,6 +146,49 @@ interface AdmittedClawclawAction {
|
|
|
143
146
|
route: 'game' | 'room_chat';
|
|
144
147
|
}
|
|
145
148
|
|
|
149
|
+
interface AutomatedProviderTiming {
|
|
150
|
+
readonly queuedAtMs: number;
|
|
151
|
+
readonly queueDepthAtAdmission: number;
|
|
152
|
+
readonly inFlightAtAdmission: number;
|
|
153
|
+
startedAtMs?: number;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
interface AutomatedSubmission {
|
|
157
|
+
readonly settlement: Promise<ActionResult>;
|
|
158
|
+
readonly timing: AutomatedProviderTiming;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function elapsedMs(startedAtMs: number, endedAtMs = performance.now()): number {
|
|
162
|
+
return Math.round(Math.max(0, endedAtMs - startedAtMs) * 1_000) / 1_000;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function automatedDiagnosticAttributes(
|
|
166
|
+
request: ClawclawActionRequest,
|
|
167
|
+
admitted: AdmittedClawclawAction,
|
|
168
|
+
caller: AutomatedActionCaller,
|
|
169
|
+
): Readonly<Record<string, unknown>> {
|
|
170
|
+
return {
|
|
171
|
+
action_id: admitted.actionId,
|
|
172
|
+
action_kind: typeof admitted.action.action === 'string'
|
|
173
|
+
? admitted.action.action
|
|
174
|
+
: 'unknown',
|
|
175
|
+
route: admitted.route,
|
|
176
|
+
caller_kind: caller.kind,
|
|
177
|
+
behavior_activation_id: caller.activationId,
|
|
178
|
+
behavior_activation_generation: caller.activationGeneration,
|
|
179
|
+
behavior_layer: caller.layer,
|
|
180
|
+
...(request.behaviorOriginEpochSeq === undefined
|
|
181
|
+
? {}
|
|
182
|
+
: {
|
|
183
|
+
epoch_seq: request.behaviorOriginEpochSeq,
|
|
184
|
+
origin_epoch_seq: request.behaviorOriginEpochSeq,
|
|
185
|
+
}),
|
|
186
|
+
...(request.behaviorOriginTick === undefined
|
|
187
|
+
? {}
|
|
188
|
+
: { origin_tick: request.behaviorOriginTick }),
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
146
192
|
/** Validates authoritative seat targets without consulting names or roster state. */
|
|
147
193
|
function prepareActionTarget(action: Record<string, any>): ActionTargetPreparation {
|
|
148
194
|
if (action.action !== 'kill' && action.action !== 'vote') return { action };
|
|
@@ -218,6 +264,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
218
264
|
* gameplay endpoint before an earlier one has started.
|
|
219
265
|
*/
|
|
220
266
|
private readonly automatedProviderStarts = new Map<string, Promise<void>>();
|
|
267
|
+
private readonly automatedProviderQueueDepths = new Map<string, number>();
|
|
221
268
|
|
|
222
269
|
constructor(private readonly client: GameClient) {}
|
|
223
270
|
|
|
@@ -251,6 +298,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
251
298
|
this.unregister = undefined;
|
|
252
299
|
this.diagnostic = undefined;
|
|
253
300
|
this.automatedProviderStarts.clear();
|
|
301
|
+
this.automatedProviderQueueDepths.clear();
|
|
254
302
|
}
|
|
255
303
|
|
|
256
304
|
private automatedProviderQueueKey(scope: ScopeRef): string {
|
|
@@ -263,9 +311,17 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
263
311
|
caller: AutomatedActionCaller,
|
|
264
312
|
context: ActionExecutionContext,
|
|
265
313
|
admitted: AdmittedClawclawAction,
|
|
266
|
-
):
|
|
314
|
+
): AutomatedSubmission {
|
|
267
315
|
const queueKey = this.automatedProviderQueueKey(scope);
|
|
268
316
|
const previousStarted = this.automatedProviderStarts.get(queueKey) ?? Promise.resolve();
|
|
317
|
+
const queueDepthAtAdmission = (this.automatedProviderQueueDepths.get(queueKey) ?? 0) + 1;
|
|
318
|
+
this.automatedProviderQueueDepths.set(queueKey, queueDepthAtAdmission);
|
|
319
|
+
const timing: AutomatedProviderTiming = {
|
|
320
|
+
queuedAtMs: performance.now(),
|
|
321
|
+
queueDepthAtAdmission,
|
|
322
|
+
inFlightAtAdmission: this.ownedSettlements.size + 1,
|
|
323
|
+
};
|
|
324
|
+
const diagnostic = this.diagnostic;
|
|
269
325
|
let markStarted!: () => void;
|
|
270
326
|
const started = new Promise<void>((resolve) => { markStarted = resolve; });
|
|
271
327
|
this.automatedProviderStarts.set(queueKey, started);
|
|
@@ -274,9 +330,56 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
274
330
|
this.automatedProviderStarts.delete(queueKey);
|
|
275
331
|
}
|
|
276
332
|
});
|
|
277
|
-
|
|
333
|
+
let queuePositionReleased = false;
|
|
334
|
+
const releaseQueuePosition = (endpointStarted: boolean): void => {
|
|
335
|
+
if (queuePositionReleased) return;
|
|
336
|
+
queuePositionReleased = true;
|
|
337
|
+
const releasedAtMs = performance.now();
|
|
338
|
+
if (endpointStarted) timing.startedAtMs = releasedAtMs;
|
|
339
|
+
const remainingQueueDepth = Math.max(
|
|
340
|
+
0,
|
|
341
|
+
(this.automatedProviderQueueDepths.get(queueKey) ?? 1) - 1,
|
|
342
|
+
);
|
|
343
|
+
if (remainingQueueDepth === 0) this.automatedProviderQueueDepths.delete(queueKey);
|
|
344
|
+
else this.automatedProviderQueueDepths.set(queueKey, remainingQueueDepth);
|
|
345
|
+
this.emitDiagnostic(
|
|
346
|
+
endpointStarted
|
|
347
|
+
? 'runtime.action.provider_started'
|
|
348
|
+
: 'runtime.action.provider_skipped',
|
|
349
|
+
{
|
|
350
|
+
...automatedDiagnosticAttributes(request, admitted, caller),
|
|
351
|
+
queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs),
|
|
352
|
+
queue_depth_at_admission: timing.queueDepthAtAdmission,
|
|
353
|
+
in_flight_at_admission: timing.inFlightAtAdmission,
|
|
354
|
+
remaining_queue_depth: remainingQueueDepth,
|
|
355
|
+
},
|
|
356
|
+
'debug',
|
|
357
|
+
diagnostic,
|
|
358
|
+
);
|
|
359
|
+
const queueWaitMs = elapsedMs(timing.queuedAtMs, releasedAtMs);
|
|
360
|
+
if (endpointStarted && (queueWaitMs >= 20 || timing.queueDepthAtAdmission >= 2)) {
|
|
361
|
+
this.emitDiagnostic('runtime.action.provider_queue_delayed', {
|
|
362
|
+
...automatedDiagnosticAttributes(request, admitted, caller),
|
|
363
|
+
queue_wait_ms: queueWaitMs,
|
|
364
|
+
queue_depth_at_admission: timing.queueDepthAtAdmission,
|
|
365
|
+
in_flight_at_admission: timing.inFlightAtAdmission,
|
|
366
|
+
remaining_queue_depth: remainingQueueDepth,
|
|
367
|
+
budget_exceeded: queueWaitMs >= 100,
|
|
368
|
+
}, 'warn', diagnostic);
|
|
369
|
+
}
|
|
370
|
+
markStarted();
|
|
371
|
+
};
|
|
372
|
+
const settlement = previousStarted
|
|
278
373
|
.catch(() => {})
|
|
279
|
-
.then(() => this.submitAdmitted(
|
|
374
|
+
.then(() => this.submitAdmitted(
|
|
375
|
+
request,
|
|
376
|
+
scope,
|
|
377
|
+
caller,
|
|
378
|
+
context,
|
|
379
|
+
admitted,
|
|
380
|
+
releaseQueuePosition,
|
|
381
|
+
));
|
|
382
|
+
return { settlement, timing };
|
|
280
383
|
}
|
|
281
384
|
|
|
282
385
|
private automationSafetyRejection(
|
|
@@ -407,7 +510,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
407
510
|
if (!isAutomatedCaller(caller)) {
|
|
408
511
|
return this.submitAdmitted(request, scope, caller, context, admitted);
|
|
409
512
|
}
|
|
410
|
-
const
|
|
513
|
+
const queued = this.enqueueAutomatedSubmission(
|
|
411
514
|
request,
|
|
412
515
|
scope,
|
|
413
516
|
caller,
|
|
@@ -415,11 +518,20 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
415
518
|
admitted,
|
|
416
519
|
);
|
|
417
520
|
this.emitDiagnostic('runtime.action.provider_queued', {
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
521
|
+
...automatedDiagnosticAttributes(request, admitted, caller),
|
|
522
|
+
queue_depth: queued.timing.queueDepthAtAdmission,
|
|
523
|
+
in_flight: queued.timing.inFlightAtAdmission,
|
|
421
524
|
});
|
|
422
|
-
const ownedSettlement = this.ownSettlement(
|
|
525
|
+
const ownedSettlement = this.ownSettlement(
|
|
526
|
+
scope,
|
|
527
|
+
caller,
|
|
528
|
+
action,
|
|
529
|
+
actionId,
|
|
530
|
+
admitted.route,
|
|
531
|
+
request,
|
|
532
|
+
queued.settlement,
|
|
533
|
+
queued.timing,
|
|
534
|
+
);
|
|
423
535
|
const dispatch: ActionDispatch = {
|
|
424
536
|
receipt: actionResult(scope, actionId, 'success', {
|
|
425
537
|
accepted: true,
|
|
@@ -442,7 +554,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
442
554
|
caller: ActionCaller,
|
|
443
555
|
context: ActionExecutionContext,
|
|
444
556
|
admitted: AdmittedClawclawAction,
|
|
445
|
-
markProviderStartedOrSkipped: () => void = () => {},
|
|
557
|
+
markProviderStartedOrSkipped: (endpointStarted: boolean) => void = () => {},
|
|
446
558
|
): Promise<ActionResult> {
|
|
447
559
|
let actionEndpointStarted = false;
|
|
448
560
|
const action = { ...admitted.action };
|
|
@@ -464,12 +576,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
464
576
|
request, scope, admitted.actionId, caller, context,
|
|
465
577
|
);
|
|
466
578
|
if (rejected) return rejected;
|
|
579
|
+
const pending = this.client.chatRoomConfirmed(action.text);
|
|
467
580
|
actionEndpointStarted = true;
|
|
468
|
-
markProviderStartedOrSkipped();
|
|
581
|
+
markProviderStartedOrSkipped(true);
|
|
469
582
|
return acknowledgedActionResult(
|
|
470
583
|
scope,
|
|
471
584
|
admitted.actionId,
|
|
472
|
-
await
|
|
585
|
+
await pending,
|
|
473
586
|
);
|
|
474
587
|
}
|
|
475
588
|
const preparedAction = await this.client.prepareActionForConfirmedSubmission(action as any);
|
|
@@ -477,9 +590,10 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
477
590
|
request, scope, admitted.actionId, caller, context,
|
|
478
591
|
);
|
|
479
592
|
if (rejected) return rejected;
|
|
593
|
+
const pending = this.client.submitPreparedActionConfirmed(preparedAction);
|
|
480
594
|
actionEndpointStarted = true;
|
|
481
|
-
markProviderStartedOrSkipped();
|
|
482
|
-
const response = await
|
|
595
|
+
markProviderStartedOrSkipped(true);
|
|
596
|
+
const response = await pending;
|
|
483
597
|
return acknowledgedActionResult(scope, admitted.actionId, response);
|
|
484
598
|
} catch (error) {
|
|
485
599
|
return actionResult(scope, admitted.actionId, 'failure', undefined, backendError(error), {
|
|
@@ -491,7 +605,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
491
605
|
} finally {
|
|
492
606
|
// A local rejection or preparation failure is also a resolved queue
|
|
493
607
|
// position: later Decisions may continue without waiting forever.
|
|
494
|
-
markProviderStartedOrSkipped();
|
|
608
|
+
markProviderStartedOrSkipped(false);
|
|
495
609
|
}
|
|
496
610
|
}
|
|
497
611
|
|
|
@@ -500,23 +614,41 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
|
|
|
500
614
|
caller: AutomatedActionCaller,
|
|
501
615
|
action: Record<string, any>,
|
|
502
616
|
actionId: string,
|
|
617
|
+
route: AdmittedClawclawAction['route'],
|
|
618
|
+
request: ClawclawActionRequest,
|
|
503
619
|
settlement: Promise<ActionResult>,
|
|
620
|
+
timing: AutomatedProviderTiming,
|
|
504
621
|
): Promise<ActionResult> {
|
|
505
622
|
// Keep the epoch's diagnostic sink with the owned submission. The plugin
|
|
506
623
|
// may be stopped after the Runtime starts draining, but the final provider
|
|
507
624
|
// result still belongs to this Action dispatch and must remain observable.
|
|
508
625
|
const diagnostic = this.diagnostic;
|
|
509
626
|
const report = (result: ActionResult): ActionResult => {
|
|
627
|
+
const settledAtMs = performance.now();
|
|
510
628
|
const errorCode = actionResultErrorCode(result);
|
|
511
629
|
this.emitDiagnostic('runtime.action.provider_settled', {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
630
|
+
...automatedDiagnosticAttributes(request, {
|
|
631
|
+
actionId,
|
|
632
|
+
action,
|
|
633
|
+
route,
|
|
634
|
+
}, caller),
|
|
515
635
|
status: result.status,
|
|
516
636
|
...(result.source ? { action_source: result.source } : {}),
|
|
517
637
|
...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
|
|
518
638
|
...(errorCode ? { error_code: errorCode } : {}),
|
|
519
|
-
|
|
639
|
+
queue_depth_at_admission: timing.queueDepthAtAdmission,
|
|
640
|
+
in_flight_at_admission: timing.inFlightAtAdmission,
|
|
641
|
+
in_flight_at_settlement: this.ownedSettlements.size,
|
|
642
|
+
queue_wait_ms: timing.startedAtMs === undefined
|
|
643
|
+
? elapsedMs(timing.queuedAtMs, settledAtMs)
|
|
644
|
+
: elapsedMs(timing.queuedAtMs, timing.startedAtMs),
|
|
645
|
+
...(timing.startedAtMs === undefined
|
|
646
|
+
? {}
|
|
647
|
+
: { provider_duration_ms: elapsedMs(timing.startedAtMs, settledAtMs) }),
|
|
648
|
+
total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs),
|
|
649
|
+
}, result.status === 'failure'
|
|
650
|
+
? actionFailureDiagnosticSeverity(result)
|
|
651
|
+
: 'debug', diagnostic);
|
|
520
652
|
return result;
|
|
521
653
|
};
|
|
522
654
|
let owned!: Promise<ActionResult>;
|
|
@@ -7,6 +7,7 @@ export function normalizeClawclawBehaviorAction(
|
|
|
7
7
|
behaviorOriginEpochSeq: number,
|
|
8
8
|
behaviorActionSafetyGeneration: number | undefined,
|
|
9
9
|
behaviorActivationGeneration: number,
|
|
10
|
+
behaviorOriginTick?: number,
|
|
10
11
|
): ClawclawActionRequest {
|
|
11
12
|
if (!Number.isInteger(behaviorOriginEpochSeq) || behaviorOriginEpochSeq <= 0) {
|
|
12
13
|
throw new Error('invalid_behavior_action_epoch');
|
|
@@ -20,10 +21,17 @@ export function normalizeClawclawBehaviorAction(
|
|
|
20
21
|
if (!Number.isSafeInteger(behaviorActivationGeneration) || behaviorActivationGeneration <= 0) {
|
|
21
22
|
throw new Error('invalid_behavior_activation_generation');
|
|
22
23
|
}
|
|
24
|
+
if (
|
|
25
|
+
behaviorOriginTick !== undefined
|
|
26
|
+
&& (!Number.isSafeInteger(behaviorOriginTick) || behaviorOriginTick < 0)
|
|
27
|
+
) {
|
|
28
|
+
throw new Error('invalid_behavior_action_tick');
|
|
29
|
+
}
|
|
23
30
|
return {
|
|
24
31
|
route: 'auto',
|
|
25
32
|
action: normalizeClawclawBehaviorActionPayload(value),
|
|
26
33
|
behaviorOriginEpochSeq,
|
|
34
|
+
...(behaviorOriginTick === undefined ? {} : { behaviorOriginTick }),
|
|
27
35
|
behaviorActionSafetyGeneration,
|
|
28
36
|
behaviorActivationGeneration,
|
|
29
37
|
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
BehaviorDecisionAction,
|
|
3
|
+
BehaviorDecisionFrame,
|
|
4
|
+
BehaviorDecisionFrameStatus,
|
|
5
|
+
} from '../../../../sdk/module-input/index.js';
|
|
6
|
+
|
|
7
|
+
export const BEHAVIOR_DECISION_HISTORY_LIMIT = 100;
|
|
8
|
+
|
|
9
|
+
interface DecisionFrameStart {
|
|
10
|
+
readonly epochId: number;
|
|
11
|
+
readonly tick: number;
|
|
12
|
+
readonly instanceGeneration: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function cloneActions(
|
|
16
|
+
actions: readonly Readonly<BehaviorDecisionAction>[] | undefined,
|
|
17
|
+
): readonly Readonly<BehaviorDecisionAction>[] {
|
|
18
|
+
return Object.freeze((actions ?? []).map((action) => Object.freeze(structuredClone(action))));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** One Owner-owned, activation-local ring shared by concurrent Decision computations. */
|
|
22
|
+
export class BehaviorDecisionHistory {
|
|
23
|
+
private readonly frames: BehaviorDecisionFrame[] = [];
|
|
24
|
+
private cachedSnapshot?: readonly Readonly<BehaviorDecisionFrame>[];
|
|
25
|
+
|
|
26
|
+
begin(start: DecisionFrameStart): Readonly<BehaviorDecisionFrame> {
|
|
27
|
+
const existing = this.frames.find((frame) => frame.epochId === start.epochId);
|
|
28
|
+
if (existing) return existing;
|
|
29
|
+
const frame = Object.freeze({
|
|
30
|
+
...start,
|
|
31
|
+
status: 'pending' as const,
|
|
32
|
+
actions: null,
|
|
33
|
+
});
|
|
34
|
+
this.frames.push(frame);
|
|
35
|
+
if (this.frames.length > BEHAVIOR_DECISION_HISTORY_LIMIT) {
|
|
36
|
+
this.frames.splice(0, this.frames.length - BEHAVIOR_DECISION_HISTORY_LIMIT);
|
|
37
|
+
}
|
|
38
|
+
this.cachedSnapshot = undefined;
|
|
39
|
+
return frame;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
complete(
|
|
43
|
+
epochId: number,
|
|
44
|
+
actions: readonly Readonly<BehaviorDecisionAction>[] | undefined,
|
|
45
|
+
): Readonly<BehaviorDecisionFrame> | undefined {
|
|
46
|
+
return this.resolve(epochId, 'completed', cloneActions(actions));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
notComputed(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined {
|
|
50
|
+
return this.resolve(epochId, 'not_computed', null, reason);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
fail(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined {
|
|
54
|
+
return this.resolve(epochId, 'failed', null, reason);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
snapshot(): readonly Readonly<BehaviorDecisionFrame>[] {
|
|
58
|
+
this.cachedSnapshot ??= Object.freeze([...this.frames]);
|
|
59
|
+
return this.cachedSnapshot;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
clear(): void {
|
|
63
|
+
this.frames.length = 0;
|
|
64
|
+
this.cachedSnapshot = undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private resolve(
|
|
68
|
+
epochId: number,
|
|
69
|
+
status: Exclude<BehaviorDecisionFrameStatus, 'pending'>,
|
|
70
|
+
actions: readonly Readonly<BehaviorDecisionAction>[] | null,
|
|
71
|
+
reason?: string,
|
|
72
|
+
): Readonly<BehaviorDecisionFrame> | undefined {
|
|
73
|
+
const index = this.frames.findIndex((frame) => frame.epochId === epochId);
|
|
74
|
+
if (index < 0) return undefined;
|
|
75
|
+
const previous = this.frames[index]!;
|
|
76
|
+
const next = Object.freeze({
|
|
77
|
+
epochId: previous.epochId,
|
|
78
|
+
tick: previous.tick,
|
|
79
|
+
instanceGeneration: previous.instanceGeneration,
|
|
80
|
+
status,
|
|
81
|
+
actions,
|
|
82
|
+
...(reason ? { reason } : {}),
|
|
83
|
+
});
|
|
84
|
+
this.frames[index] = next;
|
|
85
|
+
this.cachedSnapshot = undefined;
|
|
86
|
+
return next;
|
|
87
|
+
}
|
|
88
|
+
}
|