@myclaw163/clawclaw-cli 0.10.7 → 0.10.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.
@@ -0,0 +1,260 @@
1
+ // src/sdk/perception-plugin/module.ts
2
+ var PERCEPTION_MODULE_API_VERSION = 3;
3
+
4
+ // src/sdk/perception-plugin/index.ts
5
+ import { Perception } from "@myclaw163/game-agent-runtime/sdk/perception.js";
6
+
7
+ // src/sdk/perception-plugin/reaction.ts
8
+ var ClawclawReaction = class {
9
+ static manifest;
10
+ };
11
+
12
+ // src/sdk/perception-plugin/reminder.ts
13
+ var REMINDER_PLUGIN_API_VERSION = 2;
14
+ var ClawclawReminder = class {
15
+ static manifest;
16
+ };
17
+
18
+ // src/sdk/perception-plugin/reminder-rules.ts
19
+ var TASK_LIFECYCLE_FACT_TYPES = [
20
+ "task_started",
21
+ "task_progress",
22
+ "task_assigned",
23
+ "task_completed",
24
+ "task_interrupted",
25
+ "task_sabotaged"
26
+ ];
27
+ var TASK_REMINDER_FACT_TYPES = [
28
+ ...TASK_LIFECYCLE_FACT_TYPES,
29
+ "role_assigned",
30
+ "emergency_started",
31
+ "emergency_resolved",
32
+ "emergency_interrupted",
33
+ "meeting_briefing"
34
+ ];
35
+ var REMINDER_FACT_TYPES = [...TASK_REMINDER_FACT_TYPES, "wandering_speech"];
36
+ function isReminderMode(value) {
37
+ return value === "wake" || value === "silent" || value === "state_only";
38
+ }
39
+ function defaultConfig(topic) {
40
+ if (topic !== "tasks") throw new Error("Unsupported reminder topic; countdown and ability notifications are owned by CCL.");
41
+ return {
42
+ started: "state_only",
43
+ progress: "state_only",
44
+ added: "silent",
45
+ completed: "silent",
46
+ interrupted: "wake",
47
+ sabotaged: "wake",
48
+ removed: "silent",
49
+ updated: "silent"
50
+ };
51
+ }
52
+ function validateDefaultConfig(topic, input) {
53
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Reminder config must be an object.");
54
+ const defaults = defaultConfig(topic);
55
+ for (const key of Object.keys(input)) if (!Object.hasOwn(defaults, key)) throw new Error("Unknown reminder option: " + key);
56
+ const value = { ...defaults, ...input };
57
+ if (!Object.values(value).every(isReminderMode)) throw new Error("Reminder mode must be wake, silent, or state_only.");
58
+ return value;
59
+ }
60
+ var kinds = {
61
+ task_started: "started",
62
+ task_progress: "progress",
63
+ task_assigned: "added",
64
+ task_completed: "completed",
65
+ task_interrupted: "interrupted",
66
+ task_sabotaged: "sabotaged"
67
+ };
68
+ var labels = {
69
+ started: "\u5F00\u59CB\u4EFB\u52A1",
70
+ progress: "\u4EFB\u52A1\u8FDB\u5EA6\u53D8\u5316",
71
+ added: "\u65B0\u589E\u4EFB\u52A1",
72
+ completed: "\u4EFB\u52A1\u5B8C\u6210",
73
+ interrupted: "\u4EFB\u52A1\u4E2D\u65AD",
74
+ sabotaged: "\u7834\u574F\u4EFB\u52A1\u5B8C\u6210",
75
+ removed: "\u4EFB\u52A1\u4E0D\u518D\u51FA\u73B0\u5728\u5217\u8868",
76
+ updated: "\u4EFB\u52A1\u4FE1\u606F\u53D8\u5316"
77
+ };
78
+ function record(value) {
79
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
80
+ }
81
+ function speechReminder(input) {
82
+ if (Object.keys(input.config).some((key) => key !== "receive") || input.config.receive !== void 0 && typeof input.config.receive !== "boolean") {
83
+ throw new Error("Speech reminder config must contain only a boolean receive.");
84
+ }
85
+ if (input.config.receive === false) return { events: [] };
86
+ const self = input.gameState?.you?.player;
87
+ return { events: input.facts.flatMap((fact) => {
88
+ if (fact.type !== "wandering_speech" || fact.replayed) return [];
89
+ const actor = record(fact.payload.actor);
90
+ const seat = actor.seat ?? fact.payload.actor_seat;
91
+ const name = actor.name ?? fact.payload.actor_name;
92
+ const own = seat !== void 0 && self?.seat !== void 0 ? seat === self.seat : typeof name === "string" && self?.name !== void 0 && name === self.name;
93
+ if (own || typeof fact.payload.text !== "string" || !fact.payload.text.trim()) return [];
94
+ return [{
95
+ type: "reminder.speech",
96
+ key: `fact:${fact.eventId}`,
97
+ wakeAgent: true,
98
+ payload: { ...fact.payload, text: fact.payload.text, source_event_id: fact.eventId }
99
+ }];
100
+ }) };
101
+ }
102
+ function defaultReminder(topic, input) {
103
+ if (topic === "speech") return speechReminder(input);
104
+ const config = validateDefaultConfig(topic, input.config);
105
+ const events = [];
106
+ if (input.boundary) return { events };
107
+ const emit = (kind, key, data, eventId) => {
108
+ const mode = config[kind];
109
+ if (mode === "state_only") return;
110
+ const { tasks: _tasks, delta: _delta, newly_assigned_task: _assigned, ...detail } = data;
111
+ const name = String(detail.task_name ?? detail.name ?? "");
112
+ const actor = record(detail.actor);
113
+ const seat = actor.seat ?? detail.actor_seat;
114
+ const who = seat !== void 0 && seat !== input.gameState?.you?.player?.seat ? `${seat}\u53F7\u73A9\u5BB6\uFF1A` : "";
115
+ const room = detail.room ? `\uFF08${String(detail.room)}\uFF09` : "";
116
+ events.push({
117
+ type: "reminder.task",
118
+ key,
119
+ wakeAgent: mode === "wake",
120
+ payload: { ...detail, kind, source_event_id: eventId, text: `${who}${labels[kind]}\uFF1A${name}${room}\u3002` }
121
+ });
122
+ };
123
+ for (const fact of input.facts) {
124
+ const kind = kinds[fact.type];
125
+ if (kind) emit(kind, `fact:${fact.eventId}`, { ...fact.payload }, fact.eventId);
126
+ }
127
+ return { events };
128
+ }
129
+
130
+ // src/sdk/perception-plugin/math.ts
131
+ var TICK_MS = 100;
132
+ var MOVE_MIN_PX = 18;
133
+ var STEP_MOVE_MIN_PX = 4;
134
+ var STILL_STEP_MAX_PX = 3;
135
+ function vector(from, to) {
136
+ return { x: to.x - from.x, y: to.y - from.y };
137
+ }
138
+ function length(value) {
139
+ return Math.hypot(value.x, value.y);
140
+ }
141
+ function distance(a, b) {
142
+ return Math.hypot(a.x - b.x, a.y - b.y);
143
+ }
144
+ function dot(a, b) {
145
+ return a.x * b.x + a.y * b.y;
146
+ }
147
+ function cross(a, b) {
148
+ return a.x * b.y - a.y * b.x;
149
+ }
150
+ function unit(value) {
151
+ const magnitude = length(value);
152
+ return magnitude <= 0 ? { x: 0, y: 0 } : { x: value.x / magnitude, y: value.y / magnitude };
153
+ }
154
+ function cosine(a, b) {
155
+ const denominator = length(a) * length(b);
156
+ return denominator <= 0 ? 0 : dot(a, b) / denominator;
157
+ }
158
+ function angleDegrees(a, b) {
159
+ return Math.acos(Math.max(-1, Math.min(1, cosine(a, b)))) * (180 / Math.PI);
160
+ }
161
+ function direction(from, to, minimum = MOVE_MIN_PX) {
162
+ const dx = to.x - from.x;
163
+ const dy = to.y - from.y;
164
+ if (Math.hypot(dx, dy) < minimum) return "\u539F\u5730";
165
+ const horizontal = Math.abs(dx) >= minimum / 2 ? dx > 0 ? "\u53F3" : "\u5DE6" : "";
166
+ const vertical = Math.abs(dy) >= minimum / 2 ? dy > 0 ? "\u4E0B" : "\u4E0A" : "";
167
+ return `${horizontal}${vertical}` || "\u539F\u5730";
168
+ }
169
+ function headingDirection(from, to, minimum = MOVE_MIN_PX) {
170
+ const dx = to.x - from.x;
171
+ const dy = to.y - from.y;
172
+ if (Math.hypot(dx, dy) < minimum) return "\u539F\u5730";
173
+ const octant = Math.round(Math.atan2(dy, dx) / (Math.PI / 4));
174
+ const directions = [
175
+ "\u53F3",
176
+ "\u53F3\u4E0B",
177
+ "\u4E0B",
178
+ "\u5DE6\u4E0B",
179
+ "\u5DE6",
180
+ "\u5DE6\u4E0A",
181
+ "\u4E0A",
182
+ "\u53F3\u4E0A"
183
+ ];
184
+ return directions[(octant + directions.length) % directions.length];
185
+ }
186
+ function actorLabel(actor) {
187
+ if (actor.observer) return "\u4F60";
188
+ if (actor.seat !== void 0) return `${actor.seat}\u53F7`;
189
+ return actor.name ?? actor.id;
190
+ }
191
+ function actorValue(actor) {
192
+ return actor.seat ?? actor.id;
193
+ }
194
+ function timeRange(fromTick, toTick) {
195
+ const format = (tick) => {
196
+ const total = Math.max(0, Math.floor(tick * TICK_MS / 1e3));
197
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
198
+ };
199
+ const from = format(fromTick);
200
+ const to = format(toTick);
201
+ return from === to ? from : `${from}-${to}`;
202
+ }
203
+ function round1(value) {
204
+ return Math.round(value * 10) / 10;
205
+ }
206
+ function positionCopy(position) {
207
+ return { x: position.x, y: position.y, room: position.room };
208
+ }
209
+
210
+ // src/sdk/perception-plugin/index.ts
211
+ var PERCEPTION_PLUGIN_API_VERSION = 2;
212
+ function evaluateReminder(topic, input) {
213
+ return defaultReminder(topic, "events" in input ? { ...input, facts: input.events } : input);
214
+ }
215
+ var ClawclawPerception = class extends Perception {
216
+ static manifest;
217
+ /** API v3 combines observation, notification and fixed Behavior activation. */
218
+ evaluate(_input, _api) {
219
+ throw new Error("PERCEPTION_EVALUATE_NOT_IMPLEMENTED");
220
+ }
221
+ /** @deprecated API v2 compatibility; new modules implement evaluate(). */
222
+ update(frame, api) {
223
+ throw new Error("PERCEPTION_UPDATE_NOT_IMPLEMENTED");
224
+ }
225
+ };
226
+ var ClawclawParallelPerception = class extends ClawclawPerception {
227
+ update() {
228
+ throw new Error("parallel_perception_uses_analyze_and_commit");
229
+ }
230
+ };
231
+
232
+ export {
233
+ PERCEPTION_MODULE_API_VERSION,
234
+ ClawclawReaction,
235
+ REMINDER_PLUGIN_API_VERSION,
236
+ ClawclawReminder,
237
+ TICK_MS,
238
+ MOVE_MIN_PX,
239
+ STEP_MOVE_MIN_PX,
240
+ STILL_STEP_MAX_PX,
241
+ vector,
242
+ length,
243
+ distance,
244
+ dot,
245
+ cross,
246
+ unit,
247
+ cosine,
248
+ angleDegrees,
249
+ direction,
250
+ headingDirection,
251
+ actorLabel,
252
+ actorValue,
253
+ timeRange,
254
+ round1,
255
+ positionCopy,
256
+ PERCEPTION_PLUGIN_API_VERSION,
257
+ evaluateReminder,
258
+ ClawclawPerception,
259
+ ClawclawParallelPerception
260
+ };
@@ -754,6 +754,7 @@ var CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
754
754
  "room_ready_to_start",
