@myclaw163/clawclaw-cli 0.9.1 → 0.10.1

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 (216) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +27 -40
  7. package/docs/custom-modules/api-reference.md +132 -273
  8. package/docs/custom-modules/behavior.md +185 -75
  9. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +46 -806
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +18 -19
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +54 -48
  19. package/docs/runtime/components-and-boundaries.md +87 -137
  20. package/docs/runtime/events-and-state.md +52 -17
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +12 -9
  26. package/docs/user-guide/api-reference.md +132 -180
  27. package/docs/user-guide/behavior.md +175 -65
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +46 -789
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +9 -14
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +50 -48
  37. package/skills/clawclaw/references/BEHAVIORS.md +45 -65
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +65 -87
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +49 -104
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +18 -25
  53. package/src/commands/module-runtime-control.ts +113 -0
  54. package/src/commands/perception.ts +23 -4
  55. package/src/commands/strategy.ts +2 -0
  56. package/src/commands/trigger.ts +1 -1
  57. package/src/lib/capability-load-diagnostics.ts +3 -3
  58. package/src/lib/perception-config.ts +18 -6
  59. package/src/lib/runtime-cadence-config.ts +16 -0
  60. package/src/lib/workspace-runtime-lock.ts +3 -46
  61. package/src/pipeline/canonical-event-presentation.ts +23 -124
  62. package/src/pipeline/event-format.ts +12 -21
  63. package/src/pipeline/event-hints.ts +6 -6
  64. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  65. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  66. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  67. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  68. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  69. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  70. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  71. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  72. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  73. package/src/runtime/clawclaw/owner.ts +67 -8
  74. package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
  75. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  76. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  77. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  78. package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
  79. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  82. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  83. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  84. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
  85. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
  86. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  87. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  88. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  89. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
  90. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
  91. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
  92. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  93. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  94. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  95. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
  96. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  97. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  98. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  99. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  100. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  101. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  102. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  103. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  104. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  105. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  106. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  107. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
  108. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
  109. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
  110. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
  111. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
  112. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  113. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
  114. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  115. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  116. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  117. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  118. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
  119. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  120. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  121. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  122. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  123. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  124. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  125. package/src/runtime/clawclaw/runtime-state.ts +12 -1
  126. package/src/runtime/clawclaw/runtime.ts +11 -3
  127. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
  128. package/src/runtime/clawclaw/strategy-memory.ts +1 -0
  129. package/src/runtime/clawclaw-event-catalog.ts +17 -17
  130. package/src/runtime/framework/action-diagnostics.ts +3 -83
  131. package/src/runtime/framework/capability-registry.ts +2 -395
  132. package/src/runtime/framework/contracts.ts +2 -144
  133. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  134. package/src/runtime/framework/control/domain-set.ts +2 -81
  135. package/src/runtime/framework/control/index.ts +1 -3
  136. package/src/runtime/framework/control/types.ts +2 -191
  137. package/src/runtime/framework/control-coordinator.ts +2 -11
  138. package/src/runtime/framework/events/event-catalog.ts +2 -74
  139. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  140. package/src/runtime/framework/events/event-ingress.ts +2 -99
  141. package/src/runtime/framework/events/event-repository.ts +2 -82
  142. package/src/runtime/framework/events/index.ts +2 -7
  143. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  144. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  145. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  146. package/src/runtime/framework/events/test-helpers.ts +1 -1
  147. package/src/runtime/framework/events/types.ts +2 -312
  148. package/src/runtime/framework/index.ts +3 -7
  149. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  150. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  151. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  152. package/src/runtime/framework/mailbox/identity.ts +2 -38
  153. package/src/runtime/framework/mailbox/index.ts +1 -7
  154. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  155. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  156. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  157. package/src/runtime/framework/mailbox/types.ts +2 -145
  158. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  159. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  160. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  161. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  162. package/src/runtime/framework/participation-manager.ts +2 -253
  163. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  164. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  165. package/src/runtime/framework/plugins/contracts.ts +2 -388
  166. package/src/runtime/framework/plugins/index.ts +1 -4
  167. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  168. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  169. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
  170. package/src/runtime/framework/runtime.ts +5 -1843
  171. package/src/runtime/framework/serial-task-queue.ts +2 -14
  172. package/src/runtime/framework/state/contracts.ts +2 -49
  173. package/src/runtime/framework/state/current-state-store.ts +2 -184
  174. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  175. package/src/runtime/framework/state/freshness.ts +2 -72
  176. package/src/runtime/framework/state/history/contracts.ts +2 -158
  177. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  178. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  179. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  180. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  181. package/src/runtime/framework/state/index.ts +1 -13
  182. package/src/runtime/framework/state/state-ingress.ts +2 -95
  183. package/src/runtime/framework/state/state-provider.ts +2 -62
  184. package/src/runtime/framework/state/types.ts +2 -155
  185. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  186. package/src/runtime/mailbox-host-relay.ts +1 -326
  187. package/src/runtime/observability/detail-capture.ts +4 -108
  188. package/src/runtime/observability/process-timing.ts +2 -59
  189. package/src/runtime/observability/recorder.ts +2 -238
  190. package/src/runtime/observability/redaction.ts +2 -181
  191. package/src/runtime/observability/reporter.ts +2 -154
  192. package/src/runtime/observability/sinks.ts +2 -135
  193. package/src/runtime/observability/types.ts +2 -92
  194. package/src/runtime/owner-control.ts +45 -315
  195. package/src/runtime/parent-process-watch.ts +1 -51
  196. package/src/runtime/process-identity.ts +1 -72
  197. package/src/sdk/behavior-plugin/index.ts +13 -4
  198. package/src/sdk/index.ts +44 -3
  199. package/src/sdk/module-input/index.ts +5 -0
  200. package/src/sdk/perception-plugin/index.ts +9 -5
  201. package/src/sdk/perception-plugin/module.ts +25 -6
  202. package/src/sdk/perception-plugin/reaction.ts +1 -1
  203. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  204. package/src/sdk/perception-plugin/reminder.ts +2 -1
  205. package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
  206. package/src/sdk/strategy-memory.ts +1 -0
  207. package/src/sdk/strategy-plugin/index.ts +36 -0
  208. package/src/sdk/trigger-plugin/index.ts +4 -3
  209. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  210. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  211. package/docs/custom-modules/trigger.md +0 -295
  212. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  213. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
  214. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
  215. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  216. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -50,7 +50,6 @@ import {
50
50
  type RuntimeSourceStopHandle,
51
51
  } from '../../../framework/plugins/index.js';
