@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
@@ -15,6 +15,15 @@ import {
15
15
  classifyLeaveQueueResult,
16
16
  leaveFailureError,
17
17
  } from '../../../../lib/participation-leave.js';
18
+ import {
19
+ isServiceMaintenanceApiError,
20
+ parseServerServiceStatus,
21
+ serverServiceStatusFromApiError,
22
+ serverServiceStatusFromEnvelope,
23
+ serviceStatusEvent,
24
+ serviceStatusSignature,
25
+ type ServerServiceStatus,
26
+ } from '../../../../lib/service-status.js';
18
27
  import {
19
28
  isRoomMode,
20
29
  isTrainingRoomMode,
@@ -322,6 +331,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
322
331
  private matchStartedAtMs?: number;
323
332
  private lastMatchWaitingAtMs?: number;
324
333
  private matchTimedOut = false;
334
+ private lastServiceStatusSignature?: string;
325
335
  private started = false;
326
336
  private finished = false;
327
337
  private terminalStateSubmitted = false;
@@ -388,7 +398,9 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
388
398
  (error) => this.completeLifecycle(
389
399
  this.abortController.signal.aborted
390
400
  ? { reason: 'stopped' }
391
- : { reason: 'error', error },
401
+ : isServiceMaintenanceApiError(error)
402
+ ? { reason: 'maintenance', error }
403
+ : { reason: 'error', error },
392
404
  ),
393
405
  );
394
406
  return {
@@ -512,14 +524,17 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
512
524
  }
513
525
  this.requireInactiveParticipation(existing, 'start matchmaking');
514
526
  let joined: Record<string, any>;
527
+ let serverStatus: ServerServiceStatus | undefined;
515
528
  try {
516
- joined = normalizeClawclawQueueState(await this.client.joinQueue({
529
+ const response = await this.client.joinQueue({
517
530
  gameType: 'clawclaw',
518
531
  mode: this.initialIntent.mode ?? 'match',
519
532
  agentType: this.initialIntent.agentType,
520
533
  monitorStatus: this.initialIntent.monitorStatus,
521
534
  llmModel: this.initialIntent.llmModel,
522
- }));
535
+ });
536
+ serverStatus = serverServiceStatusFromEnvelope(response);
537
+ joined = normalizeClawclawQueueState(response);
523
538
  } catch (error) {
524
539
  try {
525
540
  return await this.reconcileInitialRequest(
@@ -539,11 +554,15 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
539
554
  }
540
555
  }
541
556
  if (isActiveClawclawQueueStatus(queueStatus(joined))) {
542
- await this.acceptQueueState(joined, [this.joinedEvent(joined)]);
557
+ await this.acceptQueueState(joined, [this.joinedEvent(joined)], serverStatus);
543
558
  return joined;
544
559
  }
545
560
  const reconciled = await this.readQueueRawWithRetry();
546
- await this.acceptQueueState(reconciled, [this.joinedEvent({ ...joined, ...reconciled })]);
561
+ await this.acceptQueueState(
562
+ reconciled,
563
+ [this.joinedEvent({ ...joined, ...reconciled })],
564
+ serverStatus,
565
+ );
547
566
  if (isActiveClawclawQueueStatus(queueStatus(reconciled))) return reconciled;
548
567
  throw new Error('Match join completed without creating an active participation.');
549
568
  }
@@ -556,15 +575,16 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
556
575
  }
557
576
  this.requireInactiveParticipation(existing, 'create a room');
558
577
  let created: Record<string, any>;
578
+ let serverStatus: ServerServiceStatus | undefined;
559
579
  try {
560
- created = normalizeClawclawQueueState(
561
- await this.client.createRoom({
562
- roomType: this.initialIntent.roomType,
563
- agentType: this.initialIntent.agentType,
564
- monitorStatus: this.initialIntent.monitorStatus,
565
- llmModel: this.initialIntent.llmModel,
566
- }),
567
- );
580
+ const response = await this.client.createRoom({
581
+ roomType: this.initialIntent.roomType,
582
+ agentType: this.initialIntent.agentType,
583
+ monitorStatus: this.initialIntent.monitorStatus,
584
+ llmModel: this.initialIntent.llmModel,
585
+ });
586
+ serverStatus = serverServiceStatusFromEnvelope(response);
587
+ created = normalizeClawclawQueueState(response);
568
588
  } catch (error) {
569
589
  return this.reconcileInitialRequest(
570
590
  'create_room',
@@ -581,7 +601,11 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
581
601
  mode: this.initialIntent.roomType ?? 'room',
582
602
  ...created,
583
603
  };
584
- await this.acceptQueueState(queue, [this.roomEntryEvent('room_created', queue)]);
604
+ await this.acceptQueueState(
605
+ queue,
606
+ [this.roomEntryEvent('room_created', queue)],
607
+ serverStatus,
608
+ );
585
609
  return queue;
586
610
  }