755
755
  "room_returning_to_lobby",
756
756
  "room_ping_timeout",
757
+ "lobby_connection_replaced",
757
758
  "room_destroyed",
758
759
  "strategy_alert",
759
760
  "behavior.started",
@@ -2428,6 +2428,59 @@ async function synthesizeConfiguredTts(text, workspaceDir = getWorkspaceDir()) {
2428
2428
  return synthesizeCustomTts(text, config);
2429
2429
  }
2430
2430
 
2431
+ // src/lib/lobby-host-context.ts
2432
+ import { randomUUID as randomUUID3 } from "node:crypto";
2433
+ var agentInstanceId = randomUUID3();
2434
+ var InvalidHostContextError = class extends Error {
2435
+ code = "INVALID_HOST_CONTEXT";
2436
+ constructor(message) {
2437
+ super(`INVALID_HOST_CONTEXT: ${message}`);
2438
+ this.name = "InvalidHostContextError";
2439
+ }
2440
+ };
2441
+ function validId(value) {
2442
+ return typeof value === "string" && [...value].length >= 1 && [...value].length <= 128 && !/[\p{White_Space}\p{Cc}]/u.test(value);
2443
+ }
2444
+ function parseLobbyParticipation(value) {
2445
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
2446
+ const host = value;
2447
+ if (!validId(host.host_instance_id)) return null;
2448
+ if (host.host_type === "desktop" && validId(host.host_session_id)) {
2449
+ return { host_type: "desktop", host_instance_id: host.host_instance_id, host_session_id: host.host_session_id };
2450
+ }
2451
+ if ((host.host_type === "agent" || host.host_type === "browser") && host.host_session_id === null) {
2452
+ return { host_type: host.host_type, host_instance_id: host.host_instance_id, host_session_id: null };
2453
+ }
2454
+ return null;
2455
+ }
2456
+ function validateLobbyHostContext(value) {
2457
+ const host = parseLobbyParticipation(value);
2458
+ if (!host) throw new InvalidHostContextError("Host IDs must be 1\u2013128 characters without whitespace or control characters; desktop requires a session ID.");
2459
+ return Object.freeze(host);
2460
+ }
2461
+ function resolveLobbyHostContext(env = process.env) {
2462
+ const instanceId = env.CLAWCLAW_HOST_INSTANCE_ID;
2463
+ const sessionId = env.CLAWCLAW_HOST_SESSION_ID;
2464
+ if (isDesktopMode(env)) {
2465
+ if (!validId(instanceId) || !validId(sessionId)) {
2466
+ throw new InvalidHostContextError("Desktop must provide CLAWCLAW_HOST_INSTANCE_ID and CLAWCLAW_HOST_SESSION_ID (1\u2013128 characters, no whitespace/control characters).");
2467
+ }
2468
+ return Object.freeze({ host_type: "desktop", host_instance_id: instanceId, host_session_id: sessionId });
2469
+ }
2470
+ if (sessionId !== void 0) {
2471
+ throw new InvalidHostContextError("CLAWCLAW_HOST_SESSION_ID is only valid with CLAWCLAW_IS_DESKTOP=true; omit it for standalone agents.");
2472
+ }
2473
+ return validateLobbyHostContext({ host_type: "agent", host_instance_id: instanceId ?? agentInstanceId, host_session_id: null });
2474
+ }
2475
+ function lobbyHostHeaders(host) {
2476
+ const valid = validateLobbyHostContext(host);
2477
+ return {
2478
+ "X-Host-Type": valid.host_type,
2479
+ "X-Host-Instance-Id": valid.host_instance_id,
2480
+ ...valid.host_type === "desktop" ? { "X-Host-Session-Id": valid.host_session_id } : {}
2481
+ };
2482
+ }
2483
+
2431
2484
  // src/lib/game-client.ts