52
52
  import type { RuntimeScope } from '../../../framework/state/index.js';
53
- import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
54
53
  import { normalizeGameSyncEventsSafely } from '../../../../pipeline/game-sync-event-normalization.js';
55
54
  import { isSelfKillerMurderWitnessed } from '../../../../pipeline/event-hints.js';
56
55
  import {
@@ -94,16 +93,6 @@ import type {
94
93
  ClawclawSourceStartIntent,
95
94
  ClawclawSourceTransportFactory,
96
95
  } from './types.js';
97
- import {
98
- nextPlayerProjection,
99
- type PlayerSnapshot,
100
- type PlayersChangedPayload,
101
- } from './player-change-tracker.js';
102
- import {
103
- nextTaskProjection,
104
- type TaskSnapshot,
105
- type TasksChangedPayload,
106
- } from './task-change-tracker.js';
107
96
 
108
97
  interface RoomFrameMeta {
109
98
  connectionId: string;
@@ -339,11 +328,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
339
328
  private hasFreshGameSnapshot = false;
340
329
  private latestFreshGameState?: Record<string, any>;
341
330
  private latestFreshGameTick?: number;
342
- private playerProjection: PlayerProjection[] = [];
343
- private playerProjectionInitialized = false;
344
- private playerSnapshots: PlayerSnapshot[] = [];
345
- private taskProjection: TaskSnapshot[] = [];
346
- private taskProjectionInitialized = false;
347
331
  private matchStartedAtMs?: number;
348
332
  private lastMatchWaitingAtMs?: number;
349
333
  private matchTimedOut = false;
@@ -1519,10 +1503,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1519
1503
  }, 'warn');
1520
1504
  }
1521
1505
  let acceptedStage: ClawclawRuntimeStage | undefined;
1522
- let acceptedPlayerProjection: PlayerProjection[] | undefined;
1523
- let acceptedPlayerSnapshots: PlayerSnapshot[] | undefined;
1524
- let acceptedTaskProjection: TaskSnapshot[] | undefined;
1525
- let acceptedTaskProjectionInitialized: boolean | undefined;
1526
1506
  const acceptance = await this.enqueueInputIf(() => {
1527
1507
  if (this.currentStage === 'ended') return null;
1528
1508
  try {
@@ -1530,14 +1510,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1530
1510
  CLAWCLAW_GAME_WS_SOURCE.sourceId,
1531
1511
  frame.meta.connectionId,
1532
1512
  );
1533
- const taskUpdate = nextTaskProjection({
1534
- previous: this.taskProjection,
1535
- initialized: this.taskProjectionInitialized,
1536
- summary: gameState,
1537
- events: frame.events,
1538
- selfName: this.profile.agentName,
1539
- allowUntickedInitialRole: frame.meta.origin === 'update',
1540
- });
1541
1513
  const backendEvents = this.sourceEvents(
1542
1514
  frame.events, frame.meta, CLAWCLAW_GAME_WS_SOURCE.sourceId, undefined, gameState,
1543
1515
  );
@@ -1549,36 +1521,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1549
1521
  replayed_event_count: frame.events.length,
1550
1522
  }], `${recoveryIdentity}:recovered`, frame.meta.receivedAt)
1551
1523
  : [];
1552
- const playerUpdate = nextPlayerProjection({
1553
- previous: this.playerProjection,
1554
- previousSnapshots: this.playerSnapshots,
1555
- initialized: this.playerProjectionInitialized,
1556
- summary: gameState,
1557
- events: frame.events,
1558
- selfName: this.profile.agentName,
1559
- });
1560
- const events = [
1561
- ...backendEvents,
1562
- ...recoveryEvents,
1563
- ...(playerUpdate.payload
1564
- ? [this.playersChangedEvent(
1565
- playerUpdate.payload,
1566
- frame.meta.receivedAt,
1567
- `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1568
- )]
1569
- : []),
1570
- ...(taskUpdate.payload
1571
- ? [this.tasksChangedEvent(
1572
- taskUpdate.payload,
1573
- frame.meta.receivedAt,
1574
- `${frame.meta.gameId}:${String(frame.meta.sourceSeq)}`,
1575
- )]
1576
- : []),
1577
- ];
1578
- acceptedPlayerProjection = playerUpdate.projection;
1579
- acceptedPlayerSnapshots = playerUpdate.snapshots;
1580
- acceptedTaskProjection = taskUpdate.projection;
1581
- acceptedTaskProjectionInitialized = taskUpdate.initialized;
1524
+ const events = [...backendEvents, ...recoveryEvents];
1582
1525
  this.currentTransport = 'game_ws';
1583
1526
  this.currentConnection = 'connected';
1584
1527
  acceptedStage = clawclawStageFromGameEvents(
@@ -1601,7 +1544,7 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1601
1544
  state: this.gameRuntimeState(
1602
1545
  acceptedStage,
1603
1546
  acceptedStage === 'ended' ? 'ending' : 'game_snapshot',
1604
- { status: 'fresh', state: structuredClone(gameState) },
1547
+ { status: 'fresh', state: structuredClone(gameState), origin: frame.meta.origin },
1605
1548
  ),
1606
1549
  events,
1607
1550
  completeness: frame.meta.snapshotFallback ? 'best_effort' : 'complete',
@@ -1626,15 +1569,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
1626
1569
  this.latestFreshGameState = structuredClone(gameState);
1627
1570
  this.latestFreshGameTick = tick;
1628
1571
  this.gameConnectionsWithState.add(frame.meta.connectionId);
1629
- if (acceptedPlayerProjection) {
1630
- this.playerProjection = acceptedPlayerProjection;
1631
- this.playerSnapshots = acceptedPlayerSnapshots ?? [];
1632
- this.playerProjectionInitialized = true;
1633
- }
1634
- if (acceptedTaskProjection) {
1635
- this.taskProjection = acceptedTaskProjection;
1636
- this.taskProjectionInitialized = acceptedTaskProjectionInitialized ?? false;
1637
- }
1638
1572
  });
1639
1573
  if (!acceptance) return;
1640
1574
  const ingress = frame.meta.ingress;
@@ -2129,6 +2063,12 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2129
2063
  ): RuntimeSourceEvent<Record<string, unknown>>[] {
2130
2064
  const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
2131
2065
  const normalizedValues = normalizeGameSyncEventsSafely(values);
2066
+ for (const warning of normalizedValues.warnings ?? []) {
2067
+ this.diagnostic('runtime.source.event_field_preserved', {
2068
+ source_id: sourceId, source_seq: meta.sourceSeq, event_index: warning.index,
2069
+ field: warning.field, reason: warning.reason,
2070
+ }, 'warn');
2071
+ }
2132
2072
  normalizedValues.rejected.forEach(({ index, error }) => {
2133
2073
  const value = values[index];
2134
2074
  const raw = value && typeof value === 'object' && !Array.isArray(value)
@@ -2215,11 +2155,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2215
2155
  this.hasFreshGameSnapshot = false;
2216
2156
  this.latestFreshGameState = undefined;
2217
2157
  this.latestFreshGameTick = undefined;
2218
- this.playerProjection = [];
2219
- this.playerProjectionInitialized = false;
2220
- this.playerSnapshots = [];
2221
- this.taskProjection = [];
2222
- this.taskProjectionInitialized = false;
2223
2158
  this.sourceCoalescingBoundaryState = undefined;
2224
2159
  this.actionSafetyGeneration = 0;
2225
2160
  return next;
@@ -2280,36 +2215,6 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2280
2215
  });
2281
2216
  }
2282
2217
 
2283
- private playersChangedEvent(
2284
- payload: PlayersChangedPayload,
2285
- receivedAt: string,
2286
- sourceSeq: number | string,
2287
- ): RuntimeSourceEvent<Record<string, unknown>> {
2288
- return {
2289
- type: 'players_changed',
2290
- producer: 'local_synth',
2291
- payload,
2292
- sourceEventId: `local:${this.sourceInstanceId}:players-changed:${String(sourceSeq)}`,
2293
- sourceSeq: `${String(sourceSeq)}:players-changed`,
2294
- receivedAt,
2295
- };
2296
- }
2297
-
2298
- private tasksChangedEvent(
2299
- payload: TasksChangedPayload,
2300
- receivedAt: string,
2301
- sourceSeq: number | string,
2302
- ): RuntimeSourceEvent<Record<string, unknown>> {
2303
- return {
2304
- type: 'tasks_changed',
2305
- producer: 'local_synth',
2306
- payload,
2307
- sourceEventId: `local:${this.sourceInstanceId}:tasks-changed:${String(sourceSeq)}`,
2308
- sourceSeq: `${String(sourceSeq)}:tasks-changed`,
2309
- receivedAt,
2310
- };
2311
- }
2312
-
2313
2218
  private runtimeState(
2314
2219
  cause: ClawclawRuntimeCause,
2315
2220
  gameSnapshot?: ClawclawRuntimeState['game_snapshot'],
@@ -0,0 +1,107 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput,
2
+ RuntimeEpochPluginResult, RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
3
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
4
+ import type { ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
5
+
6
+ export class PerceptionRuleRunner
7
+ implements RuntimeEpochPlugin<Record<string, any>> {
8
+ readonly kind = 'epoch' as const;
9
+ readonly id: string;
10
+ readonly version = '2';
11
+ readonly produces: { events: readonly string[] };
12
+ readonly consumes: { events: readonly string[] };
13
+ // Never skip a computation boundary. Fixed-cadence boundaries may contain multiple Source inputs.
14
+ readonly catchUp = 'strict_ordered' as const;
15
+ readonly timeoutMs = 1_000;
16
+
17
+ private readonly rules: ClawclawDerivedEventRule[];
18
+ private lastFrameSeq = 0;
19
+
20
+ constructor(id: string, rules: readonly ClawclawDerivedEventRule[]) {
21
+ this.id = id;
22
+ this.rules = [...rules].sort((left, right) => left.id.localeCompare(right.id));
23
+ this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
24
+ this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
25
+ }
26
+
27
+ start(): void {
28
+ this.reset();
29
+ }
30
+
31
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
32
+ const completedThrough = context.progress().completedThroughEpochSeq;
33
+ if (completedThrough <= 0) return;
34
+ if (context.processingIntervalMs !== undefined) {
35
+ const frame = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: completedThrough, order: 'desc', limit: 1 }).frames[0];
36
+ if (frame) {
37
+ const sourceEpoch = frame.state.cycle?.stateVersion ?? frame.epochSeq;
38
+ this.inspectFrame(frame, sourceEpoch ? context.sourceEventsAt?.(sourceEpoch) ?? [] : []);
39
+ }
40
+ return;
41
+ }
42
+ this.scanHistory(context, completedThrough, false);
43
+ }
44
+
45
+ update(
46
+ input: RuntimeEpochPluginInput<Record<string, any>>,
47
+ context: RuntimeEpochPluginContext<Record<string, any>>,
48
+ ): RuntimeEpochPluginResult {
49
+ const facts = input.pendingEvents.filter(event => !event.producerPluginId && !event.notificationOf)
50
+ .map(event => ({ type: event.type, payload: event.payload, producer: event.producer,
51
+ sourceEventId: event.sourceEventId, sourceSeq: event.sourceSequence, observedAt: event.occurredAt,
52
+ receivedAt: event.receivedAt, replayed: event.replayed }));
53
+ const events = context.processingIntervalMs !== undefined
54
+ ? this.inspectFrame(input.frame, facts)
55
+ : this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
56
+ return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
57
+ : { outcome: 'noop' as const, reason: 'no_derived_event' }),
58
+ ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
59
+ }
60
+
61
+ stop(): void {
62
+ this.reset();
63
+ }
64
+
65
+ private scanHistory(
66
+ context: RuntimeEpochPluginContext<Record<string, any>>,
67
+ throughEpochSeq: number,
68
+ collect: boolean,
69
+ throughFrameSeq?: number,
70
+ currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
71
+ ): RuntimeEventProposal[] {
72
+ if (this.rules.length === 0) return [];
73
+ const proposals: RuntimeEventProposal[] = [];
74
+ let afterFrameSeq = this.lastFrameSeq;
75
+ while (true) {
76
+ const page = context.stateHistory.queryStateFrames({
77
+ scope: context.scope,
78
+ afterFrameSeq,
79
+ toEpochSeq: throughEpochSeq,
80
+ ...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }),
81
+ order: 'asc',
82
+ limit: 500,
83
+ });
84
+ if (page.frames.length === 0) break;
85
+ for (const frame of page.frames) {
86
+ const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
87
+ ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
88
+ const frameEvents = this.inspectFrame(frame, facts);
89
+ if (collect) proposals.push(...frameEvents);
90
+ afterFrameSeq = frame.frameSeq;
91
+ }
92
+ if (!page.page.hasMore) break;
93
+ }
94
+ return proposals;
95
+ }
96
+
97
+ private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
98
+ if (frame.frameSeq <= this.lastFrameSeq) return [];
99
+ this.lastFrameSeq = frame.frameSeq;
100
+ return this.rules.flatMap((rule) => rule.inspect(frame, facts));
101
+ }
102
+
103
+ private reset(): void {
104
+ this.lastFrameSeq = 0;
105
+ for (const rule of this.rules) rule.reset();
106
+ }
107
+ }
@@ -0,0 +1,107 @@
1
+ import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js';
2
+ import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
+ import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
4
+ import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js';
5
+ import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule,
6
+ type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
7
+ import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js';
8
+ import { PerceptionRuleRunner } from './rule-runner.js';
9
+ import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js';
10
+ import { clawclawComputationGameState } from '../../runtime-state.js';
11
+ import { createCanonicalGameState } from '../../behavior-input.js';
12
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
+
14
+ export const BUILTIN_PERCEPTION_NAMES = {
15
+ players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
16
+ flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息',
17
+ } as const;
18
+ type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES;
19
+ interface TaskCheckpoint { gameId?: string; connectionId?: string }
20
+
21
+ /** Native mandatory perception. Public resource loadouts cannot replace or disable it. */
22
+ export class SystemPerceptionPlugin extends PerceptionRuleRunner {
23
+ readonly agentNotificationProducer = true;
24
+ override readonly consumes: { events: readonly string[] };
25
+ override readonly produces: { events: readonly string[] };
26
+ readonly notificationRelay: { sourceEvents?: boolean; producerPluginIds?: readonly string[]; previousEpochOnly?: boolean };
27
+ private taskState: TaskCheckpoint = {};
28
+ constructor(readonly domain: Domain, private readonly forwardedTypes: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
29
+ super(`${BUILTIN_PERCEPTION_PREFIX}${domain}`, rules);
30
+ this.notificationRelay = domain === 'behavior'
31
+ ? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true };
32
+ this.consumes = { events: [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwardedTypes,
33
+ ...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])] };
34
+ this.produces = { events: [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwardedTypes,
35
+ ...(domain === 'tasks' ? ['reminder.task'] : [])])] };
36
+ }
37
+ override start(): void { super.start(); this.taskState = {}; }
38
+ override recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
39
+ super.recover(context);
40
+ if (this.domain === 'tasks') this.taskState = structuredClone(context.checkpoint() as TaskCheckpoint ?? {});
41
+ }
42
+ override update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): RuntimeEpochPluginResult {
43
+ const ruleResult = super.update(input, context);
44
+ const events: RuntimeEventProposal[] = [...(ruleResult.events ?? [])];
45
+ let cursor: number | undefined;
46
+ for (const event of input.pendingEvents) {
47
+ // A same-round Behavior output is deliberately held for the next round.
48
+ // Do not move the cursor past it, even if commit order overlaps epochs.
49
+ if (this.domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
50
+ && (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
51
+ cursor = event.commitSeq;
52
+ if (event.notificationOf || !this.forwardedTypes.includes(event.type)) continue;
53
+ if (this.domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
54
+ events.push({ type: event.type, forwardEventId: event.eventId, dedupeKey: event.eventId, payload: {},
55
+ notificationContent: prepareNotificationContent(event.type, event.payload, notificationStateAt(context, event.epochSeq), 'builtin', event) });
56
+ }
57
+ if (this.domain === 'tasks') {
58
+ const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
59
+ const game = raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
60
+ const boundary = game && this.taskState.gameId !== game.game_id ? 'initial'
61
+ : this.taskState.connectionId !== undefined && this.taskState.connectionId !== input.epoch.connectionId ? 'recovery' : null;
62
+ this.taskState = { gameId: game?.game_id ?? this.taskState.gameId, connectionId: input.epoch.connectionId };
63
+ // Task facts have one notification owner. Do not recreate them from State differences.
64
+ const result = defaultReminder('tasks', { scope: input.epoch.scope, gameState: game, frame: null,
65
+ facts: input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({
66
+ eventId: event.eventId, epochId: event.epochSeq, type: event.type, occurredAt: event.occurredAt,
67
+ producer: event.producer, replayed: event.replayed, payload: projectTaskChoiceEventPayload(game, event.type, event.payload),
68
+ })), taskChanges: [], boundary, config: {}, state: undefined,
69
+ nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs });
70
+ for (const event of result.events ?? []) events.push({ type: event.type, dedupeKey: event.key,
71
+ wakeAgent: event.wakeAgent, payload: { ...event.payload }, occurredAt: new Date(input.frame.receivedAtMs).toISOString() });
72
+ }
73
+ const notifications = events.map(event => event.notificationContent ? event : { ...event,
74
+ notificationContent: prepareNotificationContent(event.type, event.payload,
75
+ notificationStateAt(context, input.epoch.epochSeq), 'builtin', { producer: 'local_synth', producerPluginId: this.id }),
76
+ });
77
+ return { outcome: events.length ? 'processed' : 'noop', events: notifications,
78
+ ...(this.domain === 'tasks' ? { checkpoint: structuredClone(this.taskState) } : {}),
79
+ ...(cursor === undefined ? {} : { consumeEventsThroughCommitSeq: cursor }) };
80
+ }
81
+ }
82
+
83
+ /** Every currently public Source gameplay Event has exactly one builtin owner. */
84
+ export function createSystemPerceptions(behaviorEventTypes: readonly string[] = []): SystemPerceptionPlugin[] {
85
+ const groups: Record<Exclude<Domain, 'behavior'>, string[]> = {
86
+ players: ['kill', 'killed', 'murder_witnessed', 'body_dropped', 'corpse_spotted', 'warrior_shrimp_self_destruct', 'role_assigned'],
87
+ tasks: [], abilities: [],
88
+ emergency: ['emergency_started', 'emergency_resolved', 'emergency_interrupted'],
89
+ meeting: ['exile', 'no_exile', 'vote_speech_phase_ended', 'death_speech', 'meeting_briefing',
90
+ 'speech', 'speech_skipped', 'speech_your_turn', 'speech_next_turn', 'vote_phase_start'],
91
+ flow: [],
92
+ };
93
+ const assigned = new Set(Object.values(groups).flat());
94
+ groups.flow = [...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, 'game_over_recovered', 'robot_speak_rule']
95
+ .filter(type => !assigned.has(type) && !CLAWCLAW_SYSTEM_CONTROL_EVENTS.has(type));
96
+ const behaviorTypes = [...new Set([...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => type.startsWith('behavior.') || type === 'strategy_alert'),
97
+ ...behaviorEventTypes])];
98
+ return [
99
+ new SystemPerceptionPlugin('players', groups.players, [new PlayerChangesDerivedEventRule()]),
100
+ new SystemPerceptionPlugin('tasks', groups.tasks),
101
+ new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule()]),
102
+ new SystemPerceptionPlugin('emergency', groups.emergency, [new EmergencyCountdownDerivedEventRule()]),
103
+ new SystemPerceptionPlugin('flow', groups.flow, [new RoomReadyDerivedEventRule()]),
104
+ new SystemPerceptionPlugin('meeting', groups.meeting),
105
+ new SystemPerceptionPlugin('behavior', behaviorTypes),
106
+ ];
107
+ }
@@ -9,6 +9,8 @@ export const CLAWCLAW_TRIGGER_PLUGIN_ID = 'clawclaw.trigger';
9
9
 
10
10
  /** Effective outer configuration for one statically discovered Trigger. */
11
11
  export interface ClawclawTriggerRegistration {
12
+ /** Optional scope lease for an explicitly configured standalone Trigger. */
13
+ readonly scope?: Readonly<BehaviorScope>;
12
14
  readonly source: ResolvedClawclawTriggerSource;
13
15
  /** New community Trigger installations are supplied as false by the outer configuration layer. */
14
16
  readonly enabled: boolean;
@@ -23,7 +25,7 @@ export interface ClawclawTriggerRegistration {
23
25
  }
24
26
 
25
27
  export interface BehaviorReflexActivationRequest {
26
- readonly source: 'trigger';
28
+ readonly source: 'trigger' | 'perception';
27
29
  readonly triggerId: string;
28
30
  readonly scope: Readonly<BehaviorScope>;
29
31
  readonly epochId: number;
@@ -88,10 +88,11 @@ export function validateClawclawTriggerModule(
88
88
  loaded: Readonly<Record<string, unknown>>,
89
89
  source: ResolvedClawclawTriggerSource,
90
90
  ): ClawclawTriggerClass {
91
- if (typeof loaded.default !== 'function') {
91
+ const entry = 'default';
92
+ if (typeof loaded[entry] !== 'function') {
92
93
  throw new Error(`Trigger module '${source.id}' has no default class.`);
93
94
  }
94
- const ModuleClass = loaded.default as unknown as ClawclawTriggerClass;
95
+ const ModuleClass = loaded[entry] as unknown as ClawclawTriggerClass;
95
96
  const manifest = normalizedManifest(ModuleClass.manifest);
96
97
  if (!isDeepStrictEqual(manifest, source.manifest)) {
97
98
  throw new Error(`Trigger module '${source.id}' changed after static discovery.`);
@@ -99,6 +100,8 @@ export function validateClawclawTriggerModule(
99
100
  return ModuleClass;
100
101
  }
101
102
 
103
+
104
+
102
105
  /** One Runtime-scoped direct importer. Disabled Trigger sources never reach it. */
103
106
  export class TriggerModuleLoader {
104
107
  private readonly runtimeId = randomUUID();