@myclaw163/clawclaw-cli 0.7.5 → 0.7.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/desktop-event-push.md +120 -0
- package/package.json +2 -1
- package/src/commands/game/index.test.ts +167 -1
- package/src/commands/game/index.ts +124 -35
- package/src/lib/game-client.test.ts +15 -0
- package/src/lib/game-client.ts +4 -0
- package/src/lib/participation-status.ts +113 -0
- package/src/pipeline/event-format.test.ts +17 -0
- package/src/pipeline/event-format.ts +15 -1
- package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
- package/src/pipeline/game-sync-event-normalization.ts +51 -0
- package/src/runtime/clawclaw/owner.ts +56 -3
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
- package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +339 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +207 -0
- package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +372 -0
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
- package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +52 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +4 -3
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { createConnection, type Socket } from 'node:net';
|
|
3
|
+
import type {
|
|
4
|
+
MailboxEventBatchAcceptance,
|
|
5
|
+
MailboxEventBatchEnvelope,
|
|
6
|
+
MailboxEventBatchSink,
|
|
7
|
+
} from './mailbox-event-batch-delivery.js';
|
|
8
|
+
|
|
9
|
+
export const DESKTOP_EVENT_PROTOCOL_SCHEMA = 'ccl.desktop-events.v1';
|
|
10
|
+
|
|
11
|
+
const WINDOWS_PIPE_PREFIX = '\\\\.\\pipe\\';
|
|
12
|
+
const MAX_ACK_BUFFER_CHARACTERS = 64 * 1024;
|
|
13
|
+
const DEFAULT_ACK_TIMEOUT_MS = 10_000;
|
|
14
|
+
const DEFAULT_RECONNECT_BASE_MS = 100;
|
|
15
|
+
const DEFAULT_RECONNECT_MAX_MS = 5_000;
|
|
16
|
+
|
|
17
|
+
export interface DesktopEventSocketConfig {
|
|
18
|
+
socketPath: string;
|
|
19
|
+
token: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
|
|
23
|
+
ackTimeoutMs?: number;
|
|
24
|
+
reconnectBaseMs?: number;
|
|
25
|
+
reconnectMaxMs?: number;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
platform?: NodeJS.Platform;
|
|
28
|
+
onConnected?: () => void;
|
|
29
|
+
diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface PendingDesktopAck {
|
|
33
|
+
connectionId: string;
|
|
34
|
+
seq: number;
|
|
35
|
+
deliveryId: string;
|
|
36
|
+
timer: ReturnType<typeof setTimeout>;
|
|
37
|
+
signal: AbortSignal;
|
|
38
|
+
onAbort: () => void;
|
|
39
|
+
resolve: (acceptance: MailboxEventBatchAcceptance) => void;
|
|
40
|
+
reject: (error: Error) => void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class DesktopEventSocketDeliveryError extends Error {
|
|
44
|
+
readonly code: string;
|
|
45
|
+
readonly retryable: boolean;
|
|
46
|
+
|
|
47
|
+
constructor(code: string, message: string, retryable = true) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = 'DesktopEventSocketDeliveryError';
|
|
50
|
+
this.code = code;
|
|
51
|
+
this.retryable = retryable;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function controlledText(value: string, label: string, maxLength: number): string {
|
|
56
|
+
const text = value.trim();
|
|
57
|
+
if (!text) throw new Error(`${label} is required.`);
|
|
58
|
+
if (text.length > maxLength || /[\0\r\n]/u.test(text)) {
|
|
59
|
+
throw new Error(`${label} is invalid.`);
|
|
60
|
+
}
|
|
61
|
+
return text;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function normalizeDesktopEventSocketPath(
|
|
65
|
+
value: string,
|
|
66
|
+
platform: NodeJS.Platform = process.platform,
|
|
67
|
+
): string {
|
|
68
|
+
const path = controlledText(value, 'Desktop event socket', 512);
|
|
69
|
+
if (platform === 'win32') {
|
|
70
|
+
if (path.startsWith(WINDOWS_PIPE_PREFIX)) return path;
|
|
71
|
+
if (path.startsWith('\\\\')) {
|
|
72
|
+
throw new Error('Desktop event socket must be a local named pipe.');
|
|
73
|
+
}
|
|
74
|
+
if (/[\\/]/u.test(path)) {
|
|
75
|
+
throw new Error('Desktop event socket must be a named-pipe name or local named-pipe path.');
|
|
76
|
+
}
|
|
77
|
+
return `${WINDOWS_PIPE_PREFIX}${path}`;
|
|
78
|
+
}
|
|
79
|
+
if (!path.startsWith('/')) {
|
|
80
|
+
throw new Error('Desktop event socket must be an absolute Unix socket path.');
|
|
81
|
+
}
|
|
82
|
+
return path;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function validateDesktopEventToken(value: string): string {
|
|
86
|
+
const token = controlledText(value, 'Desktop event token', 1_024);
|
|
87
|
+
if (token.length < 16) {
|
|
88
|
+
throw new Error('Desktop event token must contain at least 16 characters.');
|
|
89
|
+
}
|
|
90
|
+
return token;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Persistent NDJSON client for a Desktop-owned local socket/named pipe. */
|
|
94
|
+
export class DesktopEventSocketSink implements MailboxEventBatchSink {
|
|
95
|
+
private readonly path: string;
|
|
96
|
+
private readonly token: string;
|
|
97
|
+
private readonly ackTimeoutMs: number;
|
|
98
|
+
private readonly reconnectBaseMs: number;
|
|
99
|
+
private readonly reconnectMaxMs: number;
|
|
100
|
+
private readonly now: () => number;
|
|
101
|
+
private readonly onConnected?: DesktopEventSocketOptions['onConnected'];
|
|
102
|
+
private readonly diagnostic?: DesktopEventSocketOptions['diagnostic'];
|
|
103
|
+
|
|
104
|
+
private socket: Socket | undefined;
|
|
105
|
+
private connected = false;
|
|
106
|
+
private stopped = false;
|
|
107
|
+
private connectionId: string | undefined;
|
|
108
|
+
private sequence = 0;
|
|
109
|
+
private reconnectAttempt = 0;
|
|
110
|
+
private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
|
|
111
|
+
private inputBuffer = '';
|
|
112
|
+
private pendingAck: PendingDesktopAck | undefined;
|
|
113
|
+
|
|
114
|
+
constructor(options: DesktopEventSocketOptions) {
|
|
115
|
+
this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
|
|
116
|
+
this.token = validateDesktopEventToken(options.token);
|
|
117
|
+
this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
|
|
118
|
+
this.reconnectBaseMs = options.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
|
|
119
|
+
this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
|
|
120
|
+
this.now = options.now ?? Date.now;
|
|
121
|
+
this.onConnected = options.onConnected;
|
|
122
|
+
this.diagnostic = options.diagnostic;
|
|
123
|
+
if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
|
|
124
|
+
throw new Error('Desktop event ACK timeout must be positive.');
|
|
125
|
+
}
|
|
126
|
+
if (
|
|
127
|
+
!Number.isFinite(this.reconnectBaseMs)
|
|
128
|
+
|| this.reconnectBaseMs <= 0
|
|
129
|
+
|| !Number.isFinite(this.reconnectMaxMs)
|
|
130
|
+
|| this.reconnectMaxMs < this.reconnectBaseMs
|
|
131
|
+
) {
|
|
132
|
+
throw new Error('Desktop event reconnect delays are invalid.');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
start(): void {
|
|
137
|
+
if (this.stopped || this.socket) return;
|
|
138
|
+
this.connect();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async deliver(
|
|
142
|
+
envelope: MailboxEventBatchEnvelope,
|
|
143
|
+
signal: AbortSignal,
|
|
144
|
+
): Promise<MailboxEventBatchAcceptance> {
|
|
145
|
+
if (this.stopped) {
|
|
146
|
+
throw new DesktopEventSocketDeliveryError(
|
|
147
|
+
'desktop_event_socket_stopped',
|
|
148
|
+
'Desktop event socket is stopped.',
|
|
149
|
+
false,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
if (signal.aborted) throw this.abortError(signal);
|
|
153
|
+
const socket = this.socket;
|
|
154
|
+
const connectionId = this.connectionId;
|
|
155
|
+
if (!socket || !this.connected || !connectionId) {
|
|
156
|
+
this.start();
|
|
157
|
+
throw new DesktopEventSocketDeliveryError(
|
|
158
|
+
'desktop_event_socket_not_connected',
|
|
159
|
+
'Desktop event socket is not connected.',
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (this.pendingAck) {
|
|
163
|
+
throw new DesktopEventSocketDeliveryError(
|
|
164
|
+
'desktop_event_batch_in_flight',
|
|
165
|
+
'A Desktop event batch is already awaiting acknowledgement.',
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const seq = ++this.sequence;
|
|
170
|
+
const frame = {
|
|
171
|
+
schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
|
|
172
|
+
type: 'mailbox_batch',
|
|
173
|
+
connection_id: connectionId,
|
|
174
|
+
seq,
|
|
175
|
+
delivery_id: envelope.deliveryId,
|
|
176
|
+
payload: {
|
|
177
|
+
schema: 'clawclaw.channel-events.v1',
|
|
178
|
+
...envelope.batch,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
return new Promise<MailboxEventBatchAcceptance>((resolve, reject) => {
|
|
183
|
+
const onAbort = (): void => {
|
|
184
|
+
if (this.pendingAck?.seq !== seq) return;
|
|
185
|
+
this.rejectPending(this.abortError(signal));
|
|
186
|
+
socket.destroy();
|
|
187
|
+
};
|
|
188
|
+
const timer = setTimeout(() => {
|
|
189
|
+
if (this.pendingAck?.seq !== seq) return;
|
|
190
|
+
this.rejectPending(new DesktopEventSocketDeliveryError(
|
|
191
|
+
'desktop_event_ack_timeout',
|
|
192
|
+
'Desktop did not acknowledge the event batch in time.',
|
|
193
|
+
));
|
|
194
|
+
socket.destroy();
|
|
195
|
+
}, this.ackTimeoutMs);
|
|
196
|
+
timer.unref?.();
|
|
197
|
+
this.pendingAck = {
|
|
198
|
+
connectionId,
|
|
199
|
+
seq,
|
|
200
|
+
deliveryId: envelope.deliveryId,
|
|
201
|
+
timer,
|
|
202
|
+
signal,
|
|
203
|
+
onAbort,
|
|
204
|
+
resolve,
|
|
205
|
+
reject,
|
|
206
|
+
};
|
|
207
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
208
|
+
|
|
209
|
+
const line = `${JSON.stringify(frame)}\n`;
|
|
210
|
+
socket.write(line, (error?: Error | null) => {
|
|
211
|
+
if (!error || this.pendingAck?.seq !== seq) return;
|
|
212
|
+
this.rejectPending(new DesktopEventSocketDeliveryError(
|
|
213
|
+
'desktop_event_socket_write_failed',
|
|
214
|
+
error.message,
|
|
215
|
+
));
|
|
216
|
+
socket.destroy();
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async close(): Promise<void> {
|
|
222
|
+
if (this.stopped) return;
|
|
223
|
+
this.stopped = true;
|
|
224
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
225
|
+
this.reconnectTimer = undefined;
|
|
226
|
+
this.rejectPending(new DesktopEventSocketDeliveryError(
|
|
227
|
+
'desktop_event_socket_stopped',
|
|
228
|
+
'Desktop event socket stopped before acknowledgement.',
|
|
229
|
+
false,
|
|
230
|
+
));
|
|
231
|
+
const socket = this.socket;
|
|
232
|
+
this.socket = undefined;
|
|
233
|
+
this.connected = false;
|
|
234
|
+
this.connectionId = undefined;
|
|
235
|
+
if (!socket || socket.destroyed) return;
|
|
236
|
+
await new Promise<void>((resolve) => {
|
|
237
|
+
socket.once('close', () => resolve());
|
|
238
|
+
socket.destroy();
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
private connect(): void {
|
|
243
|
+
if (this.stopped || this.socket) return;
|
|
244
|
+
const connectionId = randomUUID();
|
|
245
|
+
const socket = createConnection(this.path);
|
|
246
|
+
this.socket = socket;
|
|
247
|
+
this.connectionId = connectionId;
|
|
248
|
+
this.inputBuffer = '';
|
|
249
|
+
socket.setEncoding('utf8');
|
|
250
|
+
socket.setNoDelay(true);
|
|
251
|
+
|
|
252
|
+
socket.once('connect', () => {
|
|
253
|
+
if (this.socket !== socket || this.stopped) return;
|
|
254
|
+
this.connected = true;
|
|
255
|
+
this.reconnectAttempt = 0;
|
|
256
|
+
socket.write(`${JSON.stringify({
|
|
257
|
+
schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
|
|
258
|
+
type: 'hello',
|
|
259
|
+
connection_id: connectionId,
|
|
260
|
+
token: this.token,
|
|
261
|
+
pid: process.pid,
|
|
262
|
+
})}\n`);
|
|
263
|
+
this.diagnostic?.('runtime.desktop_event_socket.connected', {
|
|
264
|
+
connection_id: connectionId,
|
|
265
|
+
});
|
|
266
|
+
this.onConnected?.();
|
|
267
|
+
});
|
|
268
|
+
socket.on('data', (chunk: string) => this.onData(socket, chunk));
|
|
269
|
+
socket.once('error', (error) => {
|
|
270
|
+
this.diagnostic?.('runtime.desktop_event_socket.error', {
|
|
271
|
+
code: typeof (error as NodeJS.ErrnoException).code === 'string'
|
|
272
|
+
? (error as NodeJS.ErrnoException).code
|
|
273
|
+
: error.name,
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
socket.once('close', () => this.onClose(socket));
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
private onData(socket: Socket, chunk: string): void {
|
|
280
|
+
if (this.socket !== socket || this.stopped) return;
|
|
281
|
+
this.inputBuffer += chunk;
|
|
282
|
+
if (this.inputBuffer.length > MAX_ACK_BUFFER_CHARACTERS) {
|
|
283
|
+
socket.destroy(new Error('desktop_event_ack_frame_too_large'));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
for (;;) {
|
|
287
|
+
const newline = this.inputBuffer.indexOf('\n');
|
|
288
|
+
if (newline < 0) return;
|
|
289
|
+
const line = this.inputBuffer.slice(0, newline).trim();
|
|
290
|
+
this.inputBuffer = this.inputBuffer.slice(newline + 1);
|
|
291
|
+
if (!line) continue;
|
|
292
|
+
let frame: Record<string, unknown>;
|
|
293
|
+
try {
|
|
294
|
+
const parsed = JSON.parse(line);
|
|
295
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error();
|
|
296
|
+
frame = parsed as Record<string, unknown>;
|
|
297
|
+
} catch {
|
|
298
|
+
socket.destroy(new Error('desktop_event_ack_invalid_json'));
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
this.handleFrame(frame);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private handleFrame(frame: Record<string, unknown>): void {
|
|
306
|
+
const pending = this.pendingAck;
|
|
307
|
+
if (
|
|
308
|
+
!pending
|
|
309
|
+
|| frame.schema !== DESKTOP_EVENT_PROTOCOL_SCHEMA
|
|
310
|
+
|| frame.type !== 'ack'
|
|
311
|
+
|| frame.connection_id !== pending.connectionId
|
|
312
|
+
|| frame.seq !== pending.seq
|
|
313
|
+
|| frame.delivery_id !== pending.deliveryId
|
|
314
|
+
) {
|
|
315
|
+
this.diagnostic?.('runtime.desktop_event_socket.ack_ignored');
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const receiptId = typeof frame.receipt_id === 'string' && frame.receipt_id.length <= 256
|
|
319
|
+
? frame.receipt_id
|
|
320
|
+
: undefined;
|
|
321
|
+
this.pendingAck = undefined;
|
|
322
|
+
clearTimeout(pending.timer);
|
|
323
|
+
pending.signal.removeEventListener('abort', pending.onAbort);
|
|
324
|
+
pending.resolve({
|
|
325
|
+
acceptedAt: new Date(this.now()).toISOString(),
|
|
326
|
+
...(receiptId ? { receiptId } : {}),
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private onClose(socket: Socket): void {
|
|
331
|
+
if (this.socket !== socket) return;
|
|
332
|
+
this.socket = undefined;
|
|
333
|
+
this.connected = false;
|
|
334
|
+
this.connectionId = undefined;
|
|
335
|
+
this.inputBuffer = '';
|
|
336
|
+
this.rejectPending(new DesktopEventSocketDeliveryError(
|
|
337
|
+
'desktop_event_socket_disconnected',
|
|
338
|
+
'Desktop event socket disconnected before acknowledgement.',
|
|
339
|
+
));
|
|
340
|
+
if (this.stopped) return;
|
|
341
|
+
this.reconnectAttempt += 1;
|
|
342
|
+
const delayMs = Math.min(
|
|
343
|
+
this.reconnectMaxMs,
|
|
344
|
+
this.reconnectBaseMs * (2 ** Math.min(8, this.reconnectAttempt - 1)),
|
|
345
|
+
);
|
|
346
|
+
this.diagnostic?.('runtime.desktop_event_socket.reconnecting', {
|
|
347
|
+
retry_in_ms: delayMs,
|
|
348
|
+
});
|
|
349
|
+
const timer = setTimeout(() => {
|
|
350
|
+
this.reconnectTimer = undefined;
|
|
351
|
+
this.connect();
|
|
352
|
+
}, delayMs);
|
|
353
|
+
timer.unref?.();
|
|
354
|
+
this.reconnectTimer = timer;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
private rejectPending(error: Error): void {
|
|
358
|
+
const pending = this.pendingAck;
|
|
359
|
+
if (!pending) return;
|
|
360
|
+
this.pendingAck = undefined;
|
|
361
|
+
clearTimeout(pending.timer);
|
|
362
|
+
pending.signal.removeEventListener('abort', pending.onAbort);
|
|
363
|
+
pending.reject(error);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
private abortError(signal: AbortSignal): DesktopEventSocketDeliveryError {
|
|
367
|
+
return new DesktopEventSocketDeliveryError(
|
|
368
|
+
'desktop_event_delivery_aborted',
|
|
369
|
+
signal.reason instanceof Error ? signal.reason.message : 'Desktop event delivery aborted.',
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { presentCanonicalEventForCclEvents } from '../../../../pipeline/canonical-event-presentation.js';
|
|
3
|
+
import { compactStateForEvents } from '../../../../pipeline/event-format.js';
|
|
4
|
+
import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
|
|
5
|
+
import {
|
|
6
|
+
EventIngress,
|
|
7
|
+
MemoryEventRepository,
|
|
8
|
+
type CanonicalEvent,
|
|
9
|
+
} from '../../../framework/events/index.js';
|
|
10
|
+
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
11
|
+
import { AgentMailboxCoordinator } from './agent-mailbox-coordinator.js';
|
|
12
|
+
import { ClawclawMailboxService } from './mailbox-service.js';
|
|
13
|
+
|
|
14
|
+
function readyView(epochSeq: number, eventWatermark: number): RuntimeReadyView {
|
|
15
|
+
const scope = {
|
|
16
|
+
adapterId: 'clawclaw',
|
|
17
|
+
accountId: 'account-1',
|
|
18
|
+
sessionId: 'session-1',
|
|
19
|
+
segmentId: 'game-1',
|
|
20
|
+
segmentSeq: 1,
|
|
21
|
+
};
|
|
22
|
+
return {
|
|
23
|
+
scope,
|
|
24
|
+
state: {
|
|
25
|
+
state: {
|
|
26
|
+
phase: 'wandering',
|
|
27
|
+
tick: 42,
|
|
28
|
+
you: { name: 'self', seat: 1, alive: true },
|
|
29
|
+
},
|
|
30
|
+
stateStatus: {
|
|
31
|
+
status: 'fresh',
|
|
32
|
+
semantics: 'latest_received',
|
|
33
|
+
source: 'owner_memory',
|
|
34
|
+
scope,
|
|
35
|
+
connectionId: 'connection-1',
|
|
36
|
+
connectionState: 'connected',
|
|
37
|
+
receivedAtMs: Date.parse('2026-08-04T00:00:00.000Z'),
|
|
38
|
+
ageMs: 0,
|
|
39
|
+
backendTick: 42,
|
|
40
|
+
reason: null,
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
pluginStates: {},
|
|
44
|
+
pluginOutcomes: {},
|
|
45
|
+
events: [],
|
|
46
|
+
throughCommitSeq: eventWatermark,
|
|
47
|
+
frameSeq: epochSeq,
|
|
48
|
+
eventWatermark,
|
|
49
|
+
epochSeq,
|
|
50
|
+
hasMore: false,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
describe('Mailbox Agent event batch', () => {
|
|
55
|
+
it('uses the full Channels stream and advances details only after Host ACK', async () => {
|
|
56
|
+
const repository = new MemoryEventRepository();
|
|
57
|
+
repository.saveSession({
|
|
58
|
+
sessionId: 'session-1',
|
|
59
|
+
adapterId: 'clawclaw',
|
|
60
|
+
accountId: 'account-1',
|
|
61
|
+
status: 'open',
|
|
62
|
+
isCurrent: true,
|
|
63
|
+
openedAt: '2026-08-04T00:00:00.000Z',
|
|
64
|
+
});
|
|
65
|
+
repository.saveSegment({
|
|
66
|
+
segmentId: 'game-1',
|
|
67
|
+
sessionId: 'session-1',
|
|
68
|
+
sequence: 1,
|
|
69
|
+
kind: 'game',
|
|
70
|
+
status: 'open',
|
|
71
|
+
isCurrent: true,
|
|
72
|
+
openedAt: '2026-08-04T00:00:00.000Z',
|
|
73
|
+
});
|
|
74
|
+
const ingress = new EventIngress(repository, createClawclawEventCatalog());
|
|
75
|
+
const publish = async (input: {
|
|
76
|
+
eventId: string;
|
|
77
|
+
type: string;
|
|
78
|
+
producer: 'backend_push' | 'local_synth';
|
|
79
|
+
payload: Record<string, unknown>;
|
|
80
|
+
}): Promise<CanonicalEvent> => (await ingress.publish({
|
|
81
|
+
epochSeq: 1,
|
|
82
|
+
eventId: input.eventId,
|
|
83
|
+
type: input.type,
|
|
84
|
+
producer: input.producer,
|
|
85
|
+
sessionId: 'session-1',
|
|
86
|
+
segmentId: 'game-1',
|
|
87
|
+
payload: input.payload,
|
|
88
|
+
source: { sourceId: 'test', eventId: `remote:${input.eventId}` },
|
|
89
|
+
})).event;
|
|
90
|
+
|
|
91
|
+
const longText = 'x'.repeat(70 * 1024);
|
|
92
|
+
const monitorEvent = await publish({
|
|
93
|
+
eventId: 'speech-1',
|
|
94
|
+
type: 'speech',
|
|
95
|
+
producer: 'backend_push',
|
|
96
|
+
payload: { actor_name: 'player-2', text: longText },
|
|
97
|
+
});
|
|
98
|
+
const visualEvent = await publish({
|
|
99
|
+
eventId: 'visual-1',
|
|
100
|
+
type: 'visual.player_moved',
|
|
101
|
+
producer: 'local_synth',
|
|
102
|
+
payload: { text: 'player-2 moved through engine' },
|
|
103
|
+
});
|
|
104
|
+
const internalEvent = await publish({
|
|
105
|
+
eventId: 'task-assigned-1',
|
|
106
|
+
type: 'task_assigned',
|
|
107
|
+
producer: 'backend_push',
|
|
108
|
+
payload: { task_name: 'repair' },
|
|
109
|
+
});
|
|
110
|
+
let ready = readyView(1, internalEvent.commitSeq);
|
|
111
|
+
const coordinator = new AgentMailboxCoordinator({
|
|
112
|
+
repository,
|
|
113
|
+
readyView: () => structuredClone(ready),
|
|
114
|
+
presentEvent: presentCanonicalEventForCclEvents,
|
|
115
|
+
compactState: compactStateForEvents,
|
|
116
|
+
});
|
|
117
|
+
const service = new ClawclawMailboxService({
|
|
118
|
+
repository,
|
|
119
|
+
readyView: () => structuredClone(ready),
|
|
120
|
+
agentMailbox: coordinator,
|
|
121
|
+
monitorEnabled: false,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const prepared = coordinator.prepareEvents({ bypassDelay: true });
|
|
125
|
+
|
|
126
|
+
expect(prepared.deliveryToken).toBeTypeOf('string');
|
|
127
|
+
expect(prepared.batch).toMatchObject({
|
|
128
|
+
state: { phase: 'wandering', tick: 42 },
|
|
129
|
+
});
|
|
130
|
+
expect(prepared.batch.events).toHaveLength(2);
|
|
131
|
+
expect(prepared.batch.events[0]).toBe('visual.player_moved | player-2 moved through engine');
|
|
132
|
+
expect(prepared.batch.events[1]).toMatchObject({ type: 'speech', text: longText });
|
|
133
|
+
expect(JSON.stringify(prepared.batch).length).toBeGreaterThan(64 * 1024);
|
|
134
|
+
expect(JSON.stringify(prepared.batch)).not.toContain('task_assigned');
|
|
135
|
+
expect(repository.delivery(monitorEvent.eventId, 'local-agent')).toMatchObject({
|
|
136
|
+
monitorState: 'pending',
|
|
137
|
+
detailState: 'pending',
|
|
138
|
+
});
|
|
139
|
+
expect(repository.delivery(visualEvent.eventId, 'local-agent')).toMatchObject({
|
|
140
|
+
monitorState: 'not_applicable',
|
|
141
|
+
detailState: 'pending',
|
|
142
|
+
});
|
|
143
|
+
expect(service.prepareMonitor(true)).toBe(0);
|
|
144
|
+
expect(() => service.prepareEvents()).toThrow('mailbox_events_delivery_busy');
|
|
145
|
+
|
|
146
|
+
expect(coordinator.ack(prepared.deliveryToken!)).toBe(true);
|
|
147
|
+
expect(repository.delivery(monitorEvent.eventId, 'local-agent')).toMatchObject({
|
|
148
|
+
monitorState: 'pending',
|
|
149
|
+
detailState: 'delivered',
|
|
150
|
+
detailDeliveryVia: 'mailbox_full',
|
|
151
|
+
});
|
|
152
|
+
expect(repository.delivery(visualEvent.eventId, 'local-agent')).toMatchObject({
|
|
153
|
+
detailState: 'delivered',
|
|
154
|
+
detailDeliveryVia: 'mailbox_full',
|
|
155
|
+
});
|
|
156
|
+
expect(repository.delivery(internalEvent.eventId, 'local-agent')).toMatchObject({
|
|
157
|
+
monitorState: 'not_applicable',
|
|
158
|
+
detailState: 'not_applicable',
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
ready = readyView(2, internalEvent.commitSeq);
|
|
162
|
+
expect(service.prepareEvents().output.events).toEqual([]);
|
|
163
|
+
await service.stop();
|
|
164
|
+
await coordinator.stop();
|
|
165
|
+
});
|
|
166
|
+
});
|