@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,363 @@
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
+ activeResources: () => ({
200
+ locale: 'zh-CN',
201
+ strategy: {
202
+ id: 'normal-shrimp',
203
+ name: '普通虾',
204
+ description: '完成任务并保持警觉。',
205
+ },
206
+ perceptions: [{
207
+ id: 'visual.visibility',
208
+ name: '视野变化',
209
+ description: '感知其他玩家进入、离开或重新出现在视野中。',
210
+ }],
211
+ }),
212
+ });
213
+ pump = new MailboxEventBatchPump({
214
+ source: {
215
+ prepare: () => coordinator.prepareEvents({
216
+ deliveryVia: 'mailbox_full',
217
+ ownerIdPrefix: 'desktop_ipc_test',
218
+ }),
219
+ renew: (deliveryToken) => coordinator.renew(deliveryToken),
220
+ ack: (deliveryToken) => coordinator.ack(deliveryToken),
221
+ release: (deliveryToken) => coordinator.release(deliveryToken),
222
+ },
223
+ sink,
224
+ });
225
+ const mailbox = new ClawclawMailboxPlugin();
226
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([coordinator, pump]));
227
+ sink.start();
228
+
229
+ try {
230
+ await vi.waitFor(() => {
231
+ expect(received.filter(({ frame }) => frame.type === 'hello')).toHaveLength(1);
232
+ });
233
+ expect(received.find(({ frame }) => frame.type === 'hello')?.frame.active_resources)
234
+ .toMatchObject({
235
+ locale: 'zh-CN',
236
+ strategy: { id: 'normal-shrimp', name: '普通虾' },
237
+ perceptions: [{ id: 'visual.visibility', name: '视野变化' }],
238
+ });
239
+ expect(await mailbox.update({ pendingEvents: [] } as any)).toMatchObject({
240
+ outcome: 'noop',
241
+ reason: 'no_pending_events',
242
+ });
243
+
244
+ const internal = await publish(ingress, {
245
+ eventId: 'task-assigned-1',
246
+ type: 'task_assigned',
247
+ epochSeq: 1,
248
+ payload: { task_name: 'repair' },
249
+ });
250
+ ready = readyView(1, internal.commitSeq);
251
+ await mailbox.update({ pendingEvents: [internal] } as any);
252
+ await delay(AGENT_MAILBOX_COALESCE_MS + 60);
253
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(0);
254
+
255
+ const longText = `BEGIN-${'x'.repeat(70 * 1024)}-END`;
256
+ const speech = await publish(ingress, {
257
+ eventId: 'speech-1',
258
+ type: 'speech',
259
+ epochSeq: 2,
260
+ payload: { actor_name: 'player-2', text: longText },
261
+ });
262
+ expect(speech.deliveryClass).toBe('monitor_and_events');
263
+ ready = readyView(2, speech.commitSeq);
264
+ const firstObservedAt = Date.now();
265
+ await mailbox.update({ pendingEvents: [speech] } as any);
266
+ await delay(100);
267
+
268
+ const visual = await publish(ingress, {
269
+ eventId: 'visual-1',
270
+ type: 'visual.player_moved',
271
+ epochSeq: 3,
272
+ producer: 'local_synth',
273
+ payload: { text: 'player-2 moved through engine' },
274
+ });
275
+ ready = readyView(3, visual.commitSeq);
276
+ await mailbox.update({ pendingEvents: [visual] } as any);
277
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(0);
278
+
279
+ await vi.waitFor(() => {
280
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
281
+ }, { timeout: 2_000 });
282
+ const firstBatch = received.find(({ frame }) => frame.type === 'mailbox_batch')!;
283
+ expect(firstBatch.atMs - firstObservedAt).toBeGreaterThanOrEqual(
284
+ AGENT_MAILBOX_COALESCE_MS - 20,
285
+ );
286
+ expect(firstBatch.frame.payload).toMatchObject({
287
+ schema: 'clawclaw.channel-events.v1',
288
+ state: { phase: 'wandering', tick: 3 },
289
+ });
290
+ expect(firstBatch.frame.active_resources).toMatchObject({
291
+ locale: 'zh-CN',
292
+ strategy: { id: 'normal-shrimp', name: '普通虾' },
293
+ perceptions: [{ id: 'visual.visibility', name: '视野变化' }],
294
+ });
295
+ expect(firstBatch.frame.payload.events).toEqual([
296
+ 'visual.player_moved | player-2 moved through engine',
297
+ expect.objectContaining({ type: 'speech', text: longText }),
298
+ ]);
299
+ expect(Buffer.byteLength(JSON.stringify(firstBatch.frame.payload), 'utf8'))
300
+ .toBeGreaterThan(64 * 1024);
301
+ expect(JSON.stringify(firstBatch.frame.payload)).not.toContain('task_assigned');
302
+
303
+ sendAck(firstBatch, { seq: firstBatch.frame.seq + 1 });
304
+ await delay(40);
305
+ expect(repository.delivery(speech.eventId, 'local-agent')?.detailState).toBe('pending');
306
+ sendAck(firstBatch);
307
+ await vi.waitFor(() => {
308
+ expect(repository.delivery(speech.eventId, 'local-agent')).toMatchObject({
309
+ detailState: 'delivered',
310
+ detailDeliveryVia: 'mailbox_full',
311
+ });
312
+ });
313
+ await delay(300);
314
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
315
+
316
+ const boundaryEvent = await publish(ingress, {
317
+ eventId: 'speech-boundary',
318
+ type: 'speech',
319
+ epochSeq: 4,
320
+ payload: { actor_name: 'player-3', text: 'held behind ReadyView' },
321
+ });
322
+ const previousReady = ready;
323
+ disconnectNextBatch = true;
324
+ await mailbox.update({ pendingEvents: [boundaryEvent] } as any);
325
+ await delay(AGENT_MAILBOX_COALESCE_MS + 80);
326
+ expect(ready).toBe(previousReady);
327
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(1);
328
+
329
+ ready = readyView(4, boundaryEvent.commitSeq);
330
+ await vi.waitFor(() => {
331
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch').length)
332
+ .toBeGreaterThanOrEqual(2);
333
+ }, { timeout: 2_000 });
334
+ await vi.waitFor(() => {
335
+ expect(received.filter(({ frame }) => frame.type === 'hello')).toHaveLength(2);
336
+ }, { timeout: 2_000 });
337
+ await vi.waitFor(() => {
338
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(3);
339
+ }, { timeout: 2_000 });
340
+
341
+ const retries = received
342
+ .filter(({ frame }) => frame.type === 'mailbox_batch')
343
+ .slice(1);
344
+ expect(retries).toHaveLength(2);
345
+ expect(retries[0].frame.delivery_id).toBe(retries[1].frame.delivery_id);
346
+ expect(retries[0].frame.connection_id).not.toBe(retries[1].frame.connection_id);
347
+ expect(repository.delivery(boundaryEvent.eventId, 'local-agent')?.detailState)
348
+ .toBe('pending');
349
+
350
+ sendAck(retries[1]);
351
+ await vi.waitFor(() => {
352
+ expect(repository.delivery(boundaryEvent.eventId, 'local-agent')).toMatchObject({
353
+ detailState: 'delivered',
354
+ detailDeliveryVia: 'mailbox_full',
355
+ });
356
+ });
357
+ await delay(300);
358
+ expect(received.filter(({ frame }) => frame.type === 'mailbox_batch')).toHaveLength(3);
359
+ } finally {
360
+ await mailbox.stop('shutdown');
361
+ }
362
+ }, 10_000);
363
+ });
@@ -0,0 +1,236 @@
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 activeResources = {
89
+ locale: 'zh-CN',
90
+ strategy: null,
91
+ perceptions: [{
92
+ id: 'visual.motion',
93
+ name: '玩家移动',
94
+ description: '感知自己和可见玩家的连续移动片段及显著方向变化。',
95
+ }],
96
+ } as const;
97
+ const sink = new DesktopEventSocketSink({
98
+ socketPath,
99
+ token: '0123456789abcdef0123456789abcdef',
100
+ reconnectBaseMs: 10,
101
+ reconnectMaxMs: 20,
102
+ activeResources: () => activeResources,
103
+ });
104
+ sink.start();
105
+ await vi.waitFor(() => expect(frames[0]).toMatchObject({
106
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
107
+ type: 'hello',
108
+ token: '0123456789abcdef0123456789abcdef',
109
+ pid: process.pid,
110
+ active_resources: activeResources,
111
+ }));
112
+
113
+ const largeText = 'z'.repeat(70 * 1024);
114
+ const first = await sink.deliver({
115
+ deliveryId: 'delivery-1',
116
+ batch: {
117
+ state: { phase: 'meeting' },
118
+ events: [{ type: 'meeting_briefing', text: largeText }],
119
+ },
120
+ }, new AbortController().signal);
121
+ const second = await sink.deliver({
122
+ deliveryId: 'delivery-2',
123
+ batch: {
124
+ state: { phase: 'wandering' },
125
+ events: [{ type: 'speech_your_turn' }],
126
+ },
127
+ }, new AbortController().signal);
128
+
129
+ expect(first.receiptId).toBe('wake-1');
130
+ expect(second.receiptId).toBe('wake-2');
131
+ expect(connections).toHaveLength(1);
132
+ expect(frames.filter((frame) => frame.type === 'mailbox_batch')).toEqual([
133
+ expect.objectContaining({
134
+ seq: 1,
135
+ delivery_id: 'delivery-1',
136
+ active_resources: activeResources,
137
+ payload: expect.objectContaining({
138
+ schema: 'clawclaw.channel-events.v1',
139
+ events: [expect.objectContaining({ text: largeText })],
140
+ }),
141
+ }),
142
+ expect.objectContaining({ seq: 2, delivery_id: 'delivery-2' }),
143
+ ]);
144
+
145
+ await sink.close();
146
+ });
147
+
148
+ it('rejects an unacknowledged batch, reconnects, and permits the durable retry', async () => {
149
+ const pipeName = `ccl-desktop-retry-${randomUUID()}`;
150
+ const socketPath = process.platform === 'win32'
151
+ ? `\\\\.\\pipe\\${pipeName}`
152
+ : `/tmp/${pipeName}.sock`;
153
+ const hellos: Array<Record<string, any>> = [];
154
+ const batches: Array<Record<string, any>> = [];
155
+ let connectionNumber = 0;
156
+ const server = createServer((socket) => {
157
+ connectionNumber += 1;
158
+ const currentConnection = connectionNumber;
159
+ socket.setEncoding('utf8');
160
+ let buffer = '';
161
+ socket.on('data', (chunk: string) => {
162
+ buffer += chunk;
163
+ for (;;) {
164
+ const newline = buffer.indexOf('\n');
165
+ if (newline < 0) break;
166
+ const line = buffer.slice(0, newline);
167
+ buffer = buffer.slice(newline + 1);
168
+ if (!line.trim()) continue;
169
+ const frame = JSON.parse(line) as Record<string, any>;
170
+ if (frame.type === 'hello') hellos.push(frame);
171
+ if (frame.type !== 'mailbox_batch') continue;
172
+ batches.push(frame);
173
+ if (currentConnection === 1) {
174
+ socket.destroy();
175
+ continue;
176
+ }
177
+ socket.write(`${JSON.stringify({
178
+ schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
179
+ type: 'ack',
180
+ connection_id: frame.connection_id,
181
+ seq: frame.seq,
182
+ delivery_id: frame.delivery_id,
183
+ })}\n`);
184
+ }
185
+ });
186
+ });
187
+ servers.push(server);
188
+ await new Promise<void>((resolve, reject) => {
189
+ server.once('error', reject);
190
+ server.listen(socketPath, resolve);
191
+ });
192
+
193
+ let strategy = {
194
+ id: 'strategy-a',
195
+ name: '策略甲',
196
+ description: '策略甲描述。',
197
+ };
198
+ const sink = new DesktopEventSocketSink({
199
+ socketPath,
200
+ token: '0123456789abcdef0123456789abcdef',
201
+ reconnectBaseMs: 10,
202
+ reconnectMaxMs: 20,
203
+ activeResources: () => ({ locale: 'zh-CN', strategy, perceptions: [] }),
204
+ });
205
+ sink.start();
206
+ await vi.waitFor(() => expect(hellos).toHaveLength(1));
207
+ const envelope = {
208
+ deliveryId: 'durable-delivery',
209
+ batch: {
210
+ state: null,
211
+ events: [{ type: 'game_over' }],
212
+ },
213
+ };
214
+
215
+ await expect(sink.deliver(envelope, new AbortController().signal)).rejects.toMatchObject({
216
+ code: 'desktop_event_socket_disconnected',
217
+ retryable: true,
218
+ });
219
+ strategy = {
220
+ id: 'strategy-b',
221
+ name: '策略乙',
222
+ description: '策略乙描述。',
223
+ };
224
+ await vi.waitFor(() => expect(hellos).toHaveLength(2));
225
+ await expect(sink.deliver(envelope, new AbortController().signal)).resolves.toMatchObject({
226
+ acceptedAt: expect.any(String),
227
+ });
228
+ expect(hellos[1].connection_id).not.toBe(hellos[0].connection_id);
229
+ expect(hellos[1].active_resources.strategy.id).toBe('strategy-b');
230
+ expect(batches).toHaveLength(2);
231
+ expect(batches[0].active_resources.strategy.id).toBe('strategy-a');
232
+ expect(batches[1].active_resources.strategy.id).toBe('strategy-a');
233
+
234
+ await sink.close();
235
+ });
236
+ });