@myclaw163/clawclaw-cli 0.7.4 → 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.
Files changed (35) hide show
  1. package/docs/desktop-event-push.md +120 -0
  2. package/docs/runtime/events-and-state.md +1 -1
  3. package/package.json +3 -1
  4. package/skills/clawclaw/SKILL.md +9 -9
  5. package/skills/clawclaw/references/GAME-MECHANICS.md +2 -2
  6. package/src/assets/clawclaw-spatial-model.txt +142 -0
  7. package/src/commands/game/index.test.ts +167 -1
  8. package/src/commands/game/index.ts +124 -35
  9. package/src/commands/game-map.test.ts +8 -4
  10. package/src/lib/game-client.test.ts +15 -0
  11. package/src/lib/game-client.ts +4 -0
  12. package/src/lib/game-context.ts +6 -6
  13. package/src/lib/participation-status.ts +113 -0
  14. package/src/pipeline/canonical-event-presentation.test.ts +5 -4
  15. package/src/pipeline/event-format.test.ts +17 -0
  16. package/src/pipeline/event-format.ts +15 -1
  17. package/src/pipeline/game-sync-event-normalization.test.ts +58 -1
  18. package/src/pipeline/game-sync-event-normalization.ts +51 -0
  19. package/src/runtime/clawclaw/owner.ts +56 -3
  20. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +189 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +532 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +339 -0
  23. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +207 -0
  24. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +372 -0
  25. package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
  26. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +166 -0
  27. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +194 -0
  28. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +262 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +28 -0
  30. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +49 -0
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +77 -259
  32. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +5 -0
  33. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +52 -0
  34. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +4 -3
  35. package/src/assets/clawclaw-ascii-map.txt +0 -40
