@myclaw163/clawclaw-cli 0.7.8 → 0.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/docs/desktop-event-push.md +14 -2
  2. package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +15 -1
  3. package/package.json +1 -1
  4. package/src/pipeline/game-sync-event-normalization.test.ts +33 -0
  5. package/src/pipeline/game-sync-event-normalization.ts +52 -9
  6. package/src/runtime/clawclaw/owner.ts +8 -0
  7. package/src/runtime/clawclaw/plugins/assembly.test.ts +13 -0
  8. package/src/runtime/clawclaw/plugins/assembly.ts +10 -0
  9. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +17 -5
  10. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +37 -3
  11. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +49 -14
  12. package/src/runtime/clawclaw/plugins/perception/contracts.ts +1 -0
  13. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +16 -0
  14. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +16 -0
  15. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +16 -0
  16. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +23 -0
  17. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +16 -0
  18. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +16 -0
  19. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +23 -0
  20. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +19 -0
  21. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +41 -0
  22. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +49 -0
  23. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +105 -5
  24. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +174 -0
  25. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +146 -66
  26. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +36 -0
  27. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +0 -5
  28. package/src/sdk/perception-plugin/index.ts +8 -0
@@ -49,7 +49,7 @@ import {
49
49
  } from '../../../framework/plugins/index.js';
50
50
  import type { RuntimeScope } from '../../../framework/state/index.js';
51
51
  import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
52
- import { normalizeGameSyncEvents } from '../../../../pipeline/game-sync-event-normalization.js';
52
+ import { normalizeGameSyncEventsSafely } from '../../../../pipeline/game-sync-event-normalization.js';
53
53
  import {
54
54
  projectClawclawRoomState,
55
55
  } from '../../../clawclaw-room-state.js';
@@ -1127,6 +1127,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1127
1127
  transport: 'game_ws',
1128
1128
  connection_id: info.connectionId,
1129
1129
  reason: info.reason,
1130
+ ...(info.details ? { details: info.details } : {}),
1130
1131
  }, 'warn');
1131
1132
  },
1132
1133
  onRecoveryStarted: (info) => this.handleGameRecoveryStarted(info),
@@ -1302,72 +1303,133 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1302
1303
  }, 'error');
1303
1304
  return 'error';
1304
1305
  }
1305
- const gameState = frame.state;
1306
+ const rawState: unknown = frame.state;
1307
+ if (!rawState || typeof rawState !== 'object' || Array.isArray(rawState)) {
1308
+ this.diagnostic('runtime.source.frame_rejected', {
1309
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1310
+ source_seq: frame.meta.sourceSeq,
1311
+ error_code: 'GAME_SYNC_STATE_INVALID',
1312
+ reason: 'state_not_object',
1313
+ }, 'error');
1314
+ return;
1315
+ }
1316
+ const gameState = rawState as Record<string, any>;
1306
1317
  const tick = frame.meta.domainTick;
1318
+ const stateTick = gameState.tick;
1319
+ if (
1320
+ !Number.isInteger(tick)
1321
+ || tick < 0
1322
+ || !Number.isInteger(stateTick)
1323
+ || Number(stateTick) < 0
1324
+ || Number(stateTick) !== tick
1325
+ ) {
1326
+ this.diagnostic('runtime.source.frame_rejected', {
1327
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1328
+ source_seq: frame.meta.sourceSeq,
1329
+ error_code: 'GAME_SYNC_TICK_INVALID',
1330
+ reason: Number.isInteger(tick) && Number.isInteger(stateTick)
1331
+ ? 'tick_mismatch'
1332
+ : 'tick_missing_or_invalid',
1333
+ frame_tick: tick,
1334
+ state_tick: stateTick,
1335
+ }, 'error');
1336
+ return;
1337
+ }
1338
+ const previousState = this.latestFreshGameState;
1339
+ const missingFields = new Set<string>();
1340
+ if (!Object.prototype.hasOwnProperty.call(gameState, 'phase')) missingFields.add('phase');
1341
+ if (previousState) {
1342
+ for (const field of Object.keys(previousState)) {
1343
+ if (!Object.prototype.hasOwnProperty.call(gameState, field)) missingFields.add(field);
1344
+ }
1345
+ }
1346
+ if (missingFields.size > 0) {
1347
+ this.diagnostic('runtime.source.state_degraded', {
1348
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1349
+ source_seq: frame.meta.sourceSeq,
1350
+ error_code: 'GAME_SYNC_STATE_FIELDS_MISSING',
1351
+ missing_fields: [...missingFields].sort(),
1352
+ }, 'warn');
1353
+ }
1307
1354
  let acceptedStage: ClawclawRuntimeStage | undefined;
