@myclaw163/clawclaw-cli 0.7.8 → 0.7.9

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 (28) hide show
  1. package/docs/desktop-event-push.md +14 -2
  2. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +15 -1
  3. package/package.json +1 -1
  4. package/src/pipeline/game-sync-event-normalization.test.ts +33 -0
  5. package/src/pipeline/game-sync-event-normalization.ts +52 -9
  6. package/src/runtime/clawclaw/owner.ts +8 -0
  7. package/src/runtime/clawclaw/plugins/assembly.test.ts +13 -0
  8. package/src/runtime/clawclaw/plugins/assembly.ts +10 -0
  9. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +17 -5
  10. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +37 -3
  11. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +49 -14
  12. package/src/runtime/clawclaw/plugins/perception/contracts.ts +1 -0
  13. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +16 -0
  14. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +16 -0
  15. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +16 -0
  16. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +23 -0
  17. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +16 -0
  18. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +16 -0
  19. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +23 -0
  20. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +19 -0
  21. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +41 -0
  22. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +49 -0
  23. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +105 -5
  24. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +174 -0
  25. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +146 -66
  26. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +36 -0
  27. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +0 -5
  28. package/src/sdk/perception-plugin/index.ts +8 -0
@@ -113,16 +113,28 @@ CCL 在以下条件全部满足时发送一个 `mailbox_batch`:
113
113
  }
114
114
  ]
115
115
  },
116
+ "event_descriptors": [
117
+ {
118
+ "type": "visual.player_moved",
119
+ "perception_id": "visual.motion",
120
+ "name": "玩家移动",
121
+ "description": "玩家持续移动形成一段可观察的移动轨迹。"
122
+ }
123
+ ],
116
124
  "payload": {
117
125
  "schema": "clawclaw.channel-events.v1",
118
126
  "state": {},
119
- "events": []
127
+ "events": [
128
+ "visual.player_moved | 9:41,你从导航仓左上侧移动到2号走廊右下侧。"
129
+ ]
120
130
  }
121
131
  }