@@ -0,0 +1,339 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createServer, type Server, type Socket } from 'node:net';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import { presentCanonicalEventForCclEvents } from '../../../../pipeline/canonical-event-presentation.js';
5
+ import { compactStateForEvents } from '../../../../pipeline/event-format.js';
6
+ import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
7
+ import {
8
+ EventIngress,
9
+ MemoryEventRepository,
10
+ type CanonicalEvent,
11
+ } from '../../../framework/events/index.js';
12
+ import type { RuntimeReadyView } from '../../../framework/runtime.js';
13
+ import {
14
+ AGENT_MAILBOX_COALESCE_MS,
15
+ AgentMailboxCoordinator,
16
+ } from './agent-mailbox-coordinator.js';
17
+ import {
18
+ DESKTOP_EVENT_PROTOCOL_SCHEMA,
19
+ DesktopEventSocketSink,
20
+ } from './desktop-event-socket.js';
21
+ import {
22
+ ClawclawMailboxPlugin,
23
+ CompositeClawclawMailboxDriver,
24
+ } from './mailbox-plugin.js';
25
+ import { MailboxEventBatchPump } from './mailbox-event-batch-delivery.js';
26
+
27
+ interface ReceivedFrame {
28
+ atMs: number;
29
+ frame: Record<string, any>;
30
+ socket: Socket;
31
+ }
32
+
33
+ const servers: Server[] = [];
34
+ const serverSockets: Socket[] = [];
35
+
36
+ async function closeServer(server: Server): Promise<void> {
37
+ if (!server.listening) return;
38
+ await new Promise<void>((resolve, reject) => {
39
+ server.close((error) => error ? reject(error) : resolve());
40
+ });
41
+ }
42
+
43
+ afterEach(async () => {
44
+ for (const socket of serverSockets.splice(0)) socket.destroy();
45
+ await Promise.all(servers.splice(0).map((server) => closeServer(server)));
46
+ });
47
+
48
+ function delay(milliseconds: number): Promise<void> {
49
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
50
+ }
51
+
52
+ function readyView(epochSeq: number, eventWatermark: number): RuntimeReadyView {
53
+ const scope = {
54
+ adapterId: 'clawclaw',
55
+ accountId: 'account-1',
56
+ sessionId: 'session-1',
57
+ segmentId: 'game-1',
58
+ segmentSeq: 1,
59
+ };
60
+ return {
61
+ scope,
62
+ state: {
63
+ state: {
64
+ phase: 'wandering',
65
+ tick: epochSeq,
66
+ you: { name: 'self', seat: 1, alive: true },
67
+ },
68
+ stateStatus: {
69
+ status: 'fresh',
70
+ semantics: 'latest_received',
71
+ source: 'owner_memory',
72
+ scope,
73
+ connectionId: 'connection-1',
74
+ connectionState: 'connected',
75
+ receivedAtMs: Date.now(),
76
+ ageMs: 0,
77
+ backendTick: epochSeq,
78
+ reason: null,
79
+ },
80
+ },
81
+ pluginStates: {},
82
+ pluginOutcomes: {},
83
+ events: [],
84
+ throughCommitSeq: eventWatermark,
85
+ frameSeq: epochSeq,
86
+ eventWatermark,
87
+ epochSeq,
88
+ hasMore: false,
89
+ };
90
+ }
91
+
92
+ async function publish(
93
+ ingress: EventIngress,
94
+ input: {
95
+ eventId: string;
96
+ type: string;
97
+ epochSeq: number;
98
+ producer?: 'backend_push' | 'local_synth';
99
+ payload?: Record<string, unknown>;
100
+ },
101
+ ): Promise<CanonicalEvent> {
102
+ return (await ingress.publish({
103
+ epochSeq: input.epochSeq,
104
+ eventId: input.eventId,
105
+ type: input.type,
106
+ producer: input.producer ?? 'backend_push',
107
+ sessionId: 'session-1',
108
+ segmentId: 'game-1',
109
+ payload: input.payload ?? {},
110
+ source: { sourceId: 'test', eventId: `remote:${input.eventId}` },
111
+ })).event;
112
+ }
113
+
114
+ function sendAck(
115
+ received: ReceivedFrame,
116
+ overrides: Partial<Record<'connection_id' | 'seq' | 'delivery_id', unknown>> = {},
117
+ ): void {
118
+ const frame = received.frame;
119
+ received.socket.write(`${JSON.stringify({
120
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
121
+ type: 'ack',
122
+ connection_id: frame.connection_id,
123
+ seq: frame.seq,
124
+ delivery_id: frame.delivery_id,
125
+ receipt_id: `wake-${frame.seq}`,
126
+ ...overrides,
127
+ })}\n`);
128
+ }
129
+
130
+ describe('Desktop Agent event push integration', () => {
131
+ it('pushes only ready visible Events and retries one durable batch until exact ACK', async () => {
132
+ const pipeName = `ccl-desktop-integration-${randomUUID()}`;
133
+ const socketPath = process.platform === 'win32'
134
+ ? `\\\\.\\pipe\\${pipeName}`
135
+ : `/tmp/${pipeName}.sock`;
136
+ const received: ReceivedFrame[] = [];
137
+ let disconnectNextBatch = false;
138
+ const server = createServer((socket) => {
139
+ serverSockets.push(socket);
140
+ socket.setEncoding('utf8');
141
+ let buffer = '';
142
+ socket.on('data', (chunk: string) => {
143
+ buffer += chunk;
144
+ for (;;) {
145
+ const newline = buffer.indexOf('\n');
146
+ if (newline < 0) break;
147
+ const line = buffer.slice(0, newline);
148
+ buffer = buffer.slice(newline + 1);
149
+ if (!line.trim()) continue;
150
+ const frame = JSON.parse(line) as Record<string, any>;
151
+ received.push({ atMs: Date.now(), frame, socket });
152
+ if (frame.type === 'mailbox_batch' && disconnectNextBatch) {
153
+ disconnectNextBatch = false;
154
+ socket.destroy();
155
+ }
156
+ }
157
+ });
158
+ });
159
+ servers.push(server);
160
+ await new Promise<void>((resolve, reject) => {
161
+ server.once('error', reject);
162
+ server.listen(socketPath, resolve);
163
+ });
164
+
165
+ const repository = new MemoryEventRepository();
166
+ repository.saveSession({
167
+ sessionId: 'session-1',
168
+ adapterId: 'clawclaw',
169
+ accountId: 'account-1',
170
+ status: 'open',
171
+ isCurrent: true,
172
+ openedAt: '2026-08-04T00:00:00.000Z',
173
+ });
174
+ repository.saveSegment({
175
+ segmentId: 'game-1',
176
+ sessionId: 'session-1',
177
+ sequence: 1,
178
+ kind: 'game',
179
+ status: 'open',
180
+ isCurrent: true,
181
+ openedAt: '2026-08-04T00:00:00.000Z',
182
+ });
183
+ const ingress = new EventIngress(repository, createClawclawEventCatalog());
184
+ let ready = readyView(1, 0);
185
+ const coordinator = new AgentMailboxCoordinator({
186
+ repository,
187
+ readyView: () => structuredClone(ready),
188
+ presentEvent: presentCanonicalEventForCclEvents,
189
+ compactState: compactStateForEvents,
190
+ });
191
+ let pump: MailboxEventBatchPump | undefined;
192
+ const sink = new DesktopEventSocketSink({
193
+ socketPath,
194
+ token: '0123456789abcdef0123456789abcdef',
195
+ ackTimeoutMs: 2_000,
196
+ reconnectBaseMs: 10,
197
+ reconnectMaxMs: 20,
198
+ onConnected: () => pump?.retryNow(),
199
+ });
200
+ pump = new MailboxEventBatchPump({
201
+ source: {
202
+ prepare: () => coordinator.prepareEvents({
203
+ deliveryVia: 'mailbox_full',
204
+ ownerIdPrefix: 'desktop_ipc_test',
205
+ }),
206
+ renew: (deliveryToken) => coordinator.renew(deliveryToken),
207
+ ack: (deliveryToken) => coordinator.ack(deliveryToken),
208
+ release: (deliveryToken) => coordinator.release(deliveryToken),
209
+ },
210
+ sink,
211
+ });
212
+ const mailbox = new ClawclawMailboxPlugin();
213
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([coordinator, pump]));
214
+ sink.start();
215
+
216
+ try {
217
+ await vi.waitFor(() => {
218
+ expect(received.filter(({ frame }) => frame.type === 'hello')).toHaveLength(1);
219
+ });
220
+ expect(await mailbox.update({ pendingEvents: [] } as any)).toMatchObject({
221
+ outcome: 'noop',
222
+ reason: 'no_pending_events',
223
+ });
224
+
225
+ const internal = await publish(ingress, {
226
+ eventId: 'task-assigned-1',
227
+ type: 'task_assigned',
228
+ epochSeq: 1,
229
+ payload: { task_name: 'repair' },
230
+ });
231
+ ready = readyView(1, internal.commitSeq);
232
+ await mailbox.update({ pendingEvents: [internal] } as any);
233
+ await delay(AGENT_MAILBOX_COALESCE_MS + 60);
234
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(0);
235
+
236
+ const longText = `BEGIN-${'x'.repeat(70 * 1024)}-END`;
237
+ const speech = await publish(ingress, {
238
+ eventId: 'speech-1',
239
+ type: 'speech',
240
+ epochSeq: 2,
241
+ payload: { actor_name: 'player-2', text: longText },
242
+ });
243
+ expect(speech.deliveryClass).toBe('monitor_and_events');
244
+ ready = readyView(2, speech.commitSeq);
245
+ const firstObservedAt = Date.now();
246
+ await mailbox.update({ pendingEvents: [speech] } as any);
247
+ await delay(100);
248
+
249
+ const visual = await publish(ingress, {
250
+ eventId: 'visual-1',
251
+ type: 'visual.player_moved',
252
+ epochSeq: 3,
253
+ producer: 'local_synth',
254
+ payload: { text: 'player-2 moved through engine' },
255
+ });
256
+ ready = readyView(3, visual.commitSeq);
257
+ await mailbox.update({ pendingEvents: [visual] } as any);
258
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(0);
259
+
260
+ await vi.waitFor(() => {
261
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
262
+ }, { timeout: 2_000 });
263
+ const firstBatch = received.find(({ frame }) => frame.type === 'mailbox_batch')!;
264
+ expect(firstBatch.atMs - firstObservedAt).toBeGreaterThanOrEqual(
265
+ AGENT_MAILBOX_COALESCE_MS - 20,
266
+ );
267
+ expect(firstBatch.frame.payload).toMatchObject({
268
+ schema: 'clawclaw.channel-events.v1',
269
+ state: { phase: 'wandering', tick: 3 },
270
+ });
271
+ expect(firstBatch.frame.payload.events).toEqual([
272
+ 'visual.player_moved | player-2 moved through engine',
273
+ expect.objectContaining({ type: 'speech', text: longText }),
274
+ ]);
275
+ expect(Buffer.byteLength(JSON.stringify(firstBatch.frame.payload), 'utf8'))
276
+ .toBeGreaterThan(64 * 1024);
277
+ expect(JSON.stringify(firstBatch.frame.payload)).not.toContain('task_assigned');
278
+
279
+ sendAck(firstBatch, { seq: firstBatch.frame.seq + 1 });
280
+ await delay(40);
281
+ expect(repository.delivery(speech.eventId, 'local-agent')?.detailState).toBe('pending');
282
+ sendAck(firstBatch);
283
+ await vi.waitFor(() => {
284
+ expect(repository.delivery(speech.eventId, 'local-agent')).toMatchObject({
285
+ detailState: 'delivered',
286
+ detailDeliveryVia: 'mailbox_full',
287
+ });
288
+ });
289
+ await delay(300);
290
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
291
+
292
+ const boundaryEvent = await publish(ingress, {
293
+ eventId: 'speech-boundary',
294
+ type: 'speech',
295
+ epochSeq: 4,
296
+ payload: { actor_name: 'player-3', text: 'held behind ReadyView' },
297
+ });
298
+ const previousReady = ready;
299
+ disconnectNextBatch = true;
300
+ await mailbox.update({ pendingEvents: [boundaryEvent] } as any);
301
+ await delay(AGENT_MAILBOX_COALESCE_MS + 80);
302
+ expect(ready).toBe(previousReady);
303
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
304
+
305
+ ready = readyView(4, boundaryEvent.commitSeq);
306
+ await vi.waitFor(() => {
307
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch').length)
308
+ .toBeGreaterThanOrEqual(2);
309
+ }, { timeout: 2_000 });
310
+ await vi.waitFor(() => {
311
+ expect(received.filter(({ frame }) => frame.type === 'hello')).toHaveLength(2);
312
+ }, { timeout: 2_000 });
313
+ await vi.waitFor(() => {
314
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(3);
315
+ }, { timeout: 2_000 });
316
+
317
+ const retries = received
318
+ .filter(({ frame }) => frame.type === 'mailbox_batch')
319
+ .slice(1);
320
+ expect(retries).toHaveLength(2);
321
+ expect(retries[0].frame.delivery_id).toBe(retries[1].frame.delivery_id);
322
+ expect(retries[0].frame.connection_id).not.toBe(retries[1].frame.connection_id);
323
+ expect(repository.delivery(boundaryEvent.eventId, 'local-agent')?.detailState)
324
+ .toBe('pending');
325
+
326
+ sendAck(retries[1]);
327
+ await vi.waitFor(() => {
328
+ expect(repository.delivery(boundaryEvent.eventId, 'local-agent')).toMatchObject({
329
+ detailState: 'delivered',
330
+ detailDeliveryVia: 'mailbox_full',
331
+ });
332
+ });
333
+ await delay(300);
334
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(3);
335
+ } finally {
336
+ await mailbox.stop('shutdown');
337
+ }
338
+ }, 10_000);
339
+ });
@@ -0,0 +1,207 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createServer, type Server, type Socket } from 'node:net';
3
+ import { afterEach, describe, expect, it, vi } from 'vitest';
4
+ import {
5
+ DESKTOP_EVENT_PROTOCOL_SCHEMA,
6
+ DesktopEventSocketSink,
7
+ normalizeDesktopEventSocketPath,
8
+ validateDesktopEventToken,
9
+ } from './desktop-event-socket.js';
10
+
11
+ const servers: Server[] = [];
12
+
13
+ async function closeServer(server: Server): Promise<void> {
14
+ if (!server.listening) return;
15
+ await new Promise<void>((resolve, reject) => {
16
+ server.close((error) => error ? reject(error) : resolve());
17
+ });
18
+ }
19
+
20
+ afterEach(async () => {
21
+ await Promise.all(servers.splice(0).map((server) => closeServer(server)));
22
+ });
23
+
24
+ describe('DesktopEventSocketSink', () => {
25
+ it('normalizes only local IPC endpoints and validates the nonce', () => {
26
+ expect(normalizeDesktopEventSocketPath('clawclaw-desktop', 'win32'))
27
+ .toBe('\\\\.\\pipe\\clawclaw-desktop');
28
+ expect(normalizeDesktopEventSocketPath('\\\\.\\pipe\\clawclaw-desktop', 'win32'))
29
+ .toBe('\\\\.\\pipe\\clawclaw-desktop');
30
+ expect(() => normalizeDesktopEventSocketPath('\\\\remote\\pipe\\event', 'win32'))
31
+ .toThrow('local named pipe');
32
+ expect(normalizeDesktopEventSocketPath('/tmp/clawclaw.sock', 'linux'))
33
+ .toBe('/tmp/clawclaw.sock');
34
+ expect(() => normalizeDesktopEventSocketPath('relative.sock', 'linux'))
35
+ .toThrow('absolute Unix socket');
36
+ expect(validateDesktopEventToken('0123456789abcdef')).toBe('0123456789abcdef');
37
+ expect(() => validateDesktopEventToken('short')).toThrow('at least 16');
38
+ });
39
+
40
+ it('reuses one connection and resolves only a matching application ACK', async () => {
41
+ const pipeName = `ccl-desktop-test-${randomUUID()}`;
42
+ const socketPath = process.platform === 'win32'
43
+ ? `\\\\.\\pipe\\${pipeName}`
44
+ : `/tmp/${pipeName}.sock`;
45
+ const frames: Array<Record<string, any>> = [];
46
+ const connections: Socket[] = [];
47
+ const server = createServer((socket) => {
48
+ connections.push(socket);
49
+ socket.setEncoding('utf8');
50
+ let buffer = '';
51
+ socket.on('data', (chunk: string) => {
52
+ buffer += chunk;
53
+ for (;;) {
54
+ const newline = buffer.indexOf('\n');
55
+ if (newline < 0) break;
56
+ const line = buffer.slice(0, newline);
57
+ buffer = buffer.slice(newline + 1);
58
+ if (!line.trim()) continue;
59
+ const frame = JSON.parse(line) as Record<string, any>;
60
+ frames.push(frame);
61
+ if (frame.type !== 'mailbox_batch') continue;
62
+ socket.write(`${JSON.stringify({
63
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
64
+ type: 'ack',
65
+ connection_id: frame.connection_id,
66
+ seq: frame.seq + 1,
67
+ delivery_id: frame.delivery_id,
68
+ })}\n`);
69
+ const ack = `${JSON.stringify({
70
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
71
+ type: 'ack',
72
+ connection_id: frame.connection_id,
73
+ seq: frame.seq,
74
+ delivery_id: frame.delivery_id,
75
+ receipt_id: `wake-${frame.seq}`,
76
+ })}\n`;
77
+ socket.write(ack.slice(0, 7));
78
+ socket.write(ack.slice(7));
79
+ }
80
+ });
81
+ });
82
+ servers.push(server);
83
+ await new Promise<void>((resolve, reject) => {
84
+ server.once('error', reject);
85
+ server.listen(socketPath, resolve);
86
+ });
87
+
88
+ const sink = new DesktopEventSocketSink({
89
+ socketPath,
90
+ token: '0123456789abcdef0123456789abcdef',
91
+ reconnectBaseMs: 10,
92
+ reconnectMaxMs: 20,
93
+ });
94
+ sink.start();
95
+ await vi.waitFor(() => expect(frames[0]).toMatchObject({
96
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
97
+ type: 'hello',
98
+ token: '0123456789abcdef0123456789abcdef',
99
+ pid: process.pid,
100
+ }));
101
+
102
+ const largeText = 'z'.repeat(70 * 1024);
103
+ const first = await sink.deliver({
104
+ deliveryId: 'delivery-1',
105
+ batch: {
106
+ state: { phase: 'meeting' },
107
+ events: [{ type: 'meeting_briefing', text: largeText }],
108
+ },
109
+ }, new AbortController().signal);
110
+ const second = await sink.deliver({
111
+ deliveryId: 'delivery-2',
112
+ batch: {
113
+ state: { phase: 'wandering' },
114
+ events: [{ type: 'speech_your_turn' }],
115
+ },
116
+ }, new AbortController().signal);
117
+
118
+ expect(first.receiptId).toBe('wake-1');
119
+ expect(second.receiptId).toBe('wake-2');
120
+ expect(connections).toHaveLength(1);
121
+ expect(frames.filter((frame) => frame.type === 'mailbox_batch')).toEqual([
122
+ expect.objectContaining({
123
+ seq: 1,
124
+ delivery_id: 'delivery-1',
125
+ payload: expect.objectContaining({
126
+ schema: 'clawclaw.channel-events.v1',
127
+ events: [expect.objectContaining({ text: largeText })],
128
+ }),
129
+ }),
130
+ expect.objectContaining({ seq: 2, delivery_id: 'delivery-2' }),
131
+ ]);
132
+
133
+ await sink.close();
134
+ });
135
+
136
+ it('rejects an unacknowledged batch, reconnects, and permits the durable retry', async () => {
137
+ const pipeName = `ccl-desktop-retry-${randomUUID()}`;
138
+ const socketPath = process.platform === 'win32'
139
+ ? `\\\\.\\pipe\\${pipeName}`
140
+ : `/tmp/${pipeName}.sock`;
141
+ const hellos: Array<Record<string, any>> = [];
142
+ let connectionNumber = 0;
143
+ const server = createServer((socket) => {
144
+ connectionNumber += 1;
145
+ const currentConnection = connectionNumber;
146
+ socket.setEncoding('utf8');
147
+ let buffer = '';
148
+ socket.on('data', (chunk: string) => {
149
+ buffer += chunk;
150
+ for (;;) {
151
+ const newline = buffer.indexOf('\n');
152
+ if (newline < 0) break;
153
+ const line = buffer.slice(0, newline);
154
+ buffer = buffer.slice(newline + 1);
155
+ if (!line.trim()) continue;
156
+ const frame = JSON.parse(line) as Record<string, any>;
157
+ if (frame.type === 'hello') hellos.push(frame);
158
+ if (frame.type !== 'mailbox_batch') continue;
159
+ if (currentConnection === 1) {
160
+ socket.destroy();
161
+ continue;
162
+ }
163
+ socket.write(`${JSON.stringify({
164
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
165
+ type: 'ack',
166
+ connection_id: frame.connection_id,
167
+ seq: frame.seq,
168
+ delivery_id: frame.delivery_id,
169
+ })}\n`);
170
+ }
171
+ });
172
+ });
173
+ servers.push(server);
174
+ await new Promise<void>((resolve, reject) => {
175
+ server.once('error', reject);
176
+ server.listen(socketPath, resolve);
177
+ });
178
+
179
+ const sink = new DesktopEventSocketSink({
180
+ socketPath,
181
+ token: '0123456789abcdef0123456789abcdef',
182
+ reconnectBaseMs: 10,
183
+ reconnectMaxMs: 20,
184
+ });
185
+ sink.start();
186
+ await vi.waitFor(() => expect(hellos).toHaveLength(1));
187
+ const envelope = {
188
+ deliveryId: 'durable-delivery',
189
+ batch: {
190
+ state: null,
191
+ events: [{ type: 'game_over' }],
192
+ },
193
+ };
194
+
195
+ await expect(sink.deliver(envelope, new AbortController().signal)).rejects.toMatchObject({
196
+ code: 'desktop_event_socket_disconnected',
197
+ retryable: true,
198
+ });
199
+ await vi.waitFor(() => expect(hellos).toHaveLength(2));
200
+ await expect(sink.deliver(envelope, new AbortController().signal)).resolves.toMatchObject({
201
+ acceptedAt: expect.any(String),
202
+ });
203
+ expect(hellos[1].connection_id).not.toBe(hellos[0].connection_id);
204
+
205
+ await sink.close();
206
+ });
207
+ });