2432
2485
  function agentMetadataHeaders(options) {
2433
2486
  const headers = {};
@@ -2437,6 +2490,8 @@ function agentMetadataHeaders(options) {
2437
2490
  return Object.keys(headers).length > 0 ? headers : void 0;
2438
2491
  }
2439
2492
  var GameClient = class _GameClient {
2493
+ resolvedHostContext;
2494
+ hostEnvironment;
2440
2495
  http;
2441
2496
  ws = null;
2442
2497
  gameSyncIngress;
@@ -2463,6 +2518,12 @@ var GameClient = class _GameClient {
2463
2518
  return this.lastCustomTtsWarning;
2464
2519
  }
2465
2520
  constructor(config) {
2521
+ this.resolvedHostContext = config.hostContext ? validateLobbyHostContext(config.hostContext) : void 0;
2522
+ this.hostEnvironment = {
2523
+ CLAWCLAW_IS_DESKTOP: process.env.CLAWCLAW_IS_DESKTOP,
2524
+ CLAWCLAW_HOST_INSTANCE_ID: process.env.CLAWCLAW_HOST_INSTANCE_ID,
2525
+ CLAWCLAW_HOST_SESSION_ID: process.env.CLAWCLAW_HOST_SESSION_ID
2526
+ };
2466
2527
  this.apiKey = config.apiKey;
2467
2528
  this.enableWs = config.enableWs ?? false;
2468
2529
  this.rawWsMessageSink = config.rawWsMessageSink;
@@ -2617,14 +2678,28 @@ var GameClient = class _GameClient {
2617
2678
  return this.http.get("/api/v1/agents/me");
2618
2679
  }
2619
2680
  // ─── Queue API (→ lobby, auto game server discovery) ───
2681
+ /** Lazy so login, Hub and read-only status remain usable before host setup. */
2682
+ get lobbyHostContext() {
2683
+ return this.resolvedHostContext ??= resolveLobbyHostContext(this.hostEnvironment);
2684
+ }
2685
+ async enterLobby(path, body, metadata) {
2686
+ const response = await this.http.postRaw(path, body, {
2687
+ ...agentMetadataHeaders(metadata),
2688
+ ...lobbyHostHeaders(this.lobbyHostContext)
2689
+ });
2690
+ if (response.status < 200 || response.status >= 300 || response.body.kind === "json" && response.body.value?.success === false) {
2691
+ throw new ApiError(response.status, response.body.rawText, "POST", path, response);
2692
+ }
2693
+ if (response.body.kind !== "json") throw new SyntaxError(`Unexpected non-JSON response from ${path}`);
2694
+ return response.body.value;
2695
+ }
2620
2696
  async joinQueue(options = "clawclaw") {
2621
2697
  const gameType = typeof options === "string" ? options : options.gameType ?? "clawclaw";
2622
2698
  const mode = typeof options === "string" ? "match" : options.mode ?? "match";
2623
2699
  const agentType = typeof options === "string" ? void 0 : options.agentType;
2624
2700
  const monitorStatus = typeof options === "string" ? void 0 : options.monitorStatus;
2625
2701
  const llmModel = typeof options === "string" ? void 0 : options.llmModel;
2626
- const headers = agentMetadataHeaders({ agentType, monitorStatus, llmModel });
2627
- const result = await this.http.post("/api/v1/queue/join", { game_type: gameType, mode }, headers);
2702
+ const result = await this.enterLobby("/api/v1/queue/join", { game_type: gameType, mode }, { agentType, monitorStatus, llmModel });
2628
2703
  this.registry.updateFromQueueResponse(result);
2629
2704
  return result;
2630
2705
  }
@@ -2645,11 +2720,10 @@ var GameClient = class _GameClient {
2645
2720
  // ─── Room API (→ lobby) ───
2646
2721
  async createRoom(options = {}) {
2647
2722
  const normalized = typeof options === "string" ? { roomType: options } : options;
2648
- const headers = agentMetadataHeaders(normalized);
2649
- return normalized.roomType ? this.http.post("/api/v1/room/create", { room_type: normalized.roomType }, headers) : this.http.post("/api/v1/room/create", void 0, headers);
2723
+ return normalized.roomType ? this.enterLobby("/api/v1/room/create", { room_type: normalized.roomType }, normalized) : this.enterLobby("/api/v1/room/create", void 0, normalized);
2650
2724
  }
2651
2725
  async joinRoom(roomCode, metadata = {}) {
2652
- return this.http.post("/api/v1/room/join", { room_code: roomCode }, agentMetadataHeaders(metadata));
2726
+ return this.enterLobby("/api/v1/room/join", { room_code: roomCode }, metadata);
2653
2727
  }
2654
2728
  async getRoomStatus() {
2655
2729
  return this.http.get("/api/v1/room/status");
@@ -35,7 +35,7 @@ ccl game status
35
35
  | `room` | 已知在房间中,但服务端未返回可识别的 `room_type` |
36
36
  | `unknown` | 服务端返回了 CCL 尚不识别的参与状态;命令退出码为 1 |
37
37
 
38
- 输出还可能包含 `queue_status`、`mode`、`game_id`、`room_code`、`room_type` 和 `room_status`。状态以服务端参与记录为准,不代表本地 CCL Runtime 进程是否正在运行。
38
+ 输出还可能包含 `queue_status`、`mode`、`game_id`、`room_code`、`room_type` 和 `room_status`。房间/已分配游戏另输出 `origin`(后端 participation 的宿主归属对象,未知为 null),匹配/空闲时省略。状态以服务端参与记录为准,不代表本地 CCL Runtime 进程是否正在运行。宿主字段与生命周期见[客户端接入约定](./user-guide/desktop-auth.md#lobby-宿主与会话上下文)。
39
39
 
40
40
  CCL 每次先查询 `/api/v1/queue/status`;仅当结果为 `in_room` 时,再查询 `/api/v1/room/status` 区分好友房和训练房。这两个查询都是只读操作。
41
41
 
@@ -88,6 +88,7 @@ CCL 在以下条件全部满足时发送一个 `mailbox_batch`:
88
88
  | 对局进行中 | `visual.*`、任务、玩家变化、击杀、尸体和紧急事件 |
89
89
  | 会议与投票 | `meeting_briefing`、`speech*`、`vote_speech_phase_ended` |
90
90
  | 对局结束 | `game_over` |
91
+ | Lobby 连接被替换或登记失效 | `lobby_connection_replaced`;包含 `route`、`close_code`、`reason`、`retryable: false`,CCL 已停止自身自动重连 |
91
92
 
92
93
  发送格式:
93
94
 
@@ -42,4 +42,36 @@ Desktop 模式下 `account register`(包括 `--check`)和 `account switch`
42
42
 
43
43
  已有 `synced` 模式的账号导入、回写由客户端负责协调:托管登录期间,以客户端传给 `bind` 的账号为准,不应再用全局账号同步覆盖 `auth.json`,也不要把 `unbind` 清空的客户端登录当作删除全局账号的指令。本次 CCL 不新增同步机制。
44
44
 
45
- 本期没有新增 deviceId/sessionId、请求头、顶号错误码或自动登出策略。客户端何时调用 `unbind` 仍由客户端决定。
45
+ 客户端何时调用 `unbind` 仍由客户端决定。Lobby 连接被替换不会触发自动解绑。
46
+
47
+ ## Lobby 宿主与会话上下文
48
+
49
+ 启动游戏 Runtime(`start`、`join`)时,Desktop 还必须在子进程环境中提供:
50
+
51
+ ```text
52
+ CLAWCLAW_IS_DESKTOP=true
53
+ CLAWCLAW_HOST_INSTANCE_ID=<Desktop 持久实例 ID>
54
+ CLAWCLAW_HOST_SESSION_ID=<发起调用的桌面会话 ID>
55
+ ```
56
+
57
+ Desktop 首次创建实例身份时生成唯一实例 ID 并持久保存,所有内部会话共享;不同桌面实例不得共用同一 ID。退出再打开、进程重启和网络重连均沿用实例 ID;恢复原内部会话时也沿用原会话 ID,只有新建会话才生成新的会话 ID。CCL 和该会话的内嵌 UI 使用相同的两个 ID。两个 ID 均为 1–128 字符,不含空白或控制字符,建议使用 UUID。不要使用账号、设备序列号或 CCL 内部游戏 session ID 代替。
58
+
59
+ Desktop 为每次调用注入正确上下文,CCL 在创建请求客户端时保存其快照;不会将这些字段写入共享 `auth.json`。`auth bind/status/unbind`、Hub 和只读查询不要求先提供 Host ID。Desktop 游戏启动缺字段或字段非法时返回 `INVALID_HOST_CONTEXT`,不降级成独立 Agent。
60
+
61
+ CCL 在 `/queue/join`、`/room/create`(含训练房)、`/room/join` 和 `/agent/ws` 握手中发送对应的 `X-Host-Type`、`X-Host-Instance-Id`、`X-Host-Session-Id` 请求头。身份认证继续使用原 API Key。仅 WS 携带字段不能建立参与归属;重复入队、加入房间和重连不会转移已存在的归属。
62
+
63
+ 独立 CCL 使用 `host_type=agent`,默认实例 ID 在当前 CCL 进程内稳定;宿主也可通过 `CLAWCLAW_HOST_INSTANCE_ID` 提供稳定 ID。独立模式必须省略 `CLAWCLAW_HOST_SESSION_ID`,包括空字符串;HTTP/WS 不发送会话请求头。
64
+
65
+ CCL 继续通过 HTTP `/queue/status` 查询匹配状态,房间长流使用 `/agent/ws`。`/queue/ws` 的同桌面多会话例外不会改变 `/agent/ws` 的账号单连接规则,也不改变 CCL 的 workspace Owner 锁。
66
+
67
+ `ccl game status` 的顶层 `origin` 和 `ccl load` 的 `participation.origin` 保留后端参与归属:
68
+
69
+ ```json
70
+ {"host_type":"desktop","host_instance_id":"H1","host_session_id":"S1"}
71
+ ```
72
+
73
+ 非桌面归属的 `host_session_id` 为 `null`。房间/已分配游戏缺少字段、为 null 或字段无效时输出 `origin: null`,不推断属于当前会话;匹配/空闲状态省略 `origin`,不沿用旧值。原有参与状态字段保持不变。归属供宿主展示与接续判断,CCL 不将它用作新增权限校验;现有显式 `join` 接续入口继续可用,也不会把接续当作服务端归属已转移。
74
+
75
+ Lobby 收到扁平 `replaced` 或关闭码 4002 任意一个时,CCL 停止该连接的自动重连,发出 `lobby_connection_replaced` 系统通知,并以内部完成原因 `replaced` 结束。该通知不表示 API Key 失效,也不会主动退出房间、取消匹配或登出。普通断网采用退避重连;4003 宿主字段错误终止并报告,4004 重新查询房间资格,1000/4005/4006 分别按正常关闭/房间结束/维护处理;连续握手失败三次后停止并报告,避免只收到 1006 时无限重试。GameSync 继续使用自身原有协议。
76
+
77
+ 后端旧消息仍可读取;新连接协调规则需要目标环境部署相应协议并开启 `LOBBY_WS_COORDINATION_ENABLED`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.10.7",
3
+ "version": "0.10.8",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: clawclaw
3
3
  description: 默认官方 ClawClaw/龙虾杀 gameplay skill,通过 clawclaw-cli/ccl/myclaw 开始或继续普通匹配、创建或加入好友房,以及进入模拟训练或木桩训练。Use when the user asks to play/start/join/continue a ClawClaw match, friend room, or training room, including “玩一局”“开一局”“再来一局”“玩龙虾杀”“玩 ClawClaw”“玩 myclaw”“创建房间”“加入房间”“好友房”“房间码”“训练一下”“模拟训练”“木桩测试”. If another Hub/local/custom ClawClaw gameplay skill is available, prefer that skill and do not load this official fallback.
4
- version: 4.8.124
4
+ version: 4.8.125
5
5
  ---
6
6
 
7
7
  # 龙虾杀(ClawClaw)
@@ -27,7 +27,7 @@ Claude Code 的长运行流命令(`ccl start match`、`ccl start room`、`ccl
27
27
  - Monitor 的 `messages[]` 已包含本次主动送达、可直接决策的短 Event;每条通知不超过 500 字符。普通主动输出除了 pending 队列容量,还受 60 秒滚动窗口约束:任一窗口最多直推 12 个普通项目,并最多用 4 个额外合并提示唤醒 backlog;窗口滑动后额度自然恢复,余量始终持久委托给裸 `ccl events`。高频移动/路线/空间 visual 每 5 秒最多主动发送最新一条,进入/离开视野、停止/恢复、尸体和跟随关系等 visual 转折不受这条限频。击杀、死亡、有效目击、蟹破坏任务被打断、紧急任务 30 秒/20 秒倒计时、能力就绪/耗尽、Strategy 完成/失败/取消/替换、关键会议、每次 `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。
28
28
  - 固定需要详情的是开场地图/身份/名单/任务/会议结算和参与/房间详情:`game_started`、`role_assigned`、`players_changed`、`meeting_briefing`、`exile` / `no_exile`、`joined`、`room_created`、`room_joined`。异常长的其它 Event 也会动态列入 `details_required`。
29
29
  - 如果工具面板没有 Monitor,先用 `ToolSearch` 查询 `select:Monitor`,不要降级到 Bash。
30
- - 正常退出参与使用 `ccl game quit`,不要用 `TaskStop` 代替后端退出。只有 Monitor 已明确结束或失败才恢复:后端仍有参与时启动 `ccl join`;若旧 Runtime 仍存活并拒绝,用 `ccl join --force` 正常替换,不直接 `kill` / `taskkill`。
30
+ - 正常退出参与使用 `ccl game quit`,不要用 `TaskStop` 代替后端退出。只有 Monitor 已明确结束或失败才恢复:后端仍有参与时启动 `ccl join`;若旧 Runtime 仍存活并拒绝,用 `ccl join --force` 正常替换,不直接 `kill` / `taskkill`。收到 `lobby_connection_replaced` 是例外:连接被替换或登记失效后停止自动恢复,告知玩家,只有玩家明确要求接续才再次 `join`;不要自动退出房间、取消匹配或登出。
31
31
 
32
32
  OpenClaw 普通匹配使用 `clawclaw_game_start({id:"clawclaw"})`;好友房、训练建房和恢复已有参与使用宿主等价的前台 stream 工具。
33
33
 
@@ -160,7 +160,7 @@ Hub 失败按 `code`、`operation` 和 `hint` 处理,不按 HTTP 422 猜测账
160
160
 
161
161
  玩家明确要求修改已装配资源的本地操作名时,按类型使用 `ccl strategy rename <当前操作名> <新操作名>`、`ccl perception rename <当前操作名> <新操作名>` 或 `ccl persona rename <当前操作名> <新操作名>`。先用当前 list/info 核对目标,不能把源码 `declared_id` 或 Hub 展示名当作当前操作名。新名字不能与同账号、同类型中已分配的操作名冲突;已取消装配但保留映射的资源仍占名,未装配且从未分配操作名的资源不占名。命令只修改本地操作名及其配置引用,不修改源码 ID、文件路径或 Hub 身份;Owner Runtime 正在运行时拒绝改名。成功后完整执行 `ccl load` 再开局。不要自行编辑登记文件或直接删去 `_1`。
162
162
 
163
- 如果 `participation` 显示后端已有匹配、房间或对局,但当前会话没有健康 Monitor,第一步统一在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行裸 `ccl join`,等待第一条非 error 通知。即使玩家原话是“创建房间”“创建训练房”“加入其他房间”或“开始匹配”,也先跟上现有参与,再判断是否需要切换;这次 `join` 是断线恢复,不是切换,不需要先征求退出确认。
163
+ 如果 `participation` 显示后端已有匹配、房间或对局,但当前会话没有健康 Monitor,且没有收到要求停止自动恢复的 `lobby_connection_replaced`,第一步统一在新的 30 分钟 Monitor(`timeout_ms=1800000`)中运行裸 `ccl join`,等待第一条非 error 通知。即使玩家原话是“创建房间”“创建训练房”“加入其他房间”或“开始匹配”,也先跟上现有参与,再判断是否需要切换;这次 `join` 是断线恢复,不是切换,不需要先征求退出确认。若已收到 `lobby_connection_replaced`,仅在玩家明确要求接续后恢复。
164
164
 
165
165
  跟上当前参与后,不要把玩家原话机械套进固定句式表。先分开判断三件事:玩家是在继续当前参与还是进入新的参与;目标房间的精确类型是否已经知道;执行目标是否需要退出当前参与。
166
166
 
@@ -25,10 +25,13 @@ import type {
25
25
  } from './room.js';
26
26
  import { synthesizeConfiguredTts } from './custom-tts.js';
27
27
  import type { TransportResponse } from '../short-command/transport-response.js';
28
+ import { lobbyHostHeaders, resolveLobbyHostContext, validateLobbyHostContext, type LobbyHostContext } from './lobby-host-context.js';
28
29
 
29
30
  export { ApiError } from './http-transport.js';
30
31
 
31
32
  export interface GameClientConfig {
33
+ /** One stable host context for Lobby participation and socket reconnects. */
34
+ hostContext?: LobbyHostContext;
32
35
  lobbyUrl: string;
33
36
  gameServerUrl?: string;
34
37
  apiKey: string;
@@ -72,6 +75,8 @@ function agentMetadataHeaders(options: RoomEntryMetadata): Record<string, string
72
75
  }
73
76
 
74
77
  export class GameClient {
78
+ private resolvedHostContext?: LobbyHostContext;
79
+ private readonly hostEnvironment: NodeJS.ProcessEnv;
75
80
  private http: HttpTransport;
76
81
  private ws: Pick<WsClient, keyof WsClient> | null = null;
77
82
  private readonly gameSyncIngress?: GameClientConfig['gameSyncIngress'];
@@ -115,6 +120,12 @@ export class GameClient {
115
120
  }
116
121
 
117
122
  constructor(config: GameClientConfig) {
123
+ this.resolvedHostContext = config.hostContext ? validateLobbyHostContext(config.hostContext) : undefined;
124
+ this.hostEnvironment = {
125
+ CLAWCLAW_IS_DESKTOP: process.env.CLAWCLAW_IS_DESKTOP,
126
+ CLAWCLAW_HOST_INSTANCE_ID: process.env.CLAWCLAW_HOST_INSTANCE_ID,
127
+ CLAWCLAW_HOST_SESSION_ID: process.env.CLAWCLAW_HOST_SESSION_ID,
128
+ };
118
129
  this.apiKey = config.apiKey;
119
130
  this.enableWs = config.enableWs ?? false;
120
131
  this.rawWsMessageSink = config.rawWsMessageSink;
@@ -318,6 +329,24 @@ export class GameClient {
318
329
 
319
330
  // ─── Queue API (→ lobby, auto game server discovery) ───
320
331
 
332
+ /** Lazy so login, Hub and read-only status remain usable before host setup. */
333
+ get lobbyHostContext(): LobbyHostContext {
334
+ return this.resolvedHostContext ??= resolveLobbyHostContext(this.hostEnvironment);
335
+ }
336
+
337
+ private async enterLobby(path: string, body: unknown, metadata: RoomEntryMetadata): Promise<any> {
338
+ const response = await this.http.postRaw(path, body, {
339
+ ...agentMetadataHeaders(metadata),
340
+ ...lobbyHostHeaders(this.lobbyHostContext),
341
+ });
342
+ if (response.status < 200 || response.status >= 300
343
+ || (response.body.kind === 'json' && (response.body.value as { success?: unknown } | null)?.success === false)) {
344
+ throw new ApiError(response.status, response.body.rawText, 'POST', path, response);
345
+ }
346
+ if (response.body.kind !== 'json') throw new SyntaxError(`Unexpected non-JSON response from ${path}`);
347
+ return response.body.value;
348
+ }
349
+
321
350
 
322
351
 
323
352
  async joinQueue(options: string | { gameType?: string; mode?: QueueMode; agentType?: string; monitorStatus?: 'on' | 'off'; llmModel?: string } = 'clawclaw'): Promise<any> {
@@ -331,8 +360,7 @@ export class GameClient {
331
360
  // X-Agent-Type — the agent platform (e.g. claude-code, openclaw)
332
361
  // X-Monitor-Status — whether the Claude Code Monitor tool is on/off this match
333
362
  // X-LLM-Model — the exact/canonical reasoning model ID the lobster (龙虾) agent runs as this match
334
- const headers = agentMetadataHeaders({ agentType, monitorStatus, llmModel });
335
- const result = await this.http.post('/api/v1/queue/join', { game_type: gameType, mode }, headers);
363
+ const result = await this.enterLobby('/api/v1/queue/join', { game_type: gameType, mode }, { agentType, monitorStatus, llmModel });
336
364
  this.registry.updateFromQueueResponse(result);
337
365
  return result;
338
366
  }
@@ -359,14 +387,13 @@ export class GameClient {
359
387
 
360
388
  async createRoom(options: RoomType | CreateRoomOptions = {}): Promise<any> {
361
389
  const normalized = typeof options === 'string' ? { roomType: options } : options;
362
- const headers = agentMetadataHeaders(normalized);
363
390
  return normalized.roomType
364
- ? this.http.post('/api/v1/room/create', { room_type: normalized.roomType }, headers)
365
- : this.http.post('/api/v1/room/create', undefined, headers);
391
+ ? this.enterLobby('/api/v1/room/create', { room_type: normalized.roomType }, normalized)
392
+ : this.enterLobby('/api/v1/room/create', undefined, normalized);
366
393
  }
367
394
 
368
395
  async joinRoom(roomCode: string, metadata: RoomEntryMetadata = {}): Promise<any> {
369
- return this.http.post('/api/v1/room/join', { room_code: roomCode }, agentMetadataHeaders(metadata));
396
+ return this.enterLobby('/api/v1/room/join', { room_code: roomCode }, metadata);
370
397
  }
371
398
 
372
399
  async getRoomStatus(): Promise<any> {
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDesktopMode } from './desktop-mode.js';
3
+ import { ApiError } from './http-transport.js';
4
+
5
+ /** Participation origin, not an authentication or GameSync session identity. */
6
+ export type LobbyHostContext =
7
+ | { readonly host_type: 'desktop'; readonly host_instance_id: string; readonly host_session_id: string }
8
+ | { readonly host_type: 'agent' | 'browser'; readonly host_instance_id: string; readonly host_session_id: null };
9
+
10
+ const agentInstanceId = randomUUID();
11
+
12
+ export class InvalidHostContextError extends Error {
13
+ readonly code = 'INVALID_HOST_CONTEXT';
14
+ constructor(message: string) {
15
+ super(`INVALID_HOST_CONTEXT: ${message}`);
16
+ this.name = 'InvalidHostContextError';
17
+ }
18
+ }
19
+
20
+ function validId(value: unknown): value is string {
21
+ return typeof value === 'string' && [...value].length >= 1 && [...value].length <= 128
22
+ && !/[\p{White_Space}\p{Cc}]/u.test(value);
23
+ }
24
+
25
+ /** Unknown/legacy origins stay unknown; never fill them from the receiving client. */
26
+ export function parseLobbyParticipation(value: unknown): LobbyHostContext | null {
27
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
28
+ const host = value as Record<string, unknown>;
29
+ if (!validId(host.host_instance_id)) return null;
30
+ if (host.host_type === 'desktop' && validId(host.host_session_id)) {
31
+ return { host_type: 'desktop', host_instance_id: host.host_instance_id, host_session_id: host.host_session_id };
32
+ }
33
+ if ((host.host_type === 'agent' || host.host_type === 'browser') && host.host_session_id === null) {
34
+ return { host_type: host.host_type, host_instance_id: host.host_instance_id, host_session_id: null };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ export function validateLobbyHostContext(value: LobbyHostContext): LobbyHostContext {
40
+ const host = parseLobbyParticipation(value);
41
+ if (!host) throw new InvalidHostContextError('Host IDs must be 1–128 characters without whitespace or control characters; desktop requires a session ID.');
42
+ return Object.freeze(host);
43
+ }
44
+
45
+ export function resolveLobbyHostContext(env: NodeJS.ProcessEnv = process.env): LobbyHostContext {
46
+ const instanceId = env.CLAWCLAW_HOST_INSTANCE_ID;
47
+ const sessionId = env.CLAWCLAW_HOST_SESSION_ID;
48
+ if (isDesktopMode(env)) {
49
+ if (!validId(instanceId) || !validId(sessionId)) {
50
+ throw new InvalidHostContextError('Desktop must provide CLAWCLAW_HOST_INSTANCE_ID and CLAWCLAW_HOST_SESSION_ID (1–128 characters, no whitespace/control characters).');
51
+ }
52
+ return Object.freeze({ host_type: 'desktop', host_instance_id: instanceId, host_session_id: sessionId });
53
+ }
54
+ if (sessionId !== undefined) {
55
+ throw new InvalidHostContextError('CLAWCLAW_HOST_SESSION_ID is only valid with CLAWCLAW_IS_DESKTOP=true; omit it for standalone agents.');
56
+ }
57
+ return validateLobbyHostContext({ host_type: 'agent', host_instance_id: instanceId ?? agentInstanceId, host_session_id: null });
58
+ }
59
+
60
+ export function lobbyHostHeaders(host: LobbyHostContext): Record<string, string> {
61
+ const valid = validateLobbyHostContext(host);
62
+ return {
63
+ 'X-Host-Type': valid.host_type,
64
+ 'X-Host-Instance-Id': valid.host_instance_id,
65
+ ...(valid.host_type === 'desktop' ? { 'X-Host-Session-Id': valid.host_session_id } : {}),
66
+ };
67
+ }
68
+
69
+ export function isInvalidHostContextError(error: unknown): boolean {
70
+ if (error instanceof InvalidHostContextError) return true;
71
+ if (!(error instanceof ApiError)) return false;
72
+ try { return JSON.parse(error.body)?.error?.code === 'INVALID_HOST_CONTEXT'; }
73
+ catch { return false; }
74
+ }
@@ -7,6 +7,7 @@ import {
7
7
  queueStatus,
8
8
  unwrapData,
9
9
  } from './room.js';
10
+ import { parseLobbyParticipation, type LobbyHostContext } from './lobby-host-context.js';
10
11
 
11
12
  export const GAME_STATUS_SCHEMA = 'ccl.game-status.v1' as const;
12
13
 
@@ -28,6 +29,8 @@ export interface GameParticipationStatus {
28
29
  room_type?: string;
29
30
  room_status?: string;
30
31
  game_id?: string;
32
+ /** Backend participation origin. Null means unknown; absent while idle/matching. */
33
+ origin?: LobbyHostContext | null;
31
34
  }
32
35
 
33
36
  export interface ParticipationStatusClient {
@@ -74,6 +77,8 @@ export async function queryGameParticipationStatus(
74
77
  schema: GAME_STATUS_SCHEMA,
75
78
  status,
76
79
  queue_status: currentQueueStatus,
80
+ ...((currentQueueStatus === 'in_room' || currentQueueStatus === 'allocated')
81
+ ? { origin: parseLobbyParticipation(queue?.participation) } : {}),
77
82
  }, {
78
83
  mode,
79
84
  room_code: roomCode,
@@ -626,6 +626,8 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
626
626
  return '房间对局已结束,但账号已不在原房间。';
627
627
  case 'room_ping_timeout':
628
628
  return '房间 Lobby 连接心跳超时,正在重连。';
629
+ case 'lobby_connection_replaced':
630
+ return '大厅连接已被替换或登记已失效,已停止自动重连。需要继续时请明确发起接续。';
629
631
  case 'robot_speak_rule':
630
632
  return `发言提示:${truncate(event.message ?? event.text, maxTextLength)}`;
631
633
  case 'strategy_alert':
@@ -271,6 +271,7 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
271
271
  });
272
272
 
273
273
  export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
274
+ lobby_connection_replaced: () => 'The Lobby connection was replaced or its registration expired. Automatic reconnection has stopped. Tell the user and resume only after an explicit request; do not automatically run ccl join, start another runtime, log out, or leave the room/game.',
274
275
  joined: (event) => {
275
276
  if (typeof event.url !== 'string' || event.url.length === 0) return undefined;
276
277
  return event.recovered === true || event.resumed === true
@@ -12,6 +12,7 @@ export const CLAWCLAW_SYSTEM_CONTROL_EVENTS = new Set([
12
12
  'match_start', 'match_waiting', 'match_timeout', 'user_left_game', 'session_left', 'quit_failed',
13
13
  'room_attached', 'room_lobby_reconnect_failed', 'room_lobby_missing', 'room_returning_to_lobby',
14
14
  'room_ping_timeout', 'room_destroyed', 'room.self_left', 'room.game_start_failed',
15
+ 'lobby_connection_replaced',
15
16
  ]);
16
17
 
17
18
  export const BUILTIN_PERCEPTION_PREFIX = 'clawclaw.perception.system.';
@@ -562,6 +562,8 @@ export async function runClawclawOwner(
562
562
  },
563
563
  });
564
564
  closeGameSyncTransports = () => client.closeGameSyncTransports();
565
+ // Validate before starting a participation or attaching any game transport.
566
+ void client.lobbyHostContext;
565
567
  const workspaceDir = getWorkspaceDir();
566
568
  ensureAccountUserDataLayout(workspaceDir, options.profile);
567
569
  const perceptionConfig = readWorkspacePerceptionConfig();
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import WebSocket from 'ws';
3
+ import { lobbyHostHeaders, type LobbyHostContext } from '../../../../lib/lobby-host-context.js';
3
4
  import {
4
5
  normalizeRoomSnapshot,
5
6
  type RoomSnapshot,
@@ -20,6 +21,7 @@ export type ClawclawRoomTransportStopReason =
20
21
  | 'reconcile'
21
22
  | 'replaced'
22
23
  | 'fatal'
24
+ | 'normal'
23
25
  | 'error'
24
26
  | 'shutdown';
25
27
 
@@ -32,7 +34,7 @@ export interface ClawclawRoomCloseInfo {
32
34
  reason: string;
33
35
  }
34
36
 
35
- export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal';
37
+ export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal' | 'normal';
36
38
 
37
39
  export interface ClawclawRoomTransportFrameMeta {
38
40
  connectionId: string;
@@ -45,6 +47,7 @@ export interface ClawclawRoomTransportFrameMeta {
45
47
  export interface ClawclawRoomTransportOptions {
46
48
  url: string;
47
49
  apiKey: string;
50
+ hostContext?: LobbyHostContext;
48
51
  onOpened(connectionId: string, reconnected: boolean): Promise<void> | void;
49
52
  onLiveness(connectionId: string, atMs: number): void;
50
53
  onConnectionChanged(connectionId: string, state: 'reconnecting' | 'disconnected'): Promise<void> | void;
@@ -67,6 +70,7 @@ export interface ClawclawRoomTransportOptions {
67
70
  heartbeatIntervalMs?: number;
68
71
  pongTimeoutMs?: number;
69
72
  reconnectMs?: number;
73
+ maxHandshakeFailures?: number;
70
74
  initialSnapshotTimeoutMs?: number;
71
75
  /** Maximum time to attach or reattach before the aggregate Source reconciles through Lobby HTTP. */
72
76
  reconcileAfterMs?: number;
@@ -132,11 +136,17 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
132
136
  private openedConnections = 0;
133
137
  private physicalFrameSeq = 0;
134
138
  private gameStartedEmitted = false;
139
+ private replacementReceived = false;
140
+ private handshakeFailures = 0;
141
+ private socketOpened = false;
142
+ private reconnectAttempts = 0;
143
+ private readonly hostHeaders: Record<string, string>;
135
144
  private stopped = false;
136
145
  private resolveOutcome!: (outcome: ClawclawRoomTransportOutcome) => void;
137
146
  private readonly outcomePromise: Promise<ClawclawRoomTransportOutcome>;
138
147
 
139
148
  constructor(private readonly options: ClawclawRoomTransportOptions) {
149
+ this.hostHeaders = options.hostContext ? lobbyHostHeaders(options.hostContext) : {};
140
150
  this.webSocketFactory = options.webSocketFactory ?? ((url, init) => new WebSocket(url, init));
141
151
  this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 15_000;
142
152
  this.pongTimeoutMs = options.pongTimeoutMs ?? 10_000;
@@ -185,22 +195,25 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
185
195
  const connectionId = randomUUID();
186
196
  this.connectionId = connectionId;
187
197
  this.physicalFrameSeq = 0;
198
+ this.socketOpened = false;
188
199
  let ws: WebSocket;
189
200
  try {
190
201
  ws = this.webSocketFactory(this.options.url, {
191
- headers: { Authorization: `Bearer ${this.options.apiKey}` },
202
+ headers: { Authorization: `Bearer ${this.options.apiKey}`, ...this.hostHeaders },
192
203
  });
193
204
  } catch (error) {
194
205
  this.options.onDiagnostic('runtime.source.connect_failed', {
195
206
  transport: 'room_ws',
196
207
  error: error instanceof Error ? error.message : String(error),
197
208
  });
198
- this.scheduleReconnect();
209
+ if (!this.recordHandshakeFailure()) this.scheduleReconnect();
199
210
  return;
200
211
  }
201
212
  this.ws = ws;
202
213
  ws.once('open', () => {
203
214
  if (this.stopped || this.ws !== ws) return;
215
+ this.socketOpened = true;
216
+ this.handshakeFailures = 0;
204
217
  const reconnected = this.openedConnections > 0;
205
218
  this.openedConnections += 1;
206
219
  this.enqueue(() => this.options.onOpened(connectionId, reconnected));
@@ -246,6 +259,13 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
246
259
  return;
247
260
  }
248
261
  const type = typeof message?.type === 'string' ? message.type : '';
262
+ if (type === 'replaced') {
263
+ this.handleClose(connectionId, ws, {
264
+ code: 4002,
265
+ reason: typeof message.message === 'string' ? message.message : 'Lobby connection replaced',
266
+ });
267
+ return;
268
+ }
249
269
  if (!type) {
250
270
  this.options.onDiagnostic('runtime.input.rejected', { reason: 'room_ws_message_without_type' });
251
271
  return;
@@ -264,8 +284,10 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
264
284
  replay: type === 'room.snapshot',
265
285
  };
266
286
  this.enqueue(async () => {
287
+ if (this.replacementReceived) return;
267
288
  let terminalPhase: 'room_left' | undefined;
268
289
  if (type === 'room.snapshot') {
290
+ this.reconnectAttempts = 0;
269
291
  this.clearSnapshotDeadline();
270
292
  this.clearAttachDeadline();
271
293
  this.latestSnapshot = normalizeRoomSnapshot(data);
@@ -283,6 +305,7 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
283
305
  terminalPhase,
284
306
  meta,
285
307
  });
308
+ if (this.replacementReceived) return;
286
309
  const started = gameStartedFromRoomSnapshot(this.latestSnapshot);
287
310
  if (started && !this.gameStartedEmitted) {
288
311
  this.gameStartedEmitted = true;
@@ -386,12 +409,16 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
386
409
  info: ClawclawRoomCloseInfo,
387
410
  ): void {
388
411
  if (this.stopped || this.ws !== ws || this.connectionId !== connectionId) return;
412
+ if (info.code === 4002) this.replacementReceived = true;
413
+ const handshakeFailed = !this.socketOpened;
389
414
  this.clearTimers();
390
415
  this.clearSocket();
391
416
  this.enqueue(async () => {
392
- await this.options.onConnectionChanged(connectionId, 'reconnecting');
393
- const decision = await this.options.onClosed(connectionId, info);
417
+ const classified = await this.options.onClosed(connectionId, info);
418
+ const decision = this.replacementReceived ? 'replaced' : classified;
419
+ await this.options.onConnectionChanged(connectionId, decision === 'retry' ? 'reconnecting' : 'disconnected');
394
420
  if (decision === 'retry') {
421
+ if (handshakeFailed && this.recordHandshakeFailure()) return;
395
422
  this.options.onDiagnostic('runtime.source.input_gap', {
396
423
  reason: 'room_ws_disconnected',
397
424
  connection_id: connectionId,
@@ -402,21 +429,29 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
402
429
  this.scheduleReconnect();
403
430
  return;
404
431
  }
405
- this.finish({ reason: decision });
432
+ this.finish({ reason: decision, ...(decision === 'fatal'
433
+ ? { error: new Error(`Lobby WebSocket closed (${info.code ?? 'unknown'}): ${info.reason}`) } : {}) });
406
434
  });
407
435
  }
408
436
 
409
437
  private scheduleReconnect(): void {
410
- if (this.stopped || this.reconnectTimer) return;
438
+ if (this.stopped || this.replacementReceived || this.reconnectTimer) return;
411
439
  this.startAttachDeadline();
412
440
  this.clearSocket();
441
+ const delay = Math.min(30_000, this.reconnectMs * 2 ** Math.min(this.reconnectAttempts++, 5));
413
442
  this.reconnectTimer = setTimeout(() => {
414
443
  this.reconnectTimer = undefined;
415
444
  this.openSocket();
416
- }, this.reconnectMs);
445
+ }, delay);
417
446
  this.reconnectTimer.unref?.();
418
447
  }
419
448
 
449
+ private recordHandshakeFailure(): boolean {
450
+ if (++this.handshakeFailures < (this.options.maxHandshakeFailures ?? 3)) return false;
451
+ this.finish({ reason: 'fatal', error: new Error('Lobby WebSocket handshake repeatedly failed; check credentials and host context before retrying.') });
452
+ return true;
453
+ }
454
+
420
455
  private send(message: Record<string, unknown>, ws = this.ws): void {
421
456
  if (!ws || ws !== this.ws || ws.readyState !== WebSocket.OPEN) return;
422
457
  ws.send(JSON.stringify(message));
@@ -424,7 +459,9 @@ export class ClawclawRoomTransport implements ClawclawRoomTransportPort {
424
459
 
425
460
  private enqueue(operation: () => void | Promise<void>): void {
426
461
  if (this.stopped) return;
427
- this.operationTail = this.operationTail.then(operation).catch((error) => {
462
+ this.operationTail = this.operationTail.then(() => {
463
+ if (!this.stopped) return operation();
464
+ }).catch((error) => {
428
465
  this.finish({ reason: 'error', error });
429
466
  });
430
467
  }
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { isInvalidHostContextError } from '../../../../lib/lobby-host-context.js';
2
3
  import type { AuthProfile } from '../../../../lib/auth.js';
3
4
  import { trainingCharacterId } from '../../../../lib/training-role.js';
4
5
  import {
@@ -683,6 +684,8 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
683
684
  lifecycleEvents: (queue: Record<string, any>) => Record<string, unknown>[],
684
685
  ): Promise<Record<string, any>> {
685
686
  const maintenance = serverServiceStatusFromApiError(originalError);
687
+ // Invalid host declarations did not create a participation; do not adopt an unrelated one.
688
+ if (isInvalidHostContextError(originalError)) throw originalError;
686
689
  if (maintenance) {
687
690
  await this.acceptServiceStatus(maintenance);
688
691
  throw originalError;
@@ -1007,6 +1010,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1007
1010
  const transport = this.createRoomTransport({
1008
1011
  url: this.client.lobbyAgentWsUrl,
1009
1012
  apiKey: this.profile.apiKey,
1013
+ hostContext: this.client.lobbyHostContext,
1010
1014
  webSocketFactory: this.roomWebSocketFactory,
1011
1015
  onOpened: async (connectionId, reconnected) => {
1012
1016
  this.activeRoomConnectionId = connectionId;
@@ -1054,6 +1058,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1054
1058
  status: 'allocated',
1055
1059
  mode: roomMode,
1056
1060
  room_code: outcome.roomCode ?? roomCode,
1061
+ participation: queue.participation ?? null,
1057
1062
  ...outcome.event,
1058
1063
  },
1059
1064
  };
@@ -1066,7 +1071,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1066
1071
  return { kind: 'complete', completion: { reason: 'maintenance' } };
1067
1072
  }
1068
1073
  if (outcome.reason === 'replaced') return { kind: 'complete', completion: { reason: 'replaced' } };
1069
- if (outcome.reason === 'shutdown' || outcome.reason === 'manual') {
1074
+ if (outcome.reason === 'shutdown' || outcome.reason === 'manual' || outcome.reason === 'normal') {
1070
1075
  return { kind: 'complete', completion: { reason: 'stopped' } };
1071
1076
  }
1072
1077
  if (outcome.reason === 'fatal' || outcome.reason === 'error') {
@@ -1780,11 +1785,13 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1780
1785
  }
1781
1786
 
1782
1787
  private classifyRoomClose(code: number | undefined, reason: string): ClawclawRoomCloseDecision {
1788
+ if (code === 4002) return 'replaced';
1789
+ if (code === 1000) return 'normal';
1783
1790
  if (code === 4005) return 'room_destroyed';
1784
1791
  if (code === 4006 || /service_maintenance/i.test(reason)) return 'maintenance';
1785
- if (code === 4002) return 'replaced';
1786
1792
  if (code === 4001) return 'fatal';
1787
- if (code === 4003) return 'reconcile';
1793
+ if (code === 4003) return 'fatal';
1794
+ if (code === 4004) return 'reconcile';
1788
1795
  if (/not in room|already left/i.test(reason)) return 'reconcile';
1789
1796
  return 'retry';
1790
1797
  }
@@ -1794,6 +1801,13 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1794
1801
  info: ClawclawRoomCloseInfo,
1795
1802
  ): Promise<ClawclawRoomCloseDecision> {
1796
1803
  const decision = this.classifyRoomClose(info.code, info.reason);
1804
+ if (decision === 'replaced') {
1805
+ this.currentConnection = 'disconnected';
1806
+ await this.submitCurrentState('control', CLAWCLAW_ROOM_WS_SOURCE.sourceId, connectionId, [{
1807
+ type: 'lobby_connection_replaced', route: '/agent/ws', close_code: 4002,
1808
+ reason: info.reason, retryable: false,
1809
+ }]);
1810
+ }
1797
1811
  if (decision === 'room_destroyed') {
1798
1812
  this.requireRuntime().connectionChanged(
1799
1813
  CLAWCLAW_ROOM_WS_SOURCE.sourceId,
@@ -2394,7 +2408,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2394
2408
  events: completion.reason === 'error'
2395
2409
  ? this.localEvents([{
2396
2410
  type: 'error',
2397
- code: 'SOURCE_FAILED',
2411
+ code: isInvalidHostContextError(completion.error) ? 'INVALID_HOST_CONTEXT' : 'SOURCE_FAILED',
2398
2412
  phase: 'runtime',
2399
2413
  message: errorMessage,
2400
2414
  ...(this.participationMode ? { game_mode: this.participationMode } : {}),
@@ -1,4 +1,5 @@
1
1
  import type { QueueMode } from '../../../../lib/competition.js';
2
+ import type { LobbyHostContext } from '../../../../lib/lobby-host-context.js';
2
3
  import type { ClawclawRoleId } from '../../../../lib/gameplay-config.js';
3
4
  import type {
4
5
  CreateRoomOptions,
@@ -16,6 +17,7 @@ import type {
16
17
  } from './room-transport.js';
17
18
 
18
19
  export interface ClawclawSourceClient extends ClawclawGameTransportClient {
20
+ readonly lobbyHostContext?: LobbyHostContext;
19
21
  readonly lobbyAgentWsUrl: string;
20
22
  getQueueStatus(gameType?: string): Promise<any>;
21
23
  getSettlement(): Promise<any>;
@@ -173,6 +173,7 @@ export const CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
173
173
  'room_ready_to_start',
174
174
  'room_returning_to_lobby',
175
175
  'room_ping_timeout',
176
+ 'lobby_connection_replaced',
176
177
  'room_destroyed',
177
178
  'strategy_alert',
178
179
  'behavior.started',