@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,113 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isTrainingRoomMode,
|
|
3
|
+
normalizeRoomSnapshot,
|
|
4
|
+
queueMode,
|
|
5
|
+
queueRoomCode,
|
|
6
|
+
queueStatus,
|
|
7
|
+
unwrapData,
|
|
8
|
+
} from './room.js';
|
|
9
|
+
|
|
10
|
+
export const GAME_STATUS_SCHEMA = 'ccl.game-status.v1' as const;
|
|
11
|
+
|
|
12
|
+
export type GameParticipationState =
|
|
13
|
+
| 'idle'
|
|
14
|
+
| 'matching'
|
|
15
|
+
| 'friend_room'
|
|
16
|
+
| 'training_room'
|
|
17
|
+
| 'in_game'
|
|
18
|
+
| 'room'
|
|
19
|
+
| 'unknown';
|
|
20
|
+
|
|
21
|
+
export interface GameParticipationStatus {
|
|
22
|
+
schema: typeof GAME_STATUS_SCHEMA;
|
|
23
|
+
status: GameParticipationState;
|
|
24
|
+
queue_status: string | null;
|
|
25
|
+
mode?: string;
|
|
26
|
+
room_code?: string;
|
|
27
|
+
room_type?: string;
|
|
28
|
+
room_status?: string;
|
|
29
|
+
game_id?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ParticipationStatusClient {
|
|
33
|
+
getQueueStatus(gameType?: string): Promise<any>;
|
|
34
|
+
getRoomStatus(): Promise<any>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function stringField(value: unknown): string | undefined {
|
|
38
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function withOptionalFields(
|
|
42
|
+
value: GameParticipationStatus,
|
|
43
|
+
fields: Partial<Pick<
|
|
44
|
+
GameParticipationStatus,
|
|
45
|
+
'mode' | 'room_code' | 'room_type' | 'room_status' | 'game_id'
|
|
46
|
+
>>,
|
|
47
|
+
): GameParticipationStatus {
|
|
48
|
+
if (fields.mode !== undefined) value.mode = fields.mode;
|
|
49
|
+
if (fields.room_code !== undefined) value.room_code = fields.room_code;
|
|
50
|
+
if (fields.room_type !== undefined) value.room_type = fields.room_type;
|
|
51
|
+
if (fields.room_status !== undefined) value.room_status = fields.room_status;
|
|
52
|
+
if (fields.game_id !== undefined) value.game_id = fields.game_id;
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Query the backend-owned participation state.
|
|
58
|
+
*
|
|
59
|
+
* Queue status is authoritative for idle/matching/game participation. A room
|
|
60
|
+
* lookup is needed only while in a room because queue status intentionally
|
|
61
|
+
* does not preserve the room type.
|
|
62
|
+
*/
|
|
63
|
+
export async function queryGameParticipationStatus(
|
|
64
|
+
client: ParticipationStatusClient,
|
|
65
|
+
): Promise<GameParticipationStatus> {
|
|
66
|
+
const queueResult = await client.getQueueStatus('clawclaw');
|
|
67
|
+
const queue = unwrapData(queueResult);
|
|
68
|
+
const currentQueueStatus = queueStatus(queueResult) ?? null;
|
|
69
|
+
const mode = queueMode(queueResult);
|
|
70
|
+
const roomCode = queueRoomCode(queueResult);
|
|
71
|
+
const base = (status: GameParticipationState): GameParticipationStatus =>
|
|
72
|
+
withOptionalFields({
|
|
73
|
+
schema: GAME_STATUS_SCHEMA,
|
|
74
|
+
status,
|
|
75
|
+
queue_status: currentQueueStatus,
|
|
76
|
+
}, {
|
|
77
|
+
mode,
|
|
78
|
+
room_code: roomCode,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
if (currentQueueStatus === 'not_in_queue') return base('idle');
|
|
82
|
+
|
|
83
|
+
if (
|
|
84
|
+
currentQueueStatus === 'queued'
|
|
85
|
+
|| currentQueueStatus === 'already_in_queue'
|
|
86
|
+
|| currentQueueStatus === 'allocating'
|
|
87
|
+
) {
|
|
88
|
+
return base('matching');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (currentQueueStatus === 'allocated') {
|
|
92
|
+
return withOptionalFields(base('in_game'), {
|
|
93
|
+
game_id: stringField(queue?.game_id),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (currentQueueStatus === 'in_room') {
|
|
98
|
+
const room = normalizeRoomSnapshot(await client.getRoomStatus());
|
|
99
|
+
const roomType = stringField(room.room_type);
|
|
100
|
+
const status: GameParticipationState = isTrainingRoomMode(roomType)
|
|
101
|
+
? 'training_room'
|
|
102
|
+
: roomType === 'casual'
|
|
103
|
+
? 'friend_room'
|
|
104
|
+
: 'room';
|
|
105
|
+
return withOptionalFields(base(status), {
|
|
106
|
+
room_code: stringField(room.room_code) ?? roomCode,
|
|
107
|
+
room_type: roomType,
|
|
108
|
+
room_status: stringField(room.status),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return base('unknown');
|
|
113
|
+
}
|
|
@@ -268,6 +268,23 @@ describe('event-format', () => {
|
|
|
268
268
|
}
|
|
269
269
|
});
|
|
270
270
|
|
|
271
|
+
it('mentions a newly assigned task only when task_completed carries one', () => {
|
|
272
|
+
expect(formatEventMessage({
|
|
273
|
+
type: 'task_completed',
|
|
274
|
+
task_name: '擦拭酒瓶',
|
|
275
|
+
newly_assigned_task: {
|
|
276
|
+
name: '消毒淋浴器',
|
|
277
|
+
room: '制氧舱',
|
|
278
|
+
x: 123,
|
|
279
|
+
y: 456,
|
|
280
|
+
},
|
|
281
|
+
})).toContain('任务完成:擦拭酒瓶;新分配任务:消毒淋浴器(制氧舱)');
|
|
282
|
+
expect(formatEventMessage({
|
|
283
|
+
type: 'task_completed',
|
|
284
|
+
task_name: '擦拭酒瓶',
|
|
285
|
+
})).toBe('tick=null task_completed 任务完成:擦拭酒瓶。');
|
|
286
|
+
});
|
|
287
|
+
|
|
271
288
|
it('formats room presence and idle lifecycle Events', () => {
|
|
272
289
|
expect(formatEventMessage({
|
|
273
290
|
type: 'room.member_status_changed', agent_id: 'agent-2', status: 'online',
|
|
@@ -363,7 +363,21 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
|
|
|
363
363
|
return `你误杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)},武士虾自爆出局。`;
|
|
364
364
|
case 'task_completed': {
|
|
365
365
|
const fakeNote = event.is_fake_shrimp ? '(伪装)' : '';
|
|
366
|
-
|
|
366
|
+
const assigned = event.newly_assigned_task;
|
|
367
|
+
const assignedTask = assigned && typeof assigned === 'object' && !Array.isArray(assigned)
|
|
368
|
+
? assigned as Record<string, any>
|
|
369
|
+
: null;
|
|
370
|
+
const assignedName = assignedTask ? firstString(assignedTask, ['name', 'task_name'], '') : '';
|
|
371
|
+
const assignedDetails = assignedTask
|
|
372
|
+
? [
|
|
373
|
+
stringValue(assignedTask.room),
|
|
374
|
+
assignedTask.is_fake_shrimp === true ? '伪装' : undefined,
|
|
375
|
+
].filter((value): value is string => value !== undefined)
|
|
376
|
+
: [];
|
|
377
|
+
const assignmentText = assignedName
|
|
378
|
+
? `;新分配任务:${assignedName}${assignedDetails.length > 0 ? `(${assignedDetails.join(',')})` : ''}`
|
|
379
|
+
: '';
|
|
380
|
+
return `任务完成:${firstString(event, ['task_name'])}${fakeNote}${assignmentText}。`;
|
|
367
381
|
}
|
|
368
382
|
case 'task_sabotaged':
|
|
369
383
|
return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
2
|
import type { CanonicalEvent } from '../runtime/framework/events/index.js';
|
|
3
3
|
import { presentCanonicalEvent } from './canonical-event-presentation.js';
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
normalizeGameSyncEvent,
|
|
6
|
+
normalizeGameSyncEvents,
|
|
7
|
+
} from './game-sync-event-normalization.js';
|
|
5
8
|
|
|
6
9
|
function canonical(event: Record<string, any>): CanonicalEvent {
|
|
7
10
|
const { type, ...payload } = event;
|
|
@@ -23,6 +26,60 @@ function canonical(event: Record<string, any>): CanonicalEvent {
|
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
describe('GameSync v2 Event normalization', () => {
|
|
29
|
+
it('enriches a task completion with its same-frame newly assigned task', () => {
|
|
30
|
+
const normalized = normalizeGameSyncEvents([{
|
|
31
|
+
event_id: 'completed-1',
|
|
32
|
+
tick: 42,
|
|
33
|
+
type: 'task_completed',
|
|
34
|
+
actor: { seat: 1, name: 'self' },
|
|
35
|
+
task_name: '擦拭酒瓶',
|
|
36
|
+
}, {
|
|
37
|
+
event_id: 'assigned-1',
|
|
38
|
+
tick: 42,
|
|
39
|
+
type: 'task_assigned',
|
|
40
|
+
actor: { seat: 1, name: 'self' },
|
|
41
|
+
task_name: '消毒淋浴器',
|
|
42
|
+
room: '制氧舱',
|
|
43
|
+
x: 123,
|
|
44
|
+
y: 456,
|
|
45
|
+
is_fake_shrimp: false,
|
|
46
|
+
}]);
|
|
47
|
+
|
|
48
|
+
expect(normalized[0]).toMatchObject({
|
|
49
|
+
type: 'task_completed',
|
|
50
|
+
task_name: '擦拭酒瓶',
|
|
51
|
+
newly_assigned_task: {
|
|
52
|
+
name: '消毒淋浴器',
|
|
53
|
+
room: '制氧舱',
|
|
54
|
+
x: 123,
|
|
55
|
+
y: 456,
|
|
56
|
+
is_fake_shrimp: false,
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
expect(normalized[1]).toMatchObject({
|
|
60
|
+
type: 'task_assigned',
|
|
61
|
+
task_name: '消毒淋浴器',
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('does not enrich a task completion without a same-tick assignment for the same player', () => {
|
|
66
|
+
const normalized = normalizeGameSyncEvents([{
|
|
67
|
+
event_id: 'completed-1',
|
|
68
|
+
tick: 42,
|
|
69
|
+
type: 'task_completed',
|
|
70
|
+
actor: { seat: 1, name: 'self' },
|
|
71
|
+
task_name: '擦拭酒瓶',
|
|
72
|
+
}, {
|
|
73
|
+
event_id: 'assigned-other',
|
|
74
|
+
tick: 43,
|
|
75
|
+
type: 'task_assigned',
|
|
76
|
+
actor: { seat: 1, name: 'self' },
|
|
77
|
+
task_name: '消毒淋浴器',
|
|
78
|
+
}]);
|
|
79
|
+
|
|
80
|
+
expect(normalized[0]).not.toHaveProperty('newly_assigned_task');
|
|
81
|
+
});
|
|
82
|
+
|
|
26
83
|
it('projects actor and target PlayerRefs to the established canonical fields', () => {
|
|
27
84
|
const wire = {
|
|
28
85
|
event_id: '68a339d7-c5f6-4eef-8f40-b8779ca8bfcc',
|
|
@@ -213,3 +213,54 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
|
|
|
213
213
|
|
|
214
214
|
return normalized;
|
|
215
215
|
}
|
|
216
|
+
|
|
217
|
+
function taskEventActorKey(event: Record<string, any>): string | null {
|
|
218
|
+
if (Number.isInteger(event.actor_seat)) return `seat:${String(event.actor_seat)}`;
|
|
219
|
+
return typeof event.actor_name === 'string' && event.actor_name.length > 0
|
|
220
|
+
? `name:${event.actor_name}`
|
|
221
|
+
: null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function newlyAssignedTask(event: Record<string, any>): Record<string, any> | null {
|
|
225
|
+
if (typeof event.task_name !== 'string' || event.task_name.length === 0) return null;
|
|
226
|
+
return {
|
|
227
|
+
name: event.task_name,
|
|
228
|
+
...(typeof event.room === 'string' && event.room.length > 0 ? { room: event.room } : {}),
|
|
229
|
+
...(typeof event.x === 'number' && Number.isFinite(event.x) ? { x: event.x } : {}),
|
|
230
|
+
...(typeof event.y === 'number' && Number.isFinite(event.y) ? { y: event.y } : {}),
|
|
231
|
+
...(typeof event.is_fake_shrimp === 'boolean'
|
|
232
|
+
? { is_fake_shrimp: event.is_fake_shrimp }
|
|
233
|
+
: {}),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Normalize one GameSync frame and enrich a completed task with its private,
|
|
239
|
+
* same-frame replacement assignment. The raw task_assigned Event remains in
|
|
240
|
+
* the batch for internal consumers; Agent delivery is still owned by the
|
|
241
|
+
* Event Catalog.
|
|
242
|
+
*/
|
|
243
|
+
export function normalizeGameSyncEvents(values: readonly unknown[]): Record<string, any>[] {
|
|
244
|
+
const normalized = values.map((value) => normalizeGameSyncEvent(value));
|
|
245
|
+
const claimedAssignments = new Set<number>();
|
|
246
|
+
|
|
247
|
+
return normalized.map((event, index) => {
|
|
248
|
+
if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return event;
|
|
249
|
+
const actorKey = taskEventActorKey(event);
|
|
250
|
+
if (!actorKey) return event;
|
|
251
|
+
|
|
252
|
+
const assignmentIndex = normalized.findIndex((candidate, candidateIndex) => (
|
|
253
|
+
candidateIndex > index
|
|
254
|
+
&& !claimedAssignments.has(candidateIndex)
|
|
255
|
+
&& candidate.type === 'task_assigned'
|
|
256
|
+
&& candidate.tick === event.tick
|
|
257
|
+
&& taskEventActorKey(candidate) === actorKey
|
|
258
|
+
));
|
|
259
|
+
if (assignmentIndex < 0) return event;
|
|
260
|
+
|
|
261
|
+
const task = newlyAssignedTask(normalized[assignmentIndex]);
|
|
262
|
+
if (!task) return event;
|
|
263
|
+
claimedAssignments.add(assignmentIndex);
|
|
264
|
+
return { ...event, newly_assigned_task: task };
|
|
265
|
+
});
|
|
266
|
+
}
|
|
@@ -44,11 +44,18 @@ import {
|
|
|
44
44
|
type ParentProcessWatchHandle,
|
|
45
45
|
} from '../parent-process-watch.js';
|
|
46
46
|
import { BufferedRawWsLog, ownerRawWsLogPath } from '../raw-ws-log.js';
|
|
47
|
+
import { presentCanonicalEventForCclEvents } from '../../pipeline/canonical-event-presentation.js';
|
|
48
|
+
import { compactStateForEvents } from '../../pipeline/event-format.js';
|
|
47
49
|
import { createClawclawRuntime } from './runtime.js';
|
|
48
50
|
import { assembleClawclawPlugins } from './plugins/assembly.js';
|
|
49
51
|
import {
|
|
50
52
|
ClawclawMailboxPlugin,
|
|
51
53
|
ClawclawMailboxService,
|
|
54
|
+
CompositeClawclawMailboxDriver,
|
|
55
|
+
DesktopEventSocketSink,
|
|
56
|
+
AgentMailboxCoordinator,
|
|
57
|
+
MailboxEventBatchPump,
|
|
58
|
+
type DesktopEventSocketConfig,
|
|
52
59
|
} from './plugins/mailbox/index.js';
|
|
53
60
|
import {
|
|
54
61
|
resolveDefaultClawclawStrategies,
|
|
@@ -72,6 +79,8 @@ export interface ClawclawOwnerOptions {
|
|
|
72
79
|
forceExistingRuntime?: boolean;
|
|
73
80
|
epochPlugins?: RuntimeEpochPlugin<Record<string, any>, Record<string, unknown>>[];
|
|
74
81
|
notificationHost?: ClawclawOwnerNotificationHost;
|
|
82
|
+
/** Desktop Host adapter for this run; Channels can be wired as a sibling adapter later. */
|
|
83
|
+
desktopEvents?: DesktopEventSocketConfig;
|
|
75
84
|
}
|
|
76
85
|
|
|
77
86
|
export interface ClawclawOwnerRuntimeStart {
|
|
@@ -466,6 +475,8 @@ export async function runClawclawOwner(
|
|
|
466
475
|
let source: ClawclawSourcePlugin | undefined;
|
|
467
476
|
let mailbox: ClawclawMailboxPlugin | undefined;
|
|
468
477
|
let mailboxService: ClawclawMailboxService | undefined;
|
|
478
|
+
let agentMailbox: AgentMailboxCoordinator | undefined;
|
|
479
|
+
let desktopEventPump: MailboxEventBatchPump | undefined;
|
|
469
480
|
let mailboxBroker: MailboxRelayBroker | undefined;
|
|
470
481
|
let ownerControl: OwnerControlServer | undefined;
|
|
471
482
|
let runtimePointer: OwnerRuntimePointer | undefined;
|
|
@@ -535,12 +546,51 @@ export async function runClawclawOwner(
|
|
|
535
546
|
throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
|
|
536
547
|
}
|
|
537
548
|
const mailboxRepository = runtime.repository;
|
|
549
|
+
agentMailbox = new AgentMailboxCoordinator({
|
|
550
|
+
repository: mailboxRepository,
|
|
551
|
+
readyView: () => runtime!.readReadyView(0, 1),
|
|
552
|
+
presentEvent: presentCanonicalEventForCclEvents,
|
|
553
|
+
compactState: compactStateForEvents,
|
|
554
|
+
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
555
|
+
});
|
|
538
556
|
mailboxService = new ClawclawMailboxService({
|
|
539
557
|
repository: mailboxRepository,
|
|
540
558
|
readyView: () => runtime!.readReadyView(0, 1),
|
|
559
|
+
agentMailbox,
|
|
560
|
+
monitorEnabled: !options.desktopEvents,
|
|
541
561
|
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
542
562
|
});
|
|
543
|
-
|
|
563
|
+
if (options.desktopEvents) {
|
|
564
|
+
const desktopSink = new DesktopEventSocketSink({
|
|
565
|
+
...options.desktopEvents,
|
|
566
|
+
onConnected: () => desktopEventPump?.retryNow(),
|
|
567
|
+
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
568
|
+
});
|
|
569
|
+
desktopEventPump = new MailboxEventBatchPump({
|
|
570
|
+
source: {
|
|
571
|
+
prepare: () => agentMailbox!.prepareEvents({
|
|
572
|
+
deliveryVia: 'mailbox_full',
|
|
573
|
+
ownerIdPrefix: 'desktop_ipc',
|
|
574
|
+
}),
|
|
575
|
+
renew: (deliveryToken) => agentMailbox!.renew(deliveryToken),
|
|
576
|
+
ack: (deliveryToken) => agentMailbox!.ack(deliveryToken),
|
|
577
|
+
release: (deliveryToken) => agentMailbox!.release(deliveryToken),
|
|
578
|
+
},
|
|
579
|
+
sink: desktopSink,
|
|
580
|
+
diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
|
|
581
|
+
});
|
|
582
|
+
mailbox.attachDriver(new CompositeClawclawMailboxDriver([
|
|
583
|
+
mailboxService,
|
|
584
|
+
agentMailbox,
|
|
585
|
+
desktopEventPump,
|
|
586
|
+
]));
|
|
587
|
+
desktopSink.start();
|
|
588
|
+
} else {
|
|
589
|
+
mailbox.attachDriver(new CompositeClawclawMailboxDriver([
|
|
590
|
+
mailboxService,
|
|
591
|
+
agentMailbox,
|
|
592
|
+
]));
|
|
593
|
+
}
|
|
544
594
|
const ownerSource = new ClawclawSourcePlugin({
|
|
545
595
|
client,
|
|
546
596
|
profile: options.profile,
|
|
@@ -601,7 +651,7 @@ export async function runClawclawOwner(
|
|
|
601
651
|
});
|
|
602
652
|
return eventsQueryBarrier;
|
|
603
653
|
};
|
|
604
|
-
if (options.notificationHost) {
|
|
654
|
+
if (options.notificationHost && !options.desktopEvents) {
|
|
605
655
|
mailboxBroker = new MailboxRelayBroker(
|
|
606
656
|
mailboxRepository,
|
|
607
657
|
'short',
|
|
@@ -898,11 +948,14 @@ export async function runClawclawOwner(
|
|
|
898
948
|
process.on('SIGINT', onSignal);
|
|
899
949
|
process.on('SIGTERM', onSignal);
|
|
900
950
|
await runtime.startSourcePlugin(ownerSource);
|
|
951
|
+
await desktopEventPump?.flush();
|
|
901
952
|
if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' });
|
|
902
|
-
options.notificationHost?.markMailboxReady();
|
|
953
|
+
if (!options.desktopEvents) options.notificationHost?.markMailboxReady();
|
|
903
954
|
const completion = await source.waitForCompletion();
|
|
904
955
|
await runtime.flush();
|
|
905
956
|
await mailboxService.flush();
|
|
957
|
+
await agentMailbox.flush();
|
|
958
|
+
await desktopEventPump?.drain();
|
|
906
959
|
if (mailboxBroker && !(await waitForMailboxDrain(mailboxBroker))) {
|
|
907
960
|
runtime.diagnostic('runtime.shutdown.mailbox_drain_incomplete', {
|
|
908
961
|
timeout_ms: MAILBOX_DRAIN_TIMEOUT_MS,
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
|
|
3
|
+
import {
|
|
4
|
+
EventIngress,
|
|
5
|
+
MemoryEventRepository,
|
|
6
|
+
type CanonicalEvent,
|
|
7
|
+
} from '../../../framework/events/index.js';
|
|
8
|
+
import type { RuntimeReadyView } from '../../../framework/runtime.js';
|
|
9
|
+
import {
|
|
10
|
+
AGENT_MAILBOX_COALESCE_MS,
|
|
11
|
+
AgentMailboxCoordinator,
|
|
12
|
+
} from './agent-mailbox-coordinator.js';
|
|
13
|
+
|
|
14
|
+
const START_MS = Date.parse('2026-08-04T00:00:00.000Z');
|
|
15
|
+
|
|
16
|
+
function readyView(epochSeq: number, eventWatermark: number): RuntimeReadyView {
|
|
17
|
+
const scope = {
|
|
18
|
+
adapterId: 'clawclaw',
|
|
19
|
+
accountId: 'account-1',
|
|
20
|
+
sessionId: 'session-1',
|
|
21
|
+
segmentId: 'segment-1',
|
|
22
|
+
segmentSeq: 1,
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
scope,
|
|
26
|
+
state: {
|
|
27
|
+
state: { phase: 'wandering', tick: epochSeq },
|
|
28
|
+
stateStatus: {
|
|
29
|
+
status: 'fresh',
|
|
30
|
+
semantics: 'latest_received',
|
|
31
|
+
source: 'owner_memory',
|
|
32
|
+
scope,
|
|
33
|
+
connectionId: 'connection-1',
|
|
34
|
+
connectionState: 'connected',
|
|
35
|
+
receivedAtMs: START_MS,
|
|
36
|
+
ageMs: 0,
|
|
37
|
+
backendTick: epochSeq,
|
|
38
|
+
reason: null,
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
pluginStates: {},
|
|
42
|
+
pluginOutcomes: {},
|
|
43
|
+
events: [],
|
|
44
|
+
throughCommitSeq: eventWatermark,
|
|
45
|
+
frameSeq: epochSeq,
|
|
46
|
+
eventWatermark,
|
|
47
|
+
epochSeq,
|
|
48
|
+
hasMore: false,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fixture() {
|
|
53
|
+
const repository = new MemoryEventRepository();
|
|
54
|
+
repository.saveSession({
|
|
55
|
+
sessionId: 'session-1',
|
|
56
|
+
adapterId: 'clawclaw',
|
|
57
|
+
accountId: 'account-1',
|
|
58
|
+
status: 'open',
|
|
59
|
+
isCurrent: true,
|
|
60
|
+
openedAt: new Date(START_MS).toISOString(),
|
|
61
|
+
});
|
|
62
|
+
repository.saveSegment({
|
|
63
|
+
segmentId: 'segment-1',
|
|
64
|
+
sessionId: 'session-1',
|
|
65
|
+
sequence: 1,
|
|
66
|
+
kind: 'game',
|
|
67
|
+
status: 'open',
|
|
68
|
+
isCurrent: true,
|
|
69
|
+
openedAt: new Date(START_MS).toISOString(),
|
|
70
|
+
});
|
|
71
|
+
const ingress = new EventIngress(repository, createClawclawEventCatalog());
|
|
72
|
+
let nowMs = START_MS;
|
|
73
|
+
let ready = readyView(1, 0);
|
|
74
|
+
const coordinator = new AgentMailboxCoordinator({
|
|
75
|
+
repository,
|
|
76
|
+
readyView: () => structuredClone(ready),
|
|
77
|
+
presentEvent: (event) => ({
|
|
78
|
+
type: event.type,
|
|
79
|
+
...(typeof event.payload.text === 'string' ? { text: event.payload.text } : {}),
|
|
80
|
+
}),
|
|
81
|
+
compactState: (state) => state
|
|
82
|
+
? { phase: state.phase, tick: state.tick }
|
|
83
|
+
: null,
|
|
84
|
+
now: () => nowMs,
|
|
85
|
+
});
|
|
86
|
+
return {
|
|
87
|
+
repository,
|
|
88
|
+
ingress,
|
|
89
|
+
coordinator,
|
|
90
|
+
advance: (milliseconds: number) => { nowMs += milliseconds; },
|
|
91
|
+
setReady: (epochSeq: number, watermark: number) => {
|
|
92
|
+
ready = readyView(epochSeq, watermark);
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function publish(
|
|
98
|
+
ingress: EventIngress,
|
|
99
|
+
eventId: string,
|
|
100
|
+
type: string,
|
|
101
|
+
epochSeq: number,
|
|
102
|
+
payload: Record<string, unknown> = {},
|
|
103
|
+
): Promise<CanonicalEvent> {
|
|
104
|
+
return (await ingress.publish({
|
|
105
|
+
eventId,
|
|
106
|
+
epochSeq,
|
|
107
|
+
type,
|
|
108
|
+
producer: 'backend_push',
|
|
109
|
+
sessionId: 'session-1',
|
|
110
|
+
segmentId: 'segment-1',
|
|
111
|
+
payload,
|
|
112
|
+
source: { sourceId: 'game-ws', eventId: `remote:${eventId}` },
|
|
113
|
+
})).event;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
describe('AgentMailboxCoordinator', () => {
|
|
117
|
+
it('uses one fixed coalescing window without extending it for later Events', async () => {
|
|
118
|
+
const { ingress, coordinator, advance, setReady } = fixture();
|
|
119
|
+
const first = await publish(ingress, 'speech-1', 'speech', 1, { text: 'first' });
|
|
120
|
+
coordinator.observeEvents([first]);
|
|
121
|
+
setReady(1, first.commitSeq);
|
|
122
|
+
|
|
123
|
+
advance(100);
|
|
124
|
+
const second = await publish(ingress, 'speech-2', 'speech', 2, { text: 'second' });
|
|
125
|
+
coordinator.observeEvents([second]);
|
|
126
|
+
setReady(2, second.commitSeq);
|
|
127
|
+
|
|
128
|
+
advance(AGENT_MAILBOX_COALESCE_MS - 101);
|
|
129
|
+
const waiting = coordinator.prepareEvents();
|
|
130
|
+
expect(waiting.deliveryToken).toBeUndefined();
|
|
131
|
+
expect(waiting.nextAttemptAtMs).toBe(START_MS + AGENT_MAILBOX_COALESCE_MS);
|
|
132
|
+
|
|
133
|
+
advance(1);
|
|
134
|
+
const prepared = coordinator.prepareEvents();
|
|
135
|
+
expect(prepared.deliveryToken).toBeTypeOf('string');
|
|
136
|
+
expect(prepared.batch.events).toEqual([
|
|
137
|
+
{ type: 'speech', text: 'second' },
|
|
138
|
+
{ type: 'speech', text: 'first' },
|
|
139
|
+
]);
|
|
140
|
+
expect(coordinator.ack(prepared.deliveryToken!)).toBe(true);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('excludes internal facts and preserves Agent payloads larger than 64 KiB', async () => {
|
|
144
|
+
const { repository, ingress, coordinator, advance, setReady } = fixture();
|
|
145
|
+
const internal = await publish(ingress, 'task-1', 'task_assigned', 1, {
|
|
146
|
+
task_name: 'wires',
|
|
147
|
+
});
|
|
148
|
+
const text = `BEGIN-${'x'.repeat(64 * 1024)}-END`;
|
|
149
|
+
const visible = await publish(ingress, 'speech-long', 'speech', 1, { text });
|
|
150
|
+
coordinator.observeEvents([internal, visible]);
|
|
151
|
+
setReady(1, visible.commitSeq);
|
|
152
|
+
advance(AGENT_MAILBOX_COALESCE_MS);
|
|
153
|
+
|
|
154
|
+
const prepared = coordinator.prepareEvents();
|
|
155
|
+
expect(prepared.batch.events).toEqual([{ type: 'speech', text }]);
|
|
156
|
+
expect(Buffer.byteLength(JSON.stringify(prepared.batch), 'utf8')).toBeGreaterThan(64 * 1024);
|
|
157
|
+
expect(repository.delivery(internal.eventId, 'local-agent')?.detailState)
|
|
158
|
+
.toBe('not_applicable');
|
|
159
|
+
expect(coordinator.ack(prepared.deliveryToken!)).toBe(true);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('owns one details lease and only advances delivery after ACK', async () => {
|
|
163
|
+
const { repository, ingress, coordinator, advance, setReady } = fixture();
|
|
164
|
+
const event = await publish(ingress, 'speech-1', 'speech', 1, { text: 'lease me' });
|
|
165
|
+
coordinator.observeEvents([event]);
|
|
166
|
+
setReady(1, event.commitSeq);
|
|
167
|
+
advance(AGENT_MAILBOX_COALESCE_MS);
|
|
168
|
+
|
|
169
|
+
const first = coordinator.prepareEvents();
|
|
170
|
+
expect(first.deliveryToken).toBeTypeOf('string');
|
|
171
|
+
expect(coordinator.renew(first.deliveryToken!)).toBe(true);
|
|
172
|
+
expect(() => coordinator.prepareEvents()).toThrow('agent_mailbox_delivery_busy');
|
|
173
|
+
expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('pending');
|
|
174
|
+
expect(repository.acquireLease({
|
|
175
|
+
consumerId: 'local-agent',
|
|
176
|
+
channel: 'details',
|
|
177
|
+
ownerId: 'competing-adapter',
|
|
178
|
+
ttlMs: 1_000,
|
|
179
|
+
nowMs: START_MS + AGENT_MAILBOX_COALESCE_MS,
|
|
180
|
+
})).toBeNull();
|
|
181
|
+
|
|
182
|
+
expect(coordinator.release(first.deliveryToken!)).toBe(true);
|
|
183
|
+
expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('pending');
|
|
184
|
+
|
|
185
|
+
const retried = coordinator.prepareEvents();
|
|
186
|
+
expect(coordinator.ack(retried.deliveryToken!)).toBe(true);
|
|
187
|
+
expect(repository.delivery(event.eventId, 'local-agent')?.detailState).toBe('delivered');
|
|
188
|
+
});
|
|
189
|
+
});
|