@myclaw163/clawclaw-cli 0.10.6 → 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.
Files changed (68) hide show
  1. package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
  4. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
  5. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-JMX6D6A3.js +260 -0
  6. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
  7. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
  8. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
  9. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1389 -0
  10. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
  11. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
  12. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
  13. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3108 -0
  14. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
  15. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
  16. package/docs/custom-modules/api-reference.md +10 -8
  17. package/docs/custom-modules/perception.md +26 -3
  18. package/docs/desktop-event-push.md +2 -1
  19. package/docs/runtime/behavior-runtime.md +3 -1
  20. package/docs/runtime/official-perception-modules.md +2 -2
  21. package/docs/user-guide/behavior.md +3 -1
  22. package/docs/user-guide/desktop-auth.md +33 -1
  23. package/package.json +5 -3
  24. package/scripts/build-strategy-worker.mjs +28 -0
  25. package/scripts/migrate-official-perceptions.mjs +157 -0
  26. package/skills/clawclaw/SKILL.md +3 -3
  27. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  28. package/skills/clawclaw/references/TACTICS.md +4 -0
  29. package/skills/clawclaw-creator/SKILL.md +3 -1
  30. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
  31. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
  32. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  33. package/src/commands/capability.ts +4 -2
  34. package/src/commands/load.ts +5 -2
  35. package/src/lib/agent-workspace-skills.ts +12 -7
  36. package/src/lib/capability-cloud-sync.ts +13 -7
  37. package/src/lib/capability-discovery.ts +10 -3
  38. package/src/lib/capability-selection.ts +7 -0
  39. package/src/lib/game-client.ts +33 -6
  40. package/src/lib/lobby-host-context.ts +74 -0
  41. package/src/lib/package-skills.ts +11 -1
  42. package/src/lib/participation-status.ts +5 -0
  43. package/src/pipeline/event-format.ts +2 -0
  44. package/src/pipeline/event-hints.ts +1 -0
  45. package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
  46. package/src/runtime/clawclaw/notification-policy.ts +1 -0
  47. package/src/runtime/clawclaw/owner.ts +21 -4
  48. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
  49. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
  51. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  52. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
  53. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
  54. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
  55. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
  56. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
  57. package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
  58. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
  59. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
  60. package/src/runtime/clawclaw/plugins/source/room-transport.ts +46 -9
  61. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +18 -4
  62. package/src/runtime/clawclaw/plugins/source/types.ts +2 -0
  63. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
  64. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
  65. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  66. package/src/sdk/perception-plugin/index.ts +1 -0
  67. package/src/sdk/perception-plugin/lifecycle.ts +15 -0
  68. package/src/sdk/perception-plugin/module.ts +15 -0
@@ -0,0 +1,3108 @@
1
+ import "./chunk-ZQILO6OM.js";
2
+ import {
3
+ BEHAVIOR_PLUGIN_API_VERSION,
4
+ ClawclawBehavior,
5
+ getAvailableTasks,
6
+ getTaskAvailability,
7
+ getTaskKind,
8
+ isTaskAvailable
9
+ } from "./chunk-3VLVCU6P.js";
10
+ import {
11
+ ClawclawTrigger,
12
+ MAX_TRIGGER_RUNTIME_MS,
13
+ TRIGGER_PLUGIN_API_VERSION
14
+ } from "./chunk-CF6IEQ4V.js";
15
+ import {
16
+ ClawclawParallelPerception,
17
+ ClawclawPerception,
18
+ ClawclawReaction,
19
+ MOVE_MIN_PX,
20
+ PERCEPTION_MODULE_API_VERSION,
21
+ PERCEPTION_PLUGIN_API_VERSION,
22
+ STEP_MOVE_MIN_PX,
23
+ STILL_STEP_MAX_PX,
24
+ TICK_MS,
25
+ actorLabel,
26
+ actorValue,
27
+ angleDegrees,
28
+ cosine,
29
+ cross,
30
+ direction,
31
+ distance,
32
+ dot,
33
+ headingDirection,
34
+ length,
35
+ positionCopy,
36
+ round1,
37
+ timeRange,
38
+ unit,
39
+ vector
40
+ } from "./chunk-QEPKDSLE.js";
41
+ import "./chunk-ATQQZA4X.js";
42
+
43
+ // src/sdk/action.ts
44
+ var Action = class _Action {
45
+ type;
46
+ payload;
47
+ /**
48
+ * Spectator-visible reasoning string sent as `thinking_content` to the server.
49
+ * Visible to observers only — not exposed to other in-game players.
50
+ */
51
+ thinkingContent;
52
+ constructor(type, payload, thinkingContent = null) {
53
+ this.type = type;
54
+ this.payload = payload;
55
+ this.thinkingContent = thinkingContent;
56
+ Object.freeze(this);
57
+ Object.freeze(this.payload);
58
+ }
59
+ /**
60
+ * Attach (or replace) the spectator-visible thinking content.
61
+ * Returns a **new** immutable `Action` — the original is unchanged.
62
+ *
63
+ * @example Action.kill(7).withThinking('Safe kill — only one witness.')
64
+ */
65
+ withThinking(content) {
66
+ return new _Action(this.type, { ...this.payload }, content);
67
+ }
68
+ /**
69
+ * Move toward a room (by name) or a coordinate target.
70
+ *
71
+ * @param target Room id string, or a `{ x, y }` coordinate pair.
72
+ * @param stopOnPlayer If true, movement stops when encountering another alive player.
73
+ */
74
+ static move(target, stopOnPlayer = false) {
75
+ if (typeof target === "string") {
76
+ const payload2 = { target };
77
+ if (stopOnPlayer) payload2.stop_on_player = true;
78
+ return new _Action("move", payload2, `\u524D\u5F80 ${target}`);
79
+ }
80
+ const payload = { target_x: target.x, target_y: target.y };
81
+ if (stopOnPlayer) payload.stop_on_player = true;
82
+ return new _Action("move", payload);
83
+ }
84
+ /**
85
+ * Kill the player at the given seat number.
86
+ * Only succeeds when cooldown is ready, a kill use remains, and the target is in range.
87
+ * Seats are 1-based; the server resolves the target by `target_seat`.
88
+ */
89
+ static kill(seat) {
90
+ return new _Action("kill", { target_seat: seat }, `\u51FB\u6740 ${seat}\u53F7`);
91
+ }
92
+ /**
93
+ * Broadcast a speech during the wandering phase.
94
+ *
95
+ * @param text Words spoken (audible to nearby players).
96
+ * @param thinkingContent Optional spectator-visible reasoning.
97
+ * @param audioUrl Legacy owner/manual-command-only uploaded audio URL.
98
+ * Behavior-originated actions must omit this parameter;
99
+ * the runtime rejects Behavior actions that contain `audio_url`.
100
+ */
101
+ static speech(text, thinkingContent, audioUrl) {
102
+ const payload = { text };
103
+ if (audioUrl) payload.audio_url = audioUrl;
104
+ return new _Action("speech", payload, thinkingContent ?? null);
105
+ }
106
+ /**
107
+ * Cast a vote during the meeting vote sub-phase.
108
+ *
109
+ * @param seat Seat number (1-based) of the player to vote out. `0` means skip.
110
+ */
111
+ static vote(seat) {
112
+ return new _Action("vote", { target_seat: seat }, seat === 0 ? "\u6295\u7968 \u8DF3\u8FC7" : `\u6295\u7968 ${seat}\u53F7`);
113
+ }
114
+ /**
115
+ * Execute (or move toward) a task.
116
+ *
117
+ * @param taskName Optional task name. Omit to let the server resolve which
118
+ * task to execute at the current location.
119
+ */
120
+ static doTask(taskName) {
121
+ return new _Action("task", taskName ? { task_name: taskName } : {}, taskName ? `\u6267\u884C\u4EFB\u52A1 ${taskName}` : "\u6267\u884C\u4EFB\u52A1");
122
+ }
123
+ /**
124
+ * Report a corpse to trigger an emergency meeting.
125
+ *
126
+ * @param corpseName Name of the dead player (written to thinking log).
127
+ * @param room Room where the corpse was found.
128
+ */
129
+ static report(corpseName, room) {
130
+ const thinking = corpseName ? `\u53D1\u73B0\u5C38\u4F53\uFF08${corpseName}${room ? ` \u5728 ${room}` : ""}\uFF09\uFF0C\u62A5\u544A\u53EC\u5F00\u4F1A\u8BAE` : "\u53D1\u73B0\u5C38\u4F53\uFF0C\u62A5\u544A\u53EC\u5F00\u4F1A\u8BAE";
131
+ return new _Action("report", {}, thinking);
132
+ }
133
+ /**
134
+ * Pure thinking action — sends only `thinking_content` with no in-game effect.
135
+ * Useful for pushing reasoning text to spectators without altering game state.
136
+ */
137
+ static think() {
138
+ return new _Action("think", {}, "\u6B63\u5728\u601D\u8003...");
139
+ }
140
+ /**
141
+ * @deprecated Sabotage emergencies now start automatically when a Crab
142
+ * completes one of its assigned sabotage tasks. Submit the existing task
143
+ * action instead.
144
+ */
145
+ static triggerAlarm() {
146
+ throw new Error("trigger_alarm_removed_use_task");
147
+ }
148
+ /**
149
+ * Deserialize an `Action` from a plain JSON object.
150
+ * Accepts both `{ action: "move", … }` and `{ type: "move", … }` formats.
151
+ *
152
+ * @throws {Error} If the object contains no valid action type string.
153
+ */
154
+ static fromJSON(json) {
155
+ const type = json.action ?? json.type;
156
+ if (!type || typeof type !== "string") {
157
+ throw new Error(`Action.fromJSON: missing or invalid action type in ${JSON.stringify(json)}`);
158
+ }
159
+ const { action: _a, type: _t, thinking_content, ...payload } = json;
160
+ return new _Action(type, payload, thinking_content ?? null);
161
+ }
162
+ /**
163
+ * Serialize this `Action` to a plain object for transmission to the server.
164
+ * The `thinking_content` key is omitted when `thinkingContent` is null.
165
+ */
166
+ toJSON() {
167
+ const obj = { action: this.type, ...this.payload };
168
+ if (this.thinkingContent) {
169
+ obj.thinking_content = this.thinkingContent;
170
+ }
171
+ return obj;
172
+ }
173
+ };
174
+
175
+ // src/lib/desktop-mode.ts
176
+ function isDesktopMode(env = process.env) {
177
+ return env.CLAWCLAW_IS_DESKTOP === "true";
178
+ }
179
+ var DESKTOP_LOGIN_MESSAGE = "\u8BF7\u5728\u5BA2\u6237\u7AEF\u767B\u5F55\u6E38\u620F\u8D26\u53F7\u3002CCL \u7684\u767B\u5F55\u8D26\u53F7\u7531\u5BA2\u6237\u7AEF\u7BA1\u7406\u3002";
180
+ function accountRequiredMessage(standaloneMessage) {
181
+ return isDesktopMode() ? DESKTOP_LOGIN_MESSAGE : standaloneMessage;
182
+ }
183
+
184
+ // src/lib/auth.ts
185
+ import { chmodSync, existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
186
+ import { randomUUID } from "crypto";
187
+ import { join as join3, dirname as dirname2 } from "path";
188
+
189
+ // src/lib/init-command.ts
190
+ import { isAbsolute, join as join2, resolve, win32 } from "path";
191
+ import { homedir } from "os";
192
+
193
+ // src/lib/user-data.ts
194
+ import {
195
+ copyFileSync,
196
+ existsSync,
197
+ mkdirSync,
198
+ readFileSync,
199
+ writeFileSync
200
+ } from "fs";
201
+ import { createHash } from "crypto";
202
+ import { dirname, join } from "path";
203
+ var USER_DATA_DIR = "user-data";
204
+ var RUNTIME_DIR = "runtime";
205
+ var EMPTY_RESULT = () => ({
206
+ copied: [],
207
+ skipped: [],
208
+ skippedExisting: []
209
+ });
210
+ function getUserDataDir(workspaceDir) {
211
+ return join(workspaceDir, USER_DATA_DIR);
212
+ }
213
+ function getRuntimeDir(workspaceDir) {
214
+ return join(workspaceDir, RUNTIME_DIR);
215
+ }
216
+ function getUserDataAuthFile(workspaceDir) {
217
+ return join(getUserDataDir(workspaceDir), "auth.json");
218
+ }
219
+ function getRuntimeAuthStateFile(workspaceDir) {
220
+ return join(getRuntimeDir(workspaceDir), "auth-state.json");
221
+ }
222
+ function getUserDataAccountsDir(workspaceDir) {
223
+ return join(getUserDataDir(workspaceDir), "accounts");
224
+ }
225
+ function getUserDataAccountHash(apiKey) {
226
+ return createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
227
+ }
228
+ function getUserDataAccountDir(workspaceDir, profile) {
229
+ return join(getUserDataAccountsDir(workspaceDir), getUserDataAccountHash(profile.apiKey));
230
+ }
231
+ function getUserDataBehaviorsDir(workspaceDir) {
232
+ return join(getUserDataDir(workspaceDir), "behaviors");
233
+ }
234
+ function getUserDataPerceptionsDir(workspaceDir) {
235
+ return join(getUserDataDir(workspaceDir), "perceptions");
236
+ }
237
+ function getUserDataTriggersDir(workspaceDir) {
238
+ return join(getUserDataDir(workspaceDir), "triggers");
239
+ }
240
+ function getUserDataHubDir(workspaceDir) {
241
+ return join(getUserDataDir(workspaceDir), "hub");
242
+ }
243
+ function ensureDir(path) {
244
+ mkdirSync(path, { recursive: true });
245
+ }
246
+ function readJson(path) {
247
+ if (!existsSync(path)) return null;
248
+ try {
249
+ return JSON.parse(readFileSync(path, "utf8"));
250
+ } catch {
251
+ return null;
252
+ }
253
+ }
254
+ function writeJson(path, data) {
255
+ ensureDir(dirname(path));
256
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf8");
257
+ }
258
+ function splitAuthData(data) {
259
+ const auth = {
260
+ ...data,
261
+ activeProfile: data.activeProfile ?? "",
262
+ profiles: Object.fromEntries(
263
+ Object.entries(data.profiles ?? {}).map(([name, profile]) => [name, { ...profile }])
264
+ )
265
+ };
266
+ const runtime = { profiles: {} };
267
+ let changed = false;
268
+ const longTermProfiles = {};
269
+ for (const [name, originalProfile] of Object.entries(auth.profiles ?? {})) {
270
+ const { gameServerUrl, tts, ...longTermProfile } = originalProfile;
271
+ longTermProfiles[name] = longTermProfile;
272
+ if (gameServerUrl) {
273
+ runtime.profiles[name] = { gameServerUrl, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
274
+ changed = true;
275
+ }
276
+ if (tts !== void 0) changed = true;
277
+ }
278
+ auth.profiles = longTermProfiles;
279
+ if ("ttsKeys" in auth) {
280
+ delete auth.ttsKeys;
281
+ changed = true;
282
+ }
283
+ if ("neteaseTtsKey" in auth) {
284
+ delete auth.neteaseTtsKey;
285
+ changed = true;
286
+ }
287
+ return { auth, runtime, changed };
288
+ }
289
+ function readRuntimeAuthState(path) {
290
+ return readJson(path) ?? { profiles: {} };
291
+ }
292
+ function writeRuntimeAuthState(path, state) {
293
+ writeJson(path, { profiles: state.profiles ?? {} });
294
+ }
295
+ function mergeRuntimeAuthState(path, incoming, result) {
296
+ const incomingEntries = Object.entries(incoming.profiles ?? {}).filter(([, profile]) => profile.gameServerUrl);
297
+ if (incomingEntries.length === 0) return;
298
+ const current = readRuntimeAuthState(path);
299
+ let changed = false;
300
+ for (const [name, profile] of incomingEntries) {
301
+ if (current.profiles[name]?.gameServerUrl) {
302
+ result?.skippedExisting.push(`runtime/auth-state.json profiles.${name}.gameServerUrl`);
303
+ continue;
304
+ }
305
+ current.profiles[name] = profile;
306
+ changed = true;
307
+ }
308
+ if (changed) {
309
+ writeRuntimeAuthState(path, current);
310
+ result?.copied.push("auth gameServerUrl -> runtime/auth-state.json");
311
+ }
312
+ }
313
+ function migrateAuth(workspaceDir, result) {
314
+ const legacyAuthFile = join(workspaceDir, ".auth.json");
315
+ const authFile = getUserDataAuthFile(workspaceDir);
316
+ const runtimeFile = getRuntimeAuthStateFile(workspaceDir);
317
+ const source = existsSync(authFile) ? readJson(authFile) : readJson(legacyAuthFile);
318
+ if (!source) return null;
319
+ const { auth, runtime, changed } = splitAuthData(source);
320
+ if (!existsSync(authFile)) {
321
+ writeJson(authFile, auth);
322
+ result.copied.push(".auth.json -> user-data/auth.json");
323
+ } else if (changed) {
324
+ writeJson(authFile, auth);
325
+ result.copied.push("normalized user-data/auth.json");
326
+ }
327
+ mergeRuntimeAuthState(runtimeFile, runtime, result);
328
+ return auth;
329
+ }
330
+ function migrateAccountFiles(workspaceDir, auth, result) {
331
+ if (!auth) return;
332
+ for (const profile of Object.values(auth.profiles ?? {})) {
333
+ const legacyDir = join(workspaceDir, "accounts", profile.apiKey);
334
+ const newDir = getUserDataAccountDir(workspaceDir, profile);
335
+ for (const fileName of ["persona.md", "memory.md"]) {
336
+ const from = join(legacyDir, fileName);
337
+ const to = join(newDir, fileName);
338
+ if (!existsSync(from)) continue;
339
+ if (existsSync(to)) {
340
+ result.skippedExisting.push(`user-data/accounts/${getUserDataAccountHash(profile.apiKey)}/${fileName}`);
341
+ continue;
342
+ }
343
+ ensureDir(dirname(to));
344
+ copyFileSync(from, to);
345
+ result.copied.push(`accounts/<apiKey>/${fileName} -> user-data/accounts/<account-hash>/${fileName}`);
346
+ }
347
+ }
348
+ }
349
+ function writeMigrationMarker(workspaceDir, result) {
350
+ if (result.copied.length === 0 && result.skipped.length === 0 && result.skippedExisting.length === 0) return;
351
+ const marker = join(getUserDataDir(workspaceDir), ".migration.json");
352
+ if (existsSync(marker)) return;
353
+ writeJson(marker, {
354
+ from: "legacy-workspace-layout",
355
+ migrated_at: (/* @__PURE__ */ new Date()).toISOString(),
356
+ copied: result.copied,
357
+ skipped: result.skipped,
358
+ skipped_existing: result.skippedExisting
359
+ });
360
+ }
361
+ function ensureUserDataLayout(workspaceDir) {
362
+ const result = EMPTY_RESULT();
363
+ ensureDir(getUserDataDir(workspaceDir));
364
+ ensureDir(getUserDataAccountsDir(workspaceDir));
365
+ ensureDir(getUserDataBehaviorsDir(workspaceDir));
366
+ ensureDir(getUserDataPerceptionsDir(workspaceDir));
367
+ ensureDir(getUserDataTriggersDir(workspaceDir));
368
+ ensureDir(getUserDataHubDir(workspaceDir));
369
+ ensureDir(getRuntimeDir(workspaceDir));
370
+ const auth = migrateAuth(workspaceDir, result);
371
+ migrateAccountFiles(workspaceDir, auth, result);
372
+ writeMigrationMarker(workspaceDir, result);
373
+ return result;
374
+ }
375
+
376
+ // src/lib/init-command.ts
377
+ var CLAWCLAW_WORKSPACE_DIR = "CLAWCLAW_WORKSPACE_DIR";
378
+ var WORKSPACE_CONFIG_FILE = "config.json";
379
+ function resolveWorkspaceDir({
380
+ env = process.env,
381
+ platform = process.platform,
382
+ homeDir = homedir(),
383
+ cwd = process.cwd()
384
+ } = {}) {
385
+ const rawWorkspaceDir = env[CLAWCLAW_WORKSPACE_DIR];
386
+ const pathApi = platform === "win32" ? win32 : { isAbsolute, join: join2, resolve };
387
+ if (typeof rawWorkspaceDir === "string") {
388
+ const trimmedWorkspaceDir = rawWorkspaceDir.trim();
389
+ if (trimmedWorkspaceDir !== "") {
390
+ return pathApi.isAbsolute(trimmedWorkspaceDir) ? trimmedWorkspaceDir : pathApi.resolve(cwd, trimmedWorkspaceDir);
391
+ }
392
+ }
393
+ if (platform === "win32") {
394
+ const appData = env.APPDATA ?? win32.join(homeDir, "AppData", "Roaming");
395
+ return win32.join(appData, "clawclaw");
396
+ }
397
+ return join2(homeDir, ".clawclaw");
398
+ }
399
+ function getWorkspaceDir() {
400
+ return resolveWorkspaceDir();
401
+ }
402
+ function getWorkspaceConfigFile(workspaceDir = getWorkspaceDir()) {
403
+ return join2(workspaceDir, WORKSPACE_CONFIG_FILE);
404
+ }
405
+
406
+ // src/lib/workspace-runtime-lock.ts
407
+ import { tryAcquireRuntimeLock } from "@myclaw163/game-agent-runtime/owner/runtime-lock.js";
408
+ var tryAcquireWorkspaceRuntimeLock = (workspaceDir) => tryAcquireRuntimeLock(getRuntimeDir(workspaceDir));
409
+
410
+ // src/lib/auth.ts
411
+ var EMPTY_AUTH = { activeProfile: "", profiles: {} };
412
+ var RUNTIME_ACCOUNT_ID = /^acct_[a-f0-9]{32}$/;
413
+ function createRuntimeAccountId() {
414
+ return `acct_${randomUUID().replace(/-/g, "")}`;
415
+ }
416
+ function profileKeyFor(data, profile) {
417
+ if (profile.backendAccountId) {
418
+ for (const [key, savedProfile] of Object.entries(data.profiles ?? {})) {
419
+ if (savedProfile?.backendAccountId === profile.backendAccountId) return key;
420
+ }
421
+ }
422
+ for (const [key, savedProfile] of Object.entries(data.profiles ?? {})) {
423
+ if (savedProfile?.apiKey === profile.apiKey) return key;
424
+ }
425
+ const baseKey = profile.agentName;
426
+ if (!data.profiles[baseKey]) return baseKey;
427
+ const suffix = getUserDataAccountHash(profile.apiKey);
428
+ let candidate = `${baseKey}#${suffix}`;
429
+ let index = 2;
430
+ while (data.profiles[candidate] && data.profiles[candidate]?.apiKey !== profile.apiKey) {
431
+ candidate = `${baseKey}#${suffix}-${index}`;
432
+ index += 1;
433
+ }
434
+ return candidate;
435
+ }
436
+ var AuthStore = class {
437
+ authFile;
438
+ runtimeAuthStateFile;
439
+ workspaceDir;
440
+ constructor(authFile, runtimeAuthStateFile) {
441
+ if (authFile) {
442
+ this.authFile = authFile;
443
+ this.runtimeAuthStateFile = runtimeAuthStateFile ?? join3(dirname2(authFile), "auth-state.json");
444
+ return;
445
+ }
446
+ const workspaceDir = getWorkspaceDir();
447
+ this.workspaceDir = workspaceDir;
448
+ ensureUserDataLayout(workspaceDir);
449
+ this.authFile = getUserDataAuthFile(workspaceDir);
450
+ this.runtimeAuthStateFile = getRuntimeAuthStateFile(workspaceDir);
451
+ }
452
+ load() {
453
+ if (!existsSync2(this.authFile)) return { ...EMPTY_AUTH, profiles: {} };
454
+ try {
455
+ const data = JSON.parse(readFileSync2(this.authFile, "utf8"));
456
+ const { auth, runtime, changed } = splitAuthData(data);
457
+ let identityChanged = false;
458
+ for (const profile of Object.values(auth.profiles)) {
459
+ if (!RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? "")) {
460
+ profile.runtimeAccountId = createRuntimeAccountId();
461
+ identityChanged = true;
462
+ }
463
+ }
464
+ this.mergeRuntimeState(runtime);
465
+ if (changed || identityChanged) this.writeAuth(auth);
466
+ return auth;
467
+ } catch {
468
+ return { ...EMPTY_AUTH, profiles: {} };
469
+ }
470
+ }
471
+ save(data) {
472
+ const { auth, runtime } = splitAuthData(data);
473
+ this.mergeRuntimeState(runtime);
474
+ this.writeAuth(auth);
475
+ }
476
+ writeAuth(data) {
477
+ let guard = null;
478
+ if (this.workspaceDir) {
479
+ let previous = EMPTY_AUTH;
480
+ try {
481
+ previous = JSON.parse(readFileSync2(this.authFile, "utf8"));
482
+ } catch (error) {
483
+ if (error.code !== "ENOENT") throw error;
484
+ }
485
+ if (previous.profiles[previous.activeProfile]?.apiKey !== data.profiles[data.activeProfile]?.apiKey) {
486
+ guard = tryAcquireWorkspaceRuntimeLock(this.workspaceDir);
487
+ if (!guard) throw new Error("A ClawClaw runtime is running in this workspace. Stop it before switching accounts.");
488
+ }
489
+ }
490
+ try {
491
+ const dir = dirname2(this.authFile);
492
+ if (!existsSync2(dir)) mkdirSync2(dir, { recursive: true, mode: 448 });
493
+ writeFileSync2(this.authFile, JSON.stringify(data, null, 2), {
494
+ encoding: "utf8",
495
+ mode: 384
496
+ });
497
+ try {
498
+ chmodSync(this.authFile, 384);
499
+ } catch {
500
+ }
501
+ } finally {
502
+ guard?.release();
503
+ }
504
+ }
505
+ mergeRuntimeState(incoming) {
506
+ const incomingEntries = Object.entries(incoming.profiles ?? {}).filter(([, profile]) => profile.gameServerUrl);
507
+ if (incomingEntries.length === 0) return;
508
+ const current = readRuntimeAuthState(this.runtimeAuthStateFile);
509
+ let changed = false;
510
+ for (const [name, profile] of incomingEntries) {
511
+ if (current.profiles[name]?.gameServerUrl) continue;
512
+ current.profiles[name] = profile;
513
+ changed = true;
514
+ }
515
+ if (changed) writeRuntimeAuthState(this.runtimeAuthStateFile, current);
516
+ }
517
+ addProfile(profile, options = {}) {
518
+ const data = this.load();
519
+ const key = profileKeyFor(data, profile);
520
+ const existing = data.profiles[key];
521
+ if (options.replaceExisting) data.profiles = {};
522
+ data.profiles[key] = {
523
+ ...profile,
524
+ runtimeAccountId: RUNTIME_ACCOUNT_ID.test(profile.runtimeAccountId ?? "") ? profile.runtimeAccountId : existing?.runtimeAccountId ?? createRuntimeAccountId(),
525
+ backendAccountId: profile.backendAccountId ?? existing?.backendAccountId
526
+ };
527
+ data.activeProfile = key;
528
+ this.save(data);
529
+ return key;
530
+ }
531
+ /** Forget credentials and routing, without deleting account resources or memory. */
532
+ clear() {
533
+ this.save({ activeProfile: "", profiles: {} });
534
+ writeRuntimeAuthState(this.runtimeAuthStateFile, { profiles: {} });
535
+ }
536
+ removeProfile(name) {
537
+ this.removeProfileByKey(name);
538
+ }
539
+ removeProfileByKey(key) {
540
+ const data = this.load();
541
+ delete data.profiles[key];
542
+ if (data.activeProfile === key) {
543
+ const remaining = Object.keys(data.profiles);
544
+ data.activeProfile = remaining[0] ?? "";
545
+ }
546
+ this.save(data);
547
+ const state = readRuntimeAuthState(this.runtimeAuthStateFile);
548
+ if (state.profiles[key]) {
549
+ delete state.profiles[key];
550
+ writeRuntimeAuthState(this.runtimeAuthStateFile, state);
551
+ }
552
+ }
553
+ switchProfile(name) {
554
+ const data = this.load();
555
+ if (!data.profiles[name]) {
556
+ throw new Error(`Profile "${name}" not found. Available: ${Object.keys(data.profiles).join(", ") || "none"}`);
557
+ }
558
+ data.activeProfile = name;
559
+ this.save(data);
560
+ }
561
+ listProfiles() {
562
+ return Object.keys(this.load().profiles);
563
+ }
564
+ findProfileKeyByApiKey(apiKey) {
565
+ const data = this.load();
566
+ return Object.keys(data.profiles).find((key) => data.profiles[key]?.apiKey === apiKey) ?? null;
567
+ }
568
+ getActiveProfileKey() {
569
+ const data = this.load();
570
+ if (!data.activeProfile || !data.profiles[data.activeProfile]) return null;
571
+ return data.activeProfile;
572
+ }
573
+ getActive() {
574
+ const data = this.load();
575
+ if (!data.activeProfile || !data.profiles[data.activeProfile]) return null;
576
+ const profile = data.profiles[data.activeProfile];
577
+ const gameServerUrl = this.getGameServerUrl(data.activeProfile);
578
+ return gameServerUrl ? { ...profile, gameServerUrl } : { ...profile };
579
+ }
580
+ updateGameServerUrl(url, name) {
581
+ const data = this.load();
582
+ const profileName = name ?? data.activeProfile;
583
+ const profile = data.profiles[profileName];
584
+ if (!profile) return;
585
+ const state = readRuntimeAuthState(this.runtimeAuthStateFile);
586
+ if (url) {
587
+ state.profiles[profileName] = { gameServerUrl: url, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
588
+ } else {
589
+ delete state.profiles[profileName]?.gameServerUrl;
590
+ delete state.profiles[profileName]?.updatedAt;
591
+ if (state.profiles[profileName] && Object.keys(state.profiles[profileName]).length === 0) {
592
+ delete state.profiles[profileName];
593
+ }
594
+ }
595
+ writeRuntimeAuthState(this.runtimeAuthStateFile, state);
596
+ }
597
+ getGameServerUrl(profileName) {
598
+ const data = this.load();
599
+ const name = profileName ?? data.activeProfile;
600
+ if (!name) return void 0;
601
+ return readRuntimeAuthState(this.runtimeAuthStateFile).profiles[name]?.gameServerUrl;
602
+ }
603
+ };
604
+
605
+ // src/lib/server-registry.ts
606
+ function normalizeGameServerUrl(url) {
607
+ return url.replace(/^wss:/, "https:").replace(/^ws:/, "http:").replace(/\/api\/v1\/game\/sync\/?(?:\?.*)?$/, "").replace(/\/game\/sync\/?(?:\?.*)?$/, "").replace(/\/$/, "");
608
+ }
609
+ var ServerRegistry = class {
610
+ lobbyUrl;
611
+ _gameServerUrl;
612
+ _gatewayWsUrl;
613
+ agentName;
614
+ /** True when gameServerUrl was pre-configured (e.g. from auth) — prevents
615
+ * discoverGameServer() from clearing it during queue status polling. */
616
+ _urlPreconfigured;
617
+ constructor(opts) {
618
+ this.lobbyUrl = opts.lobbyUrl.replace(/\/$/, "");
619
+ this._gatewayWsUrl = null;
620
+ if (opts.gameServerUrl) {
621
+ const raw = opts.gameServerUrl.replace(/\/$/, "");
622
+ try {
623
+ const u = new URL(raw);
624
+ if (u.pathname && u.pathname !== "/") {
625
+ this._gatewayWsUrl = raw;
626
+ this._gameServerUrl = raw;
627
+ } else {
628
+ this._gameServerUrl = raw.replace(/^https:\/\//, "http://");
629
+ }
630
+ } catch {
631
+ this._gameServerUrl = raw.replace(/^https:\/\//, "http://");
632
+ }
633
+ this._urlPreconfigured = true;
634
+ } else {
635
+ this._gameServerUrl = null;
636
+ this._urlPreconfigured = false;
637
+ }
638
+ this.agentName = opts.agentName;
639
+ }
640
+ get addresses() {
641
+ return {
642
+ lobbyUrl: this.lobbyUrl,
643
+ gameServerUrl: this._gameServerUrl,
644
+ wsUrl: this.wsUrl
645
+ };
646
+ }
647
+ get gameServerUrl() {
648
+ return this._gameServerUrl;
649
+ }
650
+ get lobbyAgentWsUrl() {
651
+ const u = new URL(this.lobbyUrl);
652
+ const protocol = u.protocol === "https:" || u.protocol === "wss:" ? "wss:" : "ws:";
653
+ const basePath = u.pathname && u.pathname !== "/" ? u.pathname.replace(/\/$/, "") : "";
654
+ return `${protocol}//${u.host}${basePath}/api/v1/agent/ws`;
655
+ }
656
+ /**
657
+ * Determine the correct base URL for a given API path.
658
+ *
659
+ * Game Server routes retained by the v2 client: acknowledged Action and leave.
660
+ * Other dynamic observations use GameSync WebSocket; map geometry and paths
661
+ * remain local CCL capabilities.
662
+ * Lobby routes: everything else (/api/v1/agents/*, /api/v1/queue/*, etc.)
663
+ */
664
+ baseUrlFor(path) {
665
+ if (path.startsWith("/api/v1/game/action") || path.startsWith("/api/v1/game/leave")) {
666
+ const base = this._gatewayWsUrl ?? this._gameServerUrl;
667
+ if (!base) throw new Error("No game server allocated");
668
+ return base;
669
+ }
670
+ return this.lobbyUrl;
671
+ }
672
+ /**
673
+ * Extract game server address from a queue response and update gameServerUrl.
674
+ * Prefers ws_url (Gateway route) over raw address:port.
675
+ * Returns true if the address changed.
676
+ */
677
+ updateFromQueueResponse(data) {
678
+ if (!data || typeof data !== "object") return false;
679
+ const qs = data.data ?? data;
680
+ if (qs.status && qs.status !== "allocated") {
681
+ if (this._urlPreconfigured) return false;
682
+ if (this._gameServerUrl !== null || this._gatewayWsUrl !== null) {
683
+ this._gameServerUrl = null;
684
+ this._gatewayWsUrl = null;
685
+ this.persistGameServerUrl();
686
+ return true;
687
+ }
688
+ return false;
689
+ }
690
+ const wsUrl = qs.ws_url;
691
+ if (wsUrl && typeof wsUrl === "string") {
692
+ const httpUrl = normalizeGameServerUrl(wsUrl);
693
+ if (this._gatewayWsUrl !== httpUrl) {
694
+ this._gatewayWsUrl = httpUrl;
695
+ this._gameServerUrl = httpUrl;
696
+ this.persistGameServerUrl();
697
+ return true;
698
+ }
699
+ return false;
700
+ }
701
+ const addr = qs.address ?? qs.game_server?.address;
702
+ const port = qs.port ?? qs.game_server?.port;
703
+ if (addr && port) {
704
+ const url = `http://${addr}:${port}`;
705
+ if (this._gameServerUrl !== url) {
706
+ this._gameServerUrl = url;
707
+ this._gatewayWsUrl = null;
708
+ this.persistGameServerUrl();
709
+ return true;
710
+ }
711
+ }
712
+ return false;
713
+ }
714
+ /** Manually set the game server URL. */
715
+ setGameServerUrl(url) {
716
+ const normalized = normalizeGameServerUrl(url);
717
+ this._gameServerUrl = normalized;
718
+ try {
719
+ const parsed = new URL(normalized);
720
+ this._gatewayWsUrl = parsed.pathname && parsed.pathname !== "/" ? normalized : null;
721
+ } catch {
722
+ this._gatewayWsUrl = null;
723
+ }
724
+ this._urlPreconfigured = true;
725
+ this.persistGameServerUrl();
726
+ }
727
+ /** Set the game server URL via the public lobby gateway route. */
728
+ setGatewayGameServerName(gameServerName) {
729
+ const cleanName = gameServerName.replace(/^\/+|\/+$/g, "");
730
+ const route = `${this.lobbyUrl}/gs/${encodeURIComponent(cleanName)}`;
731
+ this._gatewayWsUrl = route;
732
+ this._gameServerUrl = route;
733
+ this._urlPreconfigured = true;
734
+ this.persistGameServerUrl();
735
+ }
736
+ /** GameSync v2 WS URL derived from gameServerUrl (Gateway or direct). */
737
+ get wsUrl() {
738
+ if (!this._gameServerUrl) return null;
739
+ try {
740
+ const u = new URL(this._gameServerUrl);
741
+ const protocol = u.protocol === "https:" || u.protocol === "wss:" ? "wss:" : "ws:";
742
+ const basePath = this._gatewayWsUrl ? u.pathname.replace(/\/$/, "") : "";
743
+ return `${protocol}//${u.host}${basePath}/api/v1/game/sync`;
744
+ } catch {
745
+ return null;
746
+ }
747
+ }
748
+ /** Persist gameServerUrl to runtime auth state (best-effort). */
749
+ persistGameServerUrl() {
750
+ if (!this.agentName) return;
751
+ try {
752
+ new AuthStore().updateGameServerUrl(this._gameServerUrl ?? void 0, this.agentName);
753
+ } catch {
754
+ }
755
+ }
756
+ };
757
+
758
+ // src/short-command/transport-response.ts
759
+ function normalizeResponseHeaders(headers) {
760
+ const out = {};
761
+ headers.forEach((value, name) => {
762
+ out[name.toLowerCase()] = value;
763
+ });
764
+ return out;
765
+ }
766
+ function requestIdFromHeaders(headers) {
767
+ return headers["x-request-id"] ?? headers["request-id"] ?? headers["x-correlation-id"];
768
+ }
769
+ async function readTransportResponse(response, context) {
770
+ const headers = normalizeResponseHeaders(response.headers);
771
+ const rawText = await response.text();
772
+ const contentType = headers["content-type"];
773
+ let body;
774
+ if (rawText.length === 0) {
775
+ body = { kind: "empty", rawText: "" };
776
+ } else {
777
+ try {
778
+ body = { kind: "json", value: JSON.parse(rawText), rawText };
779
+ } catch {
780
+ body = { kind: "text", rawText };
781
+ }
782
+ }
783
+ return {
784
+ method: context.method,
785
+ path: context.path,
786
+ status: response.status,
787
+ statusText: response.statusText || void 0,
788
+ headers,
789
+ contentType,
790
+ requestId: requestIdFromHeaders(headers),
791
+ body
792
+ };
793
+ }
794
+
795
+ // src/lib/http-transport.ts
796
+ var ApiError = class extends Error {
797
+ constructor(status, body, method, path, response) {
798
+ super(`API error ${status}: ${body}`);
799
+ this.status = status;
800
+ this.body = body;
801
+ this.method = method;
802
+ this.path = path;
803
+ this.response = response;
804
+ this.name = "ApiError";
805
+ }
806
+ status;
807
+ body;
808
+ method;
809
+ path;
810
+ response;
811
+ };
812
+ var HttpTransport = class {
813
+ apiKey;
814
+ registry;
815
+ extraHeaders;
816
+ signal;
817
+ constructor(apiKey, registry, extraHeaders = {}, signal) {
818
+ this.apiKey = apiKey;
819
+ this.registry = registry;
820
+ this.extraHeaders = extraHeaders;
821
+ this.signal = signal;
822
+ }
823
+ /**
824
+ * Generic HTTP request. Supports JSON body and FormData.
825
+ * Adds Authorization header when apiKey is non-empty.
826
+ * `perRequestHeaders` are merged last (highest precedence) so a caller can
827
+ * attach a header to a single endpoint without polluting every request.
828
+ */
829
+ async requestRaw(method, path, body, perRequestHeaders, requestSignal) {
830
+ const url = this.registry.baseUrlFor(path) + path;
831
+ const headers = {};
832
+ if (this.apiKey) {
833
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
834
+ }
835
+ for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v;
836
+ if (perRequestHeaders) {
837
+ for (const [k, v] of Object.entries(perRequestHeaders)) headers[k] = v;
838
+ }
839
+ let fetchBody;
840
+ if (body !== void 0) {
841
+ if (body instanceof FormData) {
842
+ fetchBody = body;
843
+ } else {
844
+ headers["Content-Type"] = "application/json; charset=utf-8";
845
+ fetchBody = JSON.stringify(body);
846
+ }
847
+ }
848
+ const timeout = AbortSignal.timeout(1e4);
849
+ const signals = [timeout, this.signal, requestSignal].filter((value) => value !== void 0);
850
+ const signal = signals.length === 1 ? signals[0] : AbortSignal.any(signals);
851
+ const res = await fetch(url, { method, headers, body: fetchBody, signal });
852
+ return readTransportResponse(res, { method, path });
853
+ }
854
+ async request(method, path, body, perRequestHeaders, requestSignal) {
855
+ const response = await this.requestRaw(method, path, body, perRequestHeaders, requestSignal);
856
+ if (response.status < 200 || response.status >= 300) {
857
+ throw new ApiError(response.status, response.body.rawText, method, path, response);
858
+ }
859
+ if (response.body.kind !== "json") {
860
+ throw new SyntaxError(response.body.kind === "empty" ? "Unexpected end of JSON input" : `Unexpected non-JSON response from ${path}`);
861
+ }
862
+ return response.body.value;
863
+ }
864
+ async getRaw(path) {
865
+ try {
866
+ return await this.requestRaw("GET", path);
867
+ } catch (err) {
868
+ await new Promise((r) => setTimeout(r, 500));
869
+ return this.requestRaw("GET", path);
870
+ }
871
+ }
872
+ async postRaw(path, body, perRequestHeaders, requestSignal) {
873
+ return this.requestRaw("POST", path, body, perRequestHeaders, requestSignal);
874
+ }
875
+ /** GET with one fast retry for transient network failures. */
876
+ /** GET with optional per-request cancellation in addition to owner cancellation. */
877
+ async get(path, requestSignal) {
878
+ try {
879
+ return await this.request("GET", path, void 0, void 0, requestSignal);
880
+ } catch (err) {
881
+ if (err instanceof ApiError) throw err;
882
+ if (requestSignal?.aborted) throw requestSignal.reason ?? err;
883
+ await new Promise((resolve2) => {
884
+ const timer = setTimeout(finish, 500);
885
+ const onAbort = () => finish();
886
+ function finish() {
887
+ clearTimeout(timer);
888
+ requestSignal?.removeEventListener("abort", onAbort);
889
+ resolve2();
890
+ }
891
+ requestSignal?.addEventListener("abort", onAbort, { once: true });
892
+ });
893
+ if (requestSignal?.aborted) throw requestSignal.reason ?? err;
894
+ return this.request("GET", path, void 0, void 0, requestSignal);
895
+ }
896
+ }
897
+ async post(path, body, perRequestHeaders) {
898
+ return this.request("POST", path, body, perRequestHeaders);
899
+ }
900
+ /** GET raw bytes (binary artifacts). Throws ApiError on non-ok. */
901
+ async getBytes(path) {
902
+ const url = this.registry.baseUrlFor(path) + path;
903
+ const headers = {};
904
+ if (this.apiKey) {
905
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
906
+ }
907
+ for (const [k, v] of Object.entries(this.extraHeaders)) headers[k] = v;
908
+ const res = await fetch(url, { method: "GET", headers, signal: AbortSignal.timeout(3e4) });
909
+ if (!res.ok) {
910
+ throw new ApiError(res.status, await res.text(), "GET", path);
911
+ }
912
+ return Buffer.from(await res.arrayBuffer());
913
+ }
914
+ };
915
+
916
+ // src/runtime/ws-client.ts
917
+ import WebSocket from "ws";
918
+ import { randomUUID as randomUUID2 } from "crypto";
919
+ import { performance } from "node:perf_hooks";
920
+
921
+ // src/runtime/game-sync-protocol.ts
922
+ var GAME_SYNC_PROTOCOL_VERSION = 1;
923
+ function record(value, field) {
924
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
925
+ throw new TypeError(`${field} must be an object`);
926
+ }
927
+ return value;
928
+ }
929
+ function integer(value, field, minimum = 0) {
930
+ if (!Number.isInteger(value) || Number(value) < minimum) {
931
+ throw new TypeError(`${field} must be an integer >= ${minimum}`);
932
+ }
933
+ return Number(value);
934
+ }
935
+ function nonEmptyString(value, field) {
936
+ if (typeof value !== "string" || value.length === 0) {
937
+ throw new TypeError(`${field} must be a non-empty string`);
938
+ }
939
+ return value;
940
+ }
941
+ function eventArray(value, field) {
942
+ if (!Array.isArray(value)) {
943
+ throw new TypeError(`${field} must be an array`);
944
+ }
945
+ return value.map((event, index) => {
946
+ const parsed = structuredClone(record(event, `${field}[${index}]`));
947
+ nonEmptyString(parsed.event_id, `${field}[${index}].event_id`);
948
+ nonEmptyString(parsed.type, `${field}[${index}].type`);
949
+ integer(parsed.tick, `${field}[${index}].tick`);
950
+ return parsed;
951
+ });
952
+ }
953
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
954
+ function resourceId(value, field) {
955
+ const id = nonEmptyString(value, field).trim();
956
+ if (!id || [...id].length > 128) throw new TypeError(`${field} must contain 1 to 128 characters`);
957
+ return id;
958
+ }
959
+ function gameSyncRuntimeReportMessage(report) {
960
+ if (report.perceivers == null && report.strategies == null) {
961
+ throw new TypeError("GameSync runtime report requires perceivers or strategies");
962
+ }
963
+ const data = {};
964
+ for (const key of ["perceivers", "strategies"]) {
965
+ const list = report[key];
966
+ if (list === void 0) continue;
967
+ if (list === null) {
968
+ data[key] = null;
969
+ continue;
970
+ }
971
+ if (!Array.isArray(list) || list.length > 50) throw new TypeError(`${key} must contain at most 50 resources`);
972
+ const ids = /* @__PURE__ */ new Set();
973
+ data[key] = list.map((item) => {
974
+ const id = resourceId(item.id, `${key}.id`);
975
+ if (ids.has(id)) throw new TypeError(`${key} resource IDs must be unique`);
976
+ ids.add(id);
977
+ const name = nonEmptyString(item.name, `${key}.name`).trim();
978
+ if (!name) throw new TypeError(`${key}.name must not be blank`);
979
+ if (item.description !== void 0 && typeof item.description !== "string") throw new TypeError(`${key}.description must be a string`);
980
+ return { id, name, description: item.description?.trim() ?? "" };
981
+ });
982
+ }
983
+ return { type: "game.sync.runtime.report", data };
984
+ }
985
+ function gameSyncPerceptionReportMessage(perceptions) {
986
+ if (perceptions.length < 1 || perceptions.length > 20) {
987
+ throw new TypeError("GameSync perception report must contain between 1 and 20 items");
988
+ }
989
+ const ids = /* @__PURE__ */ new Set();
990
+ const detached = perceptions.map((perception, index) => {
991
+ if (!UUID_PATTERN.test(perception.id)) {
992
+ throw new TypeError(`GameSync perception report[${index}].id must be a UUID`);
993
+ }
994
+ if (ids.has(perception.id)) {
995
+ throw new TypeError("GameSync perception report IDs must be unique within a batch");
996
+ }
997
+ ids.add(perception.id);
998
+ if (typeof perception.name !== "string" || perception.name.length === 0) {
999
+ throw new TypeError(`GameSync perception report[${index}].name must be a non-empty string`);
1000
+ }
1001
+ if (typeof perception.output !== "string") {
1002
+ throw new TypeError(`GameSync perception report[${index}].output must be a string`);
1003
+ }
1004
+ const instant = perception.source_tick !== void 0;
1005
+ const interval = perception.from_source_tick !== void 0 || perception.to_source_tick !== void 0;
1006
+ if (instant === interval) throw new TypeError("Perception report requires exactly one instantaneous or interval time");
1007
+ if (instant) integer(perception.source_tick, `GameSync perception report[${index}].source_tick`);
1008
+ else {
1009
+ integer(perception.from_source_tick, `GameSync perception report[${index}].from_source_tick`);
1010
+ integer(perception.to_source_tick, `GameSync perception report[${index}].to_source_tick`);
1011
+ if (perception.from_source_tick > perception.to_source_tick) throw new TypeError("Perception report time interval is reversed");
1012
+ }
1013
+ return { ...perception, ...perception.perceiver_id === void 0 ? {} : {
1014
+ perceiver_id: resourceId(perception.perceiver_id, `GameSync perception report[${index}].perceiver_id`)
1015
+ } };
1016
+ });
1017
+ return {
1018
+ type: "game.sync.perception.report",
1019
+ data: { perceptions: detached }
1020
+ };
1021
+ }
1022
+ function parseGameSyncMessage(value) {
1023
+ const envelope = record(value, "GameSync message");
1024
+ const type = nonEmptyString(envelope.type, "GameSync message.type");
1025
+ const data = record(envelope.data, "GameSync message.data");
1026
+ if (type === "game.sync.snapshot") {
1027
+ const locale = data.locale;
1028
+ if (locale !== "zh-CN" && locale !== "en-US") {
1029
+ throw new TypeError("game.sync.snapshot.data.locale is invalid");
1030
+ }
1031
+ return {
1032
+ type,
1033
+ data: {
1034
+ seq: integer(data.seq, "game.sync.snapshot.data.seq", 1),
1035
+ game_id: nonEmptyString(data.game_id, "game.sync.snapshot.data.game_id"),
1036
+ tick: integer(data.tick, "game.sync.snapshot.data.tick"),
1037
+ locale,
1038
+ state: structuredClone(record(data.state, "game.sync.snapshot.data.state")),
1039
+ // Older v2 instances did not emit this field. Treat absence as an
1040
+ // empty history so a rolling backend update cannot break CCL startup.
1041
+ events: eventArray(data.events ?? [], "game.sync.snapshot.data.events")
1042
+ }
1043
+ };
1044
+ }
1045
+ if (type === "game.sync.update") {
1046
+ const events = eventArray(data.events, "game.sync.update.data.events");
1047
+ return {
1048
+ type,
1049
+ data: {
1050
+ seq: integer(data.seq, "game.sync.update.data.seq", 1),
1051
+ game_id: nonEmptyString(data.game_id, "game.sync.update.data.game_id"),
1052
+ tick: integer(data.tick, "game.sync.update.data.tick"),
1053
+ state_delta: structuredClone(record(data.state_delta, "game.sync.update.data.state_delta")),
1054
+ events
1055
+ }
1056
+ };
1057
+ }
1058
+ if (type === "game.sync.resume") {
1059
+ if (data.status !== "complete") throw new TypeError("game.sync.resume.data.status is invalid");
1060
+ const fromSeq = data.from_seq == null ? data.from_seq : integer(data.from_seq, "game.sync.resume.data.from_seq", 1);
1061
+ const toSeq = integer(data.to_seq, "game.sync.resume.data.to_seq", 1);
1062
+ const replayedCount = integer(
1063
+ data.replayed_count,
1064
+ "game.sync.resume.data.replayed_count"
1065
+ );
1066
+ if (fromSeq == null && replayedCount !== 0) {
1067
+ throw new TypeError(
1068
+ "game.sync.resume.data.from_seq must be present when replayed_count is non-zero"
1069
+ );
1070
+ }
1071
+ if (fromSeq != null) {
1072
+ if (replayedCount === 0) {
1073
+ throw new TypeError(
1074
+ "game.sync.resume.data.from_seq must be null when replayed_count is zero"
1075
+ );
1076
+ }
1077
+ if (toSeq < fromSeq || replayedCount !== toSeq - fromSeq + 1) {
1078
+ throw new TypeError("game.sync.resume.data replay range is inconsistent");
1079
+ }
1080
+ }
1081
+ return {
1082
+ type,
1083
+ data: {
1084
+ status: "complete",
1085
+ ...fromSeq === void 0 ? {} : { from_seq: fromSeq },
1086
+ to_seq: toSeq,
1087
+ replayed_count: replayedCount,
1088
+ tick: integer(data.tick, "game.sync.resume.data.tick")
1089
+ }
1090
+ };
1091
+ }
1092
+ if (type === "game.sync.error") {
1093
+ if (typeof data.recoverable !== "boolean") {
1094
+ throw new TypeError("game.sync.error.data.recoverable must be a boolean");
1095
+ }
1096
+ return {
1097
+ type,
1098
+ data: {
1099
+ code: nonEmptyString(data.code, "game.sync.error.data.code"),
1100
+ recoverable: data.recoverable,
1101
+ ...typeof data.message === "string" ? { message: data.message } : {}
1102
+ }
1103
+ };
1104
+ }
1105
+ throw new TypeError(`unsupported GameSync message type '${type}'`);
1106
+ }
1107
+ function mergeObject(previous, delta) {
1108
+ const result = structuredClone(previous);
1109
+ for (const [key, value] of Object.entries(delta)) {
1110
+ const old = result[key];
1111
+ result[key] = old && value && typeof old === "object" && typeof value === "object" && !Array.isArray(old) && !Array.isArray(value) ? mergeObject(old, value) : structuredClone(value);
1112
+ }
1113
+ return result;
1114
+ }
1115
+ function mergePlayers(previous, delta) {
1116
+ const prior = Array.isArray(previous) ? structuredClone(previous) : [];
1117
+ if (!Array.isArray(delta)) throw new TypeError("GameSync state_delta.players must be an array");
1118
+ const bySeat = /* @__PURE__ */ new Map();
1119
+ for (const player of prior) {
1120
+ const value = record(player, "GameSync players entry");
1121
+ if (Number.isInteger(value.seat)) bySeat.set(Number(value.seat), value);
1122
+ }
1123
+ for (const player of delta) {
1124
+ const value = record(player, "GameSync state_delta.players entry");
1125
+ const seat = integer(value.seat, "GameSync state_delta.players.seat");
1126
+ bySeat.set(seat, mergeObject(bySeat.get(seat) ?? {}, value));
1127
+ }
1128
+ return [...bySeat.values()].sort((left, right) => Number(left.seat) - Number(right.seat));
1129
+ }
1130
+ function semanticActive(previous, delta, field) {
1131
+ const value = record(delta, `GameSync state_delta.${field}`);
1132
+ if (value.active === false) return { active: false };
1133
+ return mergeObject(
1134
+ previous && typeof previous === "object" && !Array.isArray(previous) ? previous : {},
1135
+ value
1136
+ );
1137
+ }
1138
+ function applyGameSyncDelta(previous, stateDelta) {
1139
+ const next = structuredClone(previous);
1140
+ for (const [field, rawValue] of Object.entries(stateDelta)) {
1141
+ if (field === "players") {
1142
+ next.players = mergePlayers(next.players, rawValue);
1143
+ continue;
1144
+ }
1145
+ if (field === "visible_players" || field === "visible_corpses") {
1146
+ if (!Array.isArray(rawValue)) throw new TypeError(`GameSync state_delta.${field} must be an array`);
1147
+ next[field] = structuredClone(rawValue);
1148
+ continue;
1149
+ }
1150
+ if (field === "you") {
1151
+ const delta = record(rawValue, "GameSync state_delta.you");
1152
+ next.you = mergeObject(record(next.you ?? {}, "GameSync state.you"), delta);
1153
+ if (delta.activity?.kind === "idle") next.you.activity = { kind: "idle" };
1154
+ continue;
1155
+ }
1156
+ if (field === "meeting") {
1157
+ const delta = record(rawValue, "GameSync state_delta.meeting");
1158
+ next.meeting = semanticActive(next.meeting, delta, field);
1159
+ if (delta.active !== false) {
1160
+ for (const replace of ["speech_order", "speeches", "speech_skipped", "votes_submitted"]) {
1161
+ if (Object.hasOwn(delta, replace)) next.meeting[replace] = structuredClone(delta[replace]);
1162
+ }
1163
+ }
1164
+ continue;
1165
+ }
1166
+ if (field === "emergency" || field === "octopus_time") {
1167
+ next[field] = semanticActive(next[field], rawValue, field);
1168
+ continue;
1169
+ }
1170
+ if (field === "crab_sabotage") {
1171
+ const delta = record(rawValue, "GameSync state_delta.crab_sabotage");
1172
+ next.crab_sabotage = mergeObject(
1173
+ record(next.crab_sabotage ?? {}, "GameSync state.crab_sabotage"),
1174
+ delta
1175
+ );
1176
+ if (typeof delta.status === "string" && !delta.status.startsWith("cooldown_")) {
1177
+ delete next.crab_sabotage.cooldown_remaining_secs;
1178
+ }
1179
+ continue;
1180
+ }
1181
+ next[field] = structuredClone(rawValue);
1182
+ }
1183
+ return next;
1184
+ }
1185
+ function gameSyncUrl(baseUrl, resumeSeq) {
1186
+ const url = new URL(baseUrl);
1187
+ url.searchParams.set("protocol_version", String(GAME_SYNC_PROTOCOL_VERSION));
1188
+ if (resumeSeq !== void 0) url.searchParams.set("resume_seq", String(resumeSeq));
1189
+ else url.searchParams.delete("resume_seq");
1190
+ return url.toString();
1191
+ }
1192
+
1193
+ // src/runtime/ws-client.ts
1194
+ var DEFAULT_ACK_INTERVAL_MS = 1e4;
1195
+ var MAX_SEEN_EVENT_IDS = 2e4;
1196
+ function wsMessageToString(data) {
1197
+ if (typeof data === "string") return data;
1198
+ if (Buffer.isBuffer(data)) return data.toString("utf8");
1199
+ if (data instanceof ArrayBuffer) return Buffer.from(data).toString("utf8");
1200
+ return Buffer.concat(data).toString("utf8");
1201
+ }
1202
+ function closeIsTerminal(code) {
1203
+ return code === 1e3 || code === 1002 || code === 4e3 || code === 4001 || code === 4002 || code === 4003;
1204
+ }
1205
+ var WsClient = class {
1206
+ constructor(config) {
1207
+ this.config = config;
1208
+ this.baseline = config.resumeState ? structuredClone(config.resumeState) : null;
1209
+ this.committedBaseline = config.resumeState ? structuredClone(config.resumeState) : null;
1210
+ this.rawMessageSink = config.rawMessageSink;
1211
+ }
1212
+ config;
1213
+ ws = null;
1214
+ _state = "disconnected" /* Disconnected */;
1215
+ shouldReconnect = false;
1216
+ reconnectAttempt = 0;
1217
+ reconnectTimer = null;
1218
+ ackTimer = null;
1219
+ connectionIdValue = "";
1220
+ lastPongAtValue = null;
1221
+ baseline;
1222
+ /** Last baseline accepted by the consumer (Source or the ingress memory cache). */
1223
+ committedBaseline;
1224
+ recovering = false;
1225
+ awaitingSnapshot = false;
1226
+ recoveryStartSeq = null;
1227
+ recoveryFirstSeq = null;
1228
+ recoveryFrameCount = 0;
1229
+ recoveryEvents = [];
1230
+ pendingBaselines = /* @__PURE__ */ new Map();
1231
+ pendingEventIds = /* @__PURE__ */ new Map();
1232
+ inFlightEventIds = /* @__PURE__ */ new Set();
1233
+ ackDirty = false;
1234
+ lastAckSent = 0;
1235
+ seenEventIds = /* @__PURE__ */ new Set();
1236
+ rawMessageSink;
1237
+ socketReceivedAtMs = 0;
1238
+ decodeStartedAt = 0;
1239
+ inputFrameHandlers = /* @__PURE__ */ new Set();
1240
+ connectionOpenedHandlers = /* @__PURE__ */ new Set();
1241
+ livenessHandlers = /* @__PURE__ */ new Set();
1242
+ protocolErrorHandlers = /* @__PURE__ */ new Set();
1243
+ recoveryStartedHandlers = /* @__PURE__ */ new Set();
1244
+ disconnectHandlers = /* @__PURE__ */ new Set();
1245
+ stateChangeHandlers = /* @__PURE__ */ new Set();
1246
+ get connected() {
1247
+ return this._state === "connected" /* Connected */;
1248
+ }
1249
+ get state() {
1250
+ return this._state;
1251
+ }
1252
+ get connectionId() {
1253
+ return this.connectionIdValue;
1254
+ }
1255
+ get lastPongAt() {
1256
+ return this.lastPongAtValue;
1257
+ }
1258
+ get resumeState() {
1259
+ return this.committedBaseline ? structuredClone(this.committedBaseline) : void 0;
1260
+ }
1261
+ /** Best-effort perception output; the server intentionally sends no acknowledgement. */
1262
+ reportPerceptions(perceptions) {
1263
+ return this.send(gameSyncPerceptionReportMessage(perceptions));
1264
+ }
1265
+ reportRuntime(report) {
1266
+ return this.send(gameSyncRuntimeReportMessage(report));
1267
+ }
1268
+ /**
1269
+ * Advance the resume/ACK watermark after the consumer has accepted the frame.
1270
+ * The threaded consumer retains it in memory before ACK; this is not a disk flush.
1271
+ */
1272
+ acknowledge(ackToken, immediate = false) {
1273
+ if (!ackToken) return;
1274
+ const pending = this.pendingBaselines.get(ackToken);
1275
+ if (!pending || pending.connectionId !== this.connectionIdValue) return;
1276
+ const committed = pending.baseline;
1277
+ const { seq, tick } = committed;
1278
+ if (!this.committedBaseline || seq >= this.committedBaseline.seq) {
1279
+ this.committedBaseline = structuredClone(committed);
1280
+ }
1281
+ for (const [pendingSeq, ids] of [...this.pendingEventIds]) {
1282
+ if (pendingSeq > seq) continue;
1283
+ for (const eventId of ids) {
1284
+ this.inFlightEventIds.delete(eventId);
1285
+ this.seenEventIds.add(eventId);
1286
+ }
1287
+ this.pendingEventIds.delete(pendingSeq);
1288
+ }
1289
+ for (const [key, candidate] of [...this.pendingBaselines]) {
1290
+ const candidateBaseline = candidate.baseline;
1291
+ if (candidate.connectionId === pending.connectionId && candidateBaseline.gameId === committed.gameId && (candidateBaseline.seq < seq || candidateBaseline.seq === seq && candidateBaseline.tick <= tick)) {
1292
+ this.pendingBaselines.delete(key);
1293
+ }
1294
+ }
1295
+ this.trimSeenEventIds();
1296
+ this.ackDirty = true;
1297
+ if (immediate) this.sendAck();
1298
+ }
1299
+ connect() {
1300
+ this.shouldReconnect = true;
1301
+ this.reconnectAttempt = 0;
1302
+ this.setState("connecting" /* Connecting */);
1303
+ return this.openSocket();
1304
+ }
1305
+ openSocket() {
1306
+ return new Promise((resolve2, reject) => {
1307
+ this.baseline = this.committedBaseline ? structuredClone(this.committedBaseline) : null;
1308
+ this.clearPendingApplication();
1309
+ this.config.discardUnappliedMessages?.();
1310
+ this.connectionIdValue = randomUUID2();
1311
+ this.recovering = this.baseline !== null;
1312
+ this.awaitingSnapshot = false;
1313
+ this.recoveryStartSeq = this.baseline?.seq ?? null;
1314
+ this.recoveryFirstSeq = null;
1315
+ this.recoveryFrameCount = 0;
1316
+ this.recoveryEvents = [];
1317
+ const url = gameSyncUrl(this.config.url, this.baseline?.seq);
1318
+ const ws = new WebSocket(url, {
1319
+ autoPong: false,
1320
+ ...this.config.handshakeTimeoutMs === void 0 ? {} : { handshakeTimeout: this.config.handshakeTimeoutMs },
1321
+ ...this.config.maxPayloadBytes === void 0 ? {} : { maxPayload: this.config.maxPayloadBytes },
1322
+ headers: {
1323
+ Authorization: `Bearer ${this.config.apiKey}`,
1324
+ "Accept-Language": this.baseline?.locale ?? "zh-CN"
1325
+ }
1326
+ });
1327
+ this.ws = ws;
1328
+ ws.onopen = () => {
1329
+ if (this.ws !== ws) return;
1330
+ this.setState("connected" /* Connected */);
1331
+ this.reconnectAttempt = 0;
1332
+ this.startAckTimer();
1333
+ for (const handler of this.connectionOpenedHandlers) {
1334
+ try {
1335
+ handler(this.connectionIdValue);
1336
+ } catch {
1337
+ }
1338
+ }
1339
+ resolve2();
1340
+ };
1341
+ ws.onerror = (error) => reject(error);
1342
+ ws.on("ping", (data) => {
1343
+ if (this.ws !== ws) return;
1344
+ const receivedAtMs = Date.now();
1345
+ this.recordLiveness();
1346
+ this.config.diagnostic?.("runtime.ws.ping_received", { received_at_ms: receivedAtMs, bytes: data.length });
1347
+ ws.pong(data, true, (error) => this.config.diagnostic?.("runtime.ws.pong_written", {
1348
+ ping_received_at_ms: receivedAtMs,
1349
+ written_at_ms: Date.now(),
1350
+ duration_ms: Math.max(0, Date.now() - receivedAtMs),
1351
+ success: !error
1352
+ }, error ? "warn" : "debug"));
1353
+ });
1354
+ ws.on?.("pong", () => this.recordLiveness());
1355
+ ws.onmessage = (event) => {
1356
+ if (this.ws !== ws) return;
1357
+ this.socketReceivedAtMs = Date.now();
1358
+ this.decodeStartedAt = performance.now();
1359
+ const raw = wsMessageToString(event.data);
1360
+ try {
1361
+ this.rawMessageSink?.enqueue(raw);
1362
+ } catch {
1363
+ }
1364
+ this.recordLiveness();
1365
+ let parsed;
1366
+ try {
1367
+ parsed = JSON.parse(raw);
1368
+ } catch {
1369
+ this.reportProtocolError("invalid_json");
1370
+ return;
1371
+ }
1372
+ try {
1373
+ this.handleMessage(parsed, raw);
1374
+ } catch (error) {
1375
+ this.reportProtocolError("invalid_game_sync_message", {
1376
+ error: error instanceof Error ? error.message : String(error)
1377
+ });
1378
+ }
1379
+ };
1380
+ ws.onclose = (event) => {
1381
+ if (this.ws !== ws) return;
1382
+ this.stopAckTimer();
1383
+ const info = {
1384
+ code: typeof event.code === "number" ? event.code : void 0,
1385
+ reason: event.reason ?? "",
1386
+ wasClean: typeof event.wasClean === "boolean" ? event.wasClean : void 0
1387
+ };
1388
+ for (const handler of this.disconnectHandlers) handler(info);
1389
+ if (closeIsTerminal(info.code)) this.shouldReconnect = false;
1390
+ if (this.shouldReconnect) {
1391
+ this.setState("reconnecting" /* Reconnecting */);
1392
+ this.scheduleReconnect();
1393
+ } else {
1394
+ this.setState("disconnected" /* Disconnected */);
1395
+ }
1396
+ };
1397
+ });
1398
+ }
1399
+ handleMessage(raw, wire = JSON.stringify(raw)) {
1400
+ const message = parseGameSyncMessage(raw);
1401
+ if (message.type === "game.sync.snapshot") {
1402
+ this.config.discardUnappliedMessages?.();
1403
+ if (this.config.retainInputMessage?.(wire) === false) return;
1404
+ const wasRecovering = this.recovering;
1405
+ const previousGameId = this.baseline?.gameId;
1406
+ if (previousGameId !== void 0 && previousGameId !== message.data.game_id) {
1407
+ this.seenEventIds.clear();
1408
+ }
1409
+ this.baseline = {
1410
+ gameId: message.data.game_id,
1411
+ seq: message.data.seq,
1412
+ tick: message.data.tick,
1413
+ locale: message.data.locale,
1414
+ state: structuredClone(message.data.state)
1415
+ };
1416
+ this.recovering = false;
1417
+ this.awaitingSnapshot = false;
1418
+ this.recoveryStartSeq = null;
1419
+ this.recoveryFirstSeq = null;
1420
+ this.recoveryFrameCount = 0;
1421
+ this.recoveryEvents = [];
1422
+ this.clearPendingApplication();
1423
+ const events = this.newEvents(message.data.events, message.data.seq);
1424
+ const ackToken = this.recordPendingBaseline(this.baseline);
1425
+ this.dispatch(this.baseline, events, {
1426
+ origin: "snapshot",
1427
+ replayed: false,
1428
+ ackToken,
1429
+ ...wasRecovering ? { snapshotFallback: true } : {}
1430
+ });
1431
+ return;
1432
+ }
1433
+ if (message.type === "game.sync.update") {
1434
+ const baseline = this.baseline;
1435
+ if (!baseline || this.awaitingSnapshot) {
1436
+ this.reportProtocolError("update_without_snapshot", { received_seq: message.data.seq });
1437
+ this.requestResync("missing_baseline", void 0, message.data.seq);
1438
+ return;
1439
+ }
1440
+ if (message.data.game_id !== baseline.gameId) {
1441
+ this.reportProtocolError("game_id_changed", {
1442
+ expected_game_id: baseline.gameId,
1443
+ received_game_id: message.data.game_id
1444
+ });
1445
+ this.requestResync("game_id_changed", baseline.seq + 1, message.data.seq);
1446
+ return;
1447
+ }
1448
+ if (message.data.seq <= baseline.seq) return;
1449
+ const expectedSeq = baseline.seq + 1;
1450
+ if (message.data.seq !== expectedSeq) {
1451
+ this.reportProtocolError("seq_gap", {
1452
+ expected_seq: expectedSeq,
1453
+ received_seq: message.data.seq
1454
+ });
1455
+ this.requestResync("seq_gap", expectedSeq, message.data.seq);
1456
+ return;
1457
+ }
1458
+ if (this.config.retainInputMessage?.(wire) === false) return;
1459
+ this.baseline = {
1460
+ ...baseline,
1461
+ seq: message.data.seq,
1462
+ tick: message.data.tick,
1463
+ state: applyGameSyncDelta(baseline.state, message.data.state_delta)
1464
+ };
1465
+ const events = this.newEvents(message.data.events, message.data.seq);
1466
+ if (this.recovering) {
1467
+ if (this.recoveryFrameCount === 0) this.recoveryFirstSeq = message.data.seq;
1468
+ this.recoveryFrameCount += 1;
1469
+ this.recoveryEvents.push(...events);
1470
+ return;
1471
+ }
1472
+ const ackToken = this.recordPendingBaseline(this.baseline);
1473
+ this.dispatch(this.baseline, events, { origin: "update", replayed: false, ackToken });
1474
+ return;
1475
+ }
1476
+ if (message.type === "game.sync.resume") {
1477
+ const baseline = this.baseline;
1478
+ const expectedToSeq = this.recoveryStartSeq === null ? void 0 : this.recoveryStartSeq + this.recoveryFrameCount;
1479
+ if (!this.recovering || !baseline || message.data.to_seq !== baseline.seq || message.data.tick < baseline.tick || message.data.replayed_count !== this.recoveryFrameCount || message.data.to_seq !== expectedToSeq || this.recoveryFrameCount === 0 && message.data.from_seq != null || this.recoveryFrameCount > 0 && message.data.from_seq !== this.recoveryFirstSeq) {
1480
+ this.reportProtocolError("invalid_resume", {
1481
+ from_seq: message.data.from_seq,
1482
+ applied_from_seq: this.recoveryFirstSeq,
1483
+ to_seq: message.data.to_seq,
1484
+ applied_seq: baseline?.seq,
1485
+ replayed_count: message.data.replayed_count,
1486
+ applied_count: this.recoveryFrameCount,
1487
+ resume_tick: message.data.tick,
1488
+ applied_tick: baseline?.tick
1489
+ });
1490
+ this.requestResync("invalid_resume", baseline ? baseline.seq + 1 : void 0, message.data.to_seq);
1491
+ return;
1492
+ }
1493
+ if (this.config.retainInputMessage?.(wire) === false) return;
1494
+ const events = this.recoveryEvents;
1495
+ const replayedEventCount = events.length;
1496
+ this.recoveryEvents = [];
1497
+ this.recoveryStartSeq = null;
1498
+ this.recoveryFirstSeq = null;
1499
+ this.recoveryFrameCount = 0;
1500
+ this.recovering = false;
1501
+ this.awaitingSnapshot = false;
1502
+ this.baseline = { ...baseline, tick: message.data.tick };
1503
+ const ackToken = this.recordPendingBaseline(this.baseline);
1504
+ this.dispatch(this.baseline, events, {
1505
+ origin: "resume",
1506
+ replayed: true,
1507
+ ackToken,
1508
+ replayedEventCount
1509
+ });
1510
+ return;
1511
+ }
1512
+ this.handleServerError(message.data);
1513
+ }
1514
+ handleServerError(error) {
1515
+ this.reportProtocolError("server_error", {
1516
+ code: error.code,
1517
+ recoverable: error.recoverable,
1518
+ ...error.message ? { message: error.message } : {}
1519
+ });
1520
+ if (!error.recoverable) {
1521
+ this.shouldReconnect = false;
1522
+ this.ws?.close(1002, error.code);
1523
+ }
1524
+ }
1525
+ requestResync(reason, expectedSeq, receivedSeq) {
1526
+ if (this.awaitingSnapshot) return;
1527
+ this.config.discardUnappliedMessages?.();
1528
+ this.awaitingSnapshot = true;
1529
+ this.recovering = true;
1530
+ this.recoveryStartSeq = this.baseline?.seq ?? null;
1531
+ this.recoveryFirstSeq = null;
1532
+ this.recoveryFrameCount = 0;
1533
+ this.recoveryEvents = [];
1534
+ const recovery = {
1535
+ connectionId: this.connectionIdValue,
1536
+ reason,
1537
+ ...expectedSeq === void 0 ? {} : { expectedSeq },
1538
+ ...receivedSeq === void 0 ? {} : { receivedSeq }
1539
+ };
1540
+ for (const handler of this.recoveryStartedHandlers) {
1541
+ try {
1542
+ handler(recovery);
1543
+ } catch {
1544
+ }
1545
+ }
1546
+ this.send({
1547
+ type: "game.sync.resync",
1548
+ data: {
1549
+ reason,
1550
+ ...expectedSeq === void 0 ? {} : { expected_seq: expectedSeq },
1551
+ ...receivedSeq === void 0 ? {} : { received_seq: receivedSeq }
1552
+ }
1553
+ });
1554
+ }
1555
+ newEvents(events, seq) {
1556
+ const result = [];
1557
+ const eventIds = [];
1558
+ for (const event of events) {
1559
+ const eventId = String(event.event_id);
1560
+ if (this.seenEventIds.has(eventId) || this.inFlightEventIds.has(eventId)) continue;
1561
+ this.inFlightEventIds.add(eventId);
1562
+ eventIds.push(eventId);
1563
+ result.push(structuredClone(event));
1564
+ }
1565
+ if (eventIds.length > 0) this.pendingEventIds.set(seq, eventIds);
1566
+ return result;
1567
+ }
1568
+ trimSeenEventIds() {
1569
+ while (this.seenEventIds.size > MAX_SEEN_EVENT_IDS) {
1570
+ const oldest = this.seenEventIds.values().next().value;
1571
+ if (oldest === void 0) break;
1572
+ this.seenEventIds.delete(oldest);
1573
+ }
1574
+ }
1575
+ dispatch(baseline, events, meta) {
1576
+ const frame = {
1577
+ kind: "state",
1578
+ state: {
1579
+ ...structuredClone(baseline.state),
1580
+ game_id: baseline.gameId,
1581
+ tick: baseline.tick
1582
+ },
1583
+ events: structuredClone(events),
1584
+ meta: {
1585
+ connectionId: this.connectionIdValue,
1586
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
1587
+ locale: baseline.locale,
1588
+ ingress: {
1589
+ socketReceivedAtMs: this.socketReceivedAtMs,
1590
+ decodedAtMs: Date.now(),
1591
+ decodeDurationMs: Math.max(0, performance.now() - this.decodeStartedAt)
1592
+ },
1593
+ origin: meta.origin,
1594
+ sourceSeq: baseline.seq,
1595
+ gameId: baseline.gameId,
1596
+ domainTick: baseline.tick,
1597
+ replayed: meta.replayed,
1598
+ ackToken: meta.ackToken,
1599
+ ...meta.snapshotFallback ? { snapshotFallback: true } : {},
1600
+ ...meta.replayedEventCount === void 0 ? {} : { replayedEventCount: meta.replayedEventCount }
1601
+ }
1602
+ };
1603
+ for (const handler of this.inputFrameHandlers) handler(frame);
1604
+ }
1605
+ recordPendingBaseline(baseline) {
1606
+ const ackToken = randomUUID2();
1607
+ this.pendingBaselines.set(ackToken, {
1608
+ connectionId: this.connectionIdValue,
1609
+ baseline: structuredClone(baseline)
1610
+ });
1611
+ return ackToken;
1612
+ }
1613
+ clearPendingApplication() {
1614
+ this.pendingBaselines.clear();
1615
+ this.pendingEventIds.clear();
1616
+ this.inFlightEventIds.clear();
1617
+ }
1618
+ sendAck() {
1619
+ const seq = this.committedBaseline?.seq;
1620
+ if (!this.ackDirty || seq === void 0 || seq <= this.lastAckSent) return;
1621
+ if (this.send({ type: "game.sync.ack", data: { seq } })) {
1622
+ this.lastAckSent = seq;
1623
+ this.ackDirty = false;
1624
+ this.config.diagnostic?.("runtime.ws.ack_submitted", { source_seq: seq, submitted_at_ms: Date.now() });
1625
+ }
1626
+ }
1627
+ send(value) {
1628
+ if (!this.ws || this._state !== "connected" /* Connected */) return false;
1629
+ try {
1630
+ this.ws.send(JSON.stringify(value));
1631
+ return true;
1632
+ } catch {
1633
+ return false;
1634
+ }
1635
+ }
1636
+ startAckTimer() {
1637
+ this.stopAckTimer();
1638
+ const intervalMs = this.config.ackIntervalMs ?? DEFAULT_ACK_INTERVAL_MS;
1639
+ if (intervalMs <= 0) return;
1640
+ this.ackTimer = setInterval(() => this.sendAck(), intervalMs);
1641
+ this.ackTimer.unref?.();
1642
+ }
1643
+ stopAckTimer() {
1644
+ if (!this.ackTimer) return;
1645
+ clearInterval(this.ackTimer);
1646
+ this.ackTimer = null;
1647
+ }
1648
+ recordLiveness() {
1649
+ const atMs = Date.now();
1650
+ this.lastPongAtValue = new Date(atMs).toISOString();
1651
+ for (const handler of this.livenessHandlers) {
1652
+ try {
1653
+ handler(this.connectionIdValue, atMs);
1654
+ } catch {
1655
+ }
1656
+ }
1657
+ }
1658
+ reportProtocolError(reason, details) {
1659
+ const info = {
1660
+ connectionId: this.connectionIdValue,
1661
+ reason,
1662
+ ...details ? { details } : {}
1663
+ };
1664
+ for (const handler of this.protocolErrorHandlers) {
1665
+ try {
1666
+ handler(info);
1667
+ } catch {
1668
+ }
1669
+ }
1670
+ }
1671
+ setState(next) {
1672
+ if (next === this._state) return;
1673
+ this._state = next;
1674
+ for (const handler of this.stateChangeHandlers) handler(next);
1675
+ }
1676
+ scheduleReconnect() {
1677
+ const delay = Math.min(1e3 * 2 ** this.reconnectAttempt, this.config.reconnectMaxMs ?? 3e4);
1678
+ this.reconnectAttempt += 1;
1679
+ this.reconnectTimer = setTimeout(() => {
1680
+ if (!this.shouldReconnect) return;
1681
+ if (this.config.reconnectReady?.() === false) {
1682
+ this.reconnectAttempt = Math.max(0, this.reconnectAttempt - 1);
1683
+ this.scheduleReconnect();
1684
+ return;
1685
+ }
1686
+ this.setState("connecting" /* Connecting */);
1687
+ void this.openSocket().catch(() => {
1688
+ });
1689
+ }, delay);
1690
+ }
1691
+ onInputFrame(handler) {
1692
+ this.inputFrameHandlers.add(handler);
1693
+ return () => this.inputFrameHandlers.delete(handler);
1694
+ }
1695
+ onConnectionOpened(handler) {
1696
+ this.connectionOpenedHandlers.add(handler);
1697
+ return () => this.connectionOpenedHandlers.delete(handler);
1698
+ }
1699
+ onLiveness(handler) {
1700
+ this.livenessHandlers.add(handler);
1701
+ return () => this.livenessHandlers.delete(handler);
1702
+ }
1703
+ onProtocolError(handler) {
1704
+ this.protocolErrorHandlers.add(handler);
1705
+ return () => this.protocolErrorHandlers.delete(handler);
1706
+ }
1707
+ onRecoveryStarted(handler) {
1708
+ this.recoveryStartedHandlers.add(handler);
1709
+ return () => this.recoveryStartedHandlers.delete(handler);
1710
+ }
1711
+ onStateChange(handler) {
1712
+ this.stateChangeHandlers.add(handler);
1713
+ return () => this.stateChangeHandlers.delete(handler);
1714
+ }
1715
+ onDisconnect(handler) {
1716
+ this.disconnectHandlers.add(handler);
1717
+ return () => this.disconnectHandlers.delete(handler);
1718
+ }
1719
+ clearHandlers() {
1720
+ this.inputFrameHandlers.clear();
1721
+ this.connectionOpenedHandlers.clear();
1722
+ this.livenessHandlers.clear();
1723
+ this.protocolErrorHandlers.clear();
1724
+ this.recoveryStartedHandlers.clear();
1725
+ this.stateChangeHandlers.clear();
1726
+ this.disconnectHandlers.clear();
1727
+ }
1728
+ disconnect() {
1729
+ this.shouldReconnect = false;
1730
+ this.sendAck();
1731
+ this.stopAckTimer();
1732
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
1733
+ this.reconnectTimer = null;
1734
+ const ws = this.ws;
1735
+ this.ws = null;
1736
+ if (ws) {
1737
+ ws.onclose = null;
1738
+ ws.close();
1739
+ }
1740
+ this.setState("disconnected" /* Disconnected */);
1741
+ }
1742
+ };
1743
+
1744
+ // src/runtime/runtime-logger.ts
1745
+ var LEVEL_NAMES = {
1746
+ [0 /* DEBUG */]: "DEBUG",
1747
+ [1 /* INFO */]: "INFO",
1748
+ [2 /* WARN */]: "WARN",
1749
+ [3 /* ERROR */]: "ERROR"
1750
+ };
1751
+ function parseLogLevel(raw) {
1752
+ switch (raw?.toUpperCase()) {
1753
+ case "DEBUG":
1754
+ return 0 /* DEBUG */;
1755
+ case "INFO":
1756
+ return 1 /* INFO */;
1757
+ case "WARN":
1758
+ return 2 /* WARN */;
1759
+ case "ERROR":
1760
+ return 3 /* ERROR */;
1761
+ default:
1762
+ return 0 /* DEBUG */;
1763
+ }
1764
+ }
1765
+ function isTrue(value) {
1766
+ if (typeof value !== "string") return false;
1767
+ const normalized = value.trim().toLowerCase();
1768
+ return normalized === "1" || normalized === "true";
1769
+ }
1770
+ var RuntimeLogger = class {
1771
+ minLevel;
1772
+ logToConsole;
1773
+ constructor() {
1774
+ this.minLevel = parseLogLevel(process.env.CLAWCLAW_LOG_LEVEL);
1775
+ this.logToConsole = isTrue(process.env.CLAWCLAW_RUNTIME_LOG_TO_CONSOLE);
1776
+ }
1777
+ // ─── Core log methods ────────────────────────────────────────────────────
1778
+ debug(tag, msg) {
1779
+ this.log(0 /* DEBUG */, tag, msg);
1780
+ }
1781
+ info(tag, msg) {
1782
+ this.log(1 /* INFO */, tag, msg);
1783
+ }
1784
+ warn(tag, msg) {
1785
+ this.log(2 /* WARN */, tag, msg);
1786
+ }
1787
+ error(tag, msg, err) {
1788
+ const suffix = err instanceof Error ? ` err=${err.message}` : err ? ` err=${err}` : "";
1789
+ this.log(3 /* ERROR */, tag, msg + suffix);
1790
+ if (this.logToConsole && err instanceof Error && err.stack) {
1791
+ console.error(err.stack);
1792
+ }
1793
+ }
1794
+ // ─── Helpers ─────────────────────────────────────────────────────────────
1795
+ /**
1796
+ * Log a list of tasks at DEBUG level (reduces repetitive loop logging).
1797
+ * Outputs one indented line per task — pair with a preceding info() call for the summary.
1798
+ */
1799
+ logTaskList(tag, tasks) {
1800
+ for (const t of tasks) {
1801
+ this.debug(tag, ` \u2514\u2500 ${t.name} room=${t.room ?? "?"} coords=(${t.x ?? "?"},${t.y ?? "?"})${t.status ? ` status=${t.status}` : ""}`);
1802
+ }
1803
+ }
1804
+ // ─── Internal ────────────────────────────────────────────────────────────
1805
+ log(level, tag, msg) {
1806
+ if (level < this.minLevel) return;
1807
+ if (!this.logToConsole) return;
1808
+ const prefix = `[Runtime:${LEVEL_NAMES[level]}]`;
1809
+ const line = `${prefix} ${tag} ${msg}`;
1810
+ console.error(line);
1811
+ }
1812
+ };
1813
+
1814
+ // src/runtime/threaded-ws-client.ts
1815
+ import { Worker } from "node:worker_threads";
1816
+ import { EventEmitter } from "node:events";
1817
+ var ThreadedWsClient = class {
1818
+ constructor(config) {
1819
+ this.config = config;
1820
+ const frames = config.maxInFlightFrames ?? 10;
1821
+ const bytes = config.maxPendingBytes ?? 32 * 1024 * 1024;
1822
+ if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1e3) throw new Error("GAME_SYNC_FRAME_LIMIT_INVALID");
1823
+ if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error("GAME_SYNC_BYTE_LIMIT_INVALID");
1824
+ this.committed = config.resumeState ? structuredClone(config.resumeState) : void 0;
1825
+ }
1826
+ config;
1827
+ events = new EventEmitter();
1828
+ worker;
1829
+ stateValue = "disconnected" /* Disconnected */;
1830
+ connectionIdValue = "";
1831
+ lastLivenessAt = null;
1832
+ committed;
1833
+ pending = /* @__PURE__ */ new Map();
1834
+ pendingReports = 0;
1835
+ stopped = false;
1836
+ connectedTask;
1837
+ resolveConnect;
1838
+ rejectConnect;
1839
+ closeTask = Promise.resolve();
1840
+ resolveClose;
1841
+ closeTimer;
1842
+ startupTimer;
1843
+ get connected() {
1844
+ return this.stateValue === "connected" /* Connected */;
1845
+ }
1846
+ get state() {
1847
+ return this.stateValue;
1848
+ }
1849
+ get connectionId() {
1850
+ return this.connectionIdValue;
1851
+ }
1852
+ get lastPongAt() {
1853
+ return this.lastLivenessAt;
1854
+ }
1855
+ get resumeState() {
1856
+ return this.committed ? structuredClone(this.committed) : void 0;
1857
+ }
1858
+ connect() {
1859
+ if (this.connectedTask) return this.connectedTask;
1860
+ if (this.stopped) return Promise.reject(new Error("GAME_SYNC_INGRESS_STOPPED"));
1861
+ this.stateValue = "connecting" /* Connecting */;
1862
+ this.connectedTask = new Promise((resolve2, reject) => {
1863
+ this.resolveConnect = resolve2;
1864
+ this.rejectConnect = reject;
1865
+ });
1866
+ this.closeTask = new Promise((resolve2) => {
1867
+ this.resolveClose = resolve2;
1868
+ });
1869
+ this.startupTimer = setTimeout(() => this.fail("GAME_SYNC_INGRESS_START_TIMEOUT"), 2e4);
1870
+ this.startupTimer.unref();
1871
+ const config = {
1872
+ url: this.config.url,
1873
+ apiKey: this.config.apiKey,
1874
+ resumeState: this.committed,
1875
+ reconnectMaxMs: this.config.reconnectMaxMs,
1876
+ ackIntervalMs: this.config.ackIntervalMs,
1877
+ maxInFlightFrames: this.config.maxInFlightFrames ?? 10,
1878
+ maxPendingBytes: this.config.maxPendingBytes ?? 32 * 1024 * 1024,
1879
+ rawLog: this.config.rawLog
1880
+ };
1881
+ try {
1882
+ this.worker = new Worker(new URL("./framework/modules/runtime-module-worker-bootstrap.mjs", import.meta.url), {
1883
+ execArgv: [],
1884
+ stdout: true,
1885
+ stderr: true,
1886
+ resourceLimits: { maxOldGenerationSizeMb: 128 },
1887
+ workerData: { config, runtimeModuleBootstrap: {
1888
+ hostUrl: new URL("./game-sync-ingress-worker.ts", import.meta.url).href,
1889
+ hooksUrl: new URL("./framework/modules/runtime-module-loader-hooks.mjs", import.meta.url).href,
1890
+ sdkAliases: {},
1891
+ esmModuleRoots: []
1892
+ } }
1893
+ });
1894
+ this.worker.stdout?.on("data", () => {
1895
+ });
1896
+ this.worker.stderr?.on("data", () => {
1897
+ });
1898
+ this.worker.on("message", (message) => this.receive(message));
1899
+ this.worker.on("error", () => this.fail("GAME_SYNC_INGRESS_WORKER_FAILED"));
1900
+ this.worker.on("exit", (code) => {
1901
+ if (!this.stopped) this.fail("GAME_SYNC_INGRESS_WORKER_EXITED");
1902
+ if (this.closeTimer) clearTimeout(this.closeTimer);
1903
+ this.resolveClose?.();
1904
+ this.diagnostic("runtime.ws.ingress_stopped", { exit_code: code });
1905
+ });
1906
+ } catch {
1907
+ this.fail("GAME_SYNC_INGRESS_START_FAILED");
1908
+ this.resolveClose?.();
1909
+ }
1910
+ return this.connectedTask;
1911
+ }
1912
+ receive(message) {
1913
+ if (message.type === "telemetry") {
1914
+ const a = message.attributes;
1915
+ const at = Number(a.last_liveness_at_ms);
1916
+ if (at > 0 && !this.stopped) {
1917
+ this.lastLivenessAt = new Date(at).toISOString();
1918
+ this.events.emit("liveness", String(a.connection_id), at);
1919
+ }
1920
+ this.diagnostic("runtime.ws.ingress_window", { ...a, owner_observed_at_ms: Date.now() }, Number(a.overload_count) ? "warn" : "info");
1921
+ this.post({ type: "telemetry_ack" });
1922
+ return;
1923
+ }
1924
+ if (message.type === "stopped") {
1925
+ if (message.rawStats) this.diagnostic("runtime.raw_ws.capture_stopped", { ...message.rawStats });
1926
+ return;
1927
+ }
1928
+ if (this.stopped) return;
1929
+ switch (message.type) {
1930
+ case "connected":
1931
+ if (this.startupTimer) clearTimeout(this.startupTimer);
1932
+ this.resolveConnect?.();
1933
+ break;
1934
+ case "failed":
1935
+ this.fail(message.code);
1936
+ break;
1937
+ case "state":
1938
+ this.stateValue = message.state;
1939
+ this.events.emit("state", message.state);
1940
+ break;
1941
+ case "opened":
1942
+ this.connectionIdValue = message.connectionId;
1943
+ this.events.emit("opened", message.connectionId);
1944
+ break;
1945
+ case "close":
1946
+ this.connectionIdValue = message.connectionId;
1947
+ this.diagnostic("runtime.ws.ingress_disconnected", { code: message.info.code, reason: message.info.reason, pending_frames: this.pending.size }, "warn");
1948
+ this.events.emit("close", message.info);
1949
+ break;
1950
+ case "protocol":
1951
+ this.events.emit("protocol", message.info);
1952
+ break;
1953
+ case "recovery":
1954
+ this.events.emit("recovery", message.info);
1955
+ break;
1956
+ case "report_done":
1957
+ this.pendingReports = Math.max(0, this.pendingReports - 1);
1958
+ break;
1959
+ case "frame": {
1960
+ const frame = message.frame;
1961
+ frame.meta.ingress = { ...frame.meta.ingress, ownerReceivedAtMs: Date.now(), transportGeneration: this.config.transportGeneration ?? 1 };
1962
+ this.pending.set(frame.meta.ackToken, frame);
1963
+ this.lastLivenessAt = frame.meta.receivedAt;
1964
+ this.events.emit("liveness", frame.meta.connectionId, Date.parse(frame.meta.receivedAt));
1965
+ this.events.emit("frame", frame);
1966
+ break;
1967
+ }
1968
+ }
1969
+ }
1970
+ acknowledge(token, _immediate = false) {
1971
+ const frame = this.pending.get(token);
1972
+ if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return;
1973
+ const seq = Number(frame.meta.sourceSeq);
1974
+ if (!this.committed || seq >= this.committed.seq) {
1975
+ const { game_id: _gameId, tick: _tick, ...state } = frame.state;
1976
+ this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? "zh-CN", state: structuredClone(state) };
1977
+ }
1978
+ for (const key of this.pending.keys()) {
1979
+ this.pending.delete(key);
1980
+ if (key === token) break;
1981
+ }
1982
+ this.post({ type: "consumed", token });
1983
+ }
1984
+ reportPerceptions(perceptions) {
1985
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
1986
+ const message = gameSyncPerceptionReportMessage(perceptions);
1987
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
1988
+ this.pendingReports++;
1989
+ this.post({ type: "report", perceptions: message.data.perceptions, connectionId: this.connectionId });
1990
+ return true;
1991
+ }
1992
+ reportRuntime(report) {
1993
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
1994
+ const message = gameSyncRuntimeReportMessage(report);
1995
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
1996
+ this.pendingReports++;
1997
+ this.post({ type: "runtime_report", report: message.data, connectionId: this.connectionId });
1998
+ return true;
1999
+ }
2000
+ post(message) {
2001
+ try {
2002
+ this.worker?.postMessage(message);
2003
+ } catch {
2004
+ if (!this.stopped) this.fail("GAME_SYNC_INGRESS_PORT_FAILED");
2005
+ }
2006
+ }
2007
+ diagnostic(name, attributes, severity = "info") {
2008
+ try {
2009
+ this.config.diagnostic?.(name, { transport_generation: this.config.transportGeneration ?? 1, ...attributes }, severity);
2010
+ } catch {
2011
+ }
2012
+ }
2013
+ fail(code) {
2014
+ if (this.stopped) return;
2015
+ this.rejectConnect?.(new Error(code));
2016
+ this.diagnostic("runtime.ws.ingress_failed", { error_code: code }, "warn");
2017
+ this.stateValue = "disconnected" /* Disconnected */;
2018
+ this.events.emit("close", { code: 1013, reason: code, wasClean: false });
2019
+ this.disconnect();
2020
+ }
2021
+ disconnect() {
2022
+ if (this.stopped) return;
2023
+ this.stopped = true;
2024
+ if (this.startupTimer) clearTimeout(this.startupTimer);
2025
+ this.stateValue = "disconnected" /* Disconnected */;
2026
+ this.rejectConnect?.(new Error("GAME_SYNC_INGRESS_STOPPED"));
2027
+ this.post({ type: "stop" });
2028
+ this.pending.clear();
2029
+ this.events.emit("state", this.stateValue);
2030
+ if (this.worker) {
2031
+ this.closeTimer = setTimeout(() => {
2032
+ this.diagnostic("runtime.ws.ingress_stop_timeout", {}, "warn");
2033
+ void this.worker?.terminate();
2034
+ }, 5e3);
2035
+ this.closeTimer.unref();
2036
+ }
2037
+ }
2038
+ async close() {
2039
+ this.disconnect();
2040
+ await this.closeTask;
2041
+ }
2042
+ clearHandlers() {
2043
+ this.events.removeAllListeners();
2044
+ }
2045
+ on(event, handler) {
2046
+ this.events.on(event, handler);
2047
+ return () => {
2048
+ this.events.off(event, handler);
2049
+ };
2050
+ }
2051
+ onInputFrame(handler) {
2052
+ return this.on("frame", handler);
2053
+ }
2054
+ onConnectionOpened(handler) {
2055
+ return this.on("opened", handler);
2056
+ }
2057
+ onLiveness(handler) {
2058
+ return this.on("liveness", handler);
2059
+ }
2060
+ onProtocolError(handler) {
2061
+ return this.on("protocol", handler);
2062
+ }
2063
+ onRecoveryStarted(handler) {
2064
+ return this.on("recovery", handler);
2065
+ }
2066
+ onStateChange(handler) {
2067
+ return this.on("state", handler);
2068
+ }
2069
+ onDisconnect(handler) {
2070
+ return this.on("close", handler);
2071
+ }
2072
+ };
2073
+
2074
+ // src/lib/custom-tts.ts
2075
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
2076
+ import { basename, extname } from "path";
2077
+ var DEFAULT_TIMEOUT_MS = 1e4;
2078
+ var MAX_TIMEOUT_MS = 6e4;
2079
+ var MAX_AUDIO_BYTES = 10 * 1024 * 1024;
2080
+ var SUPPORTED_AUDIO_FORMATS = "mp3, wav, m4a, ogg, webm";
2081
+ var AUDIO_FORMATS = {
2082
+ mp3: { format: "mp3", contentType: "audio/mpeg", extension: ".mp3" },
2083
+ wav: { format: "wav", contentType: "audio/wav", extension: ".wav" },
2084
+ m4a: { format: "m4a", contentType: "audio/mp4", extension: ".m4a" },
2085
+ ogg: { format: "ogg", contentType: "audio/ogg", extension: ".ogg" },
2086
+ webm: { format: "webm", contentType: "audio/webm", extension: ".webm" }
2087
+ };
2088
+ var AUDIO_FORMAT_ALIASES = {
2089
+ mp3: "mp3",
2090
+ mpeg: "mp3",
2091
+ "audio/mpeg": "mp3",
2092
+ "audio/mp3": "mp3",
2093
+ wav: "wav",
2094
+ wave: "wav",
2095
+ "audio/wav": "wav",
2096
+ "audio/x-wav": "wav",
2097
+ m4a: "m4a",
2098
+ mp4: "m4a",
2099
+ "audio/mp4": "m4a",
2100
+ "audio/x-m4a": "m4a",
2101
+ ogg: "ogg",
2102
+ oga: "ogg",
2103
+ "audio/ogg": "ogg",
2104
+ webm: "webm",
2105
+ "audio/webm": "webm"
2106
+ };
2107
+ var CustomTtsError = class extends Error {
2108
+ constructor(message) {
2109
+ super(message);
2110
+ this.name = "CustomTtsError";
2111
+ }
2112
+ };
2113
+ function isRecord(value) {
2114
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2115
+ }
2116
+ function validateHttpUrl(raw, field) {
2117
+ if (typeof raw !== "string" || raw.trim() === "") {
2118
+ throw new CustomTtsError(`${field} must be a non-empty HTTP(S) URL.`);
2119
+ }
2120
+ let url;
2121
+ try {
2122
+ url = new URL(raw);
2123
+ } catch {
2124
+ throw new CustomTtsError(`${field} must be a valid HTTP(S) URL.`);
2125
+ }
2126
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
2127
+ throw new CustomTtsError(`${field} must use http:// or https://.`);
2128
+ }
2129
+ return url.toString();
2130
+ }
2131
+ function validateHeaders(raw) {
2132
+ if (raw === void 0) return { "Content-Type": "application/json" };
2133
+ if (!isRecord(raw)) throw new CustomTtsError("request.headers must be a JSON object.");
2134
+ const headers = {};
2135
+ for (const [name, value] of Object.entries(raw)) {
2136
+ if (typeof value !== "string") {
2137
+ throw new CustomTtsError(`request.headers.${name} must be a string.`);
2138
+ }
2139
+ headers[name] = value;
2140
+ }
2141
+ if (!Object.keys(headers).some((name) => name.toLowerCase() === "content-type")) {
2142
+ headers["Content-Type"] = "application/json";
2143
+ }
2144
+ return headers;
2145
+ }
2146
+ function validateTimeout(raw) {
2147
+ if (raw === void 0) return DEFAULT_TIMEOUT_MS;
2148
+ if (!Number.isInteger(raw) || Number(raw) <= 0 || Number(raw) > MAX_TIMEOUT_MS) {
2149
+ throw new CustomTtsError(`request.timeout_ms must be an integer between 1 and ${MAX_TIMEOUT_MS}.`);
2150
+ }
2151
+ return Number(raw);
2152
+ }
2153
+ function validateResponse(raw) {
2154
+ if (raw === void 0) return { type: "binary" };
2155
+ if (!isRecord(raw)) throw new CustomTtsError("response must be a JSON object.");
2156
+ const type = raw.type ?? "binary";
2157
+ if (type !== "binary" && type !== "json_base64" && type !== "json_url") {
2158
+ throw new CustomTtsError("response.type must be binary, json_base64, or json_url.");
2159
+ }
2160
+ const path = raw.path;
2161
+ if (type !== "binary" && (typeof path !== "string" || path.trim() === "")) {
2162
+ throw new CustomTtsError(`response.path is required when response.type is ${type}.`);
2163
+ }
2164
+ if (raw.content_type !== void 0 && (typeof raw.content_type !== "string" || raw.content_type.trim() === "")) {
2165
+ throw new CustomTtsError("response.content_type must be a non-empty string.");
2166
+ }
2167
+ if (raw.format !== void 0 && (typeof raw.format !== "string" || raw.format.trim() === "")) {
2168
+ throw new CustomTtsError("response.format must be a non-empty string.");
2169
+ }
2170
+ if (raw.format_path !== void 0 && (typeof raw.format_path !== "string" || raw.format_path.trim() === "")) {
2171
+ throw new CustomTtsError("response.format_path must be a non-empty string.");
2172
+ }
2173
+ if (type === "binary" && raw.format_path !== void 0) {
2174
+ throw new CustomTtsError("response.format_path is only supported for json_base64 and json_url responses.");
2175
+ }
2176
+ if (raw.filename !== void 0) {
2177
+ if (typeof raw.filename !== "string" || raw.filename.trim() === "" || basename(raw.filename) !== raw.filename) {
2178
+ throw new CustomTtsError("response.filename must be a plain filename without directories.");
2179
+ }
2180
+ }
2181
+ const configuredFormat = typeof raw.format === "string" ? resolveAudioFormat(raw.format, "response.format") : void 0;
2182
+ const configuredContentType = typeof raw.content_type === "string" ? resolveAudioFormat(raw.content_type, "response.content_type") : void 0;
2183
+ if (configuredFormat && configuredContentType && configuredFormat.format !== configuredContentType.format) {
2184
+ throw new CustomTtsError("response.format and response.content_type describe different audio formats.");
2185
+ }
2186
+ return {
2187
+ type,
2188
+ ...typeof path === "string" ? { path } : {},
2189
+ ...typeof raw.format === "string" ? { format: raw.format.trim() } : {},
2190
+ ...typeof raw.format_path === "string" ? { format_path: raw.format_path.trim() } : {},
2191
+ ...typeof raw.content_type === "string" ? { content_type: raw.content_type } : {},
2192
+ ...typeof raw.filename === "string" ? { filename: raw.filename } : {}
2193
+ };
2194
+ }
2195
+ function validateTextField(raw) {
2196
+ if (raw === void 0) return void 0;
2197
+ if (typeof raw !== "string" || raw.trim() === "") {
2198
+ throw new CustomTtsError("request.text_field must be a non-empty string.");
2199
+ }
2200
+ return raw.trim();
2201
+ }
2202
+ function validateBody(raw) {
2203
+ if (raw === void 0) return {};
2204
+ if (!isRecord(raw)) throw new CustomTtsError("request.body must be a JSON object.");
2205
+ return raw;
2206
+ }
2207
+ function containsTextPlaceholder(value) {
2208
+ if (typeof value === "string") return value.includes("{{text}}");
2209
+ if (Array.isArray(value)) return value.some(containsTextPlaceholder);
2210
+ if (value !== null && typeof value === "object") {
2211
+ return Object.values(value).some(containsTextPlaceholder);
2212
+ }
2213
+ return false;
2214
+ }
2215
+ function substituteText(value, text) {
2216
+ if (typeof value === "string") return value.replaceAll("{{text}}", text);
2217
+ if (Array.isArray(value)) return value.map((item) => substituteText(item, text));
2218
+ if (value !== null && typeof value === "object") {
2219
+ return Object.fromEntries(
2220
+ Object.entries(value).map(([key, item]) => [key, substituteText(item, text)])
2221
+ );
2222
+ }
2223
+ return value;
2224
+ }
2225
+ function parseCustomTtsConfig(raw) {
2226
+ if (!isRecord(raw)) throw new CustomTtsError("TTS config must be a JSON object.");
2227
+ if (raw.customize_tts === void 0 || raw.customize_tts === false) return null;
2228
+ if (raw.customize_tts !== true) throw new CustomTtsError("customize_tts must be a JSON boolean.");
2229
+ if (!isRecord(raw.request)) throw new CustomTtsError("request must be a JSON object.");
2230
+ const method = typeof raw.request.method === "string" ? raw.request.method.toUpperCase() : "POST";
2231
+ if (method !== "POST") throw new CustomTtsError("request.method currently supports POST only.");
2232
+ const textField = validateTextField(raw.request.text_field);
2233
+ const body = validateBody(raw.request.body);
2234
+ if (!textField && !containsTextPlaceholder(body)) {
2235
+ throw new CustomTtsError(
2236
+ "Configure request.text_field or place {{text}} in request.body to specify the speech text."
2237
+ );
2238
+ }
2239
+ return {
2240
+ customize_tts: true,
2241
+ request: {
2242
+ url: validateHttpUrl(raw.request.url, "request.url"),
2243
+ method: "POST",
2244
+ headers: validateHeaders(raw.request.headers),
2245
+ ...textField ? { text_field: textField } : {},
2246
+ body,
2247
+ timeout_ms: validateTimeout(raw.request.timeout_ms)
2248
+ },
2249
+ response: validateResponse(raw.response)
2250
+ };
2251
+ }
2252
+ function loadCustomTtsConfig(workspaceDir = getWorkspaceDir()) {
2253
+ const path = getWorkspaceConfigFile(workspaceDir);
2254
+ if (!existsSync3(path)) return null;
2255
+ let raw;
2256
+ try {
2257
+ raw = JSON.parse(readFileSync3(path, "utf8"));
2258
+ } catch (err) {
2259
+ const detail = err instanceof Error ? err.message : String(err);
2260
+ throw new CustomTtsError(`Cannot parse ${path}: ${detail}`);
2261
+ }
2262
+ if (!isRecord(raw)) throw new CustomTtsError(`${path} must contain a JSON object.`);
2263
+ if (raw.tts === void 0) return null;
2264
+ return parseCustomTtsConfig(raw.tts);
2265
+ }
2266
+ function valueAtPath(value, path) {
2267
+ let current = value;
2268
+ for (const segment of path.split(".")) {
2269
+ if (segment === "") throw new CustomTtsError(`Invalid response.path: ${path}`);
2270
+ if (Array.isArray(current) && /^\d+$/.test(segment)) {
2271
+ current = current[Number(segment)];
2272
+ } else if (isRecord(current)) {
2273
+ current = current[segment];
2274
+ } else {
2275
+ return void 0;
2276
+ }
2277
+ }
2278
+ return current;
2279
+ }
2280
+ function normalizeContentType(value) {
2281
+ const normalized = value?.split(";", 1)[0].trim().toLowerCase();
2282
+ return normalized || void 0;
2283
+ }
2284
+ function resolveAudioFormat(raw, label) {
2285
+ const normalized = normalizeContentType(raw)?.replace(/^\./, "");
2286
+ const format = normalized ? AUDIO_FORMAT_ALIASES[normalized] : void 0;
2287
+ if (!format) {
2288
+ throw new CustomTtsError(`${label} has unsupported audio format "${raw}". Supported: ${SUPPORTED_AUDIO_FORMATS}.`);
2289
+ }
2290
+ return AUDIO_FORMATS[format];
2291
+ }
2292
+ function formatFromServerContentType(contentType, label) {
2293
+ const normalized = normalizeContentType(contentType);
2294
+ if (!normalized || normalized === "application/octet-stream" || normalized === "binary/octet-stream") {
2295
+ return void 0;
2296
+ }
2297
+ return resolveAudioFormat(normalized, `${label} content-type`);
2298
+ }
2299
+ function configuredAudioFormat(response) {
2300
+ return response.format ? resolveAudioFormat(response.format, "response.format") : response.content_type ? resolveAudioFormat(response.content_type, "response.content_type") : void 0;
2301
+ }
2302
+ function selectAudioFormat(response, serverFormats) {
2303
+ const authoritative = serverFormats.filter(
2304
+ (candidate) => candidate.value !== void 0
2305
+ );
2306
+ const first = authoritative[0];
2307
+ for (const candidate of authoritative.slice(1)) {
2308
+ if (candidate.value.format !== first.value.format) {
2309
+ throw new CustomTtsError(
2310
+ `TTS response audio formats conflict: ${first.label} is ${first.value.format}, ${candidate.label} is ${candidate.value.format}.`
2311
+ );
2312
+ }
2313
+ }
2314
+ const configured = configuredAudioFormat(response);
2315
+ if (first && configured && first.value.format !== configured.format) {
2316
+ throw new CustomTtsError(
2317
+ `TTS response audio format ${first.value.format} conflicts with configured format ${configured.format}.`
2318
+ );
2319
+ }
2320
+ if (first) return first.value;
2321
+ if (configured) return configured;
2322
+ throw new CustomTtsError(
2323
+ "Cannot determine custom TTS audio format. Return a supported audio Content-Type/format or set response.format in config.json."
2324
+ );
2325
+ }
2326
+ function validateAudio(audio) {
2327
+ if (audio.length === 0) throw new CustomTtsError("Custom TTS returned empty audio.");
2328
+ if (audio.length > MAX_AUDIO_BYTES) {
2329
+ throw new CustomTtsError(`Custom TTS audio exceeds ${MAX_AUDIO_BYTES / 1024 / 1024} MB.`);
2330
+ }
2331
+ return audio;
2332
+ }
2333
+ async function responseError(response, label) {
2334
+ let detail = "";
2335
+ try {
2336
+ detail = (await response.text()).trim().slice(0, 500);
2337
+ } catch {
2338
+ }
2339
+ return new CustomTtsError(`${label} failed with status ${response.status}${detail ? `: ${detail}` : ""}`);
2340
+ }
2341
+ async function fetchWithTimeout(url, init, timeoutMs, label) {
2342
+ try {
2343
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
2344
+ } catch (err) {
2345
+ if (err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError")) {
2346
+ throw new CustomTtsError(`${label} timed out after ${timeoutMs} ms.`);
2347
+ }
2348
+ throw new CustomTtsError(`${label} failed: ${err instanceof Error ? err.message : String(err)}`);
2349
+ }
2350
+ }
2351
+ function decodeBase64(raw) {
2352
+ const dataUrl = raw.match(/^data:([^;,]+)?;base64,([\s\S]*)$/i);
2353
+ const encoded = (dataUrl?.[2] ?? raw).replace(/\s+/g, "");
2354
+ if (encoded === "") throw new CustomTtsError("Custom TTS returned empty base64 audio.");
2355
+ const audio = Buffer.from(encoded, "base64");
2356
+ return { audio: validateAudio(audio), contentType: normalizeContentType(dataUrl?.[1]) };
2357
+ }
2358
+ function finalAudio(audio, response, serverFormats) {
2359
+ const format = selectAudioFormat(response, serverFormats);
2360
+ const filename = response.filename ?? `tts${format.extension}`;
2361
+ const filenameExtension = extname(filename).toLowerCase();
2362
+ if (filenameExtension !== format.extension) {
2363
+ throw new CustomTtsError(
2364
+ `response.filename extension "${filenameExtension || "(none)"}" does not match audio format ${format.format}.`
2365
+ );
2366
+ }
2367
+ return { audio: validateAudio(audio), contentType: format.contentType, filename };
2368
+ }
2369
+ async function synthesizeCustomTts(text, config) {
2370
+ const substitutedBody = substituteText(config.request.body, text);
2371
+ const requestBody = config.request.text_field ? { ...substitutedBody, [config.request.text_field]: text } : substitutedBody;
2372
+ const response = await fetchWithTimeout(config.request.url, {
2373
+ method: config.request.method,
2374
+ headers: config.request.headers,
2375
+ body: JSON.stringify(requestBody)
2376
+ }, config.request.timeout_ms, "Custom TTS request");
2377
+ if (!response.ok) throw await responseError(response, "Custom TTS request");
2378
+ if (config.response.type === "binary") {
2379
+ const contentTypeFormat = formatFromServerContentType(response.headers.get("content-type"), "Custom TTS request");
2380
+ return finalAudio(Buffer.from(await response.arrayBuffer()), config.response, [
2381
+ { value: contentTypeFormat, label: "HTTP Content-Type" }
2382
+ ]);
2383
+ }
2384
+ let payload;
2385
+ try {
2386
+ payload = await response.json();
2387
+ } catch {
2388
+ throw new CustomTtsError("Custom TTS response is not valid JSON.");
2389
+ }
2390
+ const value = valueAtPath(payload, config.response.path);
2391
+ if (typeof value !== "string" || value.trim() === "") {
2392
+ throw new CustomTtsError(`Custom TTS response path "${config.response.path}" did not contain a string.`);
2393
+ }
2394
+ if (config.response.type === "json_base64") {
2395
+ const decoded = decodeBase64(value);
2396
+ const dataUrlFormat = decoded.contentType ? resolveAudioFormat(decoded.contentType, "Base64 data URL content-type") : void 0;
2397
+ const responseFormat2 = config.response.format_path ? valueAtPath(payload, config.response.format_path) : void 0;
2398
+ if (config.response.format_path && (typeof responseFormat2 !== "string" || responseFormat2.trim() === "")) {
2399
+ throw new CustomTtsError(
2400
+ `Custom TTS response format path "${config.response.format_path}" did not contain a string.`
2401
+ );
2402
+ }
2403
+ const formatPathFormat2 = typeof responseFormat2 === "string" ? resolveAudioFormat(responseFormat2, `response.format_path "${config.response.format_path}"`) : void 0;
2404
+ return finalAudio(decoded.audio, config.response, [
2405
+ { value: dataUrlFormat, label: "Base64 data URL" },
2406
+ { value: formatPathFormat2, label: `response.format_path "${config.response.format_path}"` }
2407
+ ]);
2408
+ }
2409
+ const audioUrl = validateHttpUrl(value, `response.${config.response.path}`);
2410
+ const responseFormat = config.response.format_path ? valueAtPath(payload, config.response.format_path) : void 0;
2411
+ if (config.response.format_path && (typeof responseFormat !== "string" || responseFormat.trim() === "")) {
2412
+ throw new CustomTtsError(
2413
+ `Custom TTS response format path "${config.response.format_path}" did not contain a string.`
2414
+ );
2415
+ }
2416
+ const formatPathFormat = typeof responseFormat === "string" ? resolveAudioFormat(responseFormat, `response.format_path "${config.response.format_path}"`) : void 0;
2417
+ const download = await fetchWithTimeout(audioUrl, { method: "GET" }, config.request.timeout_ms, "Custom TTS audio download");
2418
+ if (!download.ok) throw await responseError(download, "Custom TTS audio download");
2419
+ const downloadFormat = formatFromServerContentType(download.headers.get("content-type"), "Custom TTS audio download");
2420
+ return finalAudio(Buffer.from(await download.arrayBuffer()), config.response, [
2421
+ { value: downloadFormat, label: "download HTTP Content-Type" },
2422
+ { value: formatPathFormat, label: `response.format_path "${config.response.format_path}"` }
2423
+ ]);
2424
+ }
2425
+ async function synthesizeConfiguredTts(text, workspaceDir = getWorkspaceDir()) {
2426
+ const config = loadCustomTtsConfig(workspaceDir);
2427
+ if (!config) return null;
2428
+ return synthesizeCustomTts(text, config);
2429
+ }
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
+
2484
+ // src/lib/game-client.ts
2485
+ function agentMetadataHeaders(options) {
2486
+ const headers = {};
2487
+ if (options.agentType) headers["X-Agent-Type"] = options.agentType;
2488
+ if (options.monitorStatus) headers["X-Monitor-Status"] = options.monitorStatus;
2489
+ if (options.llmModel) headers["X-LLM-Model"] = options.llmModel;
2490
+ return Object.keys(headers).length > 0 ? headers : void 0;
2491
+ }
2492
+ var GameClient = class _GameClient {
2493
+ resolvedHostContext;
2494
+ hostEnvironment;
2495
+ http;
2496
+ ws = null;
2497
+ gameSyncIngress;
2498
+ closingIngress = /* @__PURE__ */ new Set();
2499
+ transportGeneration = 0;
2500
+ /** Last continuously reduced v2 baseline, retained across failed socket replacements. */
2501
+ gameSyncResumeState;
2502
+ /** Queue/room-owned game identity that the retained baseline must belong to. */
2503
+ expectedGameSyncGameId;
2504
+ wsCloseHandlers = [];
2505
+ wsInputFrameHandlers = [];
2506
+ wsConnectionOpenedHandlers = [];
2507
+ wsLivenessHandlers = [];
2508
+ wsProtocolErrorHandlers = [];
2509
+ wsRecoveryStartedHandlers = [];
2510
+ registry;
2511
+ apiKey;
2512
+ enableWs;
2513
+ rawWsMessageSink;
2514
+ log = new RuntimeLogger();
2515
+ lastCustomTtsWarning = null;
2516
+ /** 最近一次 TTS 降级警告,供 CLI 命令纳入 stdout JSON 输出。 */
2517
+ get ttsWarning() {
2518
+ return this.lastCustomTtsWarning;
2519
+ }
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
+ };
2527
+ this.apiKey = config.apiKey;
2528
+ this.enableWs = config.enableWs ?? false;
2529
+ this.rawWsMessageSink = config.rawWsMessageSink;
2530
+ this.gameSyncIngress = config.gameSyncIngress;
2531
+ this.registry = new ServerRegistry({
2532
+ lobbyUrl: config.lobbyUrl,
2533
+ gameServerUrl: config.gameServerUrl,
2534
+ agentName: config.agentName
2535
+ });
2536
+ this.http = new HttpTransport(config.apiKey, this.registry, {}, config.signal);
2537
+ }
2538
+ // ─── Factory Methods ───
2539
+ /**
2540
+ * Create GameClient from active auth profile.
2541
+ * Used by both runtime listeners (ws: true) and CLI commands (ws: false).
2542
+ */
2543
+ static fromAuth(opts) {
2544
+ const store = opts?.authStore ?? new AuthStore();
2545
+ const profile = store.getActive();
2546
+ if (!profile) {
2547
+ throw new Error(accountRequiredMessage("No active auth profile. Run: clawclaw-cli account register"));
2548
+ }
2549
+ return new _GameClient({
2550
+ lobbyUrl: profile.serverUrl,
2551
+ gameServerUrl: profile.gameServerUrl,
2552
+ apiKey: profile.apiKey,
2553
+ agentName: profile.agentName,
2554
+ enableWs: opts?.ws ?? false,
2555
+ rawWsMessageSink: opts?.rawWsMessageSink,
2556
+ signal: opts?.signal
2557
+ });
2558
+ }
2559
+ /** Get current server addresses. */
2560
+ get addresses() {
2561
+ return this.registry.addresses;
2562
+ }
2563
+ /**
2564
+ * Structured transport result for migrated short-command handlers. Existing
2565
+ * typed methods keep their legacy throw/JSON behavior.
2566
+ */
2567
+ requestRaw(method, path, body, headers) {
2568
+ return this.http.requestRaw(method, path, body, headers);
2569
+ }
2570
+ // ─── Game API (→ game server) ───
2571
+ /** GameSync v2 carries observations only; all Actions use acknowledged HTTP. */
2572
+ async submitAction(action) {
2573
+ const preparedAction = await this.prepareAction(action);
2574
+ return this.http.post("/api/v1/game/action", preparedAction);
2575
+ }
2576
+ /**
2577
+ * Submit through the acknowledged HTTP request/response boundary even while
2578
+ * the owner has an active WS stream. Agent-facing commands must not call a
2579
+ * fire-and-forget WS send a confirmed success.
2580
+ */
2581
+ async submitActionConfirmed(action) {
2582
+ const preparedAction = await this.prepareActionForConfirmedSubmission(action);
2583
+ return this.submitPreparedActionConfirmed(preparedAction);
2584
+ }
2585
+ /**
2586
+ * Reversible preparation phase for an acknowledged Action. Runtime adapters
2587
+ * may revalidate local authority after this resolves and before calling the
2588
+ * corresponding submit method.
2589
+ */
2590
+ async prepareActionForConfirmedSubmission(action) {
2591
+ return this.prepareAction(action);
2592
+ }
2593
+ /** Irreversible confirmed Action endpoint; input must already be prepared. */
2594
+ async submitPreparedActionConfirmed(action, signal) {
2595
+ return this.http.postRaw("/api/v1/game/action", action, void 0, signal);
2596
+ }
2597
+ async prepareAction(action) {
2598
+ let preparedAction = action;
2599
+ if (action.action === "speech" && typeof action.text === "string" && action.text.length > 0 && !action.audio_url) {
2600
+ try {
2601
+ const synthesized = await synthesizeConfiguredTts(action.text);
2602
+ if (synthesized) {
2603
+ const { audio_url } = await this.uploadAudio(
2604
+ synthesized.audio,
2605
+ synthesized.filename,
2606
+ synthesized.contentType
2607
+ );
2608
+ preparedAction = { ...action, audio_url };
2609
+ this.lastCustomTtsWarning = null;
2610
+ }
2611
+ } catch (err) {
2612
+ const message = err instanceof Error ? err.message : String(err);
2613
+ if (message !== this.lastCustomTtsWarning) {
2614
+ console.error(`Custom TTS failed: ${message}. Sending speech without audio.`);
2615
+ this.lastCustomTtsWarning = message;
2616
+ }
2617
+ this.log.warn("CUSTOM_TTS_FAILED", message);
2618
+ }
2619
+ }
2620
+ return preparedAction;
2621
+ }
2622
+ async uploadAudio(filePathOrBuffer, filename, contentType = "audio/mpeg") {
2623
+ const form = new FormData();
2624
+ if (typeof filePathOrBuffer === "string") {
2625
+ const { existsSync: existsSync4, readFileSync: readFileSync4 } = await import("fs");
2626
+ const { basename: basename2 } = await import("path");
2627
+ if (!existsSync4(filePathOrBuffer)) {
2628
+ throw new Error(`Audio file not found: ${filePathOrBuffer}`);
2629
+ }
2630
+ const buffer = readFileSync4(filePathOrBuffer);
2631
+ form.append("file", new Blob([buffer], { type: contentType }), filename ?? basename2(filePathOrBuffer));
2632
+ } else {
2633
+ form.append("file", new Blob([filePathOrBuffer], { type: contentType }), filename ?? "audio.mp3");
2634
+ }
2635
+ const response = await this.http.postRaw("/api/v1/agents/upload_audio", form);
2636
+ const result = response.body.kind === "json" ? response.body.value : null;
2637
+ if (response.status < 200 || response.status >= 300 || !result || typeof result !== "object" || result.success === false) {
2638
+ throw new ApiError(
2639
+ response.status,
2640
+ response.body.rawText,
2641
+ "POST",
2642
+ "/api/v1/agents/upload_audio",
2643
+ response
2644
+ );
2645
+ }
2646
+ const audioUrl = result?.audio_url ?? result?.data?.audio_url;
2647
+ if (!audioUrl) {
2648
+ throw new Error(`upload_audio: unexpected response: ${JSON.stringify(result)}`);
2649
+ }
2650
+ return { audio_url: audioUrl };
2651
+ }
2652
+ // ─── Agent API (→ lobby) ───
2653
+ /**
2654
+ * Register a new agent. No auth required.
2655
+ * Server expects multipart/form-data with optional name/description/avatar fields.
2656
+ */
2657
+ async registerAgent(opts) {
2658
+ const form = new FormData();
2659
+ if (opts.name) form.append("name", opts.name);
2660
+ if (opts.description) form.append("description", opts.description);
2661
+ if (opts.inviteCode) form.append("invite_code", opts.inviteCode);
2662
+ if (opts.avatarUrl) form.append("avatar_url", opts.avatarUrl);
2663
+ if (opts.avatarFile) {
2664
+ const { readFileSync: readFileSync4 } = await import("fs");
2665
+ const { basename: basename2 } = await import("path");
2666
+ const buf = readFileSync4(opts.avatarFile);
2667
+ form.append("avatar_file", new Blob([buf]), basename2(opts.avatarFile));
2668
+ }
2669
+ return this.http.post("/api/v1/agents/register", form);
2670
+ }
2671
+ async renameAgent(name) {
2672
+ return this.http.request("PATCH", "/api/v1/agents/name", { name });
2673
+ }
2674
+ async login(apiKey) {
2675
+ return this.http.post("/api/v1/agents/login", { api_key: apiKey });
2676
+ }
2677
+ async getMe() {
2678
+ return this.http.get("/api/v1/agents/me");
2679
+ }
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
+ }
2696
+ async joinQueue(options = "clawclaw") {
2697
+ const gameType = typeof options === "string" ? options : options.gameType ?? "clawclaw";
2698
+ const mode = typeof options === "string" ? "match" : options.mode ?? "match";
2699
+ const agentType = typeof options === "string" ? void 0 : options.agentType;
2700
+ const monitorStatus = typeof options === "string" ? void 0 : options.monitorStatus;
2701
+ const llmModel = typeof options === "string" ? void 0 : options.llmModel;
2702
+ const result = await this.enterLobby("/api/v1/queue/join", { game_type: gameType, mode }, { agentType, monitorStatus, llmModel });
2703
+ this.registry.updateFromQueueResponse(result);
2704
+ return result;
2705
+ }
2706
+ async getQueueStatus(gameType) {
2707
+ const query = gameType ? `?game_type=${encodeURIComponent(gameType)}` : "";
2708
+ const result = await this.http.get(`/api/v1/queue/status${query}`);
2709
+ this.registry.updateFromQueueResponse(result);
2710
+ return result;
2711
+ }
2712
+ async leaveQueue(gameType) {
2713
+ const query = gameType ? `?game_type=${encodeURIComponent(gameType)}` : "";
2714
+ return this.http.post(`/api/v1/queue/leave${query}`);
2715
+ }
2716
+ /** Leave the active game. Normal matches require death; a training owner may abandon while alive. */
2717
+ async leaveGame() {
2718
+ return this.http.post("/api/v1/game/leave");
2719
+ }
2720
+ // ─── Room API (→ lobby) ───
2721
+ async createRoom(options = {}) {
2722
+ const normalized = typeof options === "string" ? { roomType: options } : options;
2723
+ return normalized.roomType ? this.enterLobby("/api/v1/room/create", { room_type: normalized.roomType }, normalized) : this.enterLobby("/api/v1/room/create", void 0, normalized);
2724
+ }
2725
+ async joinRoom(roomCode, metadata = {}) {
2726
+ return this.enterLobby("/api/v1/room/join", { room_code: roomCode }, metadata);
2727
+ }
2728
+ async getRoomStatus() {
2729
+ return this.http.get("/api/v1/room/status");
2730
+ }
2731
+ async leaveRoom() {
2732
+ return this.http.post("/api/v1/room/leave");
2733
+ }
2734
+ async startRoom() {
2735
+ return this.http.post("/api/v1/room/start");
2736
+ }
2737
+ async setTrainingRoomMode(roomType) {
2738
+ return this.http.request("PUT", "/api/v1/room/training/mode", { room_type: roomType });
2739
+ }
2740
+ async setTrainingRoleLock(characterId) {
2741
+ return this.http.request("PUT", "/api/v1/room/training/role-lock", { character_id: characterId });
2742
+ }
2743
+ async clearTrainingRoleLock() {
2744
+ return this.http.request("DELETE", "/api/v1/room/training/role-lock");
2745
+ }
2746
+ async chatRoom(content) {
2747
+ return this.http.post("/api/v1/room/chat", { content });
2748
+ }
2749
+ async chatRoomConfirmed(content) {
2750
+ return this.http.postRaw("/api/v1/room/chat", { content });
2751
+ }
2752
+ get lobbyAgentWsUrl() {
2753
+ return this.registry.lobbyAgentWsUrl;
2754
+ }
2755
+ setRoomGameServer(gameServerName) {
2756
+ this.registry.setGatewayGameServerName(gameServerName);
2757
+ }
2758
+ setGameServerUrl(url) {
2759
+ this.registry.setGameServerUrl(url);
2760
+ }
2761
+ // ─── Economy / Leaderboard ───
2762
+ async getLeaderboard(page, limit) {
2763
+ const params = new URLSearchParams();
2764
+ if (page != null) params.set("page", String(page));
2765
+ if (limit != null) params.set("limit", String(limit));
2766
+ const query = params.toString() ? `?${params.toString()}` : "";
2767
+ return this.http.get(`/api/v1/leaderboard${query}`);
2768
+ }
2769
+ async getCompetitionStatus() {
2770
+ return this.http.get("/api/v1/competition/status");
2771
+ }
2772
+ async getMyCompetitionRank() {
2773
+ return this.http.get("/api/v1/leaderboard/competition/me");
2774
+ }
2775
+ async getSettlement() {
2776
+ return this.http.get("/api/v1/game/settlement");
2777
+ }
2778
+ async getGameHistory(page, limit) {
2779
+ const params = new URLSearchParams();
2780
+ if (page != null) params.set("page", String(page));
2781
+ if (limit != null) params.set("limit", String(limit));
2782
+ const query = params.toString() ? `?${params.toString()}` : "";
2783
+ return this.http.get(`/api/v1/game/history${query}`);
2784
+ }
2785
+ // ─── Connection Management ───
2786
+ /** Bind resumable GameSync state to the game selected by Source lifecycle. */
2787
+ setExpectedGameSyncGameId(gameId) {
2788
+ const expected = gameId?.trim() || void 0;
2789
+ if (this.expectedGameSyncGameId !== expected) {
2790
+ this.expectedGameSyncGameId = expected;
2791
+ if (!expected || this.gameSyncResumeState?.gameId !== expected) {
2792
+ this.gameSyncResumeState = void 0;
2793
+ }
2794
+ return;
2795
+ }
2796
+ if (expected && this.gameSyncResumeState?.gameId !== expected) {
2797
+ this.gameSyncResumeState = void 0;
2798
+ }
2799
+ }
2800
+ /** Connect WebSocket to the current server (game server or lobby). */
2801
+ async connectWs() {
2802
+ if (!this.enableWs) return false;
2803
+ if (this.wsConnected) return true;
2804
+ const wsUrl = this.registry.wsUrl;
2805
+ if (!wsUrl) {
2806
+ this.log.warn("WS_CONNECT", "no game server URL for WebSocket");
2807
+ return false;
2808
+ }
2809
+ const resumeState = this.resumeStateForExpectedGame(
2810
+ this.ws?.resumeState ?? this.gameSyncResumeState
2811
+ );
2812
+ if (resumeState) this.gameSyncResumeState = resumeState;
2813
+ if (this.ws) {
2814
+ this.ws.clearHandlers();
2815
+ await this.stopWs(this.ws);
2816
+ this.markWsHandlersDetached();
2817
+ }
2818
+ const newWs = this.createWs({
2819
+ url: wsUrl,
2820
+ apiKey: this.apiKey,
2821
+ rawMessageSink: this.rawWsMessageSink,
2822
+ ...resumeState ? { resumeState } : {}
2823
+ });
2824
+ this.ws = newWs;
2825
+ this.attachWsHandlers();
2826
+ try {
2827
+ await newWs.connect();
2828
+ return true;
2829
+ } catch {
2830
+ this.rememberGameSyncResumeState(newWs.resumeState);
2831
+ this.log.warn("WS_CONNECT", "GameSync WebSocket connection failed; runtime will retry");
2832
+ await this.stopWs(newWs);
2833
+ this.ws = null;
2834
+ this.markWsHandlersDetached();
2835
+ return false;
2836
+ }
2837
+ }
2838
+ /** Disconnect WebSocket. */
2839
+ disconnectWs(options = {}) {
2840
+ if (options.preserveGameSyncResumeState) {
2841
+ this.rememberGameSyncResumeState(this.ws?.resumeState);
2842
+ }
2843
+ if (this.ws) {
2844
+ this.stopWs(this.ws);
2845
+ this.ws = null;
2846
+ }
2847
+ if (!options.preserveGameSyncResumeState) {
2848
+ this.gameSyncResumeState = void 0;
2849
+ this.expectedGameSyncGameId = void 0;
2850
+ }
2851
+ }
2852
+ /** Commit one Source-accepted GameSync frame and advance its resumable ACK. */
2853
+ acknowledgeGameSync(ackToken, immediate = false) {
2854
+ this.ws?.acknowledge(ackToken, immediate);
2855
+ this.rememberGameSyncResumeState(this.ws?.resumeState);
2856
+ }
2857
+ /** Send display-only perception output over the active GameSync connection. */
2858
+ reportGameSyncPerceptions(perceptions) {
2859
+ return this.ws?.reportPerceptions(perceptions) ?? false;
2860
+ }
2861
+ /** A report must still belong to the Source-accepted game/connection it describes. */
2862
+ reportGameSyncRuntime(report, gameId, connectionId) {
2863
+ if (this.ws?.connectionId !== connectionId || this.ws?.resumeState?.gameId !== gameId) return false;
2864
+ return this.ws.reportRuntime(report);
2865
+ }
2866
+ get gameSyncLocale() {
2867
+ return this.ws?.resumeState?.locale ?? this.gameSyncResumeState?.locale ?? "zh-CN";
2868
+ }
2869
+ /**
2870
+ * Try to discover game server from /queue/status.
2871
+ * If found and WS is enabled, reconnects WS to the game server.
2872
+ * Returns both the usable-route decision and the authoritative queue probe.
2873
+ *
2874
+ * Note: uses http.get directly instead of getQueueStatus() to avoid
2875
+ * double-calling registry.updateFromQueueResponse().
2876
+ */
2877
+ async discoverGameServer() {
2878
+ try {
2879
+ const result = await this.http.get("/api/v1/queue/status");
2880
+ const changed = this.registry.updateFromQueueResponse(result);
2881
+ if (changed && this._gameServerUrl) {
2882
+ this.log.info("GAME_SERVER_DISCOVERED", `url=${this._gameServerUrl}`);
2883
+ if (this.enableWs) {
2884
+ await this.reconnectWsToGameServer();
2885
+ }
2886
+ return { routeChanged: true, queue: structuredClone(result) };
2887
+ }
2888
+ return { routeChanged: false, queue: structuredClone(result) };
2889
+ } catch {
2890
+ }
2891
+ return { routeChanged: false };
2892
+ }
2893
+ /** Reconnect WS to the current game server address. */
2894
+ async reconnectWsToGameServer() {
2895
+ const wsUrl = this.registry.wsUrl;
2896
+ if (!wsUrl) return;
2897
+ const resumeState = this.resumeStateForExpectedGame(
2898
+ this.ws?.resumeState ?? this.gameSyncResumeState
2899
+ );
2900
+ if (resumeState) this.gameSyncResumeState = resumeState;
2901
+ if (this.ws) {
2902
+ this.ws.clearHandlers();
2903
+ await this.stopWs(this.ws);
2904
+ this.markWsHandlersDetached();
2905
+ }
2906
+ const newWs = this.createWs({
2907
+ url: wsUrl,
2908
+ apiKey: this.apiKey,
2909
+ rawMessageSink: this.rawWsMessageSink,
2910
+ ...resumeState ? { resumeState } : {}
2911
+ });
2912
+ this.ws = newWs;
2913
+ this.attachWsHandlers();
2914
+ try {
2915
+ await newWs.connect();
2916
+ this.log.info("WS_RECONNECT", `connected to ${wsUrl}`);
2917
+ } catch {
2918
+ this.rememberGameSyncResumeState(newWs.resumeState);
2919
+ this.log.warn("WS_RECONNECT", "GameSync WebSocket reconnect failed; runtime will retry");
2920
+ await this.stopWs(newWs);
2921
+ this.ws = null;
2922
+ this.markWsHandlersDetached();
2923
+ }
2924
+ }
2925
+ /** Get the current game server URL. */
2926
+ get _gameServerUrl() {
2927
+ return this.registry.gameServerUrl;
2928
+ }
2929
+ // ─── GameSync v2 proxy ───
2930
+ onWsClose(handler) {
2931
+ this.wsCloseHandlers.push(handler);
2932
+ return () => {
2933
+ const idx = this.wsCloseHandlers.indexOf(handler);
2934
+ if (idx >= 0) this.wsCloseHandlers.splice(idx, 1);
2935
+ };
2936
+ }
2937
+ onInputFrame(handler) {
2938
+ const entry = { handler, unsubscribe: void 0 };
2939
+ this.wsInputFrameHandlers.push(entry);
2940
+ if (this.ws) entry.unsubscribe = this.ws.onInputFrame(handler);
2941
+ return () => {
2942
+ entry.unsubscribe?.();
2943
+ const idx = this.wsInputFrameHandlers.indexOf(entry);
2944
+ if (idx >= 0) this.wsInputFrameHandlers.splice(idx, 1);
2945
+ };
2946
+ }
2947
+ onWsConnectionOpened(handler) {
2948
+ const entry = { handler, unsubscribe: void 0 };
2949
+ this.wsConnectionOpenedHandlers.push(entry);
2950
+ if (this.ws) entry.unsubscribe = this.ws.onConnectionOpened(handler);
2951
+ return () => {
2952
+ entry.unsubscribe?.();
2953
+ const idx = this.wsConnectionOpenedHandlers.indexOf(entry);
2954
+ if (idx >= 0) this.wsConnectionOpenedHandlers.splice(idx, 1);
2955
+ };
2956
+ }
2957
+ onWsLiveness(handler) {
2958
+ const entry = { handler, unsubscribe: void 0 };
2959
+ this.wsLivenessHandlers.push(entry);
2960
+ if (this.ws) entry.unsubscribe = this.ws.onLiveness(handler);
2961
+ return () => {
2962
+ entry.unsubscribe?.();
2963
+ const idx = this.wsLivenessHandlers.indexOf(entry);
2964
+ if (idx >= 0) this.wsLivenessHandlers.splice(idx, 1);
2965
+ };
2966
+ }
2967
+ onWsProtocolError(handler) {
2968
+ const entry = { handler, unsubscribe: void 0 };
2969
+ this.wsProtocolErrorHandlers.push(entry);
2970
+ if (this.ws) entry.unsubscribe = this.ws.onProtocolError(handler);
2971
+ return () => {
2972
+ entry.unsubscribe?.();
2973
+ const idx = this.wsProtocolErrorHandlers.indexOf(entry);
2974
+ if (idx >= 0) this.wsProtocolErrorHandlers.splice(idx, 1);
2975
+ };
2976
+ }
2977
+ onWsRecoveryStarted(handler) {
2978
+ const entry = { handler, unsubscribe: void 0 };
2979
+ this.wsRecoveryStartedHandlers.push(entry);
2980
+ if (this.ws) entry.unsubscribe = this.ws.onRecoveryStarted(handler);
2981
+ return () => {
2982
+ entry.unsubscribe?.();
2983
+ const idx = this.wsRecoveryStartedHandlers.indexOf(entry);
2984
+ if (idx >= 0) this.wsRecoveryStartedHandlers.splice(idx, 1);
2985
+ };
2986
+ }
2987
+ get wsConnected() {
2988
+ return this.ws?.connected ?? false;
2989
+ }
2990
+ /** True while the owned WsClient is connecting, connected, or auto-reconnecting. */
2991
+ get wsConnectionActive() {
2992
+ return this.ws !== null && this.ws.state !== "disconnected" /* Disconnected */;
2993
+ }
2994
+ get wsConnectionId() {
2995
+ return this.ws?.connectionId || null;
2996
+ }
2997
+ attachWsHandlers() {
2998
+ if (!this.ws) return;
2999
+ const attachedWs = this.ws;
3000
+ attachedWs.onInputFrame(() => {
3001
+ this.rememberGameSyncResumeState(attachedWs.resumeState);
3002
+ });
3003
+ for (const entry of this.wsInputFrameHandlers) {
3004
+ entry.unsubscribe = this.ws.onInputFrame(entry.handler);
3005
+ }
3006
+ for (const entry of this.wsConnectionOpenedHandlers) {
3007
+ entry.unsubscribe = this.ws.onConnectionOpened(entry.handler);
3008
+ }
3009
+ for (const entry of this.wsLivenessHandlers) {
3010
+ entry.unsubscribe = this.ws.onLiveness(entry.handler);
3011
+ }
3012
+ for (const entry of this.wsProtocolErrorHandlers) {
3013
+ entry.unsubscribe = this.ws.onProtocolError(entry.handler);
3014
+ }
3015
+ for (const entry of this.wsRecoveryStartedHandlers) {
3016
+ entry.unsubscribe = this.ws.onRecoveryStarted(entry.handler);
3017
+ }
3018
+ this.ws.onDisconnect((info) => {
3019
+ for (const handler of this.wsCloseHandlers) handler(info);
3020
+ });
3021
+ }
3022
+ markWsHandlersDetached() {
3023
+ for (const entry of this.wsInputFrameHandlers) entry.unsubscribe = void 0;
3024
+ for (const entry of this.wsConnectionOpenedHandlers) entry.unsubscribe = void 0;
3025
+ for (const entry of this.wsLivenessHandlers) entry.unsubscribe = void 0;
3026
+ for (const entry of this.wsProtocolErrorHandlers) entry.unsubscribe = void 0;
3027
+ for (const entry of this.wsRecoveryStartedHandlers) entry.unsubscribe = void 0;
3028
+ }
3029
+ createWs(config) {
3030
+ if (!this.gameSyncIngress) return new WsClient(config);
3031
+ const { rawMessageSink: _sink, ...options } = config;
3032
+ return new ThreadedWsClient({ ...options, ...this.gameSyncIngress, transportGeneration: ++this.transportGeneration });
3033
+ }
3034
+ stopWs(ws) {
3035
+ ws.disconnect();
3036
+ if (ws instanceof ThreadedWsClient) {
3037
+ const closing = ws.close();
3038
+ this.closingIngress.add(closing);
3039
+ void closing.finally(() => this.closingIngress.delete(closing));
3040
+ return closing;
3041
+ }
3042
+ return Promise.resolve();
3043
+ }
3044
+ /** Drain Source-owned ingress and raw journals before Owner telemetry closes. */
3045
+ async closeGameSyncTransports() {
3046
+ this.disconnectWs();
3047
+ await Promise.allSettled([...this.closingIngress]);
3048
+ }
3049
+ rememberGameSyncResumeState(candidate) {
3050
+ if (!candidate) return;
3051
+ const expected = this.expectedGameSyncGameId;
3052
+ if (expected && candidate.gameId !== expected) {
3053
+ this.gameSyncResumeState = void 0;
3054
+ return;
3055
+ }
3056
+ if (!expected) this.expectedGameSyncGameId = candidate.gameId;
3057
+ this.gameSyncResumeState = structuredClone(candidate);
3058
+ }
3059
+ resumeStateForExpectedGame(candidate) {
3060
+ if (!candidate) return void 0;
3061
+ const expected = this.expectedGameSyncGameId;
3062
+ if (expected && candidate.gameId !== expected) {
3063
+ this.gameSyncResumeState = void 0;
3064
+ return void 0;
3065
+ }
3066
+ if (!expected) this.expectedGameSyncGameId = candidate.gameId;
3067
+ return structuredClone(candidate);
3068
+ }
3069
+ };
3070
+ export {
3071
+ Action,
3072
+ BEHAVIOR_PLUGIN_API_VERSION,
3073
+ ClawclawBehavior,
3074
+ ClawclawParallelPerception,
3075
+ ClawclawPerception,
3076
+ ClawclawReaction,
3077
+ ClawclawBehavior as ClawclawStrategy,
3078
+ ClawclawTrigger,
3079
+ GameClient,
3080
+ MAX_TRIGGER_RUNTIME_MS,
3081
+ MOVE_MIN_PX,
3082
+ PERCEPTION_MODULE_API_VERSION,
3083
+ PERCEPTION_PLUGIN_API_VERSION,
3084
+ STEP_MOVE_MIN_PX,
3085
+ STILL_STEP_MAX_PX,
3086
+ BEHAVIOR_PLUGIN_API_VERSION as STRATEGY_PLUGIN_API_VERSION,
3087
+ TICK_MS,
3088
+ TRIGGER_PLUGIN_API_VERSION,
3089
+ actorLabel,
3090
+ actorValue,
3091
+ angleDegrees,
3092
+ cosine,
3093
+ cross,
3094
+ direction,
3095
+ distance,
3096
+ dot,
3097
+ getAvailableTasks,
3098
+ getTaskAvailability,
3099
+ getTaskKind,
3100
+ headingDirection,
3101
+ isTaskAvailable,
3102
+ length,
3103
+ positionCopy,
3104
+ round1,
3105
+ timeRange,
3106
+ unit,
3107
+ vector
3108
+ };