587
611
 
@@ -603,12 +627,15 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
603
627
  }
604
628
 
605
629
  let joined: Record<string, any>;
630
+ let serverStatus: ServerServiceStatus | undefined;
606
631
  try {
607
- joined = normalizeClawclawQueueState(await this.client.joinRoom(targetRoomCode, {
632
+ const response = await this.client.joinRoom(targetRoomCode, {
608
633
  agentType: this.initialIntent.agentType,
609
634
  monitorStatus: this.initialIntent.monitorStatus,
610
635
  llmModel: this.initialIntent.llmModel,
611
- }));
636
+ });
637
+ serverStatus = serverServiceStatusFromEnvelope(response);
638
+ joined = normalizeClawclawQueueState(response);
612
639
  } catch (error) {
613
640
  return this.reconcileInitialRequest(
614
641
  'join_room',
@@ -629,7 +656,11 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
629
656
  room_code: targetRoomCode,
630
657
  ...joined,
631
658
  };
632
- await this.acceptQueueState(queue, [this.roomEntryEvent('room_joined', queue)]);
659
+ await this.acceptQueueState(
660
+ queue,
661
+ [this.roomEntryEvent('room_joined', queue)],
662
+ serverStatus,
663
+ );
633
664
  return queue;
634
665
  }
635
666
 
@@ -651,6 +682,11 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
651
682
  accepted: (queue: Record<string, any>) => boolean,
652
683
  lifecycleEvents: (queue: Record<string, any>) => Record<string, unknown>[],
653
684
  ): Promise<Record<string, any>> {
685
+ const maintenance = serverServiceStatusFromApiError(originalError);
686
+ if (maintenance) {
687
+ await this.acceptServiceStatus(maintenance);
688
+ throw originalError;
689
+ }
654
690
  this.diagnostic('runtime.source.initial_request_reconcile', {
655
691
  operation,
656
692
  error: originalError instanceof Error ? originalError.message : String(originalError),
@@ -693,6 +729,11 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
693
729
  try {
694
730
  return normalizeClawclawQueueState(await this.client.getQueueStatus('clawclaw'));
695
731
  } catch (error) {
732
+ const maintenance = serverServiceStatusFromApiError(error);
733
+ if (maintenance) {
734
+ await this.acceptServiceStatus(maintenance);
735
+ throw error;
736
+ }
696
737
  failures += 1;
697
738
  this.currentTransport = 'lobby_http';
698
739
  this.currentConnection = 'disconnected';
@@ -722,6 +763,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
722
763
  private async acceptQueueState(
723
764
  queue: Record<string, any>,
724
765
  lifecycleEvents: readonly Record<string, unknown>[] = [],
766
+ serverStatus?: ServerServiceStatus,
725
767
  ): Promise<void> {
726
768
  const status = queueStatus(queue);
727
769
  const mode = queueMode(queue);
@@ -772,6 +814,30 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
772
814
  CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
773
815
  'lobby-http',
774
816
  events,
817
+ serverStatus && this.shouldEmitServiceStatus(serverStatus)
818
+ ? [serviceStatusEvent(serverStatus)]
819
+ : [],
820
+ );
821
+ }
822
+
823
+ private shouldEmitServiceStatus(status: ServerServiceStatus): boolean {
824
+ const signature = serviceStatusSignature(status);
825
+ const previous = this.lastServiceStatusSignature;
826
+ this.lastServiceStatusSignature = signature;
827
+ if (previous === signature) return false;
828
+ return status.service_status !== 'available' || previous !== undefined;
829
+ }
830
+
831
+ private async acceptServiceStatus(status: ServerServiceStatus): Promise<void> {
832
+ if (!this.shouldEmitServiceStatus(status)) return;
833
+ this.currentTransport = 'lobby_http';
834
+ this.currentConnection = 'connected';
835
+ await this.submitCurrentState(
836
+ 'backend_event',
837
+ CLAWCLAW_LOBBY_HTTP_SOURCE.sourceId,
838
+ 'lobby-http',
839
+ [],
840
+ [serviceStatusEvent(status)],
775
841
  );
776
842
  }
777
843
 
@@ -996,6 +1062,9 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
996
1062
  if (outcome.reason === 'room_destroyed') {
997
1063
  return { kind: 'complete', completion: { reason: 'not_participating' } };
998
1064
  }
1065
+ if (outcome.reason === 'maintenance') {
1066
+ return { kind: 'complete', completion: { reason: 'maintenance' } };
1067
+ }
999
1068
  if (outcome.reason === 'replaced') return { kind: 'complete', completion: { reason: 'replaced' } };
1000
1069
  if (outcome.reason === 'shutdown' || outcome.reason === 'manual') {
1001
1070
  return { kind: 'complete', completion: { reason: 'stopped' } };
@@ -1400,7 +1469,13 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1400
1469
  else if (type === 'room.game_started' || snapshot?.status === 'playing') this.currentStage = 'loading';
1401
1470
  else this.currentStage = 'room';
1402
1471
 
1403
- const rawEvents = type === 'room.snapshot' ? [] : [{ type, ...data }];
1472
+ let rawEvents: Record<string, unknown>[] = type === 'room.snapshot' ? [] : [{ type, ...data }];
1473
+ if (type === 'service_status') {
1474
+ const serverStatus = parseServerServiceStatus(data);
1475
+ rawEvents = serverStatus && this.shouldEmitServiceStatus(serverStatus)
1476
+ ? [serviceStatusEvent(serverStatus)]
1477
+ : [];
1478
+ }
1404
1479
  await this.submit({
1405
1480
  scope,
1406
1481
  sourceId: CLAWCLAW_ROOM_WS_SOURCE.sourceId,
@@ -1475,6 +1550,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1475
1550
 
1476
1551
  private classifyRoomClose(code: number | undefined, reason: string): ClawclawRoomCloseDecision {
1477
1552
  if (code === 4005) return 'room_destroyed';
1553
+ if (code === 4006 || /service_maintenance/i.test(reason)) return 'maintenance';
1478
1554
  if (code === 4002) return 'replaced';
1479
1555
  if (code === 4001) return 'fatal';
1480
1556
  if (code === 4003) return 'reconcile';
@@ -1542,8 +1618,16 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1542
1618
  }
1543
1619
  if (intent.kind === 'start_room') {
1544
1620
  if (this.currentStage !== 'room') throw new Error('start_room requires the room stage.');
1545
- await this.client.startRoom();
1546
- return;
1621
+ try {
1622
+ const result = await this.client.startRoom();
1623
+ const serverStatus = serverServiceStatusFromEnvelope(result);
1624
+ if (serverStatus) await this.acceptServiceStatus(serverStatus);
1625
+ return result;
1626
+ } catch (error) {
1627
+ const maintenance = serverServiceStatusFromApiError(error);
1628
+ if (maintenance) await this.acceptServiceStatus(maintenance);
1629
+ throw error;
1630
+ }
1547
1631
  }
1548
1632
  if (intent.kind === 'training_mode') {
1549
1633
  this.requireTrainingRoomStage(intent.kind);
@@ -1810,6 +1894,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1810
1894
  sourceId: string,
1811
1895
  connectionId: string,
1812
1896
  eventValues: readonly Record<string, unknown>[] = [],
1897
+ backendEventValues: readonly Record<string, unknown>[] = [],
1813
1898
  ): Promise<void> {
1814
1899
  const sourceSeq = ++this.localSourceSeq;
1815
1900
  const receivedAt = new Date().toISOString();
@@ -1820,7 +1905,10 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1820
1905
  sourceKey: `source-state:${this.sourceInstanceId}:${sourceSeq}`,
1821
1906
  sourceSeq,
1822
1907
  state: this.runtimeState(cause),
1823
- events: this.localEvents(eventValues, sourceSeq, receivedAt),
1908
+ events: [
1909
+ ...this.localEvents(eventValues, sourceSeq, receivedAt),
1910
+ ...this.sourceEvents(backendEventValues, { receivedAt, sourceSeq }),
1911
+ ],
1824
1912
  completeness: 'complete',
1825
1913
  receivedAt,
1826
1914
  });
@@ -64,6 +64,7 @@ export type ClawclawSourceCompletionReason =
64
64
  | 'match_timeout'
65
65
  | 'left'
66
66
  | 'not_participating'
67
+ | 'maintenance'
67
68
  | 'replaced'
68
69
  | 'stopped'
69
70
  | 'error';
@@ -78,6 +78,12 @@ export default class RuntimeTaskDemo extends ClawclawComputeStrategy<
78
78
  id: 'runtime-task-demo',
79
79
  name: 'Runtime task demo',
80
80
  description: 'Greets newly visible players and completes the nearest task by local A* path distance.',
81
+ localizations: {
82
+ 'zh-CN': {
83
+ name: 'Runtime 任务演示',
84
+ description: '向新进入视野的玩家打招呼,并按本地 A* 路径距离完成最近任务。',
85
+ },
86
+ },
81
87
  execution: 'parallel_compute',
82
88
  controls: [{
83
89
  id: 'greeting',
@@ -1,9 +1,13 @@
1
1
  import type {
2
+ ClawclawResourceLocalizations,
2
3
  StrategyPoint,
3
4
  } from '../../../../sdk/strategy-plugin/index.js';
4
5
 
5
6
  export interface StrategySource {
6
7
  readonly id: string;
8
+ readonly name?: string;
9
+ readonly description?: string;
10
+ readonly localizations?: ClawclawResourceLocalizations;
7
11
  readonly sourcePath: string;
8
12
  readonly sourceRoot: string;
9
13
  /** Omitted strategies use the persistent, ordered update() contract. */
@@ -7,6 +7,7 @@ import {
7
7
  } from '../../../framework/modules/runtime-module-loader.js';
8
8
  import {
9
9
  STRATEGY_PLUGIN_API_VERSION,
10
+ hasValidClawclawResourceLocalizations,
10
11
  type ClawclawStrategyManifest,
11
12
  type StrategyControlSpec,
12
13
  type StrategyInstance,
@@ -91,6 +92,9 @@ export function validateStrategyModule(
91
92
  if (manifest.id !== source.id) throw new Error('strategy_id_mismatch');
92
93
  if (!nonEmpty(manifest.name)) throw new Error('strategy_name_invalid');
93
94
  if (!nonEmpty(manifest.description)) throw new Error('strategy_description_invalid');
95
+ if (!hasValidClawclawResourceLocalizations(manifest.localizations)) {
96
+ throw new Error('strategy_localizations_invalid');
97
+ }
94
98
  if (
95
99
  manifest.execution !== undefined
96
100
  && manifest.execution !== 'parallel_compute'
@@ -177,6 +177,42 @@ async function run(
177
177
  }
178
178
 
179
179
  describe('ClawClaw Strategy plugin scheduling', () => {
180
+ it('exposes localized metadata only after a strategy becomes active', async () => {
181
+ const plugin = new ClawclawStrategyPlugin({
182
+ executorFactory: () => ({
183
+ runtimeInstanceId: 'localized-metadata-test',
184
+ isAlive: true,
185
+ async start() {},
186
+ async reset() {},
187
+ async update() { return {}; },
188
+ async stop() {},
189
+ }),
190
+ });
191
+ plugin.select({
192
+ id: 'test-strategy',
193
+ name: 'Test strategy',
194
+ description: 'Runs a test strategy.',
195
+ localizations: {
196
+ 'zh-CN': {
197
+ name: '测试策略',
198
+ description: '运行测试策略。',
199
+ },
200
+ },
201
+ sourcePath: 'unused',
202
+ sourceRoot: 'unused',
203
+ });
204
+
205
+ expect(plugin.activeResourceDescriptor('zh-CN')).toBeNull();
206
+ await run(plugin, input(1), context(() => {}));
207
+ expect(plugin.activeResourceDescriptor('zh-CN')).toEqual({
208
+ id: 'test-strategy',
209
+ name: '测试策略',
210
+ description: '运行测试策略。',
211
+ });
212
+ expect(plugin.activeResourceDescriptor('en-US')?.name).toBe('Test strategy');
213
+ await plugin.stop('shutdown');
214
+ });
215
+
180
216
  it('releases each Strategy activation, including a same-id parameter generation', async () => {
181
217
  const releases: Array<{ capability: string; id: string; reason?: string }> = [];
182
218
  const baseContext = context(() => {});
@@ -1,5 +1,6 @@
1
1
  import { isDeepStrictEqual } from 'node:util';
2
2
  import type {
3
+ ClawclawResolvedResourceMetadata,
3
4
  StrategyActionAck,
4
5
  StrategyControlSpec,
5
6
  StrategyControlResult,
@@ -7,6 +8,7 @@ import type {
7
8
  StrategyFrame,
8
9
  StrategyResult,
9
10
  } from '../../../../sdk/strategy-plugin/index.js';
11
+ import { resolveClawclawResourceMetadata } from '../../../../sdk/strategy-plugin/index.js';
10
12
  import type {
11
13
  RuntimeEpochCatchUp,
12
14
  RuntimeDiagnosticSeverity,
@@ -481,6 +483,17 @@ implements RuntimeEpochPlugin<Record<string, any>> {
481
483
  };
482
484
  }
483
485
 
486
+ activeResourceDescriptor(locale: string): ClawclawResolvedResourceMetadata | null {
487
+ const selection = this.selected;
488
+ if (!selection?.name?.trim() || !selection.description?.trim()) return null;
489
+ return resolveClawclawResourceMetadata({
490
+ id: selection.id,
491
+ name: selection.name,
492
+ description: selection.description,
493
+ ...(selection.localizations ? { localizations: selection.localizations } : {}),
494
+ }, locale);
495
+ }
496
+
484
497
  async update(
485
498
  input: RuntimeEpochPluginInput<Record<string, any>>,
486
499
  context: RuntimeEpochPluginContext<Record<string, any>>,
@@ -39,6 +39,16 @@ describe('default strategy resolution', () => {
39
39
  .toEqual(Object.keys(readGameplayConfig(path).default_strategies));
40
40
  expect(listClawclawStrategySources(path).find(source => source.id === 'task-only'))
41
41
  .toMatchObject({ execution: 'parallel_analyze' });
42
+ expect(listClawclawStrategySources(path).find(source => source.id === 'runtime-task-demo'))
43
+ .toMatchObject({
44
+ name: 'Runtime task demo',
45
+ localizations: {
46
+ 'zh-CN': {
47
+ name: 'Runtime 任务演示',
48
+ description: '向新进入视野的玩家打招呼,并按本地 A* 路径距离完成最近任务。',
49
+ },
50
+ },
51
+ });
42
52
  });
43
53
 
44
54
  it('rejects a disabled default while ignoring unrelated stale disabled ids', async () => {
@@ -114,6 +124,12 @@ describe('default strategy resolution', () => {
114
124
  id: 'invalid-hybrid-controls',
115
125
  name: 'Invalid hybrid controls',
116
126
  description: 'Controls would split analyzer and reducer generations.',
127
+ localizations: {
128
+ 'zh-CN': {
129
+ name: '混合策略控制测试',
130
+ description: '验证分析器和归约器的参数屏障。',
131
+ },
132
+ },
117
133
  execution: 'parallel_analyze',
118
134
  controls: [{ id: 'target', type: 'string', description: 'Target.' }],
119
135
  };
@@ -126,6 +142,12 @@ describe('default strategy resolution', () => {
126
142
  id: 'invalid-hybrid-controls',
127
143
  execution: 'parallel_analyze',
128
144
  controls: [{ id: 'target', type: 'string', description: 'Target.' }],
145
+ localizations: {
146
+ 'zh-CN': {
147
+ name: '混合策略控制测试',
148
+ description: '验证分析器和归约器的参数屏障。',
149
+ },
150
+ },
129
151
  }));
130
152
  });
131
153
  });
@@ -23,7 +23,10 @@ import {
23
23
  getUserDataStrategiesDir,
24
24
  } from '../../../../lib/user-data.js';
25
25
  import type { StrategySource } from './strategy-executor-types.js';
26
- import type { StrategyControlSpec } from '../../../../sdk/strategy-plugin/index.js';
26
+ import type {
27
+ ClawclawResourceLocalizations,
28
+ StrategyControlSpec,
29
+ } from '../../../../sdk/strategy-plugin/index.js';
27
30
 
28
31
  export const CLAWCLAW_TASK_ONLY_DEMO_STRATEGY_ID = 'runtime-task-demo';
29
32
 
@@ -49,20 +52,9 @@ export interface ResolvedClawclawStrategySource extends StrategySource {
49
52
  }
50
53
 
51
54
  function demoSource(): ResolvedClawclawStrategySource {
52
- return {
53
- id: CLAWCLAW_TASK_ONLY_DEMO_STRATEGY_ID,
54
- name: 'Runtime task demo',
55
- description: 'Greets newly visible players and completes the nearest task by local A* path distance.',
56
- execution: 'parallel_compute',
57
- controls: [{
58
- id: 'greeting',
59
- type: 'string',
60
- description: 'Speech template used for newly visible players; {player} is replaced with the player name.',
61
- default: '你好,{player}',
62
- }],
63
- sourcePath: DEMO_SOURCE,
64
- sourceRoot: dirname(DEMO_SOURCE),
65
- };
55
+ const source = parseClassStrategy(DEMO_SOURCE, dirname(DEMO_SOURCE));
56
+ if (!source) throw new Error('Bundled Runtime task demo strategy manifest is invalid.');
57
+ return source;
66
58
  }
67
59
 
68
60
  function isPathInside(root: string, candidate: string): boolean {
@@ -258,6 +250,36 @@ function parseControlSpecs(classBody: string): StrategyControlSpec[] | undefined
258
250
  return controls;
259
251
  }
260
252
 
253
+ function literalLocalizations(
254
+ source: string,
255
+ ): ClawclawResourceLocalizations | null | undefined {
256
+ const property = /\blocalizations\s*:\s*\{/m.exec(source);
257
+ if (!property) return undefined;
258
+ const open = property.index + property[0].lastIndexOf('{');
259
+ const block = balancedBlock(source, open);
260
+ if (!block) return null;
261
+ const values: Record<string, { name: string; description: string }> = {};
262
+ const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g;
263
+ let cursor = 1;
264
+ let match: RegExpExecArray | null;
265
+ while ((match = entry.exec(block)) !== null) {
266
+ if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null;
267
+ if (match[1] === '`' && match[2].includes('${')) return null;
268
+ const locale = decodeEscapedString(match[2])?.trim();
269
+ const entryOpen = match.index + match[0].lastIndexOf('{');
270
+ const entryBlock = balancedBlock(block, entryOpen);
271
+ if (!locale || !entryBlock || values[locale]) return null;
272
+ const name = literalProperty(entryBlock, 'name')?.trim();
273
+ const description = literalProperty(entryBlock, 'description')?.trim();
274
+ if (!name || !description) return null;
275
+ values[locale] = { name, description };
276
+ cursor = entryOpen + entryBlock.length;
277
+ entry.lastIndex = cursor;
278
+ }
279
+ if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null;
280
+ return values;
281
+ }
282
+
261
283
  function parseClassStrategy(
262
284
  sourcePath: string,
263
285
  strategiesRoot: string,
@@ -285,7 +307,14 @@ function parseClassStrategy(
285
307
  const id = literalProperty(manifest, 'id')?.trim();
286
308
  const name = literalProperty(manifest, 'name')?.trim();
287
309
  const description = literalProperty(manifest, 'description')?.trim();
288
- if (!id || !name || !description || !/^[a-z0-9][a-z0-9._-]*$/.test(id)) return null;
310
+ const localizations = literalLocalizations(manifest);
311
+ if (
312
+ !id
313
+ || !name
314
+ || !description
315
+ || localizations === null
316
+ || !/^[a-z0-9][a-z0-9._-]*$/.test(id)
317
+ ) return null;
289
318
  const execution = literalProperty(manifest, 'execution')?.trim() ?? null;
290
319
  const computeClass = classMatch[1] === 'ClawclawComputeStrategy';
291
320
  const directHybridClass = classMatch[1] === 'ClawclawHybridStrategy';
@@ -320,6 +349,7 @@ function parseClassStrategy(
320
349
  id,
321
350
  name,
322
351
  description,
352
+ ...(localizations === undefined ? {} : { localizations }),
323
353
  ...(execution === null ? {} : { execution: execution as 'parallel_compute' | 'parallel_analyze' }),
324
354
  ...(controls === undefined ? {} : { controls }),
325
355
  sourcePath,
@@ -11,6 +11,7 @@ describe('ClawClaw Event Catalog', () => {
11
11
  it('uses the two explicit Agent registries and keeps events-only empty', () => {
12
12
  expect(CLAWCLAW_EVENTS_ONLY_EVENT_TYPES.size).toBe(0);
13
13
  expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('speech_your_turn');
14
+ expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('service_status');
14
15
  expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('room_attached');
15
16
  expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('quit_requested');
16
17
  expect(CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES).toContain('room_created');
@@ -26,6 +27,7 @@ describe('ClawClaw Event Catalog', () => {
26
27
  it('enforces a single producer for known semantics', () => {
27
28
  const catalog = createClawclawEventCatalog();
28
29
  expect(catalog.resolve('game_over', 'backend_push').deliveryClass).toBe('monitor_and_events');
30
+ expect(catalog.resolve('service_status', 'backend_push').deliveryClass).toBe('monitor_and_events');
29
31
  expect(() => catalog.resolve('game_over', 'local_synth')).toThrow(/must be produced by backend_push/);
30
32
  expect(catalog.resolve('future_backend_event', 'backend_push').deliveryClass).toBe('internal_only');
31
33
  });
@@ -90,6 +90,7 @@ export const CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES = [
90
90
 
91
91
  /** Backend facts that wake Monitor and remain available through ccl events. */
92
92
  export const CLAWCLAW_BACKEND_AGENT_EVENT_TYPES = [
93
+ 'service_status',
93
94
  'move_interrupted',
94
95
  'kill',
95
96
  'killed',
@@ -1,5 +1,18 @@
1
1
  export const PERCEPTION_PLUGIN_API_VERSION = 1 as const;
2
2
 
3
+ export {
4
+ hasValidClawclawResourceLocalizations,
5
+ resolveClawclawResourceMetadata,
6
+ } from '../resource-metadata.js';
7
+ export type {
8
+ ClawclawLocalizedResourceText,
9
+ ClawclawResolvedResourceMetadata,
10
+ ClawclawResourceLocalizations,
11
+ ClawclawResourceMetadata,
12
+ } from '../resource-metadata.js';
13
+
14
+ import type { ClawclawResourceLocalizations } from '../resource-metadata.js';
15
+
3
16
  export type PerceptionSubjectScope =
4
17
  | 'others'
5
18
  | 'self_and_others'
@@ -188,6 +201,7 @@ export interface ClawclawPerceptionManifest {
188
201
  readonly id: string;
189
202
  readonly name: string;
190
203
  readonly description: string;
204
+ readonly localizations?: ClawclawResourceLocalizations;
191
205
  /** Describes Event subjects; every module still receives self as a spatial reference. */
192
206
  readonly subjectScope: PerceptionSubjectScope;
193
207
  readonly produces: readonly string[];
@@ -0,0 +1,40 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ hasValidClawclawResourceLocalizations,
4
+ resolveClawclawResourceMetadata,
5
+ } from './resource-metadata.js';
6
+
7
+ const metadata = {
8
+ id: 'visual.motion',
9
+ name: 'Player movement',
10
+ description: 'Reports movement.',
11
+ localizations: {
12
+ 'zh-CN': {
13
+ name: '玩家移动',
14
+ description: '感知玩家移动。',
15
+ },
16
+ en: {
17
+ name: 'Movement',
18
+ description: 'Perceives movement.',
19
+ },
20
+ },
21
+ } as const;
22
+
23
+ describe('resource metadata localization', () => {
24
+ it('resolves an exact locale, then language and manifest fallbacks', () => {
25
+ expect(resolveClawclawResourceMetadata(metadata, 'zh_CN')).toEqual({
26
+ id: 'visual.motion',
27
+ name: '玩家移动',
28
+ description: '感知玩家移动。',
29
+ });
30
+ expect(resolveClawclawResourceMetadata(metadata, 'en-US').name).toBe('Movement');
31
+ expect(resolveClawclawResourceMetadata(metadata, 'ja-JP').name).toBe('Player movement');
32
+ });
33
+
34
+ it('rejects incomplete localized display text', () => {
35
+ expect(hasValidClawclawResourceLocalizations(metadata.localizations)).toBe(true);
36
+ expect(hasValidClawclawResourceLocalizations({
37
+ 'zh-CN': { name: '玩家移动', description: ' ' },
38
+ })).toBe(false);
39
+ });
40
+ });