@myclaw163/clawclaw-cli 0.7.6 → 0.7.8

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 (51) hide show
  1. package/docs/desktop-event-push.md +37 -3
  2. package/docs/runtime/README.md +1 -0
  3. package/docs/runtime/official-perception-modules.md +346 -0
  4. package/package.json +1 -1
  5. package/src/commands/game/index.ts +1 -1
  6. package/src/lib/service-status.test.ts +56 -0
  7. package/src/lib/service-status.ts +111 -0
  8. package/src/pipeline/event-format.test.ts +26 -0
  9. package/src/pipeline/event-format.ts +22 -1
  10. package/src/pipeline/event-hints.test.ts +18 -3
  11. package/src/pipeline/event-hints.ts +11 -0
  12. package/src/pipeline/game-sync-event-normalization.test.ts +54 -1
  13. package/src/pipeline/game-sync-event-normalization.ts +39 -6
  14. package/src/pipeline/player-projection.test.ts +19 -2
  15. package/src/pipeline/player-projection.ts +17 -2
  16. package/src/runtime/clawclaw/agent-event-policy.test.ts +4 -0
  17. package/src/runtime/clawclaw/agent-event-policy.ts +1 -0
  18. package/src/runtime/clawclaw/owner.ts +6 -0
  19. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +24 -0
  20. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +29 -0
  21. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +39 -0
  22. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +71 -0
  23. package/src/runtime/clawclaw/plugins/perception/contracts.ts +4 -0
  24. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +6 -0
  25. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +6 -0
  26. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +6 -0
  27. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +6 -0
  28. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +6 -0
  29. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +6 -0
  30. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +6 -0
  31. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +11 -0
  32. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +8 -0
  33. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +12 -0
  34. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +37 -1
  35. package/src/runtime/clawclaw/plugins/source/room-transport.ts +2 -1
  36. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +214 -1
  37. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +109 -21
  38. package/src/runtime/clawclaw/plugins/source/types.ts +1 -0
  39. package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +6 -0
  40. package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +4 -0
  41. package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +4 -0
  42. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +36 -0
  43. package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +13 -0
  44. package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +22 -0
  45. package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +46 -16
  46. package/src/runtime/clawclaw-event-catalog.test.ts +2 -0
  47. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  48. package/src/sdk/perception-plugin/index.ts +14 -0
  49. package/src/sdk/resource-metadata.test.ts +40 -0
  50. package/src/sdk/resource-metadata.ts +63 -0
  51. package/src/sdk/strategy-plugin/index.ts +14 -0
@@ -232,6 +232,16 @@ function playerLabel(name: unknown, seat: unknown, ctx: EventFormatContext): str
232
232
  return `${seatLabel(name, seat, ctx)}${text(name, '未知玩家')}`;
233
233
  }
234
234
 