122
132
  ```
123
133
 
124
134
  `payload.state` 是当前 Ready View 的紧凑状态,`payload.events` 是本批完整 Agent 事件。`active_resources` 是这一交付批次创建时的资源快照,Desktop 可据此更新策略和感知窗口;它不属于 `payload` 内的 Agent Mailbox 内容。
125
135
 
136
+ `event_descriptors` 只包含本批 `payload.events` 实际出现、并且由当前激活感知模块声明的 Event type。同一 type 在一批出现多次只附一份描述;非感知事件、禁用模块的 Event type、未激活自定义模块的 Event type,以及没有出现在本批的 Event type 都不列入。名称和描述来自对应感知模块 manifest,当前按 `zh-CN` 解析。没有匹配项时省略整个字段,原有 `payload.events` 结构始终保持不变。
137
+
126
138
  ## 什么时候不发送
127
139
 
128
140
  - Desktop 参数未配置或 IPC 尚未连接。
@@ -151,4 +163,4 @@ Desktop 将批次可靠放入自己的输入队列后返回:
151
163
 
152
164
  `connection_id`、`seq` 和 `delivery_id` 必须与当前批次完全一致,否则 ACK 被忽略。CCL 只有收到正确 ACK 后才把事件标记为已交付。
153
165
 
154
- ACK 超时或连接中断时,CCL 会重连并重发未确认批次;重试保持相同 `delivery_id`,并保留该交付首次创建时的 `active_resources` 快照。Desktop 应按 `delivery_id` 幂等入队,避免“已入队但 ACK 丢失”导致重复唤醒。
166
+ ACK 超时或连接中断时,CCL 会重连并重发未确认批次;重试保持相同 `delivery_id`,并保留该交付首次创建时的 `active_resources` 和 `event_descriptors` 快照。Desktop 应按 `delivery_id` 幂等入队,避免“已入队但 ACK 丢失”导致重复唤醒。
@@ -66,6 +66,18 @@ export default class EnterCounter extends ClawclawPerception {
66
66
  description: 'Counts other players entering the field of view.',
67
67
  subjectScope: 'others',
68
68
  produces: ['visual.enter_count_changed'],
69
+ eventMetadata: {
70
+ 'visual.enter_count_changed': {
71
+ name: 'Player enter count changed',
72
+ description: 'Reports a newly observed player entering view.',
73
+ localizations: {
74
+ 'zh-CN': {
75
+ name: '玩家进入视野',
76
+ description: '发现一名此前不可见的玩家进入当前视野。',
77
+ },
78
+ },
79
+ },
80
+ },
69
81
  };
70
82
 
71
83
  seen = new Set();
@@ -96,9 +108,11 @@ export default class EnterCounter extends ClawclawPerception {
96
108
 
97
109
  `static manifest` 必须使用可静态读取的字面量;CCL 在不执行用户代码的前提下读取它。类可以包含普通私有字段,用来保存轨迹、计数器、候选关系和“已经报告到哪里”等短期状态。
98
110
 
111
+ `eventMetadata` 为兼容已有自定义模块仍是可选字段;一旦提供,就必须完整覆盖 `produces`,不能声明额外 Event type。Desktop IPC 只会为当前激活模块、本批实际出现的 Event type 传递这里的本地化名称和描述。新模块建议始终提供该字段;文案属于模块,不应由 Mailbox 或 Desktop 建立中央映射。
112
+
99
113
  | 类成员 | 是否必需 | 作用 |
100
114
  |---|---:|---|
101
- | `static manifest` | 是 | 声明模块 ID、说明、事件主体范围和所有可能输出的 Event type |
115
+ | `static manifest` | 是 | 声明模块 ID、说明、事件主体范围、所有可能输出的 Event type,以及可选的 Event 显示元数据 |
102
116
  | `update(frame, api)` | 是 | 消费一份新的视觉帧,更新私有状态,并可返回零到多条 Event |
103
117
  | 普通实例字段 | 否 | 保存这个模块自己的跨帧状态;不同模块互不共享 |
104
118
  | `flush(boundary, api)` | 否 | 在查询或硬边界处报告尚未自然结束的长片段 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/clawclaw-cli",
3
- "version": "0.7.8",
3
+ "version": "0.7.9",
4
4
  "type": "module",
5
5
  "description": "ClawClaw social deduction game CLI",
6
6
  "bin": {
@@ -4,6 +4,7 @@ import { presentCanonicalEvent } from './canonical-event-presentation.js';
4
4
  import {
5
5
  normalizeGameSyncEvent,
6
6
  normalizeGameSyncEvents,
7
+ normalizeGameSyncEventsSafely,
7
8
  } from './game-sync-event-normalization.js';
8
9
 
9
10
  function canonical(event: Record<string, any>): CanonicalEvent {
@@ -80,6 +81,38 @@ describe('GameSync v2 Event normalization', () => {
80
81
  expect(normalized[0]).not.toHaveProperty('newly_assigned_task');
81
82
  });
82
83
 
84
+ it('isolates malformed Events while preserving original indexes and same-frame enrichment', () => {
85
+ const result = normalizeGameSyncEventsSafely([{
86
+ event_id: 'completed-1',
87
+ tick: 42,
88
+ type: 'task_completed',
89
+ actor: { seat: 1, name: 'self' },
90
+ task_name: '擦拭酒瓶',
91
+ }, {
92
+ event_id: 'malformed-killed',
93
+ tick: 42,
94
+ type: 'killed',
95
+ actor: { seat: 4, name: 'victim' },
96
+ killer: { kind: 'player', player: { seat: 2 } },
97
+ }, {
98
+ event_id: 'assigned-1',
99
+ tick: 42,
100
+ type: 'task_assigned',
101
+ actor: { seat: 1, name: 'self' },
102
+ task_name: '消毒淋浴器',
103
+ room: '制氧舱',
104
+ }]);
105
+
106
+ expect(result.rejected).toHaveLength(1);
107
+ expect(result.rejected[0]).toMatchObject({ index: 1 });
108
+ expect(result.rejected[0]?.error).toBeInstanceOf(TypeError);
109
+ expect(result.events.map(({ index }) => index)).toEqual([0, 2]);
110
+ expect(result.events[0]?.event).toMatchObject({
111
+ type: 'task_completed',
112
+ newly_assigned_task: { name: '消毒淋浴器', room: '制氧舱' },
113
+ });
114
+ });
115
+
83
116
  it('projects actor and target PlayerRefs to the established canonical fields', () => {
84
117
  const wire = {
85
118
  event_id: '68a339d7-c5f6-4eef-8f40-b8779ca8bfcc',
@@ -3,6 +3,21 @@ export interface CanonicalPlayerRef {
3
3
  seat: number;
4
4
  }
5
5
 
6
+ export interface NormalizedGameSyncEventEntry {
7
+ index: number;
8
+ event: Record<string, any>;
9
+ }
10
+
11
+ export interface RejectedGameSyncEventEntry {
12
+ index: number;
13
+ error: unknown;
14
+ }
15
+
16
+ export interface GameSyncEventNormalizationResult {
17
+ events: NormalizedGameSyncEventEntry[];
18
+ rejected: RejectedGameSyncEventEntry[];
19
+ }
20
+
6
21
  interface PlayerRefProjection {
7
22
  wireField: string;
8
23
  nameField: string;
@@ -274,26 +289,54 @@ function newlyAssignedTask(event: Record<string, any>): Record<string, any> | nu
274
289
  * Event Catalog.
275
290
  */
276
291
  export function normalizeGameSyncEvents(values: readonly unknown[]): Record<string, any>[] {
277
- const normalized = values.map((value) => normalizeGameSyncEvent(value));
292
+ return enrichTaskAssignments(values.map((value, index) => ({
293
+ index,
294
+ event: normalizeGameSyncEvent(value),
295
+ }))).map(({ event }) => event);
296
+ }
297
+
298
+ /** Normalize independent Events without rejecting their valid frame siblings. */
299
+ export function normalizeGameSyncEventsSafely(
300
+ values: readonly unknown[],
301
+ ): GameSyncEventNormalizationResult {
302
+ const events: NormalizedGameSyncEventEntry[] = [];
303
+ const rejected: RejectedGameSyncEventEntry[] = [];
304
+ values.forEach((value, index) => {
305
+ try {
306
+ events.push({ index, event: normalizeGameSyncEvent(value) });
307
+ } catch (error) {
308
+ rejected.push({ index, error });
309
+ }
310
+ });
311
+ return { events: enrichTaskAssignments(events), rejected };
312
+ }
313
+
314
+ function enrichTaskAssignments(
315
+ entries: readonly NormalizedGameSyncEventEntry[],
316
+ ): NormalizedGameSyncEventEntry[] {
278
317
  const claimedAssignments = new Set<number>();
279
318
 
280
- return normalized.map((event, index) => {
281
- if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return event;
319
+ return entries.map((entry, index) => {
320
+ const { event } = entry;
321
+ if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return entry;
282
322
  const actorKey = taskEventActorKey(event);
283
- if (!actorKey) return event;
323
+ if (!actorKey) return entry;
284
324
 
285
- const assignmentIndex = normalized.findIndex((candidate, candidateIndex) => (
325
+ const assignmentIndex = entries.findIndex(({ event: candidate }, candidateIndex) => (
286
326
  candidateIndex > index
287
327
  && !claimedAssignments.has(candidateIndex)
288
328
  && candidate.type === 'task_assigned'
289
329
  && candidate.tick === event.tick
290
330
  && taskEventActorKey(candidate) === actorKey
291
331
  ));
292
- if (assignmentIndex < 0) return event;
332
+ if (assignmentIndex < 0) return entry;
293
333
 
294
- const task = newlyAssignedTask(normalized[assignmentIndex]);
295
- if (!task) return event;
334
+ const task = newlyAssignedTask(entries[assignmentIndex]!.event);
335
+ if (!task) return entry;
296
336
  claimedAssignments.add(assignmentIndex);
297
- return { ...event, newly_assigned_task: task };
337
+ return {
338
+ ...entry,
339
+ event: { ...event, newly_assigned_task: task },
340
+ };
298
341
  });
299
342
  }
@@ -569,6 +569,14 @@ export async function runClawclawOwner(
569
569
  strategy: assembly.strategy.activeResourceDescriptor(DESKTOP_RESOURCE_LOCALE),
570
570
  perceptions: assembly.perception.localizedModuleDescriptors(DESKTOP_RESOURCE_LOCALE),
571
571
  }),
572
+ eventDescriptors: () => assembly.perception
573
+ .localizedEventDescriptors(DESKTOP_RESOURCE_LOCALE)
574
+ .map((descriptor) => ({
575
+ type: descriptor.type,
576
+ perception_id: descriptor.perceptionId,
577
+ name: descriptor.name,
578
+ description: descriptor.description,
579
+ })),
572
580
  onConnected: () => desktopEventPump?.retryNow(),
573
581
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
574
582
  });
@@ -78,4 +78,17 @@ describe('ClawClaw plugin assembly', () => {
78
78
  expect(assembled.plugins.filter((plugin) => plugin.id === CLAWCLAW_PERCEPTION_PLUGIN_ID))
79
79
  .toEqual([perception]);
80
80
  });
81
+
82
+ it('rejects terminate policy for plugins loaded into the ClawClaw graph', () => {
83
+ const plugin: RuntimeEpochPlugin<Record<string, any>> = {
84
+ kind: 'epoch',
85
+ id: 'user.plugin',
86
+ version: '1',
87
+ failurePolicy: 'terminate',
88
+ update: () => ({ outcome: 'noop' }),
89
+ };
90
+
91
+ expect(() => assembleClawclawPlugins(client, { epochPlugins: [plugin] }))
92
+ .toThrow('Runtime Plugin user.plugin cannot use the terminate failure policy');
93
+ });
81
94
  });
@@ -48,6 +48,16 @@ export function assembleClawclawPlugins(
48
48
  options: ClawclawPluginAssemblyOptions = {},
49
49
  ): ClawclawPluginAssembly {
50
50
  const plugins = [...(options.epochPlugins ?? [])];
51
+ for (const plugin of plugins) {
52
+ const failureMode = typeof plugin.failurePolicy === 'string'
53
+ ? plugin.failurePolicy
54
+ : plugin.failurePolicy?.mode;
55
+ if (failureMode === 'terminate') {
56
+ throw new Error(
57
+ `Runtime Plugin ${plugin.id} cannot use the terminate failure policy in the ClawClaw plugin graph.`,
58
+ );
59
+ }
60
+ }
51
61
 
52
62
  const configuredAction = plugins.find((plugin) => plugin.id === CLAWCLAW_ACTION_PLUGIN_ID);
53
63
  if (configuredAction && !(configuredAction instanceof ClawclawActionPlugin)) {
@@ -204,11 +204,17 @@ describe('Desktop Agent event push integration', () => {
204
204
  description: '完成任务并保持警觉。',
205
205
  },
206
206
  perceptions: [{
207
- id: 'visual.visibility',
208
- name: '视野变化',
209
- description: '感知其他玩家进入、离开或重新出现在视野中。',
207
+ id: 'visual.motion',
208
+ name: '玩家移动',
209
+ description: '感知自己和可见玩家的连续移动片段及显著方向变化。',
210
210
  }],
211
211
  }),
212
+ eventDescriptors: () => [{
213
+ type: 'visual.player_moved',
214
+ perception_id: 'visual.motion',
215
+ name: '玩家移动',
216
+ description: '玩家持续移动形成一段可观察的移动轨迹。',
217
+ }],
212
218
  });
213
219
  pump = new MailboxEventBatchPump({
214
220
  source: {
@@ -234,7 +240,7 @@ describe('Desktop Agent event push integration', () => {
234
240
  .toMatchObject({
235
241
  locale: 'zh-CN',
236
242
  strategy: { id: 'normal-shrimp', name: '普通虾' },
237
- perceptions: [{ id: 'visual.visibility', name: '视野变化' }],
243
+ perceptions: [{ id: 'visual.motion', name: '玩家移动' }],
238
244
  });
239
245
  expect(await mailbox.update({ pendingEvents: [] } as any)).toMatchObject({
240
246
  outcome: 'noop',
@@ -290,8 +296,14 @@ describe('Desktop Agent event push integration', () => {
290
296
  expect(firstBatch.frame.active_resources).toMatchObject({
291
297
  locale: 'zh-CN',
292
298
  strategy: { id: 'normal-shrimp', name: '普通虾' },
293
- perceptions: [{ id: 'visual.visibility', name: '视野变化' }],
299
+ perceptions: [{ id: 'visual.motion', name: '玩家移动' }],
294
300
  });
301
+ expect(firstBatch.frame.event_descriptors).toEqual([{
302
+ type: 'visual.player_moved',
303
+ perception_id: 'visual.motion',
304
+ name: '玩家移动',
305
+ description: '玩家持续移动形成一段可观察的移动轨迹。',
306
+ }]);
295
307
  expect(firstBatch.frame.payload.events).toEqual([
296
308
  'visual.player_moved | player-2 moved through engine',
297
309
  expect.objectContaining({ type: 'speech', text: longText }),
@@ -94,12 +94,19 @@ describe('DesktopEventSocketSink', () => {
94
94
  description: '感知自己和可见玩家的连续移动片段及显著方向变化。',
95
95
  }],
96
96
  } as const;
97
+ const eventDescriptors = [{
98
+ type: 'visual.player_moved',
99
+ perception_id: 'visual.motion',
100
+ name: '玩家移动',
101
+ description: '玩家持续移动形成一段可观察的移动轨迹。',
102
+ }] as const;
97
103
  const sink = new DesktopEventSocketSink({
98
104
  socketPath,
99
105
  token: '0123456789abcdef0123456789abcdef',
100
106
  reconnectBaseMs: 10,
101
107
  reconnectMaxMs: 20,
102
108
  activeResources: () => activeResources,
109
+ eventDescriptors: () => eventDescriptors,
103
110
  });
104
111
  sink.start();
105
112
  await vi.waitFor(() => expect(frames[0]).toMatchObject({
@@ -122,7 +129,11 @@ describe('DesktopEventSocketSink', () => {
122
129
  deliveryId: 'delivery-2',
123
130
  batch: {
124
131
  state: { phase: 'wandering' },
125
- events: [{ type: 'speech_your_turn' }],
132
+ events: [
133
+ 'visual.player_moved | 1:2,你向右移动。',
134
+ 'visual.following | 1:2,玩家2跟随玩家3。',
135
+ { type: 'speech_your_turn' },
136
+ ],
126
137
  },
127
138
  }, new AbortController().signal);
128
139
 
@@ -139,8 +150,21 @@ describe('DesktopEventSocketSink', () => {
139
150
  events: [expect.objectContaining({ text: largeText })],
140
151
  }),
141
152
  }),
142
- expect.objectContaining({ seq: 2, delivery_id: 'delivery-2' }),
153
+ expect.objectContaining({
154
+ seq: 2,
155
+ delivery_id: 'delivery-2',
156
+ event_descriptors: eventDescriptors,
157
+ payload: expect.objectContaining({
158
+ events: [
159
+ 'visual.player_moved | 1:2,你向右移动。',
160
+ 'visual.following | 1:2,玩家2跟随玩家3。',
161
+ { type: 'speech_your_turn' },
162
+ ],
163
+ }),
164
+ }),
143
165
  ]);
166
+ expect(frames.find((frame) => frame.delivery_id === 'delivery-1'))
167
+ .not.toHaveProperty('event_descriptors');
144
168
 
145
169
  await sink.close();
146
170
  });
@@ -195,12 +219,19 @@ describe('DesktopEventSocketSink', () => {
195
219
  name: '策略甲',
196
220
  description: '策略甲描述。',
197
221
  };
222
+ let eventName = '旧玩家移动';
198
223
  const sink = new DesktopEventSocketSink({
199
224
  socketPath,
200
225
  token: '0123456789abcdef0123456789abcdef',
201
226
  reconnectBaseMs: 10,
202
227
  reconnectMaxMs: 20,
203
228
  activeResources: () => ({ locale: 'zh-CN', strategy, perceptions: [] }),
229
+ eventDescriptors: () => [{
230
+ type: 'visual.player_moved',
231
+ perception_id: 'visual.motion',
232
+ name: eventName,
233
+ description: '重试快照测试。',
234
+ }],
204
235
  });
205
236
  sink.start();
206
237
  await vi.waitFor(() => expect(hellos).toHaveLength(1));
@@ -208,7 +239,7 @@ describe('DesktopEventSocketSink', () => {
208
239
  deliveryId: 'durable-delivery',
209
240
  batch: {
210
241
  state: null,
211
- events: [{ type: 'game_over' }],
242
+ events: ['visual.player_moved | 测试移动。'],
212
243
  },
213
244
  };
214
245
 
@@ -221,6 +252,7 @@ describe('DesktopEventSocketSink', () => {
221
252
  name: '策略乙',
222
253
  description: '策略乙描述。',
223
254
  };
255
+ eventName = '新事件名称';
224
256
  await vi.waitFor(() => expect(hellos).toHaveLength(2));
225
257
  await expect(sink.deliver(envelope, new AbortController().signal)).resolves.toMatchObject({
226
258
  acceptedAt: expect.any(String),
@@ -230,6 +262,8 @@ describe('DesktopEventSocketSink', () => {
230
262
  expect(batches).toHaveLength(2);
231
263
  expect(batches[0].active_resources.strategy.id).toBe('strategy-a');
232
264
  expect(batches[1].active_resources.strategy.id).toBe('strategy-a');
265
+ expect(batches[0].event_descriptors[0].name).toBe('旧玩家移动');
266
+ expect(batches[1].event_descriptors[0].name).toBe('旧玩家移动');
233
267
 
234
268
  await sink.close();
235
269
  });
@@ -31,6 +31,13 @@ export interface DesktopActiveResources {
31
31
  readonly perceptions: readonly DesktopActiveResource[];
32
32
  }
33
33
 
34
+ export interface DesktopEventDescriptor {
35
+ readonly type: string;
36
+ readonly perception_id: string;
37
+ readonly name: string;
38
+ readonly description: string;
39
+ }
40
+
34
41
  export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
35
42
  ackTimeoutMs?: number;
36
43
  reconnectBaseMs?: number;
@@ -39,6 +46,7 @@ export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
39
46
  platform?: NodeJS.Platform;
40
47
  onConnected?: () => void;
41
48
  activeResources?: () => DesktopActiveResources;
49
+ eventDescriptors?: () => readonly DesktopEventDescriptor[];
42
50
  diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
43
51
  }
44
52
 
@@ -53,6 +61,12 @@ interface PendingDesktopAck {
53
61
  reject: (error: Error) => void;
54
62
  }
55
63
 
64
+ interface DesktopDeliveryMetadata {
65
+ readonly deliveryId: string;
66
+ readonly activeResources: DesktopActiveResources | undefined;
67
+ readonly eventDescriptors: readonly DesktopEventDescriptor[];
68
+ }
69
+
56
70
  export class DesktopEventSocketDeliveryError extends Error {
57
71
  readonly code: string;
58
72
  readonly retryable: boolean;
@@ -74,6 +88,16 @@ function controlledText(value: string, label: string, maxLength: number): string
74
88
  return text;
75
89
  }
76
90
 
91
+ function mailboxEventType(event: Record<string, unknown> | string): string | undefined {
92
+ if (typeof event === 'string') {
93
+ const separator = event.indexOf(' | ');
94
+ const type = (separator < 0 ? event : event.slice(0, separator)).trim();
95
+ return /^visual\.[a-z0-9_.-]+$/.test(type) ? type : undefined;
96
+ }
97
+ const type = typeof event.type === 'string' ? event.type.trim() : '';
98
+ return /^visual\.[a-z0-9_.-]+$/.test(type) ? type : undefined;
99
+ }
100
+
77
101
  export function normalizeDesktopEventSocketPath(
78
102
  value: string,
79
103
  platform: NodeJS.Platform = process.platform,
@@ -113,6 +137,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
113
137
  private readonly now: () => number;
114
138
  private readonly onConnected?: DesktopEventSocketOptions['onConnected'];
115
139
  private readonly activeResources?: DesktopEventSocketOptions['activeResources'];
140
+ private readonly eventDescriptors?: DesktopEventSocketOptions['eventDescriptors'];
116
141
  private readonly diagnostic?: DesktopEventSocketOptions['diagnostic'];
117
142
 
118
143
  private socket: Socket | undefined;
@@ -124,10 +149,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
124
149
  private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
125
150
  private inputBuffer = '';
126
151
  private pendingAck: PendingDesktopAck | undefined;
127
- private deliveryResources: {
128
- deliveryId: string;
129
- value: DesktopActiveResources | undefined;
130
- } | undefined;
152
+ private deliveryMetadata: DesktopDeliveryMetadata | undefined;
131
153
 
132
154
  constructor(options: DesktopEventSocketOptions) {
133
155
  this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
@@ -138,6 +160,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
138
160
  this.now = options.now ?? Date.now;
139
161
  this.onConnected = options.onConnected;
140
162
  this.activeResources = options.activeResources;
163
+ this.eventDescriptors = options.eventDescriptors;
141
164
  this.diagnostic = options.diagnostic;
142
165
  if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
143
166
  throw new Error('Desktop event ACK timeout must be positive.');
@@ -186,14 +209,17 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
186
209
  }
187
210
 
188
211
  const seq = ++this.sequence;
189
- const activeResources = this.resourcesForDelivery(envelope.deliveryId);
212
+ const metadata = this.metadataForDelivery(envelope.deliveryId, envelope.batch.events);
190
213
  const frame = {
191
214
  schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
192
215
  type: 'mailbox_batch',
193
216
  connection_id: connectionId,
194
217
  seq,
195
218
  delivery_id: envelope.deliveryId,
196
- ...(activeResources ? { active_resources: activeResources } : {}),
219
+ ...(metadata.activeResources ? { active_resources: metadata.activeResources } : {}),
220
+ ...(metadata.eventDescriptors.length > 0
221
+ ? { event_descriptors: metadata.eventDescriptors }
222
+ : {}),
197
223
  payload: {
198
224
  schema: 'clawclaw.channel-events.v1',
199
225
  ...envelope.batch,
@@ -253,7 +279,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
253
279
  this.socket = undefined;
254
280
  this.connected = false;
255
281
  this.connectionId = undefined;
256
- this.deliveryResources = undefined;
282
+ this.deliveryMetadata = undefined;
257
283
  if (!socket || socket.destroyed) return;
258
284
  await new Promise<void>((resolve) => {
259
285
  socket.once('close', () => resolve());
@@ -345,8 +371,8 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
345
371
  this.pendingAck = undefined;
346
372
  clearTimeout(pending.timer);
347
373
  pending.signal.removeEventListener('abort', pending.onAbort);
348
- if (this.deliveryResources?.deliveryId === pending.deliveryId) {
349
- this.deliveryResources = undefined;
374
+ if (this.deliveryMetadata?.deliveryId === pending.deliveryId) {
375
+ this.deliveryMetadata = undefined;
350
376
  }
351
377
  pending.resolve({
352
378
  acceptedAt: new Date(this.now()).toISOString(),
@@ -402,10 +428,19 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
402
428
  return structuredClone(this.activeResources());
403
429
  }
404
430
 
405
- private resourcesForDelivery(deliveryId: string): DesktopActiveResources | undefined {
406
- if (this.deliveryResources?.deliveryId === deliveryId) return this.deliveryResources.value;
407
- const value = this.readActiveResources();
408
- this.deliveryResources = { deliveryId, value };
409
- return value;
431
+ private metadataForDelivery(
432
+ deliveryId: string,
433
+ events: readonly (Record<string, unknown> | string)[],
434
+ ): Omit<DesktopDeliveryMetadata, 'deliveryId'> {
435
+ if (this.deliveryMetadata?.deliveryId === deliveryId) return this.deliveryMetadata;
436
+ const activeEventTypes = new Set(events.map(mailboxEventType).filter((type) => type !== undefined));
437
+ const eventDescriptors = structuredClone(this.eventDescriptors?.() ?? [])
438
+ .filter((descriptor) => activeEventTypes.has(descriptor.type));
439
+ this.deliveryMetadata = {
440
+ deliveryId,
441
+ activeResources: this.readActiveResources(),
442
+ eventDescriptors,
443
+ };
444
+ return this.deliveryMetadata;
410
445
  }
411
446
  }
@@ -9,6 +9,7 @@ export type {
9
9
  ClawclawResolvedResourceMetadata,
10
10
  ClawclawResourceLocalizations,
11
11
  ClawclawPerceptionClass,
12
+ ClawclawPerceptionEventMetadata,
12
13
  ClawclawPerceptionManifest,
13
14
  PerceptionApi,
14
15
  PerceptionAnalysisInput,
@@ -68,6 +68,22 @@ export class CoMovementModule extends ClawclawParallelPerception<CoMovementAnaly
68
68
  'visual.players_moving_together',
69
69
  'visual.players_stopped_moving_together',
70
70
  ],
71
+ eventMetadata: {
72
+ 'visual.players_moving_together': {
73
+ name: 'Players moving together',
74
+ description: 'Reports two visible players moving close together in the same direction.',
75
+ localizations: {
76
+ 'zh-CN': { name: '共同移动', description: '两名同时可见的玩家近距离同方向稳定移动。' },
77
+ },
78
+ },
79
+ 'visual.players_stopped_moving_together': {
80
+ name: 'Players stopped moving together',
81
+ description: 'Reports when two players stop maintaining close same-direction movement.',
82
+ localizations: {
83
+ 'zh-CN': { name: '共同移动结束', description: '两名玩家不再保持近距离同方向移动。' },
84
+ },
85
+ },
86
+ },
71
87
  execution: 'parallel_analysis',
72
88
  boundaryBaseline: 'current_only',
73
89
  } as const;
@@ -72,6 +72,22 @@ export class FollowModule extends ClawclawParallelPerception<FollowAnalysis> {
72
72
  },
73
73
  subjectScope: 'visible_pairs',
74
74
  produces: ['visual.following', 'visual.following_ended'],
75
+ eventMetadata: {
76
+ 'visual.following': {
77
+ name: 'Following relation',
78
+ description: 'Reports one visible player moving steadily behind another in the same direction.',
79
+ localizations: {
80
+ 'zh-CN': { name: '跟随关系', description: '一名玩家稳定地跟在另一名玩家后方同方向移动。' },
81
+ },
82
+ },
83
+ 'visual.following_ended': {
84
+ name: 'Following relation ended',
85
+ description: 'Reports when two players stop maintaining a confirmed front/back relation.',
86
+ localizations: {
87
+ 'zh-CN': { name: '跟随关系结束', description: '两名玩家不再保持已确认的前后跟随关系。' },
88
+ },
89
+ },
90
+ },
75
91
  execution: 'parallel_analysis',
76
92
  boundaryBaseline: 'current_only',
77
93
  } as const;
@@ -88,6 +88,22 @@ export class MotionModule extends ClawclawParallelPerception<MotionAnalysis> {
88
88
  },
89
89
  subjectScope: 'self_and_others',
90
90
  produces: ['visual.player_moved', 'visual.player_motion_changed'],
91
+ eventMetadata: {
92
+ 'visual.player_moved': {
93
+ name: 'Player moved',
94
+ description: 'Reports a continuous observed movement segment for a player.',
95
+ localizations: {
96
+ 'zh-CN': { name: '玩家移动', description: '玩家持续移动形成一段可观察的移动轨迹。' },
97
+ },
98
+ },
99
+ 'visual.player_motion_changed': {
100
+ name: 'Movement direction changed',
101
+ description: 'Reports a confirmed meaningful change in a player\'s movement direction.',
102
+ localizations: {
103
+ 'zh-CN': { name: '移动方向变化', description: '玩家的移动方向发生经过确认的显著变化。' },
104
+ },
105
+ },
106
+ },
91
107
  execution: 'parallel_analysis',
92
108
  boundaryBaseline: 'current_only',
93
109
  } as const;
@@ -72,6 +72,29 @@ export class RouteModule extends ClawclawParallelPerception<RouteAnalysis> {
72
72
  'visual.player_reversed',
73
73
  'visual.player_wandering',
74
74
  ],
75
+ eventMetadata: {
76
+ 'visual.player_turned': {
77
+ name: 'Player turned',
78
+ description: 'Reports when a player changes direction and forms a turn.',
79
+ localizations: {
80
+ 'zh-CN': { name: '玩家转向', description: '玩家改变移动方向并形成一次转向。' },
81
+ },
82
+ },
83
+ 'visual.player_reversed': {
84
+ name: 'Player reversed direction',
85
+ description: 'Reports when a player changes to a roughly opposite movement direction.',
86
+ localizations: {
87
+ 'zh-CN': { name: '玩家折返', description: '玩家改变为大致相反方向移动。' },
88
+ },
89
+ },
90
+ 'visual.player_wandering': {
91
+ name: 'Player wandering',
92
+ description: 'Reports repeated nearby turns or reversals by a player.',
93
+ localizations: {
94
+ 'zh-CN': { name: '玩家徘徊', description: '玩家在附近连续多次转向或折返。' },
95
+ },
96
+ },
97
+ },
75
98
  execution: 'parallel_analysis',
76
99
  boundaryBaseline: 'current_only',
77
100
  } as const;