@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
@@ -64,9 +64,9 @@ const MODULE_CONTRACTS: Record<ModuleCapabilityType, {
64
64
  readonly manifest: RegExp;
65
65
  }> = {
66
66
  behavior: {
67
- expectedImport: '@myclaw163/clawclaw-cli/behavior-plugin',
68
- safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/behavior-plugin/,
69
- defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+ClawclawBehavior/,
67
+ expectedImport: '@myclaw163/clawclaw-cli/strategy-plugin',
68
+ safeImport: /(?:@myclaw163\/clawclaw-cli|clawclaw-cli)\/(?:behavior|strategy)-plugin/,
69
+ defaultClass: /export\s+default\s+class(?:\s+[A-Za-z_$][\w$]*)?\s+extends\s+Clawclaw(?:Behavior|Strategy)/,
70
70
  manifest: /\bstatic\s+(?:override\s+)?(?:readonly\s+)?manifest\s*=\s*\{/,
71
71
  },
72
72
  perception: {
@@ -10,15 +10,15 @@ import {
10
10
  listClawclawPerceptionSources,
11
11
  type ClawclawPerceptionConfig,
12
12
  } from '../runtime/clawclaw/plugins/perception/index.js';
13
+ import type { ClawclawEventDelivery } from '../runtime/clawclaw-event-catalog.js';
13
14
  import type { EventDeliveryClass } from '../runtime/framework/events/index.js';
14
15
 
15
16
  export interface WorkspacePerceptionConfig {
16
17
  perception: ClawclawPerceptionConfig;
17
- events: { delivery: Readonly<Partial<Record<string, EventDeliveryClass>>> };
18
+ events: { delivery: Readonly<Partial<Record<string, ClawclawEventDelivery>>> };
18
19
  }
19
20
  const DELIVERY = new Set<EventDeliveryClass>([
20
21
  'monitor_and_events',
21
- 'events_only',
22
22
  'internal_only',
23
23
  ]);
24
24
 
@@ -76,16 +76,28 @@ export function readWorkspacePerceptionConfig(
76
76
  }
77
77
  const events = record(root.events);
78
78
  const configuredDelivery = events?.delivery;
79
- const delivery: Partial<Record<string, EventDeliveryClass>> = {};
79
+ const delivery: Partial<Record<string, ClawclawEventDelivery>> = {};
80
80
  if (configuredDelivery !== undefined) {
81
81
  const values = record(configuredDelivery);
82
82
  if (!values) throw new Error('config.json events.delivery must be an object.');
83
83
  for (const [type, value] of Object.entries(values)) {
84
84
  if (!eventTypes.has(type)) throw new Error(`Unknown visual Event delivery type: ${type}`);
85
- if (typeof value !== 'string' || !DELIVERY.has(value as EventDeliveryClass)) {
86
- throw new Error(`Invalid delivery class for ${type}: ${String(value)}`);
85
+ // Normalize old configuration at the boundary; no query-only mode enters Runtime.
86
+ if (value === 'events_only') {
87
+ delivery[type] = { deliveryClass: 'monitor_and_events', wakeAgent: false };
88
+ } else if (typeof value === 'string' && DELIVERY.has(value as EventDeliveryClass)) {
89
+ delivery[type] = value as EventDeliveryClass;
90
+ } else {
91
+ const policy = record(value);
92
+ if (!policy || !DELIVERY.has(policy.deliveryClass as EventDeliveryClass)
93
+ || Object.keys(policy).some(key => key !== 'deliveryClass' && key !== 'wakeAgent')
94
+ || Object.hasOwn(policy, 'wakeAgent') && typeof policy.wakeAgent !== 'boolean'
95
+ || policy.deliveryClass === 'internal_only' && policy.wakeAgent === true) {
96
+ throw new Error(`Invalid delivery policy for ${type}. Use deliveryClass and optional boolean wakeAgent.`);
97
+ }
98
+ delivery[type] = { deliveryClass: policy.deliveryClass as EventDeliveryClass,
99
+ ...(policy.wakeAgent === undefined ? {} : { wakeAgent: policy.wakeAgent as boolean }) };
87
100
  }
88
- delivery[type] = value as EventDeliveryClass;
89
101
  }
90
102
  }
91
103
  return {
@@ -0,0 +1,16 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { getWorkspaceConfigFile } from './init-command.js';
3
+
4
+ export const DEFAULT_RUNTIME_CYCLE_INTERVAL_MS = 100;
5
+ export function readRuntimeCycleIntervalMs(path = getWorkspaceConfigFile()): number {
6
+ const config = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
7
+ if (!config || typeof config !== 'object' || Array.isArray(config)
8
+ || config.runtime !== undefined && (!config.runtime || typeof config.runtime !== 'object' || Array.isArray(config.runtime))) {
9
+ throw new TypeError('config.json runtime must be an object.');
10
+ }
11
+ const value = config.runtime?.cycleIntervalMs === undefined ? DEFAULT_RUNTIME_CYCLE_INTERVAL_MS : config.runtime.cycleIntervalMs;
12
+ if (!Number.isSafeInteger(value) || value < 1 || value > 60_000) {
13
+ throw new TypeError('config.json runtime.cycleIntervalMs must be an integer from 1 to 60000.');
14
+ }
15
+ return value;
16
+ }
@@ -1,47 +1,4 @@
1
- import { closeSync, mkdirSync, openSync, realpathSync } from 'node:fs';
2
- import { createRequire } from 'node:module';
3
- import { join } from 'node:path';
1
+ import { tryAcquireRuntimeLock } from '@myclaw163/game-agent-runtime/owner/runtime-lock.js';
4
2
  import { getRuntimeDir } from './user-data.js';
5
-
6
- interface NativeFileLocks {
7
- tryLock(fd: number): boolean;
8
- unlock(fd: number): void;
9
- }
10
-
11
- const require = createRequire(import.meta.url);
12
- let nativeLocks: NativeFileLocks | undefined;
13
- const held = new Set<string>();
14
-
15
- export interface WorkspaceRuntimeLock {
16
- release(): void;
17
- }
18
-
19
- /** The inode must remain in place: unlinking a locked file permits two owners. */
20
- export function tryAcquireWorkspaceRuntimeLock(workspaceDir: string): WorkspaceRuntimeLock | null {
21
- const directory = getRuntimeDir(workspaceDir);
22
- mkdirSync(directory, { recursive: true });
23
- const path = join(realpathSync(directory), 'owner.lock');
24
- const key = process.platform === 'win32' ? path.toLowerCase() : path;
25
- if (held.has(key)) return null;
26
- // Load only for lifecycle operations; help/schema/short commands need no addon.
27
- const locks = nativeLocks ??= require('fs-native-extensions') as NativeFileLocks;
28
- const fd = openSync(path, 'a+', 0o600);
29
- let acquired = false;
30
- try {
31
- acquired = locks.tryLock(fd);
32
- if (!acquired) return null;
33
- held.add(key);
34
- let released = false;
35
- return {
36
- release() {
37
- if (released) return;
38
- released = true;
39
- try { locks.unlock(fd); } finally {
40
- try { closeSync(fd); } finally { held.delete(key); }
41
- }
42
- },
43
- };
44
- } finally {
45
- if (!acquired) closeSync(fd);
46
- }
47
- }
3
+ export type { WorkspaceRuntimeLock } from '@myclaw163/game-agent-runtime/owner/runtime-lock.js';
4
+ export const tryAcquireWorkspaceRuntimeLock = (workspaceDir: string) => tryAcquireRuntimeLock(getRuntimeDir(workspaceDir));
@@ -1,133 +1,32 @@
1
1
  import type { CanonicalEvent } from '../runtime/framework/events/index.js';
2
- import { buildLocalGameStartedEnrichment } from '../lib/game-context.js';
3
- import { compactEventForChannel } from './event-format.js';
4
- import { formatCanonicalEventHint } from './event-hints.js';
5
-
6
- const DESKTOP_SPECTATE_EVENT_TYPES = new Set([
7
- 'joined',
8
- 'room_created',
9
- 'room_joined',
10
- 'session_resumed',
11
- ]);
12
-
13
- const DESKTOP_SPECTATE_FIELD_NAMES = new Set([
14
- 'url',
15
- 'spectate_url',
16
- 'spectateUrl',
17
- ]);
18
-
19
- function cleanObject<T extends Record<string, any>>(value: T): T {
20
- for (const key of Object.keys(value)) {
21
- if (value[key] === undefined) delete value[key];
22
- }
23
- return value;
24
- }
25
-
26
- function stripDesktopSpectateFields(value: unknown): unknown {
27
- if (Array.isArray(value)) return value.map((item) => stripDesktopSpectateFields(item));
28
- if (!value || typeof value !== 'object') return value;
29
- return Object.fromEntries(Object.entries(value)
30
- .filter(([key]) => !DESKTOP_SPECTATE_FIELD_NAMES.has(key))
31
- .map(([key, item]) => [key, stripDesktopSpectateFields(item)]));
32
- }
33
-
34
- function desktopLifecycleHint(event: Record<string, any>): string | undefined {
35
- switch (event.type) {
36
- case 'joined':
37
- return event.recovered === true || event.resumed === true
38
- ? 'The game runtime reattached; do not start a duplicate runtime.'
39
- : 'The game runtime is attached; do not start a duplicate runtime.';
40
- case 'room_created':
41
- return 'Keep the room runtime attached.';
42
- case 'room_joined':
43
- return event.recovered === true || event.resumed === true
44
- ? 'The room runtime reattached; keep it attached.'
45
- : 'Keep the room runtime attached.';
46
- default:
47
- return undefined;
48
- }
49
- }
50
-
51
- /** CCL-owned enrichment for Agent-visible Event details. */
52
- export function enrichCanonicalEventForAgent(
53
- event: Record<string, any>,
54
- summary: any | null | undefined,
55
- ): Record<string, any> {
56
- if (event.type === 'game_started') {
57
- const { map: _backendMap, ...factual } = event;
58
- return { ...factual, ...buildLocalGameStartedEnrichment() };
59
- }
60
- if (event.type !== 'meeting_briefing' || event.speech_order) return event;
61
- const speechOrder = summary?.meeting?.speech_order;
62
- if (!Array.isArray(speechOrder)) return event;
63
- const summaryCaller = summary?.meeting?.caller;
64
- const eventCaller = event.caller ?? event.meeting_caller_name;
65
- if (summaryCaller && eventCaller && summaryCaller !== eventCaller) return event;
66
- return { ...event, speech_order: speechOrder };
67
- }
68
2
 
3
+ /** Read producer-prepared content. A historical record without content is never enriched at delivery. */
69
4
  export function canonicalEventForAgent(event: CanonicalEvent): Record<string, any> {
70
- return compactEventForChannel(cleanObject({
71
- ...event.payload,
72
- type: event.type,
73
- }));
5
+ return structuredClone(event.notificationContent?.event ?? { ...event.payload, type: event.type });
74
6
  }
75
-
76
- /** One authoritative detailed Event presenter for Agent delivery. */
77
- export function presentCanonicalEvent(
78
- event: CanonicalEvent,
79
- summary: any | null | undefined,
80
- ): Record<string, any> {
81
- const enriched = enrichCanonicalEventForAgent(canonicalEventForAgent(event), summary);
82
- const {
83
- hint: _reservedHint,
84
- next_step: _reservedNextStep,
85
- notice: _reservedNotice,
86
- ...factual
87
- } = enriched;
88
- const hint = formatCanonicalEventHint(event, {
89
- ...event.payload,
90
- ...factual,
91
- type: event.type,
92
- }, { summary });
93
- return cleanObject({
94
- ...factual,
95
- hint,
96
- });
7
+ export function presentCanonicalEvent(event: CanonicalEvent, _state?: unknown): Record<string, any> {
8
+ return canonicalEventForAgent(event);
97
9
  }
98
-
99
- /** Compact Channel projection for visual Events; other Events keep their canonical shape. */
100
- export function presentCanonicalEventForChannel(
101
- event: CanonicalEvent,
102
- summary: any | null | undefined,
103
- ): Record<string, any> | string {
104
- if (event.type.startsWith('visual.')) {
105
- const content = typeof event.payload.text === 'string' ? event.payload.text.trim() : '';
106
- return `${event.type} | ${content}`.trimEnd();
107
- }
108
- return presentCanonicalEvent(event, summary);
10
+ export function presentCanonicalEventForChannel(event: CanonicalEvent, _state?: unknown): Record<string, any> | string {
11
+ const value = canonicalEventForAgent(event);
12
+ return event.type.startsWith('visual.') ? `${event.type} | ${String(value.text ?? '')}`.trimEnd() : value;
109
13
  }
110
-
111
- /** Backward-compatible name for the same compact Agent Event projection. */
112
- export function presentCanonicalEventForCclEvents(
113
- event: CanonicalEvent,
114
- summary: any | null | undefined,
115
- ): Record<string, any> | string {
116
- return presentCanonicalEventForChannel(event, summary);
14
+ export const presentCanonicalEventForCclEvents = presentCanonicalEventForChannel;
15
+ /** Old ledgers predate producer-prepared Desktop variants. Preserve the transport's link privacy boundary. */
16
+ function legacyDesktopPrivacy(value: any): any {
17
+ if (Array.isArray(value)) return value.map(legacyDesktopPrivacy);
18
+ if (!value || typeof value !== 'object') return value;
19
+ return Object.fromEntries(Object.entries(value).filter(([key]) => !['url', 'spectate_url', 'spectateUrl'].includes(key))
20
+ .map(([key, item]) => [key, legacyDesktopPrivacy(item)]));
21
+ }
22
+ export function presentCanonicalEventForDesktop(event: CanonicalEvent, _state?: unknown): Record<string, any> | string {
23
+ if (event.notificationContent?.desktopEvent) return structuredClone(event.notificationContent.desktopEvent);
24
+ const presented = presentCanonicalEventForChannel(event);
25
+ return !event.notificationContent && ['joined', 'room_created', 'room_joined', 'session_resumed'].includes(event.type)
26
+ ? legacyDesktopPrivacy(presented) : presented;
117
27
  }
118
28
 
119
- /** Desktop projection keeps lifecycle guidance but withholds spectate links from its Agent. */
120
- export function presentCanonicalEventForDesktop(
121
- event: CanonicalEvent,
122
- summary: any | null | undefined,
123
- ): Record<string, any> | string {
124
- const presented = presentCanonicalEventForCclEvents(event, summary);
125
- if (
126
- typeof presented === 'string'
127
- || !DESKTOP_SPECTATE_EVENT_TYPES.has(event.type)
128
- ) return presented;
129
- return cleanObject({
130
- ...stripDesktopSpectateFields(presented) as Record<string, any>,
131
- hint: desktopLifecycleHint(presented),
132
- });
29
+ /** Transport can shorten or split this text, but cannot infer new game facts from current State. */
30
+ export function preparedMonitorText(event: CanonicalEvent): string {
31
+ return event.notificationContent?.monitorText ?? JSON.stringify(canonicalEventForAgent(event));
133
32
  }
@@ -294,8 +294,11 @@ function voteTargetLabel(target: unknown, ctx: EventFormatContext): string {
294
294
  return raw === 'skip' ? 'skip' : playerLabel(raw, undefined, ctx);
295
295
  }
296
296
 
297
- function formatVotes(votes: unknown, ctx: EventFormatContext): Record<string, string> | undefined {
298
- if (!votes || typeof votes !== 'object' || Array.isArray(votes)) return undefined;
297
+ function formatVotes(votes: unknown, ctx: EventFormatContext): unknown[] | Record<string, string> | undefined {
298
+ // GameSync supplies [voter seat, target seat | null]. These identities already
299
+ // address players directly; do not reinterpret them as names or rebuild them from State.
300
+ if (Array.isArray(votes)) return structuredClone(votes);
301
+ if (!votes || typeof votes !== 'object') return undefined;
299
302
  const out: Record<string, string> = {};
300
303
  for (const [voter, target] of Object.entries(votes)) {
301
304
  out[playerLabel(voter, undefined, ctx)] = voteTargetLabel(target, ctx);
@@ -412,21 +415,7 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
412
415
  return `你误杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)},武士虾自爆出局。`;
413
416
  case 'task_completed': {
414
417
  const fakeNote = event.is_fake_shrimp ? '(伪装)' : '';
415
- const assigned = event.newly_assigned_task;
416
- const assignedTask = assigned && typeof assigned === 'object' && !Array.isArray(assigned)
417
- ? assigned as Record<string, any>
418
- : null;
419
- const assignedName = assignedTask ? firstString(assignedTask, ['name', 'task_name'], '') : '';
420
- const assignedDetails = assignedTask
421
- ? [
422
- stringValue(assignedTask.room),
423
- assignedTask.is_fake_shrimp === true ? '伪装' : undefined,
424
- ].filter((value): value is string => value !== undefined)
425
- : [];
426
- const assignmentText = assignedName
427
- ? `;新分配任务:${assignedName}${assignedDetails.length > 0 ? `(${assignedDetails.join(',')})` : ''}`
428
- : '';
429
- return `任务完成:${firstString(event, ['task_name'])}${fakeNote}${assignmentText}。`;
418
+ return `任务完成:${firstString(event, ['task_name'])}${fakeNote}。`;
430
419
  }
431
420
  case 'task_sabotaged':
432
421
  return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
@@ -509,8 +498,8 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
509
498
  case 'vote_speech_phase_ended':
510
499
  return '投票弹幕窗口已关闭。';
511
500
  case 'exile': {
512
- const exiledName = event.result_target ?? event.actor_name;
513
- const exiledSeat = firstNumber(event, ['result_target_seat', 'actor_seat', 'seat']);
501
+ const exiledName = event.exiled_player?.name ?? event.result_target ?? event.actor_name;
502
+ const exiledSeat = numberValue(event.exiled_player?.seat) ?? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat']);
514
503
  return `会议结束:${playerLabel(exiledName, exiledSeat, ctx)}被放逐。`;
515
504
  }
516
505
  case 'no_exile':
@@ -759,13 +748,15 @@ function compactVoteCastForEvents(event: Record<string, any>, ctx: EventFormatCo
759
748
  function compactMeetingResultForEvents(event: Record<string, any>, ctx: EventFormatContext): FormattedEvent {
760
749
  const {
761
750
  votes: _votes,
751
+ actor_name: _actorName,
752
+ actor_seat: _actorSeat,
762
753
  ...rest
763
754
  } = event;
764
755
  const exiledName = event.type === 'exile'
765
- ? event.result_target ?? event.actor_name
756
+ ? event.exiled_player?.name ?? event.result_target ?? event.actor_name
766
757
  : undefined;
767
758
  const exiledSeat = event.type === 'exile'
768
- ? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat'])
759
+ ? numberValue(event.exiled_player?.seat) ?? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat'])
769
760
  : undefined;
770
761
  return cleanObject({
771
762
  ...rest,
@@ -16,7 +16,7 @@ export interface EventHintOrigin {
16
16
  }
17
17
 
18
18
  export const CLAWCLAW_SOURCE_PLUGIN_ID = 'clawclaw.source';
19
- export const CLAWCLAW_DERIVED_EVENT_PLUGIN_ID = 'clawclaw.derived-event';
19
+ export const CLAWCLAW_FLOW_PERCEPTION_PLUGIN_ID = 'clawclaw.perception.system.flow';
20
20
 
21
21
  const ROOM_GAME_OVER_HINT = 'This room round has ended. Review the result with the user, wait for the room lifecycle to resume, and do not start normal matchmaking.';
22
22
 
@@ -222,13 +222,13 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
222
222
  + 'The emergency is still active and needs another response.'
223
223
  ),
224
224
  exile: (event) => (
225
- `Meeting ended — ${actorName(event, text(event.result_target, 'Someone'))} was exiled by the table. `
225
+ `Meeting ended — ${text(event.exiled_player?.name, actorName(event, text(event.result_target, 'Someone')))} was exiled by the table. `
226
226
  + 'If this is you, your influence is dead — tell your user and ask whether to spectate or leave.'
227
227
  ),
228
228
  no_exile: () => 'Meeting ended — no one was exiled. The table failed to strike, and every hidden threat gets another turn.',
229
229
  meeting_briefing: (event) => meetingBriefingHint(event),
230
230
  speech_skipped: (event) => `${actorName(event, 'Someone')} lost the floor — silence becomes evidence`,
231
- speech_your_turn: () => 'Submit `ccl speak "<draft>"` immediately. Server skips you after 45s.',
231
+ speech_your_turn: () => 'Submit `ccl speak "<draft>"` immediately, before any query or narration. Server skips you after 45s.',
232
232
  speech_next_turn: (event) => (
233
233
  `You speak next after ${text(event.current_speaker, 'the current speaker')}. Prepare your response now.`
234
234
  ),
@@ -369,7 +369,7 @@ export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, Even
369
369
  ),
370
370
  });
371
371
 
372
- export const DERIVED_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
372
+ export const FLOW_PERCEPTION_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
373
373
  room_ready_to_start: (event) => (
374
374
  `The room is ready to start and you are the owner. Ask the user whether to start now before running \`${isTrainingRoomMode(event.room_type) ? 'ccl game training start' : 'ccl game start-room'}\`.`
375
375
  ),
@@ -387,8 +387,8 @@ export function formatCanonicalEventHint(
387
387
  }
388
388
  if (origin.producer !== 'local_synth') return undefined;
389
389
 
390
- if (origin.producerPluginId === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID) {
391
- return DERIVED_EVENT_HINT_FORMATTERS[event.type]?.(event, ctx);
390
+ if (origin.producerPluginId === CLAWCLAW_FLOW_PERCEPTION_PLUGIN_ID) {
391
+ return FLOW_PERCEPTION_HINT_FORMATTERS[event.type]?.(event, ctx);
392
392
  }
393
393
  // Source input Events currently enter the Runtime without a plugin id;
394
394
  // epoch-plugin proposals always carry one, so Strategy/Perception cannot
@@ -16,8 +16,20 @@ export interface RejectedGameSyncEventEntry {
16
16
  export interface GameSyncEventNormalizationResult {
17
17
  events: NormalizedGameSyncEventEntry[];
18
18
  rejected: RejectedGameSyncEventEntry[];
19
+ /** Non-fatal format ambiguity; the original field remains available. */
20
+ warnings?: Array<GameSyncEventNormalizationWarning & { index: number }>;
19
21
  }
20
22
 
23
+ export interface SpeechOrderNormalizationWarning {
24
+ field: 'speech_order';
25
+ reason: 'missing_roster' | 'invalid_roster' | 'ambiguous_name' | 'unmatched_name' | 'invalid_order';
26
+ }
27
+
28
+ export type GameSyncEventNormalizationWarning = SpeechOrderNormalizationWarning | {
29
+ field: 'votes';
30
+ reason: 'invalid_vote_pairs';
31
+ };
32
+
21
33
  interface PlayerRefProjection {
22
34
  wireField: string;
23
35
  nameField: string;
@@ -158,7 +170,10 @@ function playerRefArray(value: unknown, field: string): CanonicalPlayerRef[] {
158
170
  * PlayerRef collections stay as compact `{ name, seat }` records. This
159
171
  * function never reads `hint`: presentation text is not a source of facts.
160
172
  */
161
- export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
173
+ export function normalizeGameSyncEvent(
174
+ value: unknown,
175
+ warn?: (warning: GameSyncEventNormalizationWarning) => void,
176
+ ): Record<string, any> {
162
177
  if (!isRecord(value)) {
163
178
  throw new TypeError('GameSync Event must be an object');
164
179
  }
@@ -240,14 +255,15 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
240
255
  );
241
256
  }
242
257
 
243
- // origin/dev currently emits meeting_briefing.speech_order as a comma-
244
- // separated string even though the protocol document specifies PlayerRef[].
245
- // Accept that one current-v2 wire shape without weakening other ref arrays.
258
+ // The current backend joins names with ", ". Convert only using this
259
+ // event's own complete roster; never infer missing data from current State.
246
260
  if (Object.hasOwn(normalized, 'speech_order') && Array.isArray(normalized.speech_order)) {
247
261
  normalized.speech_order = playerRefArray(
248
262
  normalized.speech_order,
249
263
  'GameSync Event.speech_order',
250
264
  );
265
+ } else if (normalized.type === 'meeting_briefing' && typeof normalized.speech_order === 'string') {
266
+ normalized.speech_order = normalizeSpeechOrderNames(normalized.speech_order, normalized.all_seats, warn);
251
267
  } else if (
252
268
  Object.hasOwn(normalized, 'speech_order')
253
269
  && typeof normalized.speech_order !== 'string'
@@ -255,40 +271,47 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
255
271
  throw new TypeError('GameSync Event.speech_order must be a string or PlayerRef array');
256
272
  }
257
273
 
274
+ if ((normalized.type === 'exile' || normalized.type === 'no_exile')
275
+ && Array.isArray(normalized.votes)
276
+ && normalized.votes.some((pair: unknown) => !Array.isArray(pair) || pair.length !== 2
277
+ || !Number.isInteger(pair[0]) || (pair[1] !== null && !Number.isInteger(pair[1])))) {
278
+ // Do not discard an authoritative exile result because its optional tally is malformed.
279
+ // Keep the supplied field for inspection; never invent a seat or turn an invalid target into abstention.
280
+ warn?.({ field: 'votes', reason: 'invalid_vote_pairs' });
281
+ }
258
282
  return normalized;
259
283
  }
260
284
 
261
- function taskEventActorKey(event: Record<string, any>): string | null {
262
- if (Number.isInteger(event.actor_seat)) return `seat:${String(event.actor_seat)}`;
263
- return typeof event.actor_name === 'string' && event.actor_name.length > 0
264
- ? `name:${event.actor_name}`
265
- : null;
266
- }
267
-
268
- function newlyAssignedTask(event: Record<string, any>): Record<string, any> | null {
269
- if (typeof event.task_name !== 'string' || event.task_name.length === 0) return null;
270
- return {
271
- name: event.task_name,
272
- ...(typeof event.room === 'string' && event.room.length > 0 ? { room: event.room } : {}),
273
- ...(typeof event.x === 'number' && Number.isFinite(event.x) ? { x: event.x } : {}),
274
- ...(typeof event.y === 'number' && Number.isFinite(event.y) ? { y: event.y } : {}),
275
- ...(typeof event.is_fake_shrimp === 'boolean'
276
- ? { is_fake_shrimp: event.is_fake_shrimp }
277
- : {}),
285
+ function normalizeSpeechOrderNames(
286
+ order: string,
287
+ roster: unknown,
288
+ warn?: (warning: SpeechOrderNormalizationWarning) => void,
289
+ ): string | CanonicalPlayerRef[] {
290
+ const unchanged = (reason: SpeechOrderNormalizationWarning['reason']): string => {
291
+ warn?.({ field: 'speech_order', reason });
292
+ return order;
278
293
  };
294
+ if (order === '') return [];
295
+ if (roster === undefined) return unchanged('missing_roster');
296
+ let refs: CanonicalPlayerRef[];
297
+ try { refs = playerRefArray(roster, 'GameSync Event.all_seats'); }
298
+ catch { return unchanged('invalid_roster'); }
299
+ const byName = new Map<string, CanonicalPlayerRef>();
300
+ const seats = new Set<number>();
301
+ for (const ref of refs) {
302
+ if (!ref.name || seats.has(ref.seat)) return unchanged('invalid_roster');
303
+ if (ref.name.includes(',') || byName.has(ref.name)) return unchanged('ambiguous_name');
304
+ byName.set(ref.name, ref); seats.add(ref.seat);
305
+ }
306
+ const names = order.split(', ');
307
+ if (names.some(name => !name) || new Set(names).size !== names.length) return unchanged('invalid_order');
308
+ if (names.some(name => !byName.has(name))) return unchanged('unmatched_name');
309
+ return names.map(name => ({ ...byName.get(name)! }));
279
310
  }
280
311
 
281
- /**
282
- * Normalize one GameSync frame and enrich a completed task with its private,
283
- * same-frame replacement assignment. The raw task_assigned Event remains in
284
- * the batch for internal consumers; Agent delivery is still owned by the
285
- * Event Catalog.
286
- */
312
+ /** Normalize each backend fact independently; perceptions own task notifications. */
287
313
  export function normalizeGameSyncEvents(values: readonly unknown[]): Record<string, any>[] {
288
- return enrichTaskAssignments(values.map((value, index) => ({
289
- index,
290
- event: normalizeGameSyncEvent(value),
291
- }))).map(({ event }) => event);
314
+ return values.map(value => normalizeGameSyncEvent(value));
292
315
  }
293
316
 
294
317
  /** Normalize independent Events without rejecting their valid frame siblings. */
@@ -297,42 +320,13 @@ export function normalizeGameSyncEventsSafely(
297
320
  ): GameSyncEventNormalizationResult {
298
321
  const events: NormalizedGameSyncEventEntry[] = [];
299
322
  const rejected: RejectedGameSyncEventEntry[] = [];
323
+ const warnings: NonNullable<GameSyncEventNormalizationResult['warnings']> = [];
300
324
  values.forEach((value, index) => {
301
325
  try {
302
- events.push({ index, event: normalizeGameSyncEvent(value) });
326
+ events.push({ index, event: normalizeGameSyncEvent(value, warning => warnings.push({ index, ...warning })) });
303
327
  } catch (error) {
304
328
  rejected.push({ index, error });
305
329
  }
306
330
  });
307
- return { events: enrichTaskAssignments(events), rejected };
308
- }
309
-
310
- function enrichTaskAssignments(
311
- entries: readonly NormalizedGameSyncEventEntry[],
312
- ): NormalizedGameSyncEventEntry[] {
313
- const claimedAssignments = new Set<number>();
314
-
315
- return entries.map((entry, index) => {
316
- const { event } = entry;
317
- if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return entry;
318
- const actorKey = taskEventActorKey(event);
319
- if (!actorKey) return entry;
320
-
321
- const assignmentIndex = entries.findIndex(({ event: candidate }, candidateIndex) => (
322
- candidateIndex > index
323
- && !claimedAssignments.has(candidateIndex)
324
- && candidate.type === 'task_assigned'
325
- && candidate.tick === event.tick
326
- && taskEventActorKey(candidate) === actorKey
327
- ));
328
- if (assignmentIndex < 0) return entry;
329
-
330
- const task = newlyAssignedTask(entries[assignmentIndex]!.event);
331
- if (!task) return entry;
332
- claimedAssignments.add(assignmentIndex);
333
- return {
334
- ...entry,
335
- event: { ...event, newly_assigned_task: task },
336
- };
337
- });
331
+ return { events, rejected, ...(warnings.length ? { warnings } : {}) };
338
332
  }
@@ -7,7 +7,7 @@ import { assertRuntimeModuleOutputSize } from '../framework/modules/runtime-modu
7
7
  const DECISION_KEYS = new Set(['actions', 'status', 'events', 'delegate', 'finish']);
8
8
  const STATUS_KEYS = new Set(['summary', 'activity', 'room', 'task', 'targetPlayer', 'data']);
9
9
  const EVENT_KEYS = new Set(['type', 'payload', 'occurredAt']);
10
- const DELEGATE_KEYS = new Set(['behavior', 'input']);
10
+ const DELEGATE_KEYS = new Set(['behavior', 'strategy', 'input']);
11
11
  const FINISH_KEYS = new Set(['outcome', 'reason', 'summary']);
12
12
 
13
13
  function objectRecord(value: unknown, code: string): Record<string, unknown> {
@@ -69,11 +69,14 @@ export function normalizeBehaviorDecision(
69
69
  }
70
70
  }
71
71
  }
72
+ let normalizedDelegate: Record<string, unknown> | undefined;
72
73
  if (source.delegate !== undefined) {
73
74
  const delegate = objectRecord(source.delegate, 'behavior_delegate_invalid');
74
75
  rejectUnknownFields(delegate, DELEGATE_KEYS, 'behavior_delegate_field_unknown');
75
- nonEmptyString(delegate.behavior, 'behavior_delegate_id_invalid');
76
+ if (delegate.behavior !== undefined && delegate.strategy !== undefined) throw new Error('strategy_delegate_name_conflict');
77
+ const target = nonEmptyString(delegate.strategy ?? delegate.behavior, 'behavior_delegate_id_invalid');
76
78
  if (delegate.input !== undefined) objectRecord(delegate.input, 'behavior_delegate_input_invalid');
79
+ normalizedDelegate = { behavior: target, ...(delegate.input === undefined ? {} : { input: delegate.input }) };
77
80
  }
78
81
  if (source.finish !== undefined) {
79
82
  const finish = objectRecord(source.finish, 'behavior_finish_invalid');
@@ -86,7 +89,8 @@ export function normalizeBehaviorDecision(
86
89
  throw new Error('behavior_finish_summary_invalid');
87
90
  }
88
91
  }
89
- const normalized = Object.freeze(structuredClone(source)) as BehaviorDecision | FiniteBehaviorDecision;
92
+ const normalized = Object.freeze(structuredClone({ ...source,
93
+ ...(normalizedDelegate ? { delegate: normalizedDelegate } : {}) })) as BehaviorDecision | FiniteBehaviorDecision;
90
94
  assertRuntimeModuleOutputSize(normalized, 'behavior_output');
91
95
  return normalized;
92
96
  }
@@ -20,7 +20,8 @@ function behaviorEvents(
20
20
  input: RuntimeEpochPluginInput<Record<string, any>>,
21
21
  gameState: GameState,
22
22
  ): readonly Readonly<GameEvent>[] {
23
- return input.pendingEvents.map((event) => ({
23
+ return input.pendingEvents.filter(event => !event.notificationOf
24
+ && !event.producerPluginId?.startsWith('clawclaw.perception.system.')).map((event) => ({
24
25
  eventId: event.eventId,
25
26
  ...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }),
26
27
  type: event.type,
@@ -42,9 +43,10 @@ export function createCanonicalGameState(
42
43
  }
43
44
 
44
45
  /**
45
- * Build the one player-module input from a fresh GameSync epoch.
46
+ * Build the player-module input from the latest authoritative observation.
46
47
  * Lifecycle plugins decide when a Behavior is eligible to run; modules never
47
- * receive Runtime State or a nullable/stale Game State through this contract.
48
+ * receive Runtime State or a nullable Game State. A cycle reports the actual
49
+ * age/version when this observation is cached rather than newly received.
48
50
  */
49
51
  export function createBehaviorInput<
50
52
  TInput extends Readonly<Record<string, unknown>>,
@@ -55,7 +57,8 @@ export function createBehaviorInput<
55
57
  decisionHistory: readonly Readonly<BehaviorDecisionFrame>[] = [],
56
58
  ): BehaviorInput<TInput> | null {
57
59
  const runtimeState = input.epoch.state;
58
- if (!isClawclawRuntimeState(runtimeState) || runtimeState.game_snapshot.status !== 'fresh') {
60
+ if (!isClawclawRuntimeState(runtimeState)
61
+ || (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached')) {
59
62
  return null;
60
63
  }
61
64
  const gameState = createCanonicalGameState(
@@ -69,6 +72,7 @@ export function createBehaviorInput<
69
72
  segmentId: input.epoch.scope.segmentId,
70
73
  },
71
74
  nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
75
+ ...(runtimeState.cycle ? { cycle: structuredClone(runtimeState.cycle) } : {}),
72
76
  gameState,
73
77
  events: behaviorEvents(input, gameState),
74
78
  input: structuredClone(behaviorInput),