@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
@@ -15,7 +15,10 @@ import {
15
15
  ensureUserDataLayout,
16
16
  getUserDataPerceptionsDir,
17
17
  } from '../../../../lib/user-data.js';
18
- import type { ClawclawPerceptionManifest } from './contracts.js';
18
+ import type {
19
+ ClawclawPerceptionManifest,
20
+ ClawclawResourceLocalizations,
21
+ } from './contracts.js';
19
22
 
20
23
  export const MAX_PERCEPTION_FILES = 512;
21
24
  const MAX_PERCEPTION_SOURCE_BYTES = 2 * 1024 * 1024;
@@ -137,6 +140,36 @@ function literalStringArray(source: string, property: string): string[] | null {
137
140
  return residue.length === 0 ? values : null;
138
141
  }
139
142
 
143
+ function literalLocalizations(
144
+ source: string,
145
+ ): ClawclawResourceLocalizations | null | undefined {
146
+ const property = /\blocalizations\s*:\s*\{/m.exec(source);
147
+ if (!property) return undefined;
148
+ const open = property.index + property[0].lastIndexOf('{');
149
+ const block = balancedBlock(source, open, '{', '}');
150
+ if (!block) return null;
151
+ const values: Record<string, { name: string; description: string }> = {};
152
+ const entry = /(["'\x60])((?:\\.|(?!\1)[\s\S])*)\1\s*:\s*\{/g;
153
+ let cursor = 1;
154
+ let match: RegExpExecArray | null;
155
+ while ((match = entry.exec(block)) !== null) {
156
+ if (block.slice(cursor, match.index).replace(/[\s,]/g, '')) return null;
157
+ if (match[1] === '`' && match[2].includes('${')) return null;
158
+ const locale = decodeString(match[2])?.trim();
159
+ const entryOpen = match.index + match[0].lastIndexOf('{');
160
+ const entryBlock = balancedBlock(block, entryOpen, '{', '}');
161
+ if (!locale || !entryBlock || values[locale]) return null;
162
+ const name = literalProperty(entryBlock, 'name')?.trim();
163
+ const description = literalProperty(entryBlock, 'description')?.trim();
164
+ if (!name || !description) return null;
165
+ values[locale] = { name, description };
166
+ cursor = entryOpen + entryBlock.length;
167
+ entry.lastIndex = cursor;
168
+ }
169
+ if (block.slice(cursor, -1).replace(/[\s,]/g, '')) return null;
170
+ return values;
171
+ }
172
+
140
173
  function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPerceptionSource | null {
141
174
  let source: string;
142
175
  try {
@@ -163,6 +196,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
163
196
  const produces = literalStringArray(manifestBlock, 'produces');
164
197
  const execution = literalProperty(manifestBlock, 'execution')?.trim();
165
198
  const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
199
+ const localizations = literalLocalizations(manifestBlock);
166
200
  const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
167
201
  if (
168
202
  !id
@@ -180,12 +214,14 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
180
214
  && (execution !== 'parallel_analysis' || boundaryBaseline !== 'current_only')
181
215
  )
182
216
  || parallelClass !== (execution === 'parallel_analysis')
217
+ || localizations === null
183
218
  ) return null;
184
219
 
185
220
  const manifest: ClawclawPerceptionManifest = {
186
221
  id,
187
222
  name,
188
223
  description,
224
+ ...(localizations === undefined ? {} : { localizations }),
189
225
  subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
190
226
  produces,
191
227
  ...(execution ? { execution: 'parallel_analysis' as const } : {}),
@@ -407,6 +407,7 @@ describe('ClawClaw runtime capabilities', () => {
407
407
 
408
408
  it('advances the Mailbox Event cursor without flushing delivery per epoch', async () => {
409
409
  const driver = {
410
+ observeEvents: vi.fn(),
410
411
  flush: vi.fn(async () => {}),
411
412
  stop: vi.fn(async () => {}),
412
413
  };
@@ -444,6 +445,10 @@ describe('ClawClaw runtime capabilities', () => {
444
445
  eventCursor: 1,
445
446
  completedThroughEpochSeq: 2,
446
447
  });
448
+ expect(driver.observeEvents).toHaveBeenCalledOnce();
449
+ expect(driver.observeEvents).toHaveBeenCalledWith([
450
+ expect.objectContaining({ type: 'task_completed' }),
451
+ ]);
447
452
  expect(driver.flush).not.toHaveBeenCalled();
448
453
  await runtime.close();
449
454
  expect(driver.flush).toHaveBeenCalledOnce();
@@ -16,6 +16,7 @@ export type ClawclawRoomTransportStopReason =
16
16
  | 'game_started'
17
17
  | 'self_left'
18
18
  | 'room_destroyed'
19
+ | 'maintenance'
19
20
  | 'reconcile'
20
21
  | 'replaced'
21
22
  | 'fatal'
@@ -31,7 +32,7 @@ export interface ClawclawRoomCloseInfo {
31
32
  reason: string;
32
33
  }
33
34
 
34
- export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'reconcile' | 'replaced' | 'fatal';
35
+ export type ClawclawRoomCloseDecision = 'retry' | 'room_destroyed' | 'maintenance' | 'reconcile' | 'replaced' | 'fatal';
35
36
 
36
37
  export interface ClawclawRoomTransportFrameMeta {
37
38
  connectionId: string;
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
  import { ApiError } from '../../../../lib/http-transport.js';
3
3
  import { presentCanonicalEvent } from '../../../../pipeline/canonical-event-presentation.js';
4
+ import { jsonTransportResponse } from '../../../../short-command/transport-response.js';
4
5
  import { createClawclawEventCatalog } from '../../../clawclaw-event-catalog.js';
5
6
  import { projectClawclawCurrentState } from '../../runtime-state.js';
6
7
  import { MemoryEventRepository } from '../../../framework/events/index.js';
@@ -46,7 +47,7 @@ class FakeClient implements ClawclawSourceClient {
46
47
  }));
47
48
  readonly leaveQueue = vi.fn(async () => ({ success: true }));
48
49
  readonly leaveGame = vi.fn(async (): Promise<any> => ({ success: true }));
49
- readonly createRoom = vi.fn(async (_options?: import('../../../../lib/room.js').CreateRoomOptions) => ({ room_code: 'R1' }));
50
+ readonly createRoom = vi.fn(async (_options?: import('../../../../lib/room.js').CreateRoomOptions): Promise<any> => ({ room_code: 'R1' }));
50
51
  readonly joinRoom = vi.fn(async (
51
52
  roomCode: string,
52
53
  _metadata?: import('../../../../lib/room.js').RoomEntryMetadata,
@@ -303,7 +304,154 @@ function gameStateFrame(
303
304
  };
304
305
  }
305
306
 
307
+ const maintenanceWindow = {
308
+ starts_at: '2026-08-05T01:00:00+00:00',
309
+ ends_at: '2026-08-05T03:00:00+00:00',
310
+ };
311
+
312
+ function maintenanceApiError(method = 'GET', path = '/api/v1/queue/status'): ApiError {
313
+ const payload = {
314
+ success: false,
315
+ error: { code: 'SERVICE_MAINTENANCE', message: 'Service is under maintenance' },
316
+ server: { service_status: 'maintenance_active', maintenance: maintenanceWindow },
317
+ };
318
+ const response = jsonTransportResponse(payload, {
319
+ method,
320
+ path,
321
+ status: 503,
322
+ headers: { 'content-type': 'application/json', 'retry-after': '7200' },
323
+ });
324
+ return new ApiError(503, response.body.rawText, method, path, response);
325
+ }
326
+
306
327
  describe('ClawclawSourcePlugin lifecycle', () => {
328
+ it('delivers upcoming maintenance through the canonical Mailbox path without blocking room creation', async () => {
329
+ const { runtime, events, client, source, rooms } = await fixture(
330
+ [{ status: 'not_in_queue' }],
331
+ { kind: 'create_room' },
332
+ {
333
+ configureClient: (fake) => {
334
+ fake.createRoom.mockResolvedValue({
335
+ success: true,
336
+ data: { room_code: 'R1' },
337
+ server: {
338
+ service_status: 'maintenance_upcoming',
339
+ maintenance: maintenanceWindow,
340
+ },
341
+ });
342
+ },
343
+ },
344
+ );
345
+ await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
346
+ await rooms[0].emit('service_status', {
347
+ service_status: 'maintenance_upcoming',
348
+ maintenance: maintenanceWindow,
349
+ }, {
350
+ room_code: 'R1',
351
+ status: 'waiting',
352
+ members: [],
353
+ }, 1);
354
+ await runtime.flush();
355
+
356
+ expect(client.createRoom).toHaveBeenCalledOnce();
357
+ const committed = runtime.repository.listCommittedEvents({
358
+ sessionId: runtime.scope().sessionId,
359
+ types: ['service_status'],
360
+ });
361
+ expect(committed).toHaveLength(1);
362
+ expect(committed[0]).toMatchObject({
363
+ type: 'service_status',
364
+ producer: 'backend_push',
365
+ deliveryClass: 'monitor_and_events',
366
+ payload: {
367
+ service_status: 'maintenance_upcoming',
368
+ maintenance: maintenanceWindow,
369
+ },
370
+ });
371
+ const mailbox = new ClawclawMailboxService({
372
+ repository: events,
373
+ readyView: () => runtime.readReadyView(),
374
+ });
375
+ const delivered = mailbox.prepareEvents({ eventType: 'service_status' }).output.event as Record<string, any>;
376
+ expect(delivered).toMatchObject({
377
+ type: 'service_status',
378
+ service_status: 'maintenance_upcoming',
379
+ maintenance: maintenanceWindow,
380
+ });
381
+ expect(delivered.hint).toContain('current request succeeded');
382
+
383
+ await source.stop();
384
+ await runtime.close();
385
+ });
386
+
387
+ it('treats the documented Lobby WebSocket maintenance close as terminal', async () => {
388
+ const { runtime, source, rooms } = await fixture([{
389
+ status: 'in_room', mode: 'room', room_code: 'R1',
390
+ }]);
391
+ await waitUntil(() => rooms.length === 1, 'Room transport was not started.');
392
+ await rooms[0].emit('service_status', {
393
+ service_status: 'maintenance_active',
394
+ maintenance: maintenanceWindow,
395
+ }, null, 1);
396
+ await rooms[0].close({ code: 4006, reason: 'SERVICE_MAINTENANCE' });
397
+
398
+ await expect(source.waitForCompletion()).resolves.toEqual({ reason: 'maintenance' });
399
+ await runtime.flush();
400
+ expect(runtime.repository.listCommittedEvents({
401
+ sessionId: runtime.scope().sessionId,
402
+ types: ['service_status'],
403
+ })).toHaveLength(1);
404
+ await runtime.close();
405
+ });
406
+
407
+ it('stops immediately on active maintenance without poll_error retries', async () => {
408
+ const maintenanceError = maintenanceApiError();
409
+ const { runtime, client, source } = await fixture([maintenanceError], { kind: 'match' });
410
+
411
+ await expect(source.waitForCompletion()).resolves.toMatchObject({
412
+ reason: 'maintenance',
413
+ error: maintenanceError,
414
+ });
415
+ await runtime.flush();
416
+
417
+ expect(client.queueStatusReads).toBe(1);
418
+ expect(runtime.repository.listCommittedEvents({
419
+ sessionId: runtime.scope().sessionId,
420
+ types: ['service_status'],
421
+ })).toMatchObject([{
422
+ type: 'service_status',
423
+ producer: 'backend_push',
424
+ payload: {
425
+ service_status: 'maintenance_active',
426
+ maintenance: maintenanceWindow,
427
+ retry_after_seconds: 7200,
428
+ },
429
+ }]);
430
+ expect(runtime.repository.listCommittedEvents({
431
+ sessionId: runtime.scope().sessionId,
432
+ types: ['poll_error', 'error'],
433
+ })).toHaveLength(0);
434
+ await runtime.close();
435
+ });
436
+
437
+ it('does not reconcile a queue join rejected by active maintenance', async () => {
438
+ const maintenanceError = maintenanceApiError('POST', '/api/v1/queue/join');
439
+ const { runtime, client, source } = await fixture(
440
+ [{ status: 'not_in_queue' }],
441
+ { kind: 'match' },
442
+ { configureClient: (fake) => fake.joinQueue.mockRejectedValue(maintenanceError) },
443
+ );
444
+
445
+ await expect(source.waitForCompletion()).resolves.toMatchObject({ reason: 'maintenance' });
446
+ await runtime.flush();
447
+ expect(client.queueStatusReads).toBe(1);
448
+ expect(runtime.repository.listCommittedEvents({
449
+ sessionId: runtime.scope().sessionId,
450
+ types: ['service_status'],
451
+ })).toHaveLength(1);
452
+ await runtime.close();
453
+ });
454
+
307
455
  it('consumes the Owner queue observation without issuing a second startup poll', async () => {
308
456
  const initialQueueState = {
309
457
  status: 'allocated', mode: 'match', game_id: 'G-preflight', ws_url: 'wss://game.test/ws',
@@ -617,6 +765,58 @@ describe('ClawclawSourcePlugin lifecycle', () => {
617
765
  await runtime.close();
618
766
  });
619
767
 
768
+ it('enriches task_completed from a same-frame task_assigned while retaining the raw internal Event', async () => {
769
+ const { runtime, source, games } = await fixture([{
770
+ status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
771
+ }]);
772
+ await waitUntil(() => games.length === 1, 'Game transport was not started.');
773
+
774
+ await games[0].emit(gameStateFrame('game-1', 1, {
775
+ tick: 42,
776
+ phase: 'wandering',
777
+ you: {
778
+ is_alive: true,
779
+ tasks: [{ name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, status: 'normal' }],
780
+ },
781
+ }, [{
782
+ event_id: 'completed-1',
783
+ tick: 42,
784
+ type: 'task_completed',
785
+ actor: { seat: 1, name: 'me' },
786
+ task_name: '擦拭酒瓶',
787
+ }, {
788
+ event_id: 'assigned-1',
789
+ tick: 42,
790
+ type: 'task_assigned',
791
+ actor: { seat: 1, name: 'me' },
792
+ task_name: '消毒淋浴器',
793
+ room: '制氧舱',
794
+ x: 123,
795
+ y: 456,
796
+ is_fake_shrimp: false,
797
+ }]));
798
+ await runtime.flush();
799
+
800
+ expect(runtime.repository.latestEventByType(
801
+ runtime.scope().sessionId,
802
+ 'task_completed',
803
+ runtime.scope().segmentId,
804
+ )?.payload).toMatchObject({
805
+ task_name: '擦拭酒瓶',
806
+ newly_assigned_task: {
807
+ name: '消毒淋浴器', room: '制氧舱', x: 123, y: 456, is_fake_shrimp: false,
808
+ },
809
+ });
810
+ expect(runtime.repository.latestEventByType(
811
+ runtime.scope().sessionId,
812
+ 'task_assigned',
813
+ runtime.scope().segmentId,
814
+ )?.deliveryClass).toBe('internal_only');
815
+
816
+ await source.stop();
817
+ await runtime.close();
818
+ });
819
+
620
820
  it('forbids coalescing only on action-safety boundary frames', async () => {
621
821
  const { runtime, source, games } = await fixture([{
622
822
  status: 'allocated', mode: 'match', game_id: 'G1', ws_url: 'wss://game.test/ws',
@@ -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,
@@ -40,7 +49,7 @@ import {
40
49
  } from '../../../framework/plugins/index.js';
41
50
  import type { RuntimeScope } from '../../../framework/state/index.js';
42
51
  import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
43
- import { normalizeGameSyncEvent } from '../../../../pipeline/game-sync-event-normalization.js';
52
+ import { normalizeGameSyncEvents } from '../../../../pipeline/game-sync-event-normalization.js';
44
53
  import {
45
54
  projectClawclawRoomState,
46
55
  } from '../../../clawclaw-room-state.js';
@@ -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);
@@ -1733,8 +1817,9 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1733
1817
  meta: Pick<WsFrameMeta, 'receivedAt' | 'sourceEventId' | 'sourceSeq'> & { replayed?: boolean },
1734
1818
  ): RuntimeSourceEvent<Record<string, unknown>>[] {
1735
1819
  const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
1736
- values.forEach((value, index) => {
1737
- const normalized = normalizeGameSyncEvent(value);
1820
+ const normalizedValues = normalizeGameSyncEvents(values);
1821
+ normalizedValues.forEach((normalized, index) => {
1822
+ const value = values[index];
1738
1823
  const sourceEventId = eventSourceId(value as Record<string, any>);
1739
1824
  const event = (
1740
1825
  (
@@ -1809,6 +1894,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1809
1894
  sourceId: string,
1810
1895
  connectionId: string,
1811
1896
  eventValues: readonly Record<string, unknown>[] = [],
1897
+ backendEventValues: readonly Record<string, unknown>[] = [],
1812
1898
  ): Promise<void> {
1813
1899
  const sourceSeq = ++this.localSourceSeq;
1814
1900
  const receivedAt = new Date().toISOString();
@@ -1819,7 +1905,10 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1819
1905
  sourceKey: `source-state:${this.sourceInstanceId}:${sourceSeq}`,
1820
1906
  sourceSeq,
1821
1907
  state: this.runtimeState(cause),
1822
- events: this.localEvents(eventValues, sourceSeq, receivedAt),
1908
+ events: [
1909
+ ...this.localEvents(eventValues, sourceSeq, receivedAt),
1910
+ ...this.sourceEvents(backendEventValues, { receivedAt, sourceSeq }),
1911
+ ],
1823
1912
  completeness: 'complete',
1824
1913
  receivedAt,
1825
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. */