235
+ function killerLabel(
236
+ name: unknown,
237
+ seat: unknown,
238
+ kind: unknown,
239
+ ctx: EventFormatContext,
240
+ ): string {
241
+ if (kind === 'system') return text(name, '未知系统来源');
242
+ return playerLabel(name, seat, ctx);
243
+ }
244
+
235
245
  function playerObject(name: unknown, seat: unknown, ctx: EventFormatContext): Record<string, any> | undefined {
236
246
  if (typeof name !== 'string' || name.length === 0) return undefined;
237
247
  return cleanObject({
@@ -338,6 +348,17 @@ function playersChangedBody(event: Record<string, any>, ctx: EventFormatContext)
338
348
  function shortBody(event: Record<string, any>, ctx: EventFormatContext): string {
339
349
  const maxTextLength = ctx.maxTextLength ?? 100;
340
350
  switch (event.type) {
351
+ case 'service_status': {
352
+ const startsAt = firstString(event.maintenance ?? {}, ['starts_at'], '计划时间未知');
353
+ const endsAt = firstString(event.maintenance ?? {}, ['ends_at'], '恢复时间未知');
354
+ if (event.service_status === 'maintenance_upcoming') {
355
+ return `服务器计划于${startsAt}开始维护,预计${endsAt}恢复;当前请求仍可继续。`;
356
+ }
357
+ if (event.service_status === 'maintenance_active') {
358
+ return `服务器正在维护,预计${endsAt}恢复;新的匹配和房间操作已停止。`;
359
+ }
360
+ return '服务器维护已结束,服务恢复可用。';
361
+ }
341
362
  case 'game_started': {
342
363
  const playerCount = numberValue(event.player_count);
343
364
  const countText = playerCount === undefined ? '对局开始' : `对局开始:${playerCount}名玩家`;
@@ -356,7 +377,7 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
356
377
  case 'kill':
357
378
  return `你在${firstString(event, ['room'])}击杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)}。`;
358
379
  case 'killed':
359
- return `你在${firstString(event, ['room'])}被${playerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']), ctx)}击杀了,你已死亡。`;
380
+ return `你在${firstString(event, ['room'])}被${killerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']), event.killer_kind, ctx)}击杀了,你已死亡。`;
360
381
  case 'murder_witnessed':
361
382
  return `你在${firstString(event, ['room'])}目击${playerLabel(event.killer_name, firstNumber(event, ['killer_seat', 'killer_player_seat']), ctx)}击杀${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)}。`;
362
383
  case 'warrior_shrimp_self_destruct':
@@ -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)
@@ -112,7 +112,7 @@ describe('GameSync v2 Event normalization', () => {
112
112
  tick: 22,
113
113
  type: 'synthetic_contract_fixture',
114
114
  caller: { seat: 1, name: 'caller' },
115
- killer: { seat: 2, name: 'killer' },
115
+ killer: { kind: 'player', player: { seat: 2, name: 'killer' } },
116
116
  resolver: { seat: 3, name: 'resolver' },
117
117
  speaker: { seat: 4, name: 'speaker' },
118
118
  current_speaker: { seat: 5, name: 'current' },
@@ -123,6 +123,7 @@ describe('GameSync v2 Event normalization', () => {
123
123
  expect(normalized).toMatchObject({
124
124
  meeting_caller_name: 'caller',
125
125
  meeting_caller_seat: 1,
126
+ killer_kind: 'player',
126
127
  killer_name: 'killer',
127
128
  killer_seat: 2,
128
129
  resolver_name: 'resolver',
@@ -141,6 +142,58 @@ describe('GameSync v2 Event normalization', () => {
141
142
  }
142
143
  });
143
144
 
145
+ it('projects structured player and system killers for Agent presentation', () => {
146
+ const playerKilled = normalizeGameSyncEvent({
147
+ event_id: 'player-killed',
148
+ tick: 41,
149
+ type: 'killed',
150
+ actor: { seat: 4, name: 'victim' },
151
+ killer: { kind: 'player', player: { seat: 2, name: 'killer' } },
152
+ room: 'engine',
153
+ });
154
+ expect(playerKilled).toMatchObject({
155
+ actor_name: 'victim',
156
+ actor_seat: 4,
157
+ killer_kind: 'player',
158
+ killer_name: 'killer',
159
+ killer_seat: 2,
160
+ });
161
+ expect(playerKilled).not.toHaveProperty('killer');
162
+ expect(presentCanonicalEvent(canonical(playerKilled), null).hint)
163
+ .toBe('YOU ARE DEAD: seat 2 killer removed you from play.');
164
+
165
+ const systemKilled = normalizeGameSyncEvent({
166
+ event_id: 'system-killed',
167
+ tick: 42,
168
+ type: 'killed',
169
+ actor: { seat: 4, name: 'victim' },
170
+ killer: { kind: 'system', name: 'Shrimp God' },
171
+ room: 'engine',
172
+ });
173
+ expect(systemKilled).toMatchObject({
174
+ actor_name: 'victim',
175
+ actor_seat: 4,
176
+ killer_kind: 'system',
177
+ killer_name: 'Shrimp God',
178
+ });
179
+ expect(systemKilled).not.toHaveProperty('killer');
180
+ expect(systemKilled).not.toHaveProperty('killer_seat');
181
+ expect(presentCanonicalEvent(canonical(systemKilled), null).hint)
182
+ .toBe('YOU ARE DEAD: Shrimp God removed you from play.');
183
+ });
184
+
185
+ it('rejects malformed structured killers', () => {
186
+ expect(() => normalizeGameSyncEvent({
187
+ type: 'killed', killer: { kind: 'player', player: { seat: 2 } },
188
+ })).toThrow('killer.player.name must be a string');
189
+ expect(() => normalizeGameSyncEvent({
190
+ type: 'killed', killer: { kind: 'system', name: 'GM', seat: 0 },
191
+ })).toThrow('killer contains unsupported fields: seat');
192
+ expect(() => normalizeGameSyncEvent({
193
+ type: 'killed', killer: { kind: 'npc', name: 'GM' },
194
+ })).toThrow("killer.kind must be 'player' or 'system'");
195
+ });
196
+
144
197
  it('preserves a faction winner scalar and projects a neutral winner PlayerRef', () => {
145
198
  expect(normalizeGameSyncEvent({
146
199
  event_id: 'faction-event', tick: 1, type: 'game_over', winner: 'lobster',
@@ -20,12 +20,6 @@ const SINGLE_PLAYER_REF_PROJECTIONS: readonly PlayerRefProjection[] = [
20
20
  seatField: 'meeting_caller_seat',
21
21
  playerRefOnlyWhenObject: true,
22
22
  },
23
- {
24
- wireField: 'killer',
25
- nameField: 'killer_name',
26
- seatField: 'killer_seat',
27
- playerRefOnlyWhenObject: true,
28
- },
29
23
  { wireField: 'resolver', nameField: 'resolver_name', seatField: 'resolver_seat' },
30
24
  {
31
25
  wireField: 'speaker',
@@ -100,6 +94,39 @@ function playerRef(value: unknown, field: string): CanonicalPlayerRef {
100
94
  return { name: value.name, seat: Number(value.seat) };
101
95
  }
102
96
 
97
+ function validateExactFields(
98
+ value: Record<string, unknown>,
99
+ allowed: readonly string[],
100
+ field: string,
101
+ ): void {
102
+ const extraFields = Object.keys(value).filter((key) => !allowed.includes(key));
103
+ if (extraFields.length > 0) {
104
+ throw new TypeError(`${field} contains unsupported fields: ${extraFields.join(', ')}`);
105
+ }
106
+ }
107
+
108
+ function projectKiller(value: unknown): Record<string, unknown> {
109
+ if (!isRecord(value)) {
110
+ throw new TypeError('GameSync Event.killer must be an object');
111
+ }
112
+
113
+ if (value.kind === 'player') {
114
+ validateExactFields(value, ['kind', 'player'], 'GameSync Event.killer');
115
+ const killer = playerRef(value.player, 'GameSync Event.killer.player');
116
+ return { killer_kind: 'player', killer_name: killer.name, killer_seat: killer.seat };
117
+ }
118
+
119
+ if (value.kind === 'system') {
120
+ validateExactFields(value, ['kind', 'name'], 'GameSync Event.killer');
121
+ if (typeof value.name !== 'string') {
122
+ throw new TypeError('GameSync Event.killer.name must be a string');
123
+ }
124
+ return { killer_kind: 'system', killer_name: value.name };
125
+ }
126
+
127
+ throw new TypeError("GameSync Event.killer.kind must be 'player' or 'system'");
128
+ }
129
+
103
130
  function playerRefArray(value: unknown, field: string): CanonicalPlayerRef[] {
104
131
  if (!Array.isArray(value)) {
105
132
  throw new TypeError(`${field} must be a PlayerRef array`);
@@ -146,6 +173,12 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
146
173
  normalized[projection.seatField] = projected.seat;
147
174
  }
148
175
 
176
+ if (Object.hasOwn(normalized, 'killer')) {
177
+ const raw = normalized.killer;
178
+ delete normalized.killer;
179
+ if (raw !== null && raw !== undefined) Object.assign(normalized, projectKiller(raw));
180
+ }
181
+
149
182
  for (const field of PLAYER_REF_ARRAY_FIELDS) {
150
183
  if (!Object.hasOwn(normalized, field)) continue;
151
184
  normalized[field] = playerRefArray(normalized[field], `GameSync Event.${field}`);
@@ -170,8 +170,7 @@ describe('GameSync v2 player projection', () => {
170
170
  { ...ref(2, 'Killer'), known_status: { is_alive: true } },
171
171
  ],
172
172
  },
173
- // The contract makes actor optional, and origin/dev currently drops
174
- // legacy killer_name instead of emitting the structured killer field.
173
+ // Both actor and killer remain optional at the wire-model boundary.
175
174
  events: [{ type: 'killed' }],
176
175
  });
177
176
 
@@ -180,6 +179,24 @@ describe('GameSync v2 player projection', () => {
180
179
  ]);
181
180
  });
182
181
 
182
+ it('accepts structured player and system killers on recipient-private killed events', () => {
183
+ for (const killer of [
184
+ { kind: 'player', player: ref(2, 'Killer') },
185
+ { kind: 'system', name: 'Shrimp God' },
186
+ ]) {
187
+ expect(() => projectPlayers({
188
+ summary: {
189
+ you: { player: ref(1, 'Self') },
190
+ players: [
191
+ { ...ref(1, 'Self'), known_status: { is_alive: false, death_cause: 'killed' } },
192
+ { ...ref(2, 'Killer'), known_status: { is_alive: true } },
193
+ ],
194
+ },
195
+ events: [{ type: 'killed', actor: ref(1, 'Self'), killer }],
196
+ })).not.toThrow();
197
+ }
198
+ });
199
+
183
200
  it('preserves richer event knowledge when a later state only confirms death', () => {
184
201
  const players = advancePlayerProjection({
185
202
  previous: [{
@@ -141,12 +141,13 @@ function rememberRoster(players: Map<string, MutablePlayerProjection>, source: u
141
141
  for (const key of [
142
142
  'actor',
143
143
  'target',
144
- 'killer',
145
144
  'caller',
146
145
  'resolver',
147
146
  'current_speaker',
148
147
  'result_target',
149
148
  ]) rememberRef(players, item[key]);
149
+ const killer = record(item.killer);
150
+ rememberRef(players, killer?.kind === 'player' ? killer.player : undefined);
150
151
  for (const key of [
151
152
  'reported_corpses',
152
153
  'dead_players',
@@ -200,6 +201,20 @@ function refName(value: unknown): string | undefined {
200
201
  return playerRef(value)?.name;
201
202
  }
202
203
 
204
+ function killerName(value: unknown): string | undefined {
205
+ const killer = record(value);
206
+ if (killer?.kind === 'player') {
207
+ const player = playerRef(killer.player);
208
+ return player?.name;
209
+ }
210
+ if (killer?.kind === 'system') {
211
+ return typeof killer.name === 'string' && killer.name.length > 0
212
+ ? killer.name
213
+ : undefined;
214
+ }
215
+ return playerRef(value)?.name;
216
+ }
217
+
203
218
  function applyEvent(
204
219
  players: Map<string, MutablePlayerProjection>,
205
220
  event: Record<string, any>,
@@ -225,7 +240,7 @@ function applyEvent(
225
240
  // optional actor ref is absent. Never mistake another ref for the victim.
226
241
  enrichKnownDeath(players, youRef ?? event.actor, {
227
242
  cause: 'killed',
228
- killer: refName(event.killer) ?? null,
243
+ killer: killerName(event.killer) ?? null,
229
244
  revealed: true,
230
245
  source: 'event_log',
231
246
  });
@@ -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,
@@ -164,6 +164,7 @@ interface OwnerRuntimePointer {
164
164
  }
165
165
 
166
166
  const MAILBOX_DRAIN_TIMEOUT_MS = 2_000;
167
+ const DESKTOP_RESOURCE_LOCALE = 'zh-CN';
167
168
  const EVENTS_QUERY_BARRIER_TIMEOUT_MS = 10_000;
168
169
  const LOCAL_STOP_FORCE_EXIT_MS = 10_000;
169
170
  const FORCE_STOP_GRACE_MS = 1_500;
@@ -563,6 +564,11 @@ export async function runClawclawOwner(
563
564
  if (options.desktopEvents) {
564
565
  const desktopSink = new DesktopEventSocketSink({
565
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
+ }),
566
572
  onConnected: () => desktopEventPump?.retryNow(),
567
573
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
568
574
  });
@@ -196,6 +196,19 @@ describe('Desktop Agent event push integration', () => {
196
196
  reconnectBaseMs: 10,
197
197
  reconnectMaxMs: 20,
198
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
+ }),
199
212
  });
200
213
  pump = new MailboxEventBatchPump({
201
214
  source: {
@@ -217,6 +230,12 @@ describe('Desktop Agent event push integration', () => {
217
230
  await vi.waitFor(() => {
218
231
  expect(received.filter(({ frame }) => frame.type === 'hello')).toHaveLength(1);
219
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
+ });
220
239
  expect(await mailbox.update({ pendingEvents: [] } as any)).toMatchObject({
221
240
  outcome: 'noop',
222
241
  reason: 'no_pending_events',
@@ -268,6 +287,11 @@ describe('Desktop Agent event push integration', () => {
268
287
  schema: 'clawclaw.channel-events.v1',
269
288
  state: { phase: 'wandering', tick: 3 },
270
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
+ });
271
295
  expect(firstBatch.frame.payload.events).toEqual([
272
296
  'visual.player_moved | player-2 moved through engine',
273
297
  expect.objectContaining({ type: 'speech', text: longText }),
@@ -85,11 +85,21 @@ describe('DesktopEventSocketSink', () => {
85
85
  server.listen(socketPath, resolve);
86
86
  });
87
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;
88
97
  const sink = new DesktopEventSocketSink({
89
98
  socketPath,
90
99
  token: '0123456789abcdef0123456789abcdef',
91
100
  reconnectBaseMs: 10,
92
101
  reconnectMaxMs: 20,
102
+ activeResources: () => activeResources,
93
103
  });
94
104
  sink.start();
95
105
  await vi.waitFor(() => expect(frames[0]).toMatchObject({
@@ -97,6 +107,7 @@ describe('DesktopEventSocketSink', () => {
97
107
  type: 'hello',
98
108
  token: '0123456789abcdef0123456789abcdef',
99
109
  pid: process.pid,
110
+ active_resources: activeResources,
100
111
  }));
101
112
 
102
113
  const largeText = 'z'.repeat(70 * 1024);
@@ -122,6 +133,7 @@ describe('DesktopEventSocketSink', () => {
122
133
  expect.objectContaining({
123
134
  seq: 1,
124
135
  delivery_id: 'delivery-1',
136
+ active_resources: activeResources,
125
137
  payload: expect.objectContaining({
126
138
  schema: 'clawclaw.channel-events.v1',
127
139
  events: [expect.objectContaining({ text: largeText })],
@@ -139,6 +151,7 @@ describe('DesktopEventSocketSink', () => {
139
151
  ? `\\\\.\\pipe\\${pipeName}`
140
152
  : `/tmp/${pipeName}.sock`;
141
153
  const hellos: Array<Record<string, any>> = [];
154
+ const batches: Array<Record<string, any>> = [];
142
155
  let connectionNumber = 0;
143
156
  const server = createServer((socket) => {
144
157
  connectionNumber += 1;
@@ -156,6 +169,7 @@ describe('DesktopEventSocketSink', () => {
156
169
  const frame = JSON.parse(line) as Record<string, any>;
157
170
  if (frame.type === 'hello') hellos.push(frame);
158
171
  if (frame.type !== 'mailbox_batch') continue;
172
+ batches.push(frame);
159
173
  if (currentConnection === 1) {
160
174
  socket.destroy();
161
175
  continue;
@@ -176,11 +190,17 @@ describe('DesktopEventSocketSink', () => {
176
190
  server.listen(socketPath, resolve);
177
191
  });
178
192
 
193
+ let strategy = {
194
+ id: 'strategy-a',
195
+ name: '策略甲',
196
+ description: '策略甲描述。',
197
+ };
179
198
  const sink = new DesktopEventSocketSink({
180
199
  socketPath,
181
200
  token: '0123456789abcdef0123456789abcdef',
182
201
  reconnectBaseMs: 10,
183
202
  reconnectMaxMs: 20,
203
+ activeResources: () => ({ locale: 'zh-CN', strategy, perceptions: [] }),
184
204
  });
185
205
  sink.start();
186
206
  await vi.waitFor(() => expect(hellos).toHaveLength(1));
@@ -196,11 +216,20 @@ describe('DesktopEventSocketSink', () => {
196
216
  code: 'desktop_event_socket_disconnected',
197
217
  retryable: true,
198
218
  });
219
+ strategy = {
220
+ id: 'strategy-b',
221
+ name: '策略乙',
222
+ description: '策略乙描述。',
223
+ };
199
224
  await vi.waitFor(() => expect(hellos).toHaveLength(2));
200
225
  await expect(sink.deliver(envelope, new AbortController().signal)).resolves.toMatchObject({
201
226
  acceptedAt: expect.any(String),
202
227
  });
203
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');
204
233
 
205
234
  await sink.close();
206
235
  });
@@ -19,6 +19,18 @@ export interface DesktopEventSocketConfig {
19
19
  token: string;
20
20
  }
21
21
 
22
+ export interface DesktopActiveResource {
23
+ readonly id: string;
24
+ readonly name: string;
25
+ readonly description: string;
26
+ }
27
+
28
+ export interface DesktopActiveResources {
29
+ readonly locale: string;
30
+ readonly strategy: DesktopActiveResource | null;
31
+ readonly perceptions: readonly DesktopActiveResource[];
32
+ }
33
+
22
34
  export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
23
35
  ackTimeoutMs?: number;
24
36
  reconnectBaseMs?: number;
@@ -26,6 +38,7 @@ export interface DesktopEventSocketOptions extends DesktopEventSocketConfig {
26
38
  now?: () => number;
27
39
  platform?: NodeJS.Platform;
28
40
  onConnected?: () => void;
41
+ activeResources?: () => DesktopActiveResources;
29
42
  diagnostic?: (name: string, attributes?: Record<string, unknown>) => void;
30
43
  }
31
44
 
@@ -99,6 +112,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
99
112
  private readonly reconnectMaxMs: number;
100
113
  private readonly now: () => number;
101
114
  private readonly onConnected?: DesktopEventSocketOptions['onConnected'];
115
+ private readonly activeResources?: DesktopEventSocketOptions['activeResources'];
102
116
  private readonly diagnostic?: DesktopEventSocketOptions['diagnostic'];
103
117
 
104
118
  private socket: Socket | undefined;
@@ -110,6 +124,10 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
110
124
  private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
111
125
  private inputBuffer = '';
112
126
  private pendingAck: PendingDesktopAck | undefined;
127
+ private deliveryResources: {
128
+ deliveryId: string;
129
+ value: DesktopActiveResources | undefined;
130
+ } | undefined;
113
131
 
114
132
  constructor(options: DesktopEventSocketOptions) {
115
133
  this.path = normalizeDesktopEventSocketPath(options.socketPath, options.platform);
@@ -119,6 +137,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
119
137
  this.reconnectMaxMs = options.reconnectMaxMs ?? DEFAULT_RECONNECT_MAX_MS;
120
138
  this.now = options.now ?? Date.now;
121
139
  this.onConnected = options.onConnected;
140
+ this.activeResources = options.activeResources;
122
141
  this.diagnostic = options.diagnostic;
123
142
  if (!Number.isFinite(this.ackTimeoutMs) || this.ackTimeoutMs <= 0) {
124
143
  throw new Error('Desktop event ACK timeout must be positive.');
@@ -167,12 +186,14 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
167
186
  }
168
187
 
169
188
  const seq = ++this.sequence;
189
+ const activeResources = this.resourcesForDelivery(envelope.deliveryId);
170
190
  const frame = {
171
191
  schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
172
192
  type: 'mailbox_batch',
173
193
  connection_id: connectionId,
174
194
  seq,
175
195
  delivery_id: envelope.deliveryId,
196
+ ...(activeResources ? { active_resources: activeResources } : {}),
176
197
  payload: {
177
198
  schema: 'clawclaw.channel-events.v1',
178
199
  ...envelope.batch,
@@ -232,6 +253,7 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
232
253
  this.socket = undefined;
233
254
  this.connected = false;
234
255
  this.connectionId = undefined;
256
+ this.deliveryResources = undefined;
235
257
  if (!socket || socket.destroyed) return;
236
258
  await new Promise<void>((resolve) => {
237
259
  socket.once('close', () => resolve());
@@ -253,12 +275,14 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
253
275
  if (this.socket !== socket || this.stopped) return;
254
276
  this.connected = true;
255
277
  this.reconnectAttempt = 0;
278
+ const activeResources = this.readActiveResources();
256
279
  socket.write(`${JSON.stringify({
257
280
  schema: DESKTOP_EVENT_PROTOCOL_SCHEMA,
258
281
  type: 'hello',
259
282
  connection_id: connectionId,
260
283
  token: this.token,
261
284
  pid: process.pid,
285
+ ...(activeResources ? { active_resources: activeResources } : {}),
262
286
  })}\n`);
263
287
  this.diagnostic?.('runtime.desktop_event_socket.connected', {
264
288
  connection_id: connectionId,
@@ -321,6 +345,9 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
321
345
  this.pendingAck = undefined;
322
346
  clearTimeout(pending.timer);
323
347
  pending.signal.removeEventListener('abort', pending.onAbort);
348
+ if (this.deliveryResources?.deliveryId === pending.deliveryId) {
349
+ this.deliveryResources = undefined;
350
+ }
324
351
  pending.resolve({
325
352
  acceptedAt: new Date(this.now()).toISOString(),
326
353
  ...(receiptId ? { receiptId } : {}),
@@ -369,4 +396,16 @@ export class DesktopEventSocketSink implements MailboxEventBatchSink {
369
396
  signal.reason instanceof Error ? signal.reason.message : 'Desktop event delivery aborted.',
370
397
  );
371
398
  }
399
+
400
+ private readActiveResources(): DesktopActiveResources | undefined {
401
+ if (!this.activeResources) return undefined;
402
+ return structuredClone(this.activeResources());
403
+ }
404
+
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;
410
+ }
372
411
  }