@myclaw163/clawclaw-cli 0.7.5 → 0.7.7

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 (62) hide show
  1. package/docs/desktop-event-push.md +154 -0
  2. package/docs/runtime/README.md +1 -0
  3. package/docs/runtime/official-perception-modules.md +346 -0
  4. package/package.json +2 -1
  5. package/src/commands/game/index.test.ts +167 -1
  6. package/src/commands/game/index.ts +125 -36
  7. package/src/lib/game-client.test.ts +15 -0
  8. package/src/lib/game-client.ts +4 -0
  9. package/src/lib/participation-status.ts +113 -0
  10. package/src/lib/service-status.test.ts +56 -0
  11. package/src/lib/service-status.ts +111 -0
  12. package/src/pipeline/event-format.test.ts +30 -0
  13. package/src/pipeline/event-format.ts +26 -1
  14. package/src/pipeline/event-hints.test.ts +18 -3
  15. package/src/pipeline/event-hints.ts +11 -0
  16. package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
  17. package/src/pipeline/game-sync-event-normalization.ts +51 -0
  18. package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  20. package/src/runtime/clawclaw/owner.ts +62 -3
  21. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
  23. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +363 -0
  24. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +236 -0
  25. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +411 -0
  26. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  27. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
  30. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
  32. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
  33. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
  34. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
  35. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
  36. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
  37. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
  38. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
  39. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
  40. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
  42. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
  43. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
  44. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
  45. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
  46. package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
  47. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +201 -1
  48. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +113 -24
  49. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  50. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
  51. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
  52. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
  53. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
  54. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
  55. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
  56. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
  57. package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
  58. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  59. package/src/sdk/perception-plugin/index.ts +14 -0
  60. package/src/sdk/resource-metadata.test.ts +40 -0
  61. package/src/sdk/resource-metadata.ts +63 -0
  62. package/src/sdk/strategy-plugin/index.ts +14 -0
@@ -0,0 +1,411 @@
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 DesktopActiveResource {
23
+ readonly id: string;
24
+ readonly name: string;
25
+ readonly description: string;
26
+ }
27
+
28
+ export interface DesktopActiveResources {
29
+ readonly locale: string;
30
+ readonly strategy: DesktopActiveResource | null;
31
+ readonly perceptions: readonly DesktopActiveResource[];
32
+ }
33
+
34
+ export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
35
+ ackTimeoutMs?: number;
36
+ reconnectBaseMs?: number;
37
+ reconnectMaxMs?: number;
38
+ now?: () => number;
39
+ platform?: NodeJS.Platform;
40
+ onConnected?: () => void;
41
+ activeResources?: () => DesktopActiveResources;
42
+ diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
43
+ }
44
+
45
+ interface PendingDesktopAck {
46
+ connectionId: string;
47
+ seq: number;
48
+ deliveryId: string;
49
+ timer: ReturnType<typeof setTimeout>;
50
+ signal: AbortSignal;
51
+ onAbort: () => void;
52
+ resolve: (acceptance: MailboxEventBatchAcceptance) => void;
53
+ reject: (error: Error) => void;
54
+ }
55
+
56
+ export class DesktopEventSocketDeliveryError extends Error {
57
+ readonly code: string;
58
+ readonly retryable: boolean;
59
+
60
+ constructor(code: string, message: string, retryable = true) {
61
+ super(message);
62
+ this.name = 'DesktopEventSocketDeliveryError';
63
+ this.code = code;
64
+ this.retryable = retryable;
65
+ }
66
+ }
67
+
68
+ function controlledText(value: string, label: string, maxLength: number): string {
69
+ const text = value.trim();
70
+ if (!text) throw new Error(`${label} is required.`);
71
+ if (text.length > maxLength || /[\0\r\n]/u.test(text)) {
72
+ throw new Error(`${label} is invalid.`);
73
+ }
74
+ return text;
75
+ }
76
+
77
+ export function normalizeDesktopEventSocketPath(
78
+ value: string,
79
+ platform: NodeJS.Platform = process.platform,
80
+ ): string {
81
+ const path = controlledText(value, 'Desktop event socket', 512);
82
+ if (platform === 'win32') {
83
+ if (path.startsWith(WINDOWS_PIPE_PREFIX)) return path;
84
+ if (path.startsWith('\\\\')) {
85
+ throw new Error('Desktop event socket must be a local named pipe.');
86
+ }
87
+ if (/[\\/]/u.test(path)) {
88
+ throw new Error('Desktop event socket must be a named-pipe name or local named-pipe path.');
89
+ }
90
+ return `${WINDOWS_PIPE_PREFIX}${path}`;
91
+ }
92
+ if (!path.startsWith('/')) {
93
+ throw new Error('Desktop event socket must be an absolute Unix socket path.');
94
+ }
95
+ return path;
96
+ }
97
+
98
+ export function validateDesktopEventToken(value: string): string {
99
+ const token = controlledText(value, 'Desktop event token', 1_024);
100
+ if (token.length < 16) {
101
+ throw new Error('Desktop event token must contain at least 16 characters.');
102
+ }
103
+ return token;
104
+ }
105
+
106
+ /** Persistent NDJSON client for a Desktop-owned local socket/named pipe. */
107
+ export class DesktopEventSocketSink implements MailboxEventBatchSink {
108
+ private readonly path: string;
109
+ private readonly token: string;
110
+ private readonly ackTimeoutMs: number;
111
+ private readonly reconnectBaseMs: number;
112
+ private readonly reconnectMaxMs: number;
113
+ private readonly now: () => number;
114
+ private readonly onConnected?: DesktopEventSocketOptions['onConnected'];
115
+ private readonly activeResources?: DesktopEventSocketOptions['activeResources'];
116
+ private readonly diagnostic?: DesktopEventSocketOptions['diagnostic'];
117
+
118
+ private socket: Socket | undefined;
119
+ private connected = false;
120
+ private stopped = false;
121
+ private connectionId: string | undefined;
122
+ private sequence = 0;
123
+ private reconnectAttempt = 0;
124
+ private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
125
+ private inputBuffer = '';
126
+ private pendingAck: PendingDesktopAck | undefined;
127
+ private deliveryResources: {
128
+ deliveryId: string;
129
+ value: DesktopActiveResources | undefined;
130
+ } | undefined;
131
+
132
+ constructor(options: DesktopEventSocketOptions) {
133
+ this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
134
+ this.token = validateDesktopEventToken(options.token);
135
+ this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
136
+ this.reconnectBaseMs = options.reconnectBaseMs ?? DEFAULT_RECONNECT_BASE_MS;
137
+ this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
138
+ this.now = options.now ?? Date.now;
139
+ this.onConnected = options.onConnected;
140
+ this.activeResources = options.activeResources;
141
+ this.diagnostic = options.diagnostic;
142
+ if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
143
+ throw new Error('Desktop event ACK timeout must be positive.');
144
+ }
145
+ if (
146
+ !Number.isFinite(this.reconnectBaseMs)
147
+ || this.reconnectBaseMs <= 0
148
+ || !Number.isFinite(this.reconnectMaxMs)
149
+ || this.reconnectMaxMs < this.reconnectBaseMs
150
+ ) {
151
+ throw new Error('Desktop event reconnect delays are invalid.');
152
+ }
153
+ }
154
+
155
+ start(): void {
156
+ if (this.stopped || this.socket) return;
157
+ this.connect();
158
+ }
159
+
160
+ async deliver(
161
+ envelope: MailboxEventBatchEnvelope,
162
+ signal: AbortSignal,
163
+ ): Promise<MailboxEventBatchAcceptance> {
164
+ if (this.stopped) {
165
+ throw new DesktopEventSocketDeliveryError(
166
+ 'desktop_event_socket_stopped',
167
+ 'Desktop event socket is stopped.',
168
+ false,
169
+ );
170
+ }
171
+ if (signal.aborted) throw this.abortError(signal);
172
+ const socket = this.socket;
173
+ const connectionId = this.connectionId;
174
+ if (!socket || !this.connected || !connectionId) {
175
+ this.start();
176
+ throw new DesktopEventSocketDeliveryError(
177
+ 'desktop_event_socket_not_connected',
178
+ 'Desktop event socket is not connected.',
179
+ );
180
+ }
181
+ if (this.pendingAck) {
182
+ throw new DesktopEventSocketDeliveryError(
183
+ 'desktop_event_batch_in_flight',
184
+ 'A Desktop event batch is already awaiting acknowledgement.',
185
+ );
186
+ }
187
+
188
+ const seq = ++this.sequence;
189
+ const activeResources = this.resourcesForDelivery(envelope.deliveryId);
190
+ const frame = {
191
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
192
+ type: 'mailbox_batch',
193
+ connection_id: connectionId,
194
+ seq,
195
+ delivery_id: envelope.deliveryId,
196
+ ...(activeResources ? { active_resources: activeResources } : {}),
197
+ payload: {
198
+ schema: 'clawclaw.channel-events.v1',
199
+ ...envelope.batch,
200
+ },
201
+ };
202
+
203
+ return new Promise<MailboxEventBatchAcceptance>((resolve, reject) => {
204
+ const onAbort = (): void => {
205
+ if (this.pendingAck?.seq !== seq) return;
206
+ this.rejectPending(this.abortError(signal));
207
+ socket.destroy();
208
+ };
209
+ const timer = setTimeout(() => {
210
+ if (this.pendingAck?.seq !== seq) return;
211
+ this.rejectPending(new DesktopEventSocketDeliveryError(
212
+ 'desktop_event_ack_timeout',
213
+ 'Desktop did not acknowledge the event batch in time.',
214
+ ));
215
+ socket.destroy();
216
+ }, this.ackTimeoutMs);
217
+ timer.unref?.();
218
+ this.pendingAck = {
219
+ connectionId,
220
+ seq,
221
+ deliveryId: envelope.deliveryId,
222
+ timer,
223
+ signal,
224
+ onAbort,
225
+ resolve,
226
+ reject,
227
+ };
228
+ signal.addEventListener('abort', onAbort, { once: true });
229
+
230
+ const line = `${JSON.stringify(frame)}\n`;
231
+ socket.write(line, (error?: Error | null) => {
232
+ if (!error || this.pendingAck?.seq !== seq) return;
233
+ this.rejectPending(new DesktopEventSocketDeliveryError(
234
+ 'desktop_event_socket_write_failed',
235
+ error.message,
236
+ ));
237
+ socket.destroy();
238
+ });
239
+ });
240
+ }
241
+
242
+ async close(): Promise<void> {
243
+ if (this.stopped) return;
244
+ this.stopped = true;
245
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
246
+ this.reconnectTimer = undefined;
247
+ this.rejectPending(new DesktopEventSocketDeliveryError(
248
+ 'desktop_event_socket_stopped',
249
+ 'Desktop event socket stopped before acknowledgement.',
250
+ false,
251
+ ));
252
+ const socket = this.socket;
253
+ this.socket = undefined;
254
+ this.connected = false;
255
+ this.connectionId = undefined;
256
+ this.deliveryResources = undefined;
257
+ if (!socket || socket.destroyed) return;
258
+ await new Promise<void>((resolve) => {
259
+ socket.once('close', () => resolve());
260
+ socket.destroy();
261
+ });
262
+ }
263
+
264
+ private connect(): void {
265
+ if (this.stopped || this.socket) return;
266
+ const connectionId = randomUUID();
267
+ const socket = createConnection(this.path);
268
+ this.socket = socket;
269
+ this.connectionId = connectionId;
270
+ this.inputBuffer = '';
271
+ socket.setEncoding('utf8');
272
+ socket.setNoDelay(true);
273
+
274
+ socket.once('connect', () => {
275
+ if (this.socket !== socket || this.stopped) return;
276
+ this.connected = true;
277
+ this.reconnectAttempt = 0;
278
+ const activeResources = this.readActiveResources();
279
+ socket.write(`${JSON.stringify({
280
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
281
+ type: 'hello',
282
+ connection_id: connectionId,
283
+ token: this.token,
284
+ pid: process.pid,
285
+ ...(activeResources ? { active_resources: activeResources } : {}),
286
+ })}\n`);
287
+ this.diagnostic?.('runtime.desktop_event_socket.connected', {
288
+ connection_id: connectionId,
289
+ });
290
+ this.onConnected?.();
291
+ });
292
+ socket.on('data', (chunk: string) => this.onData(socket, chunk));
293
+ socket.once('error', (error) => {
294
+ this.diagnostic?.('runtime.desktop_event_socket.error', {
295
+ code: typeof (error as NodeJS.ErrnoException).code === 'string'
296
+ ? (error as NodeJS.ErrnoException).code
297
+ : error.name,
298
+ });
299
+ });
300
+ socket.once('close', () => this.onClose(socket));
301
+ }
302
+
303
+ private onData(socket: Socket, chunk: string): void {
304
+ if (this.socket !== socket || this.stopped) return;
305
+ this.inputBuffer += chunk;
306
+ if (this.inputBuffer.length > MAX_ACK_BUFFER_CHARACTERS) {
307
+ socket.destroy(new Error('desktop_event_ack_frame_too_large'));
308
+ return;
309
+ }
310
+ for (;;) {
311
+ const newline = this.inputBuffer.indexOf('\n');
312
+ if (newline < 0) return;
313
+ const line = this.inputBuffer.slice(0, newline).trim();
314
+ this.inputBuffer = this.inputBuffer.slice(newline + 1);
315
+ if (!line) continue;
316
+ let frame: Record<string, unknown>;
317
+ try {
318
+ const parsed = JSON.parse(line);
319
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error();
320
+ frame = parsed as Record<string, unknown>;
321
+ } catch {
322
+ socket.destroy(new Error('desktop_event_ack_invalid_json'));
323
+ return;
324
+ }
325
+ this.handleFrame(frame);
326
+ }
327
+ }
328
+
329
+ private handleFrame(frame: Record<string, unknown>): void {
330
+ const pending = this.pendingAck;
331
+ if (
332
+ !pending
333
+ || frame.schema !== DESKTOP_EVENT_PROTOCOL_SCHEMA
334
+ || frame.type !== 'ack'
335
+ || frame.connection_id !== pending.connectionId
336
+ || frame.seq !== pending.seq
337
+ || frame.delivery_id !== pending.deliveryId
338
+ ) {
339
+ this.diagnostic?.('runtime.desktop_event_socket.ack_ignored');
340
+ return;
341
+ }
342
+ const receiptId = typeof frame.receipt_id === 'string' && frame.receipt_id.length <= 256
343
+ ? frame.receipt_id
344
+ : undefined;
345
+ this.pendingAck = undefined;
346
+ clearTimeout(pending.timer);
347
+ pending.signal.removeEventListener('abort', pending.onAbort);
348
+ if (this.deliveryResources?.deliveryId === pending.deliveryId) {
349
+ this.deliveryResources = undefined;
350
+ }
351
+ pending.resolve({
352
+ acceptedAt: new Date(this.now()).toISOString(),
353
+ ...(receiptId ? { receiptId } : {}),
354
+ });
355
+ }
356
+
357
+ private onClose(socket: Socket): void {
358
+ if (this.socket !== socket) return;
359
+ this.socket = undefined;
360
+ this.connected = false;
361
+ this.connectionId = undefined;
362
+ this.inputBuffer = '';
363
+ this.rejectPending(new DesktopEventSocketDeliveryError(
364
+ 'desktop_event_socket_disconnected',
365
+ 'Desktop event socket disconnected before acknowledgement.',
366
+ ));
367
+ if (this.stopped) return;
368
+ this.reconnectAttempt += 1;
369
+ const delayMs = Math.min(
370
+ this.reconnectMaxMs,
371
+ this.reconnectBaseMs * (2 ** Math.min(8, this.reconnectAttempt - 1)),
372
+ );
373
+ this.diagnostic?.('runtime.desktop_event_socket.reconnecting', {
374
+ retry_in_ms: delayMs,
375
+ });
376
+ const timer = setTimeout(() => {
377
+ this.reconnectTimer = undefined;
378
+ this.connect();
379
+ }, delayMs);
380
+ timer.unref?.();
381
+ this.reconnectTimer = timer;
382
+ }
383
+
384
+ private rejectPending(error: Error): void {
385
+ const pending = this.pendingAck;
386
+ if (!pending) return;
387
+ this.pendingAck = undefined;
388
+ clearTimeout(pending.timer);
389
+ pending.signal.removeEventListener('abort', pending.onAbort);
390
+ pending.reject(error);
391
+ }
392
+
393
+ private abortError(signal: AbortSignal): DesktopEventSocketDeliveryError {
394
+ return new DesktopEventSocketDeliveryError(
395
+ 'desktop_event_delivery_aborted',
396
+ signal.reason instanceof Error ? signal.reason.message : 'Desktop event delivery aborted.',
397
+ );
398
+ }
399
+
400
+ private readActiveResources(): DesktopActiveResources | undefined {
401
+ if (!this.activeResources) return undefined;
402
+ return structuredClone(this.activeResources());
403
+ }
404
+
405
+ private resourcesForDelivery(deliveryId: string): DesktopActiveResources | undefined {
406
+ if (this.deliveryResources?.deliveryId === deliveryId) return this.deliveryResources.value;
407
+ const value = this.readActiveResources();
408
+ this.deliveryResources = { deliveryId, value };
409
+ return value;
410
+ }
411
+ }
@@ -1,3 +1,6 @@
1
+ export * from './agent-mailbox-coordinator.js';
2
+ export * from './desktop-event-socket.js';
3
+ export * from './mailbox-event-batch-delivery.js';
1
4
  export * from './mailbox-plugin.js';
2
5
  export * from './mailbox-presentation.js';
3
6
  export * from './mailbox-service.js';
@@ -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
+ });