1308
1355
  let acceptedPlayerProjection: PlayerProjection[] | undefined;
1309
1356
  const acceptance = await this.enqueueInputIf(() => {
1310
1357
  if (this.currentStage === 'ended') return null;
1311
- const scope = this.requireConnectionScope(
1312
- CLAWCLAW_GAME_WS_SOURCE.sourceId,
1313
- frame.meta.connectionId,
1314
- );
1315
- const backendEvents = this.sourceEvents(frame.events, frame.meta);
1316
- const recoveryIdentity = `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:${frame.meta.connectionId}`;
1317
- const recoveryEvents = frame.meta.origin === 'resume' || frame.meta.snapshotFallback
1318
- ? this.localEvents([{
1319
- type: 'game_stream_reconnected',
1320
- recovery: frame.meta.origin,
1321
- replayed_event_count: frame.events.length,
1322
- }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt)
1323
- : [];
1324
- const playerUpdate = nextPlayerProjection({
1325
- previous: this.playerProjection,
1326
- initialized: this.playerProjectionInitialized,
1327
- summary: gameState,
1328
- events: frame.events,
1329
- selfName: this.profile.agentName,
1330
- });
1331
- const events = [
1332
- ...backendEvents,
1333
- ...recoveryEvents,
1334
- ...(playerUpdate.payload
1335
- ? [this.playersChangedEvent(
1336
- playerUpdate.payload,
1337
- frame.meta.receivedAt,
1338
- `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1339
- )]
1340
- : []),
1341
- ];
1342
- acceptedPlayerProjection = playerUpdate.projection;
1343
- this.currentTransport = 'game_ws';
1344
- this.currentConnection = 'connected';
1345
- acceptedStage = clawclawStageFromGameEvents(
1346
- frame.events,
1347
- clawclawStageFromGameState(gameState),
1348
- );
1349
- return {
1350
- scope,
1351
- sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1352
- connectionId: frame.meta.connectionId,
1353
- // A resume barrier has no sequence of its own. In the valid zero-replay
1354
- // case its to_seq equals the last update accepted before disconnect, so
1355
- // include the new connection identity to avoid retry-conflicting with
1356
- // that earlier runtime input while preserving the backend sequence.
1357
- sourceKey: frame.meta.origin === 'resume'
1358
- ? `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:resume:${frame.meta.connectionId}`
1359
- : `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1360
- sourceSeq: `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1361
- domainTick: tick,
1362
- state: this.gameRuntimeState(
1363
- acceptedStage,
1364
- acceptedStage === 'ended' ? 'ending' : 'game_snapshot',
1365
- { status: 'fresh', state: structuredClone(gameState) },
1366
- ),
1367
- events,
1368
- completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete',
1369
- receivedAt: frame.meta.receivedAt,
1370
- };
1358
+ try {
1359
+ const scope = this.requireConnectionScope(
1360
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1361
+ frame.meta.connectionId,
1362
+ );
1363
+ const backendEvents = this.sourceEvents(
1364
+ frame.events,
1365
+ frame.meta,
1366
+ CLAWCLAW_GAME_WS_SOURCE.sourceId,
1367
+ );
1368
+ const recoveryIdentity = `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:${frame.meta.connectionId}`;
1369
+ const recoveryEvents = frame.meta.origin === 'resume' || frame.meta.snapshotFallback
1370
+ ? this.localEvents([{
1371
+ type: 'game_stream_reconnected',
1372
+ recovery: frame.meta.origin,
1373
+ replayed_event_count: frame.events.length,
1374
+ }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt)
1375
+ : [];
1376
+ const playerUpdate = nextPlayerProjection({
1377
+ previous: this.playerProjection,
1378
+ initialized: this.playerProjectionInitialized,
1379
+ summary: gameState,
1380
+ events: frame.events,
1381
+ selfName: this.profile.agentName,
1382
+ });
1383
+ const events = [
1384
+ ...backendEvents,
1385
+ ...recoveryEvents,
1386
+ ...(playerUpdate.payload
1387
+ ? [this.playersChangedEvent(
1388
+ playerUpdate.payload,
1389
+ frame.meta.receivedAt,
1390
+ `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1391
+ )]
1392
+ : []),
1393
+ ];
1394
+ acceptedPlayerProjection = playerUpdate.projection;
1395
+ this.currentTransport = 'game_ws';
1396
+ this.currentConnection = 'connected';
1397
+ acceptedStage = clawclawStageFromGameEvents(
1398
+ frame.events,
1399
+ clawclawStageFromGameState(gameState),
1400
+ );
1401
+ return {
1402
+ scope,
1403
+ sourceId: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1404
+ connectionId: frame.meta.connectionId,
1405
+ // A resume barrier has no sequence of its own. In the valid zero-replay
1406
+ // case its to_seq equals the last update accepted before disconnect, so
1407
+ // include the new connection identity to avoid retry-conflicting with
1408
+ // that earlier runtime input while preserving the backend sequence.
1409
+ sourceKey: frame.meta.origin === 'resume'
1410
+ ? `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}:resume:${frame.meta.connectionId}`
1411
+ : `game:${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1412
+ sourceSeq: `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1413
+ domainTick: tick,
1414
+ state: this.gameRuntimeState(
1415
+ acceptedStage,
1416
+ acceptedStage === 'ended' ? 'ending' : 'game_snapshot',
1417
+ { status: 'fresh', state: structuredClone(gameState) },
1418
+ ),
1419
+ events,
1420
+ completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete',
1421
+ receivedAt: frame.meta.receivedAt,
1422
+ };
1423
+ } catch (error) {
1424
+ this.diagnostic('runtime.source.frame_rejected', {
1425
+ source_id: CLAWCLAW_GAME_WS_SOURCE.sourceId,
1426
+ source_seq: frame.meta.sourceSeq,
1427
+ error_code: 'GAME_SYNC_FRAME_PROJECTION_FAILED',
1428
+ error_name: error instanceof Error ? error.name : 'Error',
1429
+ error: serializeError(error),
1430
+ }, 'error');
1431
+ return null;
1432
+ }
1371
1433
  }, () => {
1372
1434
  this.currentStage = acceptedStage!;
1373
1435
  this.currentQueue = undefined;
@@ -1483,7 +1545,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1483
1545
  sourceKey: this.physicalSourceKey('room', meta),
1484
1546
  sourceSeq: `${meta.connectionId}:${String(meta.sourceSeq)}`,
1485
1547
  state: this.runtimeState(this.currentStage === 'ended' ? 'ending' : 'room_update'),
1486
- events: this.sourceEvents(rawEvents, meta),
1548
+ events: this.sourceEvents(rawEvents, meta, CLAWCLAW_ROOM_WS_SOURCE.sourceId),
1487
1549
  completeness: meta.replay || !hadSnapshot ? 'best_effort' : 'complete',
1488
1550
  receivedAt: meta.receivedAt,
1489
1551
  });
@@ -1815,10 +1877,28 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1815
1877
  private sourceEvents(
1816
1878
  values: readonly unknown[],
1817
1879
  meta: Pick<WsFrameMeta, 'receivedAt' | 'sourceEventId' | 'sourceSeq'> & { replayed?: boolean },
1880
+ sourceId: string,
1818
1881
  ): RuntimeSourceEvent<Record<string, unknown>>[] {
1819
1882
  const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
1820
- const normalizedValues = normalizeGameSyncEvents(values);
1821
- normalizedValues.forEach((normalized, index) => {
1883
+ const normalizedValues = normalizeGameSyncEventsSafely(values);
1884
+ normalizedValues.rejected.forEach(({ index, error }) => {
1885
+ const value = values[index];
1886
+ const raw = value && typeof value === 'object' && !Array.isArray(value)
1887
+ ? value as Record<string, unknown>
1888
+ : undefined;
1889
+ const sourceEventId = raw ? eventSourceId(raw) : undefined;
1890
+ this.diagnostic('runtime.source.event_rejected', {
1891
+ source_id: sourceId,
1892
+ source_seq: meta.sourceSeq,
1893
+ event_index: index,
1894
+ error_code: 'GAME_SYNC_EVENT_NORMALIZATION_FAILED',
1895
+ error_name: error instanceof Error ? error.name : 'Error',
1896
+ error: serializeError(error),
1897
+ ...(typeof raw?.type === 'string' ? { event_type: raw.type } : {}),
1898
+ ...(sourceEventId === undefined ? {} : { source_event_id: sourceEventId }),
1899
+ }, 'error');
1900
+ });
1901
+ normalizedValues.events.forEach(({ event: normalized, index }) => {
1822
1902
  const value = values[index];
1823
1903
  const sourceEventId = eventSourceId(value as Record<string, any>);
1824
1904
  const event = (
@@ -1907,7 +1987,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1907
1987
  state: this.runtimeState(cause),
1908
1988
  events: [
1909
1989
  ...this.localEvents(eventValues, sourceSeq, receivedAt),
1910
- ...this.sourceEvents(backendEventValues, { receivedAt, sourceSeq }),
1990
+ ...this.sourceEvents(backendEventValues, { receivedAt, sourceSeq }, sourceId),
1911
1991
  ],
1912
1992
  completeness: 'complete',
1913
1993
  receivedAt,
@@ -1929,6 +1929,42 @@ describe('RuntimePluginScheduler', () => {
1929
1929
  expect(stopped).toEqual(['shutdown']);
1930
1930
  });
1931
1931
 
1932
+ it('logs a plugin flush failure without failing shutdown or skipping peer plugins', async () => {
1933
+ const flushed: string[] = [];
1934
+ const test = harness([{
1935
+ kind: 'epoch',
1936
+ id: 'flush-failure',
1937
+ version: '1',
1938
+ update: () => ({ outcome: 'noop' }),
1939
+ flush() {
1940
+ flushed.push('flush-failure');
1941
+ throw new Error('broken plugin flush');
1942
+ },
1943
+ }, {
1944
+ kind: 'epoch',
1945
+ id: 'flush-peer',
1946
+ version: '1',
1947
+ update: () => ({ outcome: 'noop' }),
1948
+ flush() {
1949
+ flushed.push('flush-peer');
1950
+ },
1951
+ }]);
1952
+
1953
+ await test.scheduler.enqueue(test.work(1));
1954
+ await expect(test.scheduler.close()).resolves.toBeUndefined();
1955
+
1956
+ expect(flushed).toEqual(['flush-failure', 'flush-peer']);
1957
+ expect(test.diagnostics).toContainEqual(expect.objectContaining({
1958
+ name: 'runtime.plugin.flush_failed',
1959
+ severity: 'error',
1960
+ attributes: expect.objectContaining({
1961
+ plugin_id: 'flush-failure',
1962
+ reason: 'shutdown',
1963
+ error_code: 'RUNTIME_PLUGIN_FLUSH_FAILED',
1964
+ }),
1965
+ }));
1966
+ });
1967
+
1932
1968
  it('drains buffered parallel work in order when a failure pauses the plugin', async () => {
1933
1969
  let releaseFirst!: () => void;
1934
1970
  const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
@@ -563,7 +563,6 @@ export class RuntimePluginScheduler<
563
563
  await this.waitForIdle();
564
564
  const scope = this.activeScope;
565
565
  if (!scope) return;
566
- const failures: unknown[] = [];
567
566
  for (const layer of this.layers) {
568
567
  await Promise.all(layer.map(async (plugin) => {
569
568
  if (!plugin.flush) return;
@@ -586,7 +585,6 @@ export class RuntimePluginScheduler<
586
585
  reason,
587
586
  }, scope);
588
587
  } catch (error) {
589
- failures.push(error);
590
588
  this.onDiagnostic?.('runtime.plugin.flush_failed', {
591
589
  plugin_id: plugin.id,
592
590
  reason,
@@ -595,9 +593,6 @@ export class RuntimePluginScheduler<
595
593
  }
596
594
  }));
597
595
  }
598
- if (failures.length > 0) {
599
- throw new AggregateError(failures, `${failures.length} Runtime Epoch Plugin flush operation(s) failed.`);
600
- }
601
596
  }
602
597
 
603
598
  waitForIdle(): Promise<void> {
@@ -160,6 +160,12 @@ export interface PerceptionApi {
160
160
  readonly spatial: PerceptionSpatialApi;
161
161
  }
162
162
 
163
+ export interface ClawclawPerceptionEventMetadata {
164
+ readonly name: string;
165
+ readonly description: string;
166
+ readonly localizations?: ClawclawResourceLocalizations;
167
+ }
168
+
163
169
  /**
164
170
  * Immutable, epoch-bound input for one fresh parallel analyzer instance.
165
171
  * Frames may be skipped and different inputs may be analyzed concurrently.
@@ -205,6 +211,8 @@ export interface ClawclawPerceptionManifest {
205
211
  /** Describes Event subjects; every module still receives self as a spatial reference. */
206
212
  readonly subjectScope: PerceptionSubjectScope;
207
213
  readonly produces: readonly string[];
214
+ /** Optional display metadata for every Event in `produces`. */
215
+ readonly eventMetadata?: Readonly<Record<string, ClawclawPerceptionEventMetadata>>;
208
216
  /**
209
217
  * Omit for the main-thread, persistent, ordered `update()` contract.
210
218
  * `parallel_analysis` batches every enabled parallel module for one frame on