@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,111 @@
1
+ import { ApiError } from './http-transport.js';
2
+
3
+ export type ServiceStatus = 'available' | 'maintenance_upcoming' | 'maintenance_active';
4
+
5
+ export interface MaintenanceWindow {
6
+ starts_at: string;
7
+ ends_at: string;
8
+ }
9
+
10
+ export interface ServerServiceStatus {
11
+ service_status: ServiceStatus;
12
+ maintenance?: MaintenanceWindow;
13
+ retry_after_seconds?: number;
14
+ }
15
+
16
+ function objectValue(value: unknown): Record<string, unknown> | undefined {
17
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
18
+ ? value as Record<string, unknown>
19
+ : undefined;
20
+ }
21
+
22
+ function serviceStatusValue(value: unknown): ServiceStatus | undefined {
23
+ return value === 'available'
24
+ || value === 'maintenance_upcoming'
25
+ || value === 'maintenance_active'
26
+ ? value
27
+ : undefined;
28
+ }
29
+
30
+ function maintenanceWindow(value: unknown): MaintenanceWindow | undefined {
31
+ const root = objectValue(value);
32
+ if (!root) return undefined;
33
+ const startsAt = typeof root.starts_at === 'string' ? root.starts_at : undefined;
34
+ const endsAt = typeof root.ends_at === 'string' ? root.ends_at : undefined;
35
+ return startsAt && endsAt ? { starts_at: startsAt, ends_at: endsAt } : undefined;
36
+ }
37
+
38
+ function retryAfterSeconds(value: unknown): number | undefined {
39
+ if (typeof value !== 'string' && typeof value !== 'number') return undefined;
40
+ const parsed = Number(value);
41
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;
42
+ }
43
+
44
+ /** Parse the public server-status shape itself, without assigning transport behavior. */
45
+ export function parseServerServiceStatus(value: unknown): ServerServiceStatus | undefined {
46
+ const root = objectValue(value);
47
+ if (!root) return undefined;
48
+ const status = serviceStatusValue(root.service_status);
49
+ if (!status) return undefined;
50
+ const maintenance = maintenanceWindow(root.maintenance);
51
+ return {
52
+ service_status: status,
53
+ ...(maintenance ? { maintenance } : {}),
54
+ };
55
+ }
56
+
57
+ /** Extract the optional top-level `server` metadata added to successful Lobby responses. */
58
+ export function serverServiceStatusFromEnvelope(value: unknown): ServerServiceStatus | undefined {
59
+ return parseServerServiceStatus(objectValue(value)?.server);
60
+ }
61
+
62
+ /** Extract an active-maintenance fact from the structured Lobby 503 response. */
63
+ export function serverServiceStatusFromApiError(error: unknown): ServerServiceStatus | undefined {
64
+ if (!(error instanceof ApiError)) return undefined;
65
+ let root: Record<string, unknown> | undefined;
66
+ if (error.response?.body.kind === 'json') {
67
+ root = objectValue(error.response.body.value);
68
+ }
69
+ if (!root) {
70
+ try {
71
+ root = objectValue(JSON.parse(error.body));
72
+ } catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ const errorValue = objectValue(root?.error);
77
+ const status = parseServerServiceStatus(root?.server);
78
+ if (
79
+ errorValue?.code !== 'SERVICE_MAINTENANCE'
80
+ && status?.service_status !== 'maintenance_active'
81
+ ) return undefined;
82
+ if (!status) return undefined;
83
+ const retryAfter = retryAfterSeconds(error.response?.headers['retry-after']);
84
+ return {
85
+ ...status,
86
+ ...(retryAfter === undefined ? {} : { retry_after_seconds: retryAfter }),
87
+ };
88
+ }
89
+
90
+ export function isServiceMaintenanceApiError(error: unknown): boolean {
91
+ return serverServiceStatusFromApiError(error)?.service_status === 'maintenance_active';
92
+ }
93
+
94
+ export function serviceStatusEvent(status: ServerServiceStatus): Record<string, unknown> {
95
+ return {
96
+ type: 'service_status',
97
+ service_status: status.service_status,
98
+ ...(status.maintenance ? { maintenance: structuredClone(status.maintenance) } : {}),
99
+ ...(status.retry_after_seconds === undefined
100
+ ? {}
101
+ : { retry_after_seconds: status.retry_after_seconds }),
102
+ };
103
+ }
104
+
105
+ export function serviceStatusSignature(status: ServerServiceStatus): string {
106
+ return JSON.stringify([
107
+ status.service_status,
108
+ status.maintenance?.starts_at ?? null,
109
+ status.maintenance?.ends_at ?? null,
110
+ ]);
111
+ }
@@ -3,6 +3,19 @@ import { compactEventFields, compactStateForEvents, formatEventMessage, shortSta
3
3
  import { BACKEND_EVENT_HINT_FORMATTERS } from './event-hints.js';
4
4
 
5
5
  describe('event-format', () => {
6
+ it('formats upcoming and active maintenance as explicit service messages', () => {
7
+ const maintenance = {
8
+ starts_at: '2026-08-05T01:00:00+00:00',
9
+ ends_at: '2026-08-05T03:00:00+00:00',
10
+ };
11
+ expect(formatEventMessage({
12
+ type: 'service_status', service_status: 'maintenance_upcoming', maintenance,
13
+ })).toContain('当前请求仍可继续');
14
+ expect(formatEventMessage({
15
+ type: 'service_status', service_status: 'maintenance_active', maintenance,
16
+ })).toContain('新的匹配和房间操作已停止');
17
+ });
18
+
6
19
  it('formats killed as a short message and keeps direct compaction separate from presentation ownership', () => {
7
20
  const event = {
8
21
  type: 'killed',
@@ -268,6 +281,23 @@ describe('event-format', () => {
268
281
  }
269
282
  });
270
283
 
284
+ it('mentions a newly assigned task only when task_completed carries one', () => {
285
+ expect(formatEventMessage({
286
+ type: 'task_completed',
287
+ task_name: '擦拭酒瓶',
288
+ newly_assigned_task: {
289
+ name: '消毒淋浴器',
290
+ room: '制氧舱',
291
+ x: 123,
292
+ y: 456,
293
+ },
294
+ })).toContain('任务完成:擦拭酒瓶;新分配任务:消毒淋浴器(制氧舱)');
295
+ expect(formatEventMessage({
296
+ type: 'task_completed',
297
+ task_name: '擦拭酒瓶',
298
+ })).toBe('tick=null task_completed 任务完成:擦拭酒瓶。');
299
+ });
300
+
271
301
  it('formats room presence and idle lifecycle Events', () => {
272
302
  expect(formatEventMessage({
273
303
  type: 'room.member_status_changed', agent_id: 'agent-2', status: 'online',
@@ -338,6 +338,17 @@ function playersChangedBody(event: Record<string, any>, ctx: EventFormatContext)
338
338
  function shortBody(event: Record<string, any>, ctx: EventFormatContext): string {
339
339
  const maxTextLength = ctx.maxTextLength ?? 100;
340
340
  switch (event.type) {
341
+ case 'service_status': {
342
+ const startsAt = firstString(event.maintenance ?? {}, ['starts_at'], '计划时间未知');
343
+ const endsAt = firstString(event.maintenance ?? {}, ['ends_at'], '恢复时间未知');
344
+ if (event.service_status === 'maintenance_upcoming') {
345
+ return `服务器计划于${startsAt}开始维护,预计${endsAt}恢复;当前请求仍可继续。`;
346
+ }
347
+ if (event.service_status === 'maintenance_active') {
348
+ return `服务器正在维护,预计${endsAt}恢复;新的匹配和房间操作已停止。`;
349
+ }
350
+ return '服务器维护已结束,服务恢复可用。';
351
+ }
341
352
  case 'game_started': {
342
353
  const playerCount = numberValue(event.player_count);
343
354
  const countText = playerCount === undefined ? '对局开始' : `对局开始:${playerCount}名玩家`;
@@ -363,7 +374,21 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
363
374
  return `你误杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)},武士虾自爆出局。`;
364
375
  case 'task_completed': {
365
376
  const fakeNote = event.is_fake_shrimp ? '(伪装)' : '';
366
- return `任务完成:${firstString(event, ['task_name'])}${fakeNote}。`;
377
+ const assigned = event.newly_assigned_task;
378
+ const assignedTask = assigned && typeof assigned === 'object' && !Array.isArray(assigned)
379
+ ? assigned as Record<string, any>
380
+ : null;
381
+ const assignedName = assignedTask ? firstString(assignedTask, ['name', 'task_name'], '') : '';
382
+ const assignedDetails = assignedTask
383
+ ? [
384
+ stringValue(assignedTask.room),
385
+ assignedTask.is_fake_shrimp === true ? '伪装' : undefined,
386
+ ].filter((value): value is string => value !== undefined)
387
+ : [];
388
+ const assignmentText = assignedName
389
+ ? `;新分配任务:${assignedName}${assignedDetails.length > 0 ? `(${assignedDetails.join(',')})` : ''}`
390
+ : '';
391
+ return `任务完成:${firstString(event, ['task_name'])}${fakeNote}${assignmentText}。`;
367
392
  }
368
393
  case 'task_sabotaged':
369
394
  return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
@@ -11,12 +11,12 @@ import {
11
11
  } from './event-hints.js';
12
12
 
13
13
  describe('Mailbox-owned Event hint registries', () => {
14
- it('keeps 30 backend hint formatters and classifies 14 Agent Events as unregistered', () => {
14
+ it('keeps 31 backend hint formatters and classifies 14 Agent Events as unregistered', () => {
15
15
  const unregistered = CLAWCLAW_BACKEND_AGENT_EVENT_TYPES.filter((type) => (
16
16
  BACKEND_EVENT_HINT_FORMATTERS[type] === undefined
17
17
  ));
18
18
 
19
- expect(Object.keys(BACKEND_EVENT_HINT_FORMATTERS)).toHaveLength(30);
19
+ expect(Object.keys(BACKEND_EVENT_HINT_FORMATTERS)).toHaveLength(31);
20
20
  expect(unregistered).toEqual([
21
21
  'task_completed',
22
22
  'task_sabotaged',
@@ -35,6 +35,21 @@ describe('Mailbox-owned Event hint registries', () => {
35
35
  ]);
36
36
  });
37
37
 
38
+ it('tells the Agent when maintenance permits or blocks Lobby operations', () => {
39
+ const maintenance = {
40
+ starts_at: '2026-08-05T01:00:00+00:00',
41
+ ends_at: '2026-08-05T03:00:00+00:00',
42
+ };
43
+ expect(formatCanonicalEventHint(
44
+ { producer: 'backend_push' },
45
+ { type: 'service_status', service_status: 'maintenance_upcoming', maintenance },
46
+ )).toContain('current request succeeded');
47
+ expect(formatCanonicalEventHint(
48
+ { producer: 'backend_push' },
49
+ { type: 'service_status', service_status: 'maintenance_active', maintenance },
50
+ )).toContain('Do not retry matchmaking');
51
+ });
52
+
38
53
  it('classifies Source and Derived lifecycle Events with players_changed factual-only', () => {
39
54
  const excluded = new Set(['robot_speak_rule', 'strategy_alert']);
40
55
  const sourceTypes = CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter((type) => (
@@ -235,7 +250,7 @@ describe('Mailbox-owned Event hint registries', () => {
235
250
  ...Object.values(DERIVED_EVENT_HINT_FORMATTERS).map((formatter) => formatter(sample, {})),
236
251
  ].filter((hint): hint is string => typeof hint === 'string');
237
252
 
238
- expect(hints).toHaveLength(50);
253
+ expect(hints).toHaveLength(51);
239
254
  for (const hint of hints) expect(hint).not.toMatch(/[一-鿿]/);
240
255
  });
241
256
  });
@@ -110,6 +110,17 @@ function meetingBriefingHint(event: Record<string, any>): string | undefined {
110
110
  }
111
111
 
112
112
  export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
113
+ service_status: (event) => {
114
+ const startsAt = text(event.maintenance?.starts_at, 'the scheduled start time');
115
+ const endsAt = text(event.maintenance?.ends_at, 'the scheduled end time');
116
+ if (event.service_status === 'maintenance_upcoming') {
117
+ return `Tell the user that maintenance is scheduled from ${startsAt} to ${endsAt}. The current request succeeded and may continue; do not start an extra runtime.`;
118
+ }
119
+ if (event.service_status === 'maintenance_active') {
120
+ return `Tell the user that the service is under maintenance until ${endsAt}. Do not retry matchmaking, room creation, room joining, or room start before then; query server status before trying again.`;
121
+ }
122
+ return 'The service is available again. Tell the user if they were waiting, but do not replay a previously blocked request unless they still want it.';
123
+ },
113
124
  move_interrupted: (event) => {
114
125
  const nearby = Array.isArray(event.nearby_players)
115
126
  ? event.nearby_players.map((player: any) => text(player?.name, '')).filter(Boolean).slice(0, 3)
@@ -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 { normalizeGameSyncEvent } from './game-sync-event-normalization.js';
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
+ }
@@ -10,6 +10,10 @@ describe('ClawClaw Monitor Event policy', () => {
10
10
  .toBeGreaterThan(clawclawMonitorPriority('speech'));
11
11
  });
12
12
 
13
+ it('prioritizes service availability changes', () => {
14
+ expect(clawclawMonitorPriority('service_status')).toBe(95);
15
+ });
16
+
13
17
  it('uses the default priority for unlisted Events', () => {
14
18
  expect(clawclawMonitorPriority('speech')).toBe(50);
15
19
  });
@@ -1,6 +1,7 @@
1
1
  const DEFAULT_MONITOR_PRIORITY = 50;
2
2
 
3
3
  export const CLAWCLAW_MONITOR_EVENT_PRIORITY: Readonly<Record<string, number>> = Object.freeze({
4
+ service_status: 95,
4
5
  killed: 99,
5
6
  speech_your_turn: 99,
6
7
  vote_phase_start: 99,
@@ -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 {
@@ -155,6 +164,7 @@ interface OwnerRuntimePointer {
155
164
  }
156
165
 
157
166
  const MAILBOX_DRAIN_TIMEOUT_MS = 2_000;
167
+ const DESKTOP_RESOURCE_LOCALE = 'zh-CN';
158
168
  const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 10_000;
159
169
  const LOCAL_STOP_FORCE_EXIT_MS = 10_000;
160
170
  const FORCE_STOP_GRACE_MS = 1_500;
@@ -466,6 +476,8 @@ export async function runClawclawOwner(
466
476
  let source: ClawclawSourcePlugin | undefined;
467
477
  let mailbox: ClawclawMailboxPlugin | undefined;
468
478
  let mailboxService: ClawclawMailboxService | undefined;
479
+ let agentMailbox: AgentMailboxCoordinator | undefined;
480
+ let desktopEventPump: MailboxEventBatchPump | undefined;
469
481
  let mailboxBroker: MailboxRelayBroker | undefined;
470
482
  let ownerControl: OwnerControlServer | undefined;
471
483
  let runtimePointer: OwnerRuntimePointer | undefined;
@@ -535,12 +547,56 @@ export async function runClawclawOwner(
535
547
  throw new Error('The configured Runtime repository does not support durable Mailbox delivery.');
536
548
  }
537
549
  const mailboxRepository = runtime.repository;
550
+ agentMailbox = new AgentMailboxCoordinator({
551
+ repository: mailboxRepository,
552
+ readyView: () => runtime!.readReadyView(0, 1),
553
+ presentEvent: presentCanonicalEventForCclEvents,
554
+ compactState: compactStateForEvents,
555
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
556
+ });
538
557
  mailboxService = new ClawclawMailboxService({
539
558
  repository: mailboxRepository,
540
559
  readyView: () => runtime!.readReadyView(0, 1),
560
+ agentMailbox,
561
+ monitorEnabled: !options.desktopEvents,
541
562
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
542
563
  });
543
- mailbox.attachDriver(mailboxService);
564
+ if (options.desktopEvents) {
565
+ const desktopSink = new DesktopEventSocketSink({
566
+ ...options.desktopEvents,
567
+ activeResources: () => ({
568
+ locale: DESKTOP_RESOURCE_LOCALE,
569
+ strategy: assembly.strategy.activeResourceDescriptor(DESKTOP_RESOURCE_LOCALE),
570
+ perceptions: assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
571
+ }),
572
+ onConnected: () => desktopEventPump?.retryNow(),
573
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
574
+ });
575
+ desktopEventPump = new MailboxEventBatchPump({
576
+ source: {
577
+ prepare: () => agentMailbox!.prepareEvents({
578
+ deliveryVia: 'mailbox_full',
579
+ ownerIdPrefix: 'desktop_ipc',
580
+ }),
581
+ renew: (deliveryToken) => agentMailbox!.renew(deliveryToken),
582
+ ack: (deliveryToken) => agentMailbox!.ack(deliveryToken),
583
+ release: (deliveryToken) => agentMailbox!.release(deliveryToken),
584
+ },
585
+ sink: desktopSink,
586
+ diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
587
+ });
588
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([
589
+ mailboxService,
590
+ agentMailbox,
591
+ desktopEventPump,
592
+ ]));
593
+ desktopSink.start();
594
+ } else {
595
+ mailbox.attachDriver(new CompositeClawclawMailboxDriver([
596
+ mailboxService,
597
+ agentMailbox,
598
+ ]));
599
+ }
544
600
  const ownerSource = new ClawclawSourcePlugin({
545
601
  client,
546
602
  profile: options.profile,
@@ -601,7 +657,7 @@ export async function runClawclawOwner(
601
657
  });
602
658
  return eventsQueryBarrier;
603
659
  };
604
- if (options.notificationHost) {
660
+ if (options.notificationHost && !options.desktopEvents) {
605
661
  mailboxBroker = new MailboxRelayBroker(
606
662
  mailboxRepository,
607
663
  'short',
@@ -898,11 +954,14 @@ export async function runClawclawOwner(
898
954
  process.on('SIGINT', onSignal);
899
955
  process.on('SIGTERM', onSignal);
900
956
  await runtime.startSourcePlugin(ownerSource);
957
+ await desktopEventPump?.flush();
901
958
  if (localStopRequested) await ownerSource.submitIntent({ kind: 'stop' });
902
- options.notificationHost?.markMailboxReady();
959
+ if (!options.desktopEvents) options.notificationHost?.markMailboxReady();
903
960
  const completion = await source.waitForCompletion();
904
961
  await runtime.flush();
905
962
  await mailboxService.flush();
963
+ await agentMailbox.flush();
964
+ await desktopEventPump?.drain();
906
965
  if (mailboxBroker && !(await waitForMailboxDrain(mailboxBroker))) {
907
966
  runtime.diagnostic('runtime.shutdown.mailbox_drain_incomplete', {
908
967
  timeout_ms: MAILBOX_DRAIN_TIMEOUT_MS,