@myclaw163/clawclaw-cli 0.8.16 → 0.8.18

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 (39) hide show
  1. package/docs/configuration.md +7 -3
  2. package/docs/runtime/owner-lifecycle-and-observability.md +25 -0
  3. package/package.json +1 -1
  4. package/skills/clawclaw/SKILL.md +22 -3
  5. package/skills/clawclaw/references/COMMANDS.md +8 -4
  6. package/src/commands/account.ts +9 -1
  7. package/src/commands/behavior.ts +17 -17
  8. package/src/commands/capability.ts +33 -25
  9. package/src/commands/load.ts +145 -8
  10. package/src/commands/perception.ts +17 -16
  11. package/src/commands/persona.ts +24 -6
  12. package/src/lib/agent-workspace-client.ts +2 -0
  13. package/src/lib/agent-workspace-runtime.ts +10 -2
  14. package/src/lib/agent-workspace-skills.ts +7 -1
  15. package/src/lib/agent-workspace-sync.ts +39 -7
  16. package/src/lib/capability-cloud-presence.ts +179 -0
  17. package/src/lib/capability-cloud-refresh.ts +33 -20
  18. package/src/lib/capability-cloud-sync.ts +94 -7
  19. package/src/lib/capability-selection.ts +62 -0
  20. package/src/lib/capability-workspace.ts +4 -0
  21. package/src/lib/game-client.ts +40 -10
  22. package/src/lib/http-transport.ts +2 -2
  23. package/src/lib/hub-client.ts +75 -0
  24. package/src/lib/persona.ts +14 -1
  25. package/src/pipeline/event-hints.ts +1 -1
  26. package/src/runtime/clawclaw/owner.ts +32 -20
  27. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +33 -6
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -0
  29. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +25 -0
  30. package/src/runtime/framework/capability-registry.ts +31 -1
  31. package/src/runtime/framework/plugins/contracts.ts +2 -0
  32. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +14 -4
  33. package/src/runtime/framework/runtime.ts +5 -0
  34. package/src/runtime/game-sync-ingress-protocol.ts +34 -0
  35. package/src/runtime/game-sync-ingress-worker.ts +153 -0
  36. package/src/runtime/observability/factory.ts +2 -1
  37. package/src/runtime/observability/process-timing.ts +59 -0
  38. package/src/runtime/threaded-ws-client.ts +196 -0
  39. package/src/runtime/ws-client.ts +48 -1
@@ -0,0 +1,153 @@
1
+ import { parentPort, workerData, threadId } from 'node:worker_threads';
2
+ import { readFileSync } from 'node:fs';
3
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
4
+ import { WsConnectionState } from '../sdk/types.js';
5
+ import { WsClient } from './ws-client.js';
6
+ import { BufferedRawWsLog } from './raw-ws-log.js';
7
+ import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
8
+
9
+ const port = parentPort!;
10
+ const config = workerData.config as GameSyncIngressConfig;
11
+ const packageVersion = (JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as { version?: string }).version;
12
+ const raw = config.rawLog ? new BufferedRawWsLog(config.rawLog.path, config.rawLog.options) : undefined;
13
+ const pending = new Map<string, { seq: number; bytes: number; receivedAtMs: number }>();
14
+ let pendingBytes = 0;
15
+ let stopped = false;
16
+ let overloaded = false;
17
+ let restartTimer: ReturnType<typeof setTimeout> | undefined;
18
+ let telemetryPending = false;
19
+ let lastLiveness = 0;
20
+ let lastReceivedSeq = 0;
21
+ let acceptedSeq = config.resumeState?.seq ?? 0;
22
+ let ackSubmittedSeq = 0;
23
+ let receivedFrames = 0;
24
+ let pingCount = 0;
25
+ let pongCount = 0;
26
+ let pongErrors = 0;
27
+ let lastPingAt = 0;
28
+ let lastPongWrittenAt = 0;
29
+ let maxPongWriteMs = 0;
30
+ let maxAckHandoffMs = 0;
31
+ let overloadCount = 0;
32
+ let maxOutstanding = 0;
33
+ const delay = monitorEventLoopDelay({ resolution: 20 });
34
+ delay.enable();
35
+ const post = (message: IngressEvent): void => { if (!stopped || message.type === 'stopped') port.postMessage(message); };
36
+ const client = new WsClient({
37
+ url: config.url, apiKey: config.apiKey, resumeState: config.resumeState,
38
+ reconnectMaxMs: config.reconnectMaxMs, ackIntervalMs: config.ackIntervalMs,
39
+ maxPayloadBytes: config.maxPendingBytes, rawMessageSink: raw,
40
+ handshakeTimeoutMs: 10_000,
41
+ reconnectReady: () => pending.size === 0,
42
+ diagnostic: (name, attributes) => {
43
+ if (name === 'runtime.ws.ping_received') { pingCount++; lastPingAt = Number(attributes.received_at_ms); }
44
+ if (name === 'runtime.ws.pong_written') {
45
+ if (attributes.success) { pongCount++; lastPongWrittenAt = Number(attributes.written_at_ms); }
46
+ else pongErrors++;
47
+ maxPongWriteMs = Math.max(maxPongWriteMs, Number(attributes.duration_ms));
48
+ }
49
+ if (name === 'runtime.ws.ack_submitted') ackSubmittedSeq = Number(attributes.source_seq);
50
+ },
51
+ });
52
+
53
+ function telemetry(force = false): void {
54
+ if (stopped || (telemetryPending && !force)) return;
55
+ telemetryPending = true;
56
+ post({ type: 'telemetry', attributes: {
57
+ sampled_at_ms: Date.now(), connection_id: client.connectionId,
58
+ implementation: 'isolated_gamesync_v1', package_version: packageVersion, node_version: process.version, thread_id: threadId,
59
+ last_liveness_at_ms: lastLiveness, received_frames: receivedFrames,
60
+ received_seq: lastReceivedSeq, source_accepted_seq: acceptedSeq, ack_submitted_seq: ackSubmittedSeq,
61
+ outstanding_frames: pending.size, outstanding_bytes: pendingBytes, max_outstanding_frames: maxOutstanding,
62
+ max_pending_frames: config.maxPendingFrames, max_pending_bytes: config.maxPendingBytes,
63
+ received_ping_count: pingCount, written_pong_count: pongCount, pong_write_errors: pongErrors,
64
+ last_ping_received_at_ms: lastPingAt, last_pong_written_at_ms: lastPongWrittenAt,
65
+ max_pong_write_ms: maxPongWriteMs, max_source_ack_handoff_ms: maxAckHandoffMs,
66
+ overload_count: overloadCount, worker_event_loop_delay_p95_ms: delay.percentile(95) / 1e6,
67
+ worker_event_loop_delay_max_ms: delay.max / 1e6, worker_heap_used_bytes: process.memoryUsage().heapUsed,
68
+ ...(raw ? { raw_log: raw.stats() } : {}),
69
+ } });
70
+ delay.reset();
71
+ }
72
+
73
+ function reconnectWhenDrained(): void {
74
+ if (!overloaded || pending.size || restartTimer || stopped) return;
75
+ restartTimer = setTimeout(() => {
76
+ restartTimer = undefined;
77
+ if (stopped) return;
78
+ overloaded = false;
79
+ void client.connect().catch(() => {});
80
+ }, 1000);
81
+ }
82
+
83
+ client.onStateChange(state => post({ type: 'state', state }));
84
+ client.onConnectionOpened(connectionId => {
85
+ // Socket generation is deliberately separate from monotonically ordered source seq.
86
+ post({ type: 'opened', connectionId });
87
+ });
88
+ client.onLiveness((_connection, atMs) => { lastLiveness = atMs; });
89
+ client.onDisconnect(info => post({ type: 'close', connectionId: client.connectionId, info }));
90
+ const reportedProtocolErrors = new Set<string>();
91
+ client.onProtocolError(info => {
92
+ if (reportedProtocolErrors.has(info.reason)) return;
93
+ reportedProtocolErrors.add(info.reason);
94
+ post({ type: 'protocol', info });
95
+ });
96
+ client.onRecoveryStarted(info => post({ type: 'recovery', info }));
97
+ client.onInputFrame(frame => {
98
+ if (stopped || overloaded) return;
99
+ receivedFrames++;
100
+ lastReceivedSeq = Number(frame.meta.sourceSeq);
101
+ const bytes = Buffer.byteLength(JSON.stringify(frame));
102
+ if (pending.size >= config.maxPendingFrames || pendingBytes + bytes > config.maxPendingBytes) {
103
+ overloadCount++;
104
+ overloaded = true;
105
+ client.disconnect();
106
+ post({ type: 'close', connectionId: client.connectionId, info: {
107
+ code: 1013, reason: 'CCL_INGRESS_BACKLOG_LIMIT', wasClean: false,
108
+ } });
109
+ post({ type: 'state', state: WsConnectionState.Reconnecting });
110
+ telemetry(true);
111
+ reconnectWhenDrained();
112
+ return;
113
+ }
114
+ pending.set(frame.meta.ackToken, { seq: Number(frame.meta.sourceSeq), bytes, receivedAtMs: Date.parse(frame.meta.receivedAt) });
115
+ pendingBytes += bytes;
116
+ maxOutstanding = Math.max(maxOutstanding, pending.size);
117
+ frame.meta.ingress = {
118
+ ...frame.meta.ingress!, workerPostedAtMs: Date.now(), outstandingFrames: pending.size, outstandingBytes: pendingBytes,
119
+ };
120
+ post({ type: 'frame', frame });
121
+ });
122
+
123
+ const timer = setInterval(() => { reportedProtocolErrors.clear(); telemetry(); }, 5000);
124
+ timer.unref();
125
+ port.on('message', (message: IngressCommand) => {
126
+ if (stopped) return;
127
+ if (message.type === 'ack') {
128
+ const entry = pending.get(message.token);
129
+ if (!entry) return;
130
+ client.acknowledge(message.token, message.immediate);
131
+ acceptedSeq = Math.max(acceptedSeq, entry.seq);
132
+ maxAckHandoffMs = Math.max(maxAckHandoffMs, Date.now() - entry.receivedAtMs);
133
+ for (const [token, item] of pending) if (item.seq <= entry.seq) { pending.delete(token); pendingBytes -= item.bytes; }
134
+ reconnectWhenDrained();
135
+ } else if (message.type === 'report') {
136
+ try { client.reportPerceptions(message.perceptions); } finally { post({ type: 'report_done' }); }
137
+ } else if (message.type === 'telemetry_ack') {
138
+ telemetryPending = false;
139
+ } else if (message.type === 'stop') {
140
+ void (async () => {
141
+ client.disconnect();
142
+ telemetry(true);
143
+ stopped = true;
144
+ clearInterval(timer);
145
+ if (restartTimer) clearTimeout(restartTimer);
146
+ delay.disable();
147
+ await raw?.close();
148
+ post({ type: 'stopped', ...(raw ? { rawStats: raw.stats() } : {}) });
149
+ port.close();
150
+ })().catch(() => { post({ type: 'stopped' }); port.close(); });
151
+ }
152
+ });
153
+ void client.connect().then(() => post({ type: 'connected' }), () => post({ type: 'failed', code: 'GAME_SYNC_CONNECT_FAILED' }));
@@ -30,7 +30,6 @@ const MINIMUM_OPERATIONAL_RECORD = /^(?:runtime\.owner\.(?:started|stopped)|runt
30
30
  const FULL_REDUNDANT_DEBUG_RECORDS = new Set([
31
31
  'runtime.input.accepted',
32
32
  'runtime.channel.ready_advanced',
33
- 'runtime.view.ready',
34
33
  'behavior.decide.started',
35
34
  ]);
36
35
 
@@ -38,6 +37,8 @@ const FULL_REDUNDANT_DEBUG_RECORDS = new Set([
38
37
  * Full diagnostics keeps development evidence, not a second copy of the Runtime journals.
39
38
  * Exact per-epoch/plugin outcomes already live in runtime-epochs.sqlite3; the JSONL keeps
40
39
  * exceptional/slow samples and diagnostics that cannot be reconstructed from that journal.
40
+ * runtime.view.ready is retained: intake/finalization and ingress-to-ready latency
41
+ * are not represented by the journal's scheduler-only processing_duration_ms.
41
42
  */
42
43
  function fullObservabilityInputEnabled(input: Readonly<RecordTelemetryInput>): boolean {
43
44
  const severity = input.severity ?? (input.kind === 'error' ? 'error' : 'info');
@@ -0,0 +1,59 @@
1
+ import { monitorEventLoopDelay, performance, PerformanceObserver } from 'node:perf_hooks';
2
+
3
+ /** Full-only process/Owner-loop measurements. Does not retain GC entries or gameplay data. */
4
+ export class RuntimeProcessTimingSampler {
5
+ private readonly delay = monitorEventLoopDelay({ resolution: 20 });
6
+ private readonly observer: PerformanceObserver;
7
+ private previousCpu = process.cpuUsage();
8
+ private previousLoop = performance.eventLoopUtilization();
9
+ private previousAt = performance.now();
10
+ private gcCount = 0;
11
+ private gcMs = 0;
12
+ private stopped = false;
13
+
14
+ constructor() {
15
+ this.observer = new PerformanceObserver((entries) => {
16
+ for (const entry of entries.getEntries()) {
17
+ this.gcCount += 1;
18
+ this.gcMs += entry.duration;
19
+ }
20
+ });
21
+ this.observer.observe({ entryTypes: ['gc'] });
22
+ this.delay.enable();
23
+ }
24
+
25
+ sample(): Readonly<Record<string, number>> {
26
+ const now = performance.now();
27
+ const cpu = process.cpuUsage();
28
+ const loop = performance.eventLoopUtilization();
29
+ const elapsed = now - this.previousAt;
30
+ const deltaLoop = performance.eventLoopUtilization(loop, this.previousLoop);
31
+ const milliseconds = (ns: number): number => Number.isFinite(ns) ? Math.round(ns / 1_000) / 1_000 : 0;
32
+ const result = {
33
+ window_ms: Math.round(elapsed),
34
+ // process.cpuUsage includes Worker threads; this is not Owner-isolate CPU utilization.
35
+ process_cpu_user_ms: (cpu.user - this.previousCpu.user) / 1_000,
36
+ process_cpu_system_ms: (cpu.system - this.previousCpu.system) / 1_000,
37
+ owner_event_loop_utilization: deltaLoop.utilization,
38
+ owner_event_loop_delay_mean_ms: milliseconds(this.delay.mean),
39
+ owner_event_loop_delay_p95_ms: milliseconds(this.delay.percentile(95)),
40
+ owner_event_loop_delay_max_ms: milliseconds(this.delay.max),
41
+ owner_gc_count: this.gcCount,
42
+ owner_gc_duration_ms: Math.round(this.gcMs * 1_000) / 1_000,
43
+ };
44
+ this.previousAt = now;
45
+ this.previousCpu = cpu;
46
+ this.previousLoop = loop;
47
+ this.gcCount = 0;
48
+ this.gcMs = 0;
49
+ this.delay.reset();
50
+ return result;
51
+ }
52
+
53
+ stop(): void {
54
+ if (this.stopped) return;
55
+ this.stopped = true;
56
+ this.observer.disconnect();
57
+ this.delay.disable();
58
+ }
59
+ }
@@ -0,0 +1,196 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { EventEmitter } from 'node:events';
3
+ import { WsConnectionState } from '../sdk/types.js';
4
+ import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from './game-sync-protocol.js';
5
+ import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
6
+ import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
7
+
8
+ export interface ThreadedWsClientConfig extends Omit<WsClientConfig, 'rawMessageSink' | 'reconnectReady'> {
9
+ rawLog?: GameSyncIngressConfig['rawLog'];
10
+ maxPendingFrames?: number;
11
+ maxPendingBytes?: number;
12
+ transportGeneration?: number;
13
+ }
14
+
15
+ /** Source-owned facade. Socket/heartbeat/delta work runs exclusively in the ingress Worker. */
16
+ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
17
+ private readonly events = new EventEmitter();
18
+ private worker?: Worker;
19
+ private stateValue = WsConnectionState.Disconnected;
20
+ private connectionIdValue = '';
21
+ private lastLivenessAt: string | null = null;
22
+ private committed?: GameSyncResumeState;
23
+ private readonly pending = new Map<string, WsInputFrame>();
24
+ private pendingReports = 0;
25
+ private stopped = false;
26
+ private connectedTask?: Promise<void>;
27
+ private resolveConnect?: () => void;
28
+ private rejectConnect?: (error: Error) => void;
29
+ private closeTask: Promise<void> = Promise.resolve();
30
+ private resolveClose?: () => void;
31
+ private closeTimer?: ReturnType<typeof setTimeout>;
32
+ private startupTimer?: ReturnType<typeof setTimeout>;
33
+
34
+ constructor(private readonly config: ThreadedWsClientConfig) {
35
+ const frames = config.maxPendingFrames ?? 10;
36
+ const bytes = config.maxPendingBytes ?? 8 * 1024 * 1024;
37
+ if (!Number.isSafeInteger(frames) || frames < 1 || frames > 1000) throw new Error('GAME_SYNC_FRAME_LIMIT_INVALID');
38
+ if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > 32 * 1024 * 1024) throw new Error('GAME_SYNC_BYTE_LIMIT_INVALID');
39
+ this.committed = config.resumeState ? structuredClone(config.resumeState) : undefined;
40
+ }
41
+
42
+ get connected(): boolean { return this.stateValue === WsConnectionState.Connected; }
43
+ get state(): WsConnectionState { return this.stateValue; }
44
+ get connectionId(): string { return this.connectionIdValue; }
45
+ get lastPongAt(): string | null { return this.lastLivenessAt; }
46
+ get resumeState(): GameSyncResumeState | undefined { return this.committed ? structuredClone(this.committed) : undefined; }
47
+
48
+ connect(): Promise<void> {
49
+ if (this.connectedTask) return this.connectedTask;
50
+ if (this.stopped) return Promise.reject(new Error('GAME_SYNC_INGRESS_STOPPED'));
51
+ this.stateValue = WsConnectionState.Connecting;
52
+ this.connectedTask = new Promise((resolve, reject) => { this.resolveConnect = resolve; this.rejectConnect = reject; });
53
+ this.closeTask = new Promise(resolve => { this.resolveClose = resolve; });
54
+ this.startupTimer = setTimeout(() => this.fail('GAME_SYNC_INGRESS_START_TIMEOUT'), 20_000);
55
+ this.startupTimer.unref();
56
+ const config: GameSyncIngressConfig = {
57
+ url: this.config.url, apiKey: this.config.apiKey, resumeState: this.committed,
58
+ reconnectMaxMs: this.config.reconnectMaxMs, ackIntervalMs: this.config.ackIntervalMs,
59
+ maxPendingFrames: this.config.maxPendingFrames ?? 10,
60
+ maxPendingBytes: this.config.maxPendingBytes ?? 8 * 1024 * 1024,
61
+ rawLog: this.config.rawLog,
62
+ };
63
+ try {
64
+ this.worker = new Worker(new URL('./framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
65
+ execArgv: [], stdout: true, stderr: true,
66
+ resourceLimits: { maxOldGenerationSizeMb: 128 },
67
+ workerData: { config, runtimeModuleBootstrap: {
68
+ hostUrl: new URL('./game-sync-ingress-worker.ts', import.meta.url).href,
69
+ hooksUrl: new URL('./framework/modules/runtime-module-loader-hooks.mjs', import.meta.url).href,
70
+ sdkAliases: {}, esmModuleRoots: [],
71
+ } },
72
+ });
73
+ this.worker.stdout?.on('data', () => {});
74
+ this.worker.stderr?.on('data', () => {});
75
+ this.worker.on('message', (message: IngressEvent) => this.receive(message));
76
+ this.worker.on('error', () => this.fail('GAME_SYNC_INGRESS_WORKER_FAILED'));
77
+ this.worker.on('exit', (code) => {
78
+ if (!this.stopped) this.fail('GAME_SYNC_INGRESS_WORKER_EXITED');
79
+ if (this.closeTimer) clearTimeout(this.closeTimer);
80
+ this.resolveClose?.();
81
+ this.diagnostic('runtime.ws.ingress_stopped', { exit_code: code });
82
+ });
83
+ } catch {
84
+ this.fail('GAME_SYNC_INGRESS_START_FAILED');
85
+ this.resolveClose?.();
86
+ }
87
+ return this.connectedTask;
88
+ }
89
+
90
+ private receive(message: IngressEvent): void {
91
+ if (message.type === 'telemetry') {
92
+ const a = message.attributes;
93
+ const at = Number(a.last_liveness_at_ms);
94
+ if (at > 0 && !this.stopped) {
95
+ this.lastLivenessAt = new Date(at).toISOString();
96
+ this.events.emit('liveness', String(a.connection_id), at);
97
+ }
98
+ this.diagnostic('runtime.ws.ingress_window', { ...a, owner_observed_at_ms: Date.now() }, Number(a.overload_count) ? 'warn' : 'info');
99
+ this.post({ type: 'telemetry_ack' });
100
+ return;
101
+ }
102
+ if (message.type === 'stopped') {
103
+ if (message.rawStats) this.diagnostic('runtime.raw_ws.capture_stopped', { ...message.rawStats });
104
+ return;
105
+ }
106
+ if (this.stopped) return;
107
+ switch (message.type) {
108
+ case 'connected':
109
+ if (this.startupTimer) clearTimeout(this.startupTimer);
110
+ this.resolveConnect?.(); break;
111
+ case 'failed': this.fail(message.code); break;
112
+ case 'state': this.stateValue = message.state; this.events.emit('state', message.state); break;
113
+ case 'opened': this.connectionIdValue = message.connectionId; this.events.emit('opened', message.connectionId); break;
114
+ case 'close':
115
+ this.connectionIdValue = message.connectionId;
116
+ this.diagnostic('runtime.ws.ingress_disconnected', { code: message.info.code, reason: message.info.reason, pending_frames: this.pending.size }, 'warn');
117
+ this.events.emit('close', message.info); break;
118
+ case 'protocol': this.events.emit('protocol', message.info); break;
119
+ case 'recovery': this.events.emit('recovery', message.info); break;
120
+ case 'report_done': this.pendingReports = Math.max(0, this.pendingReports - 1); break;
121
+ case 'frame': {
122
+ const frame = message.frame;
123
+ frame.meta.ingress = { ...frame.meta.ingress!, ownerReceivedAtMs: Date.now(), transportGeneration: this.config.transportGeneration ?? 1 };
124
+ this.pending.set(frame.meta.ackToken, frame);
125
+ this.lastLivenessAt = frame.meta.receivedAt;
126
+ this.events.emit('liveness', frame.meta.connectionId, Date.parse(frame.meta.receivedAt));
127
+ this.events.emit('frame', frame);
128
+ break;
129
+ }
130
+ }
131
+ }
132
+
133
+ acknowledge(token: string, immediate = false): void {
134
+ const frame = this.pending.get(token);
135
+ if (this.stopped || !frame || frame.meta.connectionId !== this.connectionIdValue) return;
136
+ const seq = Number(frame.meta.sourceSeq);
137
+ if (!this.committed || seq >= this.committed.seq) {
138
+ const { game_id: _gameId, tick: _tick, ...state } = frame.state;
139
+ this.committed = { gameId: frame.meta.gameId, seq, tick: frame.meta.domainTick, locale: frame.meta.locale ?? 'zh-CN', state: structuredClone(state) };
140
+ }
141
+ for (const [key, pending] of this.pending) if (Number(pending.meta.sourceSeq) <= seq) this.pending.delete(key);
142
+ this.post({ type: 'ack', token, immediate });
143
+ }
144
+
145
+ reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
146
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
147
+ const message = gameSyncPerceptionReportMessage(perceptions);
148
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
149
+ this.pendingReports++;
150
+ this.post({ type: 'report', perceptions });
151
+ return true;
152
+ }
153
+
154
+ private post(message: IngressCommand): void {
155
+ try { this.worker?.postMessage(message); } catch { if (!this.stopped) this.fail('GAME_SYNC_INGRESS_PORT_FAILED'); }
156
+ }
157
+ private diagnostic(name: string, attributes: Record<string, unknown>, severity: 'debug' | 'info' | 'warn' = 'info'): void {
158
+ try { this.config.diagnostic?.(name, { transport_generation: this.config.transportGeneration ?? 1, ...attributes }, severity); } catch {}
159
+ }
160
+ private fail(code: string): void {
161
+ if (this.stopped) return;
162
+ this.rejectConnect?.(new Error(code));
163
+ this.diagnostic('runtime.ws.ingress_failed', { error_code: code }, 'warn');
164
+ this.stateValue = WsConnectionState.Disconnected;
165
+ this.events.emit('close', { code: 1013, reason: code, wasClean: false } satisfies WsCloseInfo);
166
+ this.disconnect();
167
+ }
168
+
169
+ disconnect(): void {
170
+ if (this.stopped) return;
171
+ this.stopped = true;
172
+ if (this.startupTimer) clearTimeout(this.startupTimer);
173
+ this.stateValue = WsConnectionState.Disconnected;
174
+ this.rejectConnect?.(new Error('GAME_SYNC_INGRESS_STOPPED'));
175
+ this.post({ type: 'stop' });
176
+ this.pending.clear();
177
+ this.events.emit('state', this.stateValue);
178
+ if (this.worker) {
179
+ this.closeTimer = setTimeout(() => {
180
+ this.diagnostic('runtime.ws.ingress_stop_timeout', {}, 'warn');
181
+ void this.worker?.terminate();
182
+ }, 5000);
183
+ this.closeTimer.unref();
184
+ }
185
+ }
186
+ async close(): Promise<void> { this.disconnect(); await this.closeTask; }
187
+ clearHandlers(): void { this.events.removeAllListeners(); }
188
+ private on(event: string, handler: (...args: any[]) => void): () => void { this.events.on(event, handler); return () => { this.events.off(event, handler); }; }
189
+ onInputFrame(handler: (frame: WsInputFrame) => void): () => void { return this.on('frame', handler); }
190
+ onConnectionOpened(handler: (connectionId: string) => void): () => void { return this.on('opened', handler); }
191
+ onLiveness(handler: (connectionId: string, atMs: number) => void): () => void { return this.on('liveness', handler); }
192
+ onProtocolError(handler: (info: WsProtocolErrorInfo) => void): () => void { return this.on('protocol', handler); }
193
+ onRecoveryStarted(handler: (info: WsRecoveryStartedInfo) => void): () => void { return this.on('recovery', handler); }
194
+ onStateChange(handler: (state: WsConnectionState) => void): () => void { return this.on('state', handler); }
195
+ onDisconnect(handler: (info: WsCloseInfo) => void): () => void { return this.on('close', handler); }
196
+ }
@@ -3,6 +3,7 @@
3
3
 
4
4
  import WebSocket from 'ws';
5
5
  import { randomUUID } from 'crypto';
6
+ import { performance } from 'node:perf_hooks';
6
7
  import { WsConnectionState } from '../sdk/types.js';
7
8
  import type { RawWsMessageSink } from './raw-ws-log.js';
8
9
  import {
@@ -31,6 +32,11 @@ export interface WsClientConfig {
31
32
  /** Non-blocking raw server-frame capture owned and closed by the caller. */
32
33
  rawMessageSink?: RawWsMessageSink;
33
34
  resumeState?: GameSyncResumeState;
35
+ maxPayloadBytes?: number;
36
+ handshakeTimeoutMs?: number;
37
+ /** The isolated ingress may wait for already-delivered Source applications before reconnecting. */
38
+ reconnectReady?: () => boolean;
39
+ diagnostic?: (name: string, attributes: Record<string, unknown>, severity?: 'debug' | 'info' | 'warn') => void;
34
40
  }
35
41
 
36
42
  export interface WsCloseInfo {
@@ -72,6 +78,18 @@ export interface WsFrameMeta {
72
78
  ackToken: string;
73
79
  snapshotFallback?: boolean;
74
80
  replayedEventCount?: number;
81
+ /** Local transport clocks, not backend production timestamps. */
82
+ ingress?: {
83
+ socketReceivedAtMs: number;
84
+ decodedAtMs: number;
85
+ decodeDurationMs: number;
86
+ workerPostedAtMs?: number;
87
+ ownerReceivedAtMs?: number;
88
+ outstandingFrames?: number;
89
+ outstandingBytes?: number;
90
+ transportGeneration?: number;
91
+ };
92
+ locale?: 'zh-CN' | 'en-US';
75
93
  }
76
94
 
77
95
  export type WsInputFrame = {
@@ -130,6 +148,8 @@ export class WsClient {
130
148
  private lastAckSent = 0;
131
149
  private readonly seenEventIds = new Set<string>();
132
150
  private readonly rawMessageSink?: RawWsMessageSink;
151
+ private socketReceivedAtMs = 0;
152
+ private decodeStartedAt = 0;
133
153
 
134
154
  private readonly inputFrameHandlers = new Set<(frame: WsInputFrame) => void>();
135
155
  private readonly connectionOpenedHandlers = new Set<(connectionId: string) => void>();
@@ -231,6 +251,9 @@ export class WsClient {
231
251
  this.recoveryEvents = [];
232
252
  const url = gameSyncUrl(this.config.url, this.baseline?.seq);
233
253
  const ws = new WebSocket(url, {
254
+ autoPong: false,
255
+ ...(this.config.handshakeTimeoutMs === undefined ? {} : { handshakeTimeout: this.config.handshakeTimeoutMs }),
256
+ ...(this.config.maxPayloadBytes === undefined ? {} : { maxPayload: this.config.maxPayloadBytes }),
234
257
  headers: {
235
258
  Authorization: `Bearer ${this.config.apiKey}`,
236
259
  'Accept-Language': this.baseline?.locale ?? 'zh-CN',
@@ -251,10 +274,22 @@ export class WsClient {
251
274
 
252
275
  ws.onerror = (error) => reject(error);
253
276
 
254
- (ws as any).on?.('ping', () => this.recordLiveness());
277
+ ws.on('ping', (data) => {
278
+ if (this.ws !== ws) return;
279
+ const receivedAtMs = Date.now();
280
+ this.recordLiveness();
281
+ this.config.diagnostic?.('runtime.ws.ping_received', { received_at_ms: receivedAtMs, bytes: data.length });
282
+ // Reply in the socket-owning isolate, independently of Source/Runtime work.
283
+ ws.pong(data, true, (error) => this.config.diagnostic?.('runtime.ws.pong_written', {
284
+ ping_received_at_ms: receivedAtMs, written_at_ms: Date.now(),
285
+ duration_ms: Math.max(0, Date.now() - receivedAtMs), success: !error,
286
+ }, error ? 'warn' : 'debug'));
287
+ });
255
288
  (ws as any).on?.('pong', () => this.recordLiveness());
256
289
  ws.onmessage = (event) => {
257
290
  if (this.ws !== ws) return;
291
+ this.socketReceivedAtMs = Date.now();
292
+ this.decodeStartedAt = performance.now();
258
293
  const raw = wsMessageToString(event.data);
259
294
  try { this.rawMessageSink?.enqueue(raw); } catch {}
260
295
  this.recordLiveness();
@@ -504,6 +539,12 @@ export class WsClient {
504
539
  meta: {
505
540
  connectionId: this.connectionIdValue,
506
541
  receivedAt: new Date().toISOString(),
542
+ locale: baseline.locale,
543
+ ingress: {
544
+ socketReceivedAtMs: this.socketReceivedAtMs,
545
+ decodedAtMs: Date.now(),
546
+ decodeDurationMs: Math.max(0, performance.now() - this.decodeStartedAt),
547
+ },
507
548
  origin: meta.origin,
508
549
  sourceSeq: baseline.seq,
509
550
  gameId: baseline.gameId,
@@ -540,6 +581,7 @@ export class WsClient {
540
581
  if (this.send({ type: 'game.sync.ack', data: { seq } })) {
541
582
  this.lastAckSent = seq;
542
583
  this.ackDirty = false;
584
+ this.config.diagnostic?.('runtime.ws.ack_submitted', { source_seq: seq, submitted_at_ms: Date.now() });
543
585
  }
544
586
  }
545
587
 
@@ -600,6 +642,11 @@ export class WsClient {
600
642
  this.reconnectAttempt += 1;
601
643
  this.reconnectTimer = setTimeout(() => {
602
644
  if (!this.shouldReconnect) return;
645
+ if (this.config.reconnectReady?.() === false) {
646
+ this.reconnectAttempt = Math.max(0, this.reconnectAttempt - 1);
647
+ this.scheduleReconnect();
648
+ return;
649
+ }
603
650
  this.setState(WsConnectionState.Connecting);
604
651
  void this.openSocket().catch(() => {});
605
652
  }, delay);