@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
@@ -1,1740 +1,159 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { isNotificationTurn } from '../../notification-turn.js';
2
+ import { ClawclawStrategyMemory } from '../../strategy-memory.js';
2
3
  import { resolveDetailCapture } from '../../../observability/detail-capture.js';
3
- import { performance } from 'node:perf_hooks';
4
- import type {
5
- BehaviorContinuation,
6
- BehaviorDecision,
7
- BehaviorDelegation,
8
- BehaviorFinish,
9
- BehaviorInput,
10
- BehaviorStatus,
11
- ClawclawResolvedResourceMetadata,
12
- GameAction,
13
- } from '../../../../sdk/behavior-plugin/index.js';
4
+ import type { BehaviorContinuation, BehaviorInput, ClawclawResolvedResourceMetadata, GameAction } from '../../../../sdk/behavior-plugin/index.js';
14
5
  import { resolveClawclawResourceMetadata } from '../../../../sdk/behavior-plugin/index.js';
15
- import type { ActionCaller } from '../../../framework/contracts.js';
16
- import type { RuntimeScope } from '../../../framework/state/types.js';
17
- import type {
18
- RuntimeEpochCatchUp,
19
- RuntimeEpochPlugin,
20
- RuntimeEpochPluginContext,
21
- RuntimeEpochPluginInput,
22
- RuntimeEpochPluginResult,
23
- RuntimeEventProposal,
24
- } from '../../../framework/plugins/contracts.js';
6
+ import type { RuntimeEpochCatchUp } from '../../../framework/plugins/contracts.js';
25
7
  import { createBehaviorInput } from '../../behavior-input.js';
26
8
  import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
27
9
  import { isClawclawRuntimeState } from '../../runtime-state.js';
28
- import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
29
- type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
30
10
  import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js';
31
- import { CLAWCLAW_DERIVED_EVENT_PLUGIN_ID } from '../derived-event/index.js';
32
11
  import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js';
33
12
  import { CLAWCLAW_PERCEPTION_PLUGIN_ID } from '../perception/index.js';
34
- import {
35
- CLAWCLAW_TRIGGER_PLUGIN_ID,
36
- type BehaviorReflexActivationDriver,
37
- type BehaviorReflexActivationRequest,
38
- type BehaviorReflexActivationResult,
39
- } from '../trigger/contracts.js';
40
- import {
41
- BehaviorActivationManager,
42
- type BehaviorActivationSnapshot,
43
- type BehaviorActivationSource,
44
- type BehaviorActivationTransition,
45
- } from './activation-manager.js';
13
+ import { CLAWCLAW_TRIGGER_PLUGIN_ID } from '../trigger/contracts.js';
14
+ import { BehaviorActivationManager, type BehaviorActivationSnapshot, type BehaviorActivationSource } from './activation-manager.js';
46
15
  import { normalizeClawclawBehaviorAction } from './behavior-action.js';
47
16
  import type { ClawclawBehaviorCatalog } from './behavior-catalog.js';
48
- import { BehaviorDecisionHistory } from './behavior-decision-history.js';
49
17
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
50
18
  import { ClawclawBehaviorRunner } from './behavior-runner.js';
51
- import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
52
- import type {
53
- ClawclawBehaviorControlDriver,
54
- ClawclawBehaviorControlHandle,
55
- } from './control-driver.js';
56
-
19
+ import type { ClawclawBehaviorControlDriver } from './control-driver.js';
20
+ import { StrategyHost } from '@myclaw163/game-agent-runtime/strategy/strategy-host.js';
21
+ import type { PreparedStrategy, StrategyAdapter, StrategyFrame } from '@myclaw163/game-agent-runtime/strategy/contracts.js';
22
+ import type { BehaviorDecisionFrame } from '../../../../sdk/module-input/index.js';
23
+ import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
57
24
  export const CLAWCLAW_BEHAVIOR_PLUGIN_ID = 'clawclaw.behavior';
58
25
  export const CLAWCLAW_BEHAVIOR_STATE_TOPIC = 'behavior.status';
59
26
  export const CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES = Object.freeze([
60
- 'behavior.started',
61
- 'behavior.suspended',
62
- 'behavior.restarted',
63
- 'behavior.completed',
64
- 'behavior.failed',
65
- 'behavior.cancelled',
66
- 'behavior.replaced',
27
+ 'behavior.started',
28
+ 'behavior.suspended',
29
+ 'behavior.restarted',
30
+ 'behavior.completed',
31
+ 'behavior.failed',
32
+ 'behavior.cancelled',
33
+ 'behavior.replaced',
67
34
  ] as const);
68
-
69
35
  export interface ClawclawRoleFallbackBehavior {
70
- readonly behaviorId: string;
71
- readonly input?: Readonly<Record<string, unknown>>;
36
+ readonly behaviorId: string;
37
+ readonly input?: Readonly<Record<string, unknown>>;
72
38
  }
73
-
74
- export type ClawclawRoleFallbackBehaviors = Readonly<Record<
75
- string,
76
- Readonly<ClawclawRoleFallbackBehavior> | undefined
77
- >>;
78
-
79
- const BEHAVIOR_COMPUTATION_SCHEMA = 1;
80
- const DEFAULT_DECISION_TIMEOUT_MS = 4_000;
81
- const DEFAULT_SHORT_MAX_RUNTIME_MS = 120_000;
39
+ export type ClawclawRoleFallbackBehaviors = Readonly<Record<string, Readonly<ClawclawRoleFallbackBehavior> | undefined>>;
82
40
  const BACKEND_STRATEGY_REPORT_LOCALE = 'zh-CN';
83
- const BACKEND_STRATEGY_REPORT_RETRY_MS = 1_000;
84
-
85
- interface BackendStrategyReportTarget extends ClawclawResolvedResourceMetadata {
86
- readonly fingerprint: string;
87
- }
88
-
89
- interface BackendStrategyReportAttempt {
90
- readonly lifecycleGeneration: number;
91
- readonly fingerprint: string;
92
- }
93
-
94
41
  function isSuccessfulBackendStrategyReport(value: unknown): boolean {
95
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
96
- const result = value as Record<string, unknown>;
97
- if (
98
- result.status !== 'success'
99
- || result.source !== 'backend'
100
- || result.actionOutcome !== 'confirmed'
101
- ) return false;
102
- const response = result.value;
103
- if (!response || typeof response !== 'object' || Array.isArray(response)) return false;
104
- const root = response as Record<string, unknown>;
105
- const data = root.data;
106
- return root.success === true
107
- && !!data
108
- && typeof data === 'object'
109
- && !Array.isArray(data)
110
- && (data as Record<string, unknown>).ok === true;
42
+ if (!value || typeof value !== 'object' || Array.isArray(value))
43
+ return false;
44
+ const result = value as Record<string, unknown>;
45
+ if (result.status !== 'success'
46
+ || result.source !== 'backend'
47
+ || result.actionOutcome !== 'confirmed')
48
+ return false;
49
+ const response = result.value;
50
+ if (!response || typeof response !== 'object' || Array.isArray(response))
51
+ return false;
52
+ const root = response as Record<string, unknown>;
53
+ const data = root.data;
54
+ return root.success === true
55
+ && !!data
56
+ && typeof data === 'object'
57
+ && !Array.isArray(data)
58
+ && (data as Record<string, unknown>).ok === true;
111
59
  }
112
-
113
60
  export interface ClawclawBehaviorPluginOptions {
114
- readonly perceptionActivations?: boolean;
115
- readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
116
- readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
117
- readonly manager?: BehaviorActivationManager;
118
- readonly driver?: ClawclawBehaviorControlDriver;
119
- readonly after?: readonly string[];
120
- readonly eventTypes?: readonly string[];
121
- readonly timeoutMs?: number;
122
- readonly decisionTimeoutMs?: number;
123
- readonly catchUp?: RuntimeEpochCatchUp;
124
- readonly diagnosticsEnabled?: boolean;
125
- readonly now?: () => number;
126
- readonly createActivationId?: () => string;
61
+ readonly memory?: ClawclawStrategyMemory;
62
+ readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
63
+ readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
64
+ readonly manager?: BehaviorActivationManager;
65
+ readonly driver?: ClawclawBehaviorControlDriver;
66
+ readonly after?: readonly string[];
67
+ readonly eventTypes?: readonly string[];
68
+ readonly timeoutMs?: number;
69
+ readonly decisionTimeoutMs?: number;
70
+ readonly catchUp?: RuntimeEpochCatchUp;
71
+ readonly diagnosticsEnabled?: boolean;
72
+ readonly now?: () => number;
73
+ readonly createActivationId?: () => string;
127
74
  }
128
-
129
75
  export interface StartBehaviorOptions {
130
- readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system' | 'perception'>;
131
- readonly maxRuntimeMs?: number;
132
- /** Revalidate scope/phase after asynchronous preparation, before changing control. */
133
- readonly isCurrent?: () => boolean;
76
+ readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system'>;
77
+ readonly maxRuntimeMs?: number;
78
+ /** Revalidate scope/phase after asynchronous preparation, before changing control. */
79
+ readonly isCurrent?: () => boolean;
134
80
  }
135
-
136
81
  export interface ClawclawBehaviorHostStatus {
137
- readonly running: boolean;
138
- readonly current?: Readonly<BehaviorActivationSnapshot>;
139
- readonly stack: ReturnType<BehaviorActivationManager['snapshot']>;
140
- }
141
-
142
- interface ActivationRuntime {
143
- snapshotStore?: BehaviorSnapshotStore;
144
- readonly activationId: string;
145
- readonly behaviorId: string;
146
- prepared: PreparedClawclawBehavior;
147
- runner?: ClawclawBehaviorRunner;
148
- instanceGeneration?: number;
149
- lastCommittedBackendTick?: number;
150
- lastStatus?: Readonly<BehaviorStatus>;
151
- pendingContinuation?: Readonly<BehaviorContinuation>;
152
- readonly decisionHistory: BehaviorDecisionHistory;
153
- committedActionDedupeKeys: Map<string, number>;
154
- }
155
-
156
- interface DelegatedShort {
157
- readonly parentActivationId: string;
158
- }
159
-
160
- interface BehaviorComputationProposal {
161
- readonly schema: typeof BEHAVIOR_COMPUTATION_SCHEMA;
162
- readonly kind:
163
- | 'inactive'
164
- | 'waiting_for_state'
165
- | 'boundary'
166
- | 'game_over'
167
- | 'player_inactive'
168
- | 'control_held'
169
- | 'cadence_skip'
170
- | 'serial'
171
- | 'parallel'
172
- | 'module_error';
173
- readonly activationId?: string;
174
- readonly instanceGeneration?: number;
175
- readonly eventIds?: readonly string[];
176
- readonly observationRevision?: number;
177
- readonly decision?: Readonly<BehaviorDecision>;
178
- readonly errorCode?: string;
179
- }
180
-
181
- function errorCode(error: unknown, fallback = 'BEHAVIOR_HOST_FAILED'): string {
182
- const message = error instanceof Error ? error.message : String(error);
183
- return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message) ? message : fallback;
184
- }
185
-
186
- function proposal(value: unknown): BehaviorComputationProposal {
187
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
188
- throw new Error('behavior_computation_invalid');
189
- }
190
- const parsed = value as BehaviorComputationProposal;
191
- if (parsed.schema !== BEHAVIOR_COMPUTATION_SCHEMA) {
192
- throw new Error('behavior_computation_invalid');
193
- }
194
- return parsed;
195
- }
196
-
197
- function currentRuntimeSnapshot(
198
- manager: BehaviorActivationManager,
199
- activationId: string,
200
- ): BehaviorActivationSnapshot | undefined {
201
- const snapshot = manager.snapshot();
202
- return [snapshot.reflex, snapshot.short, snapshot.long]
203
- .find((candidate) => candidate?.activationId === activationId);
204
- }
205
-
206
- function runtimeMs(
207
- prepared: PreparedClawclawBehavior,
208
- rawInput: Readonly<Record<string, unknown>>,
209
- override?: number,
210
- ): number | undefined {
211
- const base = override ?? prepared.timing?.duration_ms
212
- ?? prepared.timing?.timeout_ms
213
- ?? prepared.manifest.runtime?.defaultMs;
214
- return base === undefined
215
- ? undefined
216
- : base + (prepared.manifest.runtime?.controlGraceMs ?? 0);
217
- }
218
-
219
- function deadlineOutcome(
220
- prepared: PreparedClawclawBehavior,
221
- rawInput: Readonly<Record<string, unknown>>,
222
- ): 'completed' | 'failed' | undefined {
223
- if (rawInput.duration_ms !== undefined) return 'completed';
224
- if (rawInput.timeout_ms !== undefined) return 'failed';
225
- return prepared.manifest.runtime?.deadlineOutcome;
226
- }
227
-
228
- function eventIds(input: Readonly<BehaviorInput>): readonly string[] {
229
- return input.events.map((event) => event.eventId);
82
+ readonly running: boolean;
83
+ readonly current?: Readonly<BehaviorActivationSnapshot>;
84
+ readonly stack: ReturnType<BehaviorActivationManager['snapshot']>;
230
85
  }
231
-
232
- function sameStrings(left: readonly string[], right: readonly string[]): boolean {
233
- return left.length === right.length && left.every((value, index) => value === right[index]);
86
+ function sdkFrame(frame: StrategyFrame): Readonly<BehaviorInput> { return frame.value as Readonly<BehaviorInput>; }
87
+ function preparedValue(prepared: PreparedStrategy): PreparedClawclawBehavior {
88
+ return { ...(prepared.value as PreparedClawclawBehavior), ...(prepared.module ? { module: prepared.module as PreparedClawclawBehavior['module'] } : {}) };
234
89
  }
235
-
236
- function normalizeRoleFallbackBehaviors(
237
- value: ClawclawRoleFallbackBehaviors | undefined,
238
- ): Map<string, Readonly<ClawclawRoleFallbackBehavior>> {
239
- const result = new Map<string, Readonly<ClawclawRoleFallbackBehavior>>();
240
- for (const [role, binding] of Object.entries(value ?? {})) {
241
- if (!role.trim() || !binding) continue;
242
- if (!/^[a-z0-9][a-z0-9._-]*$/.test(binding.behaviorId)) {
243
- throw new Error('behavior_fallback_id_invalid');
244
- }
245
- result.set(role, Object.freeze({
246
- behaviorId: binding.behaviorId,
247
- input: Object.freeze(structuredClone(binding.input ?? {})),
248
- }));
249
- }
250
- return result;
251
- }
252
-
253
- function lifecycleEvent(transition: BehaviorActivationTransition): RuntimeEventProposal | undefined {
254
- if (transition.type === 'ignored') return undefined;
255
- return {
256
- type: `behavior.${transition.type}`,
257
- dedupeKey: `${transition.activationId}:${transition.instanceGeneration}:${transition.type}`,
258
- payload: {
259
- activation_id: transition.activationId,
260
- behavior: transition.behaviorId,
261
- layer: transition.layer,
262
- transition: transition.type,
263
- reason: transition.reason,
264
- instance_generation: transition.instanceGeneration,
265
- ...(transition.replacedByActivationId === undefined
266
- ? {}
267
- : { replaced_by_activation_id: transition.replacedByActivationId }),
268
- },
269
- };
270
- }
271
-
272
- function asActionCaller(caller: ClawclawBehaviorControlHandle['caller']): ActionCaller {
273
- return caller as unknown as ActionCaller;
274
- }
275
-
276
- /**
277
- * The sole long/short/reflex execution host. Activation policy is separate
278
- * from module code; every layer runs the same ClawclawBehavior contract.
279
- */
280
- export class ClawclawBehaviorPlugin
281
- implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriver {
282
- readonly kind = 'epoch' as const;
283
- readonly id = CLAWCLAW_BEHAVIOR_PLUGIN_ID;
284
- readonly version = '3';
285
- readonly after: readonly string[];
286
- readonly consumes = { events: ['*'] } as const;
287
- readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
288
- readonly capabilities: { uses: readonly string[]; provides?: readonly string[] };
289
- private releasePerceptionActivation?: () => void;
290
- readonly catchUp: RuntimeEpochCatchUp;
291
- readonly backlogPolicy = 'finish_started' as const;
292
- get maxInFlight(): number {
293
- const current = this.manager.current();
294
- return current && this.runtimes.get(current.activationId)?.prepared.manifest.execution === 'serial' ? 1 : 10;
295
- }
296
- readonly maxPendingEpochs = 10;
297
- readonly timeoutMs: number;
298
- readonly failurePolicy = 'failed_completion' as const;
299
-
300
- private readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
301
- private readonly manager: BehaviorActivationManager;
302
- private readonly now: () => number;
303
- private readonly createActivationId: () => string;
304
- private readonly decisionTimeoutMs: number;
305
- private readonly captureActions = resolveDetailCapture().actions;
306
- private readonly diagnosticsEnabled: boolean;
307
- private readonly observationMemory = new ClawclawBehaviorObservationMemory();
308
- private readonly runtimes = new Map<string, ActivationRuntime>();
309
- private readonly delegatedShorts = new Map<string, Readonly<DelegatedShort>>();
310
- private readonly finishSummaries = new Map<string, string>();
311
- private readonly controls = new Map<string, ClawclawBehaviorControlHandle>();
312
- private readonly pendingLifecycleEvents: RuntimeEventProposal[] = [];
313
- private readonly decisionControllers = new Map<string, Set<AbortController>>();
314
- private controlTail = Promise.resolve();
315
- private driver?: ClawclawBehaviorControlDriver;
316
- private scope?: Readonly<RuntimeScope>;
317
- private diagnostic?: RuntimeEpochPluginContext<Record<string, any>>['diagnostic'];
318
- private boundaryActive = false;
319
- private stopped = false;
320
- private lastCommittedEpochSeq = 0;
321
- private fallbackPrepared?: PreparedClawclawBehavior;
322
- private fallbackPreparedUsed = false;
323
- private fallbackBehaviors = new Map<string, Readonly<ClawclawRoleFallbackBehavior>>();
324
- private fallbackConfigGeneration = 1;
325
- private appliedFallbackKey?: string;
326
- private manualFallbackOverride = false;
327
- private backendStrategyReportTarget?: BackendStrategyReportTarget;
328
- private backendStrategyReportAcknowledgedFingerprint?: string;
329
- private backendStrategyReportInFlight?: BackendStrategyReportAttempt;
330
- private backendStrategyReportTimer?: ReturnType<typeof setTimeout>;
331
- private backendStrategyReportContext?: RuntimeEpochPluginContext<Record<string, any>>;
332
- private backendStrategyReportEligible = false;
333
- private backendStrategyReportLifecycleGeneration = 0;
334
-
335
- constructor(options: ClawclawBehaviorPluginOptions) {
336
- this.capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY],
337
- ...(options.perceptionActivations ? { provides: [BEHAVIOR_ACTIVATION_CAPABILITY] } : {}) };
338
- this.catalog = options.catalog;
339
- this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
340
- this.manager = options.manager ?? new BehaviorActivationManager();
341
- this.driver = options.driver;
342
- this.now = options.now ?? Date.now;
343
- this.createActivationId = options.createActivationId ?? randomUUID;
344
- this.decisionTimeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
345
- this.diagnosticsEnabled = options.diagnosticsEnabled === true;
346
- this.after = [...(options.after ?? [
347
- CLAWCLAW_ACTION_PLUGIN_ID,
348
- CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
349
- CLAWCLAW_GAME_QUERY_PLUGIN_ID,
350
- CLAWCLAW_PERCEPTION_PLUGIN_ID,
351
- CLAWCLAW_TRIGGER_PLUGIN_ID,
352
- ])];
353
- this.catchUp = options.catchUp ?? 'every_epoch';
354
- this.timeoutMs = options.timeoutMs ?? Math.max(this.decisionTimeoutMs + 1_000, 5_000);
355
- const eventTypes = new Set([
356
- ...CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES,
357
- ...(options.eventTypes ?? []),
358
- ]);
359
- this.produces = {
360
- states: [CLAWCLAW_BEHAVIOR_STATE_TOPIC],
361
- events: [...eventTypes],
362
- };
363
- }
364
-
365
- attachDriver(driver: ClawclawBehaviorControlDriver): void {
366
- if (this.driver && this.driver !== driver) throw new Error('behavior_control_driver_already_attached');
367
- this.driver = driver;
368
- }
369
-
370
- async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
371
- this.scope = context.scope;
372
- this.diagnostic = context.diagnostic;
373
- this.stopped = false;
374
- if (this.capabilities.provides?.includes(BEHAVIOR_ACTIVATION_CAPABILITY)) {
375
- this.releasePerceptionActivation = context.capabilities.provideAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>({
376
- capability: BEHAVIOR_ACTIVATION_CAPABILITY,
377
- describeControl: () => ({ domains: [] }),
378
- perform: async (request, scope, _caller, execution) => {
379
- const activationBeforePreparation = this.manager.current();
380
- const current = () => {
381
- if (execution.signal.aborted || this.stopped || scope.sessionId !== this.scope?.sessionId
382
- || scope.segmentId !== this.scope?.segmentId || request.epochId <= this.lastCommittedEpochSeq) return false;
383
- const active = this.manager.current();
384
- if (active?.activationId !== activationBeforePreparation?.activationId
385
- || active?.instanceGeneration !== activationBeforePreparation?.instanceGeneration) return false;
386
- const latest = execution.latestAcceptedState();
387
- if (!latest) return false;
388
- const state = latest.state as Record<string, any>;
389
- const game = isClawclawRuntimeState(state)
390
- ? state.connection === 'connected' && state.stage === 'game' && state.game_snapshot.status === 'fresh'
391
- ? state.game_snapshot.state : undefined
392
- : state;
393
- return !!game && game.game_id === request.gameId && game.phase === 'wandering' && game.you?.is_alive === true;
394
- };
395
- let value: PerceptionBehaviorActivationResult = { accepted: false, reason: 'stale_request' };
396
- if (current()) {
397
- try {
398
- if (!this.catalog.has(request.behavior)) value = { accepted: false, reason: 'behavior_not_loaded' };
399
- else if (request.layer === 'reflex') value = await this.requestReflex({
400
- source: 'trigger', triggerId: `perception:${request.moduleId}:${request.bindingKey}`,
401
- scope: { sessionId: scope.sessionId, segmentId: scope.segmentId }, epochId: request.epochId,
402
- configGeneration: 0, behavior: request.behavior, behaviorInput: request.input,
403
- reflexPriority: request.reflexPriority, maxRuntimeMs: request.maxRuntimeMs ?? 10_000,
404
- reason: request.reason,
405
- }, { isCurrent: current });
406
- else {
407
- const activation = await this.startLayer(request.layer, request.behavior, request.input,
408
- { source: 'perception', maxRuntimeMs: request.maxRuntimeMs, isCurrent: current });
409
- value = { accepted: true, activationId: activation.activationId };
410
- }
411
- } catch { value = { accepted: false, reason: current() ? 'binding_invalid' : 'stale_request' }; }
412
- }
413
- return { scope, actionId: randomUUID(), status: 'success', source: 'local', value };
90
+ function createAdapter(): StrategyAdapter {
91
+ const observations = new ClawclawBehaviorObservationMemory();
92
+ return {
93
+ input: (input, parameters, continuation, history) => {
94
+ const frame = createBehaviorInput(input, parameters, continuation as BehaviorContinuation, history as readonly BehaviorDecisionFrame[]);
95
+ return frame ? { value: frame, epochId: frame.epochId, scope: frame.scope, nowMs: frame.nowMs,
96
+ tick: Number(frame.gameState.tick ?? frame.epochId), cycle: frame.cycle, events: frame.events } : null;
414
97
  },
415
- });
416
- }
417
- await this.applyTransitions(this.manager.leaveBoundary(this.now()));
418
- }
419
-
420
- status(): ClawclawBehaviorHostStatus {
421
- const current = this.manager.current();
422
- return Object.freeze({
423
- running: current !== undefined,
424
- ...(current === undefined ? {} : { current }),
425
- stack: this.manager.snapshot(),
426
- });
427
- }
428
-
429
- diagnosticSnapshot(): Readonly<Record<string, unknown>> {
430
- const status = this.status();
431
- return Object.freeze({
432
- running: status.running,
433
- current_activation_id: status.current?.activationId ?? null,
434
- current_behavior_id: status.current?.behaviorId ?? null,
435
- current_layer: status.current?.layer ?? null,
436
- runtime_count: this.runtimes.size,
437
- runtimes: [...this.runtimes.values()].map((runtime) => ({
438
- activation_id: runtime.activationId,
439
- behavior_id: runtime.behaviorId,
440
- instance_generation: runtime.instanceGeneration ?? null,
441
- runner: runtime.runner?.diagnosticSnapshot() ?? null,
442
- })),
443
- });
444
- }
445
-
446
- setIdleMs(idleMs: number): Promise<void> {
447
- return this.enqueueControl(async () => {
448
- await this.applyTransitions(this.manager.setIdleMs(idleMs, this.now()));
449
- });
450
- }
451
-
452
- configureFallbackBehaviors(
453
- bindings: ClawclawRoleFallbackBehaviors,
454
- currentRole?: string,
455
- ): Promise<void> {
456
- return this.enqueueControl(async () => {
457
- this.fallbackBehaviors = normalizeRoleFallbackBehaviors(bindings);
458
- this.fallbackConfigGeneration += 1;
459
- this.appliedFallbackKey = undefined;
460
- this.manualFallbackOverride = false;
461
- // A control receipt must reflect the current role's effective binding,
462
- // including meetings with no fresh observation frame. The activation
463
- // manager still owns boundary suspension and explicit long Behaviors.
464
- await this.syncRoleFallback(currentRole, this.now());
465
- });
466
- }
467
-
468
- bindFallback(
469
- behaviorId: string,
470
- input: Readonly<Record<string, unknown>>,
471
- ): Promise<void> {
472
- return this.enqueueControl(async () => {
473
- const prepared = await this.catalog.prepare(behaviorId, input);
474
- this.manualFallbackOverride = true;
475
- this.fallbackPrepared = prepared;
476
- this.fallbackPreparedUsed = false;
477
- await this.applyTransitions(this.manager.bindFallback({
478
- behaviorId,
479
- input: prepared.input,
480
- }, this.now()));
481
- });
482
- }
483
-
484
- clearFallback(): Promise<void> {
485
- return this.enqueueControl(async () => {
486
- this.manualFallbackOverride = true;
487
- this.fallbackPrepared = undefined;
488
- this.fallbackPreparedUsed = false;
489
- await this.applyTransitions(this.manager.bindFallback(undefined, this.now()));
490
- });
491
- }
492
-
493
- startLong(
494
- behaviorId: string,
495
- input: Readonly<Record<string, unknown>>,
496
- options: StartBehaviorOptions,
497
- ): Promise<Readonly<BehaviorActivationSnapshot>> {
498
- return this.startLayer('long', behaviorId, input, options);
499
- }
500
-
501
- startShort(
502
- behaviorId: string,
503
- input: Readonly<Record<string, unknown>>,
504
- options: StartBehaviorOptions,
505
- ): Promise<Readonly<BehaviorActivationSnapshot>> {
506
- return this.startLayer('short', behaviorId, input, options);
507
- }
508
-
509
- cancel(activationId: string, reason = 'cancelled_by_control'): Promise<void> {
510
- return this.enqueueControl(async () => {
511
- await this.applyTransitions(this.manager.cancel(activationId, reason, this.now()));
512
- });
513
- }
514
-
515
- noteAgentActivity(): Promise<void> {
516
- return this.enqueueControl(async () => {
517
- await this.applyTransitions(this.manager.noteAgentActivity(this.now()));
518
- });
519
- }
520
-
521
- async requestReflex(
522
- request: Readonly<BehaviorReflexActivationRequest>,
523
- guard?: Readonly<{ isCurrent(): boolean }>,
524
- ): Promise<BehaviorReflexActivationResult> {
525
- if (this.stopped || !this.scope) return { accepted: false, reason: 'activation_ineligible' };
526
- if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
527
- if (
528
- request.scope.sessionId !== this.scope.sessionId
529
- || request.scope.segmentId !== this.scope.segmentId
530
- || request.epochId <= this.lastCommittedEpochSeq
531
- ) return { accepted: false, reason: 'stale_request' };
532
- if (!this.catalog.has(request.behavior)) return { accepted: false, reason: 'binding_invalid' };
533
- let prepared: PreparedClawclawBehavior;
534
- try {
535
- prepared = await this.catalog.prepare(request.behavior, request.behaviorInput);
536
- } catch {
537
- return { accepted: false, reason: 'binding_invalid' };
538
- }
539
- if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
540
- const activeReflex = this.manager.snapshot().reflex;
541
- if (activeReflex) {
542
- if (activeReflex.triggerId === request.triggerId) {
543
- return { accepted: false, reason: 'same_trigger_active' };
544
- }
545
- if ((activeReflex.reflexPriority ?? 0) >= request.reflexPriority) {
546
- return { accepted: false, reason: 'reflex_priority_not_higher' };
547
- }
548
- }
549
- const interrupted = this.manager.current();
550
- if (interrupted) this.interruptDecisions(interrupted.activationId, 'behavior_reflex_preempted');
551
- return this.enqueueControl(async () => {
552
- if (this.stopped || !this.scope) return { accepted: false, reason: 'activation_ineligible' };
553
- if (guard && !guard.isCurrent()) return { accepted: false, reason: 'stale_request' };
554
- if (
555
- request.scope.sessionId !== this.scope.sessionId
556
- || request.scope.segmentId !== this.scope.segmentId
557
- || request.epochId <= this.lastCommittedEpochSeq
558
- ) return { accepted: false, reason: 'stale_request' };
559
- const activationId = this.createActivationId();
560
- const transitions = this.manager.requestReflex({
561
- activationId,
562
- behaviorId: request.behavior,
563
- input: prepared.input,
564
- requestedAt: this.now(),
565
- maxRuntimeMs: request.maxRuntimeMs,
566
- deadlineOutcome: 'failed',
567
- triggerId: request.triggerId,
568
- reflexPriority: request.reflexPriority,
569
- }, this.now());
570
- const ignored = transitions.find((entry) => entry.type === 'ignored');
571
- if (ignored) {
572
- return {
573
- accepted: false,
574
- reason: ignored.reason === 'reflex_trigger_already_active'
575
- ? 'same_trigger_active'
576
- : 'reflex_priority_not_higher',
577
- };
578
- }
579
- this.runtimes.set(activationId, {
580
- activationId,
581
- behaviorId: request.behavior,
582
- prepared,
583
- decisionHistory: new BehaviorDecisionHistory(),
584
- committedActionDedupeKeys: new Map(),
585
- });
586
- const replaced = transitions.find((entry) => entry.type === 'replaced');
587
- await this.applyTransitions(transitions);
588
- return {
589
- accepted: true,
590
- activationId,
591
- ...(replaced === undefined ? {} : { replacedActivationId: replaced.activationId }),
592
- };
593
- });
594
- }
595
-
596
- async update(
597
- input: RuntimeEpochPluginInput<Record<string, any>>,
598
- context: RuntimeEpochPluginContext<Record<string, any>>,
599
- ): Promise<RuntimeEpochPluginResult> {
600
- this.scope = context.scope;
601
- const current = this.manager.current();
602
- const base = {
603
- schema: BEHAVIOR_COMPUTATION_SCHEMA,
604
- ...(current === undefined ? {} : {
605
- activationId: current.activationId,
606
- instanceGeneration: current.instanceGeneration,
607
- }),
608
- } as const;
609
- if (!current) {
610
- return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } satisfies BehaviorComputationProposal };
611
- }
612
- const runtime = this.runtimes.get(current.activationId);
613
- if (
614
- runtime
615
- && runtime.instanceGeneration === current.instanceGeneration
616
- && isClawclawRuntimeState(input.epoch.state)
617
- && input.epoch.state.game_snapshot.status === 'fresh'
618
- ) {
619
- const tick = Number(
620
- input.epoch.domainTick
621
- ?? input.epoch.state.game_snapshot.state.tick
622
- ?? input.epoch.epochSeq,
623
- );
624
- runtime.decisionHistory.begin({
625
- epochId: input.epoch.epochSeq,
626
- tick,
627
- instanceGeneration: current.instanceGeneration,
628
- });
629
- const history = runtime.decisionHistory.snapshot();
630
- context.diagnostic('behavior.decision_history.frame_pending', {
631
- behavior_id: current.behaviorId,
632
- activation_id: current.activationId,
633
- instance_generation: current.instanceGeneration,
634
- epoch_id: input.epoch.epochSeq,
635
- tick,
636
- retained_frame_count: history.length,
637
- pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
638
- }, 'debug');
639
- }
640
- const frame = createBehaviorInput(
641
- input,
642
- current.input,
643
- runtime?.pendingContinuation,
644
- runtime?.decisionHistory.snapshot(),
645
- );
646
- if (!frame) {
647
- return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } satisfies BehaviorComputationProposal };
648
- }
649
- const noDecision = (
650
- kind: BehaviorComputationProposal['kind'],
651
- reason: string,
652
- ): RuntimeEpochPluginResult => {
653
- const resolved = runtime?.decisionHistory.notComputed(frame.epochId, reason);
654
- if (resolved) {
655
- const history = runtime!.decisionHistory.snapshot();
656
- context.diagnostic('behavior.decision_history.frame_resolved', {
657
- behavior_id: current.behaviorId,
658
- activation_id: current.activationId,
659
- instance_generation: current.instanceGeneration,
660
- epoch_id: frame.epochId,
661
- tick: resolved.tick,
662
- status: resolved.status,
663
- reason,
664
- action_count: 0,
665
- retained_frame_count: history.length,
666
- pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
667
- }, 'debug');
668
- }
669
- return {
670
- outcome: 'processed',
671
- proposal: { ...base, kind } satisfies BehaviorComputationProposal,
672
- };
673
- };
674
- if (frame.gameState.phase === 'game_over') {
675
- return noDecision('game_over', 'game_over');
676
- }
677
- if (frame.gameState.you?.is_alive === false) {
678
- return noDecision('player_inactive', 'player_inactive');
679
- }
680
- const meetingShort = frame.gameState.phase === 'meeting' && current.layer === 'short';
681
- if (frame.gameState.phase !== 'wandering' && !meetingShort) {
682
- return noDecision('boundary', 'phase_boundary');
683
- }
684
- const control = this.controls.get(current.activationId);
685
- if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
686
- return noDecision('control_held', 'runner_unavailable');
687
- }
688
- if (!control?.isAuthorized()) {
689
- return noDecision('control_held', 'control_held');
690
- }
691
- const backendTick = Number(frame.gameState.tick ?? frame.epochId);
692
- if (
693
- runtime.lastCommittedBackendTick !== undefined
694
- && backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks
695
- ) {
696
- return noDecision('cadence_skip', 'cadence_skip');
697
- }
698
- const observation = this.observationMemory.capture(frame);
699
- try {
700
- const decision = await this.withDecisionTimeout(
701
- signal => runtime.runner!.execution === 'serial'
702
- ? runtime.runner!.decideSerial(frame, signal, observation)
703
- : runtime.runner!.decideParallel(frame, signal, observation),
704
- context.signal,
705
- current.activationId,
706
- );
707
- const resolved = runtime.decisionHistory.complete(frame.epochId, decision.actions);
708
- if (this.captureActions) context.diagnostic('runtime.detail.actions.decision', {
709
- behavior_id: current.behaviorId, activation_id: current.activationId,
710
- instance_generation: current.instanceGeneration, epoch_id: frame.epochId,
711
- tick: frame.gameState.tick, stage: 'computed_not_yet_committed', actions: decision.actions ?? [],
712
- }, 'debug');
713
- if (resolved) {
714
- const history = runtime.decisionHistory.snapshot();
715
- context.diagnostic('behavior.decision_history.frame_resolved', {
716
- behavior_id: current.behaviorId,
717
- activation_id: current.activationId,
718
- instance_generation: current.instanceGeneration,
719
- epoch_id: frame.epochId,
720
- tick: resolved.tick,
721
- status: resolved.status,
722
- action_count: resolved.actions?.length ?? 0,
723
- action_kinds: (resolved.actions ?? []).map((action) => action.action),
724
- retained_frame_count: history.length,
725
- pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
726
- }, 'debug');
727
- }
728
- return {
729
- outcome: 'processed',
730
- proposal: {
731
- ...base,
732
- kind: runtime.runner.execution,
733
- eventIds: eventIds(frame),
734
- observationRevision: observation.revision,
735
- decision,
736
- } satisfies BehaviorComputationProposal,
737
- };
738
- } catch (error) {
739
- const failure = errorCode(error, 'BEHAVIOR_DECIDE_FAILED');
740
- const resolved = runtime.decisionHistory.fail(frame.epochId, failure);
741
- if (resolved) {
742
- const history = runtime.decisionHistory.snapshot();
743
- context.diagnostic('behavior.decision_history.frame_resolved', {
744
- behavior_id: current.behaviorId,
745
- activation_id: current.activationId,
746
- instance_generation: current.instanceGeneration,
747
- epoch_id: frame.epochId,
748
- tick: resolved.tick,
749
- status: resolved.status,
750
- reason: failure,
751
- action_count: 0,
752
- retained_frame_count: history.length,
753
- pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
754
- }, 'debug');
755
- }
756
- return {
757
- outcome: 'processed',
758
- proposal: {
759
- ...base,
760
- kind: 'module_error',
761
- errorCode: failure,
762
- } satisfies BehaviorComputationProposal,
763
- };
764
- }
765
- }
766
-
767
- commit(
768
- input: RuntimeEpochPluginInput<Record<string, any>>,
769
- computation: Readonly<RuntimeEpochPluginResult>,
770
- context: RuntimeEpochPluginContext<Record<string, any>>,
771
- ): Promise<RuntimeEpochPluginResult> {
772
- return this.enqueueControl(async () => {
773
- const result = await this.commitOrdered(input, proposal(computation.proposal), context);
774
- // Report the final activation after this epoch's advances, finishes and
775
- // boundary transitions, rather than the activation it started with.
776
- this.refreshBackendStrategyReport(input, context);
777
- return result;
778
- });
779
- }
780
-
781
- async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
782
- this.releasePerceptionActivation?.(); this.releasePerceptionActivation = undefined;
783
- await this.enqueueControl(async () => {
784
- this.stopped = true;
785
- this.resetBackendStrategyReporting();
786
- for (const controllers of this.decisionControllers.values()) {
787
- for (const controller of controllers) controller.abort(new Error(reason));
788
- }
789
- this.decisionControllers.clear();
790
- const runnerReason = reason === 'shutdown' ? 'shutdown' : 'scope_ended';
791
- const runners = [...this.runtimes.values()].flatMap((runtime) => {
792
- const runner = runtime.runner;
793
- runtime.runner = undefined;
794
- runtime.instanceGeneration = undefined;
795
- return runner ? [runner] : [];
796
- });
797
- await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
798
- await this.applyTransitions(this.manager.clearScope(reason, this.now()));
799
- this.runtimes.clear();
800
- this.delegatedShorts.clear();
801
- this.finishSummaries.clear();
802
- for (const handle of this.controls.values()) handle.release(reason);
803
- this.controls.clear();
804
- this.observationMemory.clear();
805
- this.scope = undefined;
806
- this.diagnostic = undefined;
807
- this.boundaryActive = false;
808
- this.pendingLifecycleEvents.length = 0;
809
- this.lastCommittedEpochSeq = 0;
810
- });
811
- }
812
-
813
- private startLayer(
814
- layer: 'long' | 'short',
815
- behaviorId: string,
816
- input: Readonly<Record<string, unknown>>,
817
- options: StartBehaviorOptions,
818
- ): Promise<Readonly<BehaviorActivationSnapshot>> {
819
- return this.enqueueControl(async () => {
820
- if (this.stopped || !this.scope) throw new Error('behavior_host_not_active');
821
- const prepared = await this.catalog.prepare(behaviorId, input);
822
- if (options.isCurrent && !options.isCurrent()) throw new Error('perception_activation_stale');
823
- const activationId = this.createActivationId();
824
- const maxRuntimeMs = layer === 'short'
825
- ? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
826
- : options.maxRuntimeMs;
827
- const outcome = maxRuntimeMs === undefined
828
- ? undefined
829
- : deadlineOutcome(prepared, input) ?? 'failed';
830
- const spec = {
831
- activationId,
832
- behaviorId,
833
- source: options.source,
834
- input: prepared.input,
835
- requestedAt: this.now(),
836
- ...(maxRuntimeMs === undefined ? {} : {
837
- maxRuntimeMs,
838
- deadlineOutcome: outcome,
98
+ boundary: input => {
99
+ const state = input.epoch.state, typed = isClawclawRuntimeState(state);
100
+ const observed = typed && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached');
101
+ return { notificationOnly: isNotificationTurn(state), cycle: !!state.cycle,
102
+ terminalReason: typed && state.stage === 'ended' ? 'scope_ended' : undefined,
103
+ hasObservation: observed, observationTick: observed && 'state' in state.game_snapshot ? Number(state.game_snapshot.state.tick) : undefined,
104
+ pendingPauseReason: typed && state.stage !== 'game' && state.stage !== 'meeting' ? 'wandering_inactive' : undefined,
105
+ actionGeneration: typed ? state.action_safety_generation : undefined };
106
+ },
107
+ policy: (frame, layer) => {
108
+ const state = frame ? sdkFrame(frame).gameState : undefined;
109
+ const meeting = state?.phase === 'meeting';
110
+ return { terminalReason: state?.phase === 'game_over' ? 'game_over' : undefined,
111
+ inactiveReason: state?.you?.is_alive === false ? 'player_inactive' : undefined,
112
+ pauseReason: state && state.phase !== 'wandering' && !(meeting && layer === 'short') ? meeting ? 'meeting_started' : 'wandering_inactive' : undefined,
113
+ resume: state?.phase === 'wandering', pauseAfterDecision: meeting ? 'meeting_started' : undefined,
114
+ fallbackKey: state?.you?.role };
115
+ },
116
+ observations: { capture: frame => observations.capture(sdkFrame(frame)), snapshot: id => observations.snapshot(id), clear: () => observations.clear() },
117
+ createRunner: options => {
118
+ const runner = new ClawclawBehaviorRunner({ ...options, prepared: preparedValue(options.prepared),
119
+ memory: options.memory && ((input, active) => options.memory!({ value: input, epochId: input.epochId, scope: input.scope,
120
+ nowMs: input.nowMs, tick: Number(input.gameState.tick ?? input.epochId), cycle: input.cycle, events: input.events }, active)) });
121
+ return { execution: runner.execution, everyTicks: runner.everyTicks, prepare: () => runner.prepare(),
122
+ stop: reason => runner.stop(reason), diagnosticSnapshot: () => runner.diagnosticSnapshot(),
123
+ decideSerial: (frame, signal, observation) => runner.decideSerial(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot),
124
+ decideParallel: (frame, signal, observation) => runner.decideParallel(sdkFrame(frame), signal, observation as ClawclawBehaviorObservationSnapshot) };
125
+ },
126
+ action: (action, epoch, safety, generation, tick) => ({ ...normalizeClawclawBehaviorAction(action as GameAction, epoch, safety, generation, tick) }),
127
+ display: prepared => prepared ? resolveClawclawResourceMetadata({ ...preparedValue(prepared).manifest, display: prepared.display }, BACKEND_STRATEGY_REPORT_LOCALE)
128
+ : { id: 'clawclaw:no-active-behavior', name: '无策略在运行', description: '当前没有活跃的策略。' },
129
+ reportEligible: input => {
130
+ const state = input.epoch.state;
131
+ return isClawclawRuntimeState(state)
132
+ && state.connection === 'connected' && (state.stage === 'game' || state.stage === 'meeting')
133
+ && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached')
134
+ && (state.game_snapshot.state.phase === 'wandering' || state.game_snapshot.state.phase === 'meeting')
135
+ && state.game_snapshot.state.you?.is_alive === true;
136
+ },
137
+ reportSelection: input => {
138
+ const state = input.epoch.state;
139
+ return isClawclawRuntimeState(state)
140
+ && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached')
141
+ && state.game_snapshot.state.phase === 'meeting' ? 'selected' : 'active';
142
+ },
143
+ report: (context, target) => context.capabilities.performAction(CLAWCLAW_ACTION_CAPABILITY, {
144
+ route: 'game', action: { action: 'strategy', name: target.name, description: target.description }
839
145
  }),
840
- } as const;
841
- this.runtimes.set(activationId, {
842
- activationId,
843
- behaviorId,
844
- prepared,
845
- decisionHistory: new BehaviorDecisionHistory(),
846
- committedActionDedupeKeys: new Map(),
847
- });
848
- const transitions = layer === 'long'
849
- ? this.manager.startLong(spec, this.now())
850
- : this.manager.startShort(spec, this.now());
851
- await this.applyTransitions(transitions);
852
- const snapshot = currentRuntimeSnapshot(this.manager, activationId);
853
- if (!snapshot) throw new Error('behavior_activation_start_failed');
854
- return snapshot;
855
- });
856
- }
857
-
858
- private async commitOrdered(
859
- input: RuntimeEpochPluginInput<Record<string, any>>,
860
- computed: BehaviorComputationProposal,
861
- context: RuntimeEpochPluginContext<Record<string, any>>,
862
- ): Promise<RuntimeEpochPluginResult> {
863
- this.scope = context.scope;
864
- this.diagnostic = context.diagnostic;
865
- this.lastCommittedEpochSeq = Math.max(this.lastCommittedEpochSeq, input.epoch.epochSeq);
866
- const cursor = input.pendingEvents.at(-1)?.commitSeq;
867
- const frameForClock = createBehaviorInput(input, Object.freeze({}));
868
- const now = frameForClock?.nowMs ?? this.now();
869
- const runtimeState = input.epoch.state;
870
-
871
- await this.syncRoleFallback(frameForClock?.gameState.you?.role, now);
872
- if (
873
- !frameForClock
874
- && isClawclawRuntimeState(runtimeState)
875
- && runtimeState.stage !== 'game'
876
- && runtimeState.stage !== 'meeting'
877
- ) {
878
- // Room and terminal updates have no authoritative Game State. A pending
879
- // idle fallback must not start just because this update arrives late.
880
- await this.applyTransitions(this.manager.enterBoundary('wandering_inactive', now));
881
- this.boundaryActive = true;
882
- return this.output(cursor);
883
- }
884
-
885
- await this.applyTransitions(this.manager.advance(now));
886
- const currentForFrame = this.manager.current();
887
- const currentFrameRuntime = currentForFrame
888
- ? this.runtimes.get(currentForFrame.activationId)
889
- : undefined;
890
- const frame = currentForFrame
891
- ? createBehaviorInput(
892
- input,
893
- currentForFrame.input,
894
- currentFrameRuntime?.pendingContinuation,
895
- currentFrameRuntime?.decisionHistory.snapshot(),
896
- )
897
- : frameForClock;
898
- if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
899
- await this.applyTransitions(this.manager.clearScope('game_over', now));
900
- this.boundaryActive = true;
901
- return this.output(cursor);
902
- }
903
- if (frame?.gameState.you?.is_alive === false || computed.kind === 'player_inactive') {
904
- await this.applyTransitions(this.manager.clearScope('player_inactive', now));
905
- this.boundaryActive = true;
906
- return this.output(cursor);
907
- }
908
-
909
- const meeting = frame?.gameState.phase === 'meeting';
910
- const outsideWandering = frame !== null && frame !== undefined && frame.gameState.phase !== 'wandering';
911
- if (outsideWandering && !(meeting && this.manager.current()?.layer === 'short')) {
912
- await this.applyTransitions(this.manager.enterBoundary(
913
- meeting ? 'meeting_started' : 'wandering_inactive',
914
- now,
915
- ));
916
- this.boundaryActive = true;
917
- return this.output(cursor);
918
- }
919
- if (frame?.gameState.phase === 'wandering' && this.boundaryActive) {
920
- this.boundaryActive = false;
921
- await this.applyTransitions(this.manager.leaveBoundary(now));
922
- return this.output(cursor);
923
- }
924
-
925
- const current = this.manager.current();
926
- if (!current) {
927
- const stack = this.manager.snapshot();
928
- // An empty host has no activation that will consume this batch later.
929
- // Drain only this plugin's cursor; canonical Events remain available to
930
- // other consumers. A suspended long waiting for hand-back still owns
931
- // its pending Events, even though current() temporarily returns nothing.
932
- if (!stack.long && !stack.short && !stack.reflex) return this.output(cursor);
933
- }
934
- if (
935
- !current
936
- || computed.activationId !== current.activationId
937
- || computed.instanceGeneration !== current.instanceGeneration
938
- || !this.manager.isCurrent(current.activationId, current.instanceGeneration)
939
- ) {
940
- if (computed.activationId) {
941
- this.runtimes.get(computed.activationId)?.decisionHistory.notComputed(
942
- input.epoch.epochSeq,
943
- 'activation_superseded_before_commit',
944
- );
945
- }
946
- return this.output(undefined);
947
- }
948
-
949
- if (!frame) return this.output(undefined);
950
- const runtime = this.runtimes.get(current.activationId);
951
- const control = this.controls.get(current.activationId);
952
- if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration || !control?.isAuthorized()) {
953
- return this.output(undefined);
954
- }
955
- const backendTick = Number(frame.gameState.tick ?? frame.epochId);
956
- if (
957
- runtime.lastCommittedBackendTick !== undefined
958
- && backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks
959
- ) return this.output(undefined);
960
- if (computed.kind === 'cadence_skip' || computed.kind === 'control_held') {
961
- return this.output(undefined);
962
- }
963
- if (computed.kind === 'module_error') {
964
- await this.failCurrent(current, computed.errorCode ?? 'BEHAVIOR_DECIDE_FAILED', now);
965
- return this.output(cursor);
966
- }
967
- if (computed.kind !== 'serial' && computed.kind !== 'parallel') {
968
- return this.output(computed.kind === 'inactive' ? cursor : undefined);
969
- }
970
-
971
- const observation = this.observationMemory.snapshot(frame.epochId)
972
- ?? this.observationMemory.capture(frame);
973
- const decision = computed.decision;
974
- const proposalIsStale = !sameStrings(computed.eventIds ?? [], eventIds(frame))
975
- || computed.observationRevision !== observation.revision;
976
- if (proposalIsStale) {
977
- context.diagnostic('behavior.decision.stale_before_commit', {
978
- behavior_id: current.behaviorId,
979
- activation_id: current.activationId,
980
- instance_generation: current.instanceGeneration,
981
- epoch_id: frame.epochId,
982
- tick: frame.gameState.tick,
983
- event_input_changed: !sameStrings(computed.eventIds ?? [], eventIds(frame)),
984
- observation_revision_changed: computed.observationRevision !== observation.revision,
985
- }, 'debug');
986
- return this.output(undefined);
987
- }
988
- if (!decision || !this.manager.isCurrent(current.activationId, current.instanceGeneration)) {
989
- return this.output(undefined);
990
- }
991
- const resolvedDecision = runtime.decisionHistory.complete(frame.epochId, decision.actions);
992
- if (resolvedDecision) {
993
- const history = runtime.decisionHistory.snapshot();
994
- context.diagnostic('behavior.decision_history.frame_resolved', {
995
- behavior_id: current.behaviorId,
996
- activation_id: current.activationId,
997
- instance_generation: current.instanceGeneration,
998
- epoch_id: frame.epochId,
999
- tick: resolvedDecision.tick,
1000
- status: resolvedDecision.status,
1001
- action_count: resolvedDecision.actions?.length ?? 0,
1002
- action_kinds: (resolvedDecision.actions ?? []).map((action) => action.action),
1003
- retained_frame_count: history.length,
1004
- pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
1005
- }, 'debug');
1006
- }
1007
- runtime.lastCommittedBackendTick = backendTick;
1008
- let output: Readonly<{
1009
- status?: Readonly<BehaviorStatus>;
1010
- events: readonly RuntimeEventProposal[];
1011
- }>;
1012
- try {
1013
- output = await this.applyDecision(
1014
- current,
1015
- runtime,
1016
- frame,
1017
- decision,
1018
- input,
1019
- context,
1020
- );
1021
- } catch (error) {
1022
- await this.failCurrent(current, errorCode(error, 'BEHAVIOR_DECISION_INVALID'), now);
1023
- return this.output(cursor);
1024
- }
1025
- runtime.lastStatus = output.status ?? runtime.lastStatus;
1026
-
1027
- if (meeting) {
1028
- await this.applyTransitions(this.manager.enterBoundary('meeting_started', now));
1029
- this.boundaryActive = true;
1030
- }
1031
- return this.output(cursor, output.status, output.events);
1032
- }
1033
-
1034
- private async applyDecision(
1035
- activation: Readonly<BehaviorActivationSnapshot>,
1036
- runtime: ActivationRuntime,
1037
- frame: Readonly<BehaviorInput>,
1038
- decision: Readonly<BehaviorDecision>,
1039
- input: RuntimeEpochPluginInput<Record<string, any>>,
1040
- context: RuntimeEpochPluginContext<Record<string, any>>,
1041
- ): Promise<Readonly<{
1042
- status?: Readonly<BehaviorStatus>;
1043
- events: readonly RuntimeEventProposal[];
1044
- }>> {
1045
- if (decision.finish && (decision.actions?.length ?? 0) > 0) {
1046
- throw new Error('behavior_finish_with_actions_invalid');
1047
- }
1048
- if (decision.delegate && (decision.actions?.length ?? 0) > 0) {
1049
- throw new Error('behavior_delegate_with_actions_invalid');
1050
- }
1051
- if (decision.delegate && decision.finish) {
1052
- throw new Error('behavior_delegate_with_finish_invalid');
1053
- }
1054
- if (decision.delegate && activation.layer !== 'long') {
1055
- throw new Error('behavior_delegate_layer_invalid');
1056
- }
1057
- const delegated = decision.delegate === undefined
1058
- ? undefined
1059
- : await this.prepareDelegatedShort(decision.delegate);
1060
- const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
1061
- for (const event of decision.events ?? []) {
1062
- if (!declaredEvents.has(event.type)) throw new Error('behavior_event_output_invalid');
1063
- }
1064
- // A continuation belongs to the first Decision that actually reaches the
1065
- // ordered effect queue. Stale proposals and cadence skips never consume it.
1066
- runtime.pendingContinuation = undefined;
1067
- const state = input.epoch.state;
1068
- const safetyGeneration = isClawclawRuntimeState(state)
1069
- ? state.action_safety_generation
1070
- : undefined;
1071
- for (const [index, rawAction] of (decision.actions ?? []).entries()) {
1072
- if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) break;
1073
- const control = this.controls.get(activation.activationId);
1074
- if (!control?.isAuthorized()) break;
1075
- const action = rawAction as Readonly<GameAction>;
1076
- const dedupeKey = `${activation.instanceGeneration}:${frame.gameState.tick}:${index}:${JSON.stringify(action)}`;
1077
- if (runtime.committedActionDedupeKeys.has(dedupeKey)) continue;
1078
- const request = normalizeClawclawBehaviorAction(
1079
- action,
1080
- frame.epochId,
1081
- safetyGeneration,
1082
- activation.instanceGeneration,
1083
- frame.gameState.tick,
1084
- );
1085
- const receiptStartedAt = performance.now();
1086
- try {
1087
- const result = await context.capabilities.performAction(
1088
- CLAWCLAW_ACTION_CAPABILITY,
1089
- { ...request, behaviorOriginId: activation.behaviorId },
1090
- asActionCaller(control.caller),
1091
- );
1092
- context.diagnostic('behavior.action.receipt', {
1093
- behavior_id: activation.behaviorId,
1094
- activation_id: activation.activationId,
1095
- instance_generation: activation.instanceGeneration,
1096
- epoch_id: frame.epochId,
1097
- tick: frame.gameState.tick,
1098
- action_index: index,
1099
- action_kind: action.action,
1100
- action_id: result.actionId,
1101
- status: result.status,
1102
- ...(result.source ? { action_source: result.source } : {}),
1103
- ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
1104
- receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
1105
- }, result.status === 'failure' ? 'warn' : 'debug');
1106
- if (result.actionOutcome !== 'not_submitted') {
1107
- runtime.committedActionDedupeKeys.set(dedupeKey, frame.epochId);
1108
- while (runtime.committedActionDedupeKeys.size > 2_048) {
1109
- const oldest = runtime.committedActionDedupeKeys.keys().next().value as string | undefined;
1110
- if (oldest === undefined) break;
1111
- runtime.committedActionDedupeKeys.delete(oldest);
1112
- }
1113
- }
1114
- if (result.actionOutcome === 'not_submitted' && !control.isAuthorized()) break;
1115
- } catch (error) {
1116
- context.diagnostic('behavior.action.failed', {
1117
- behavior_id: activation.behaviorId,
1118
- activation_id: activation.activationId,
1119
- instance_generation: activation.instanceGeneration,
1120
- epoch_id: frame.epochId,
1121
- tick: frame.gameState.tick,
1122
- action_index: index,
1123
- action_kind: action.action,
1124
- receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
1125
- error_code: errorCode(error, 'BEHAVIOR_ACTION_FAILED'),
1126
- }, 'error');
1127
- }
1128
- }
1129
- if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) {
1130
- return { events: [] };
1131
- }
1132
- const events = (decision.events ?? []).map((event, index): RuntimeEventProposal => ({
1133
- type: event.type,
1134
- dedupeKey: `${activation.activationId}:${activation.instanceGeneration}:${frame.gameState.tick ?? frame.epochId}:${event.type}:${index}`,
1135
- payload: { ...event.payload },
1136
- ...(event.occurredAt === undefined ? {} : { occurredAt: event.occurredAt }),
1137
- }));
1138
- if (delegated) {
1139
- // Keep the status on the suspended parent. Publishing it as the current
1140
- // semantic status would incorrectly attach it to the newly started child.
1141
- runtime.lastStatus = decision.status ?? runtime.lastStatus;
1142
- await this.startDelegatedShort(activation, delegated, frame.nowMs);
1143
- } else if (decision.finish) {
1144
- await this.finishCurrent(activation, decision.finish, frame.nowMs);
1145
- }
1146
- return {
1147
- ...(decision.status === undefined || delegated ? {} : { status: decision.status }),
1148
- events,
1149
- };
1150
- }
1151
-
1152
- private async prepareDelegatedShort(
1153
- delegation: Readonly<BehaviorDelegation>,
1154
- ): Promise<Readonly<{
1155
- behaviorId: string;
1156
- rawInput: Readonly<Record<string, unknown>>;
1157
- prepared: PreparedClawclawBehavior;
1158
- }>> {
1159
- const rawInput = delegation.input ?? Object.freeze({});
1160
- const prepared = await this.catalog.prepare(delegation.behavior, rawInput);
1161
- return Object.freeze({
1162
- behaviorId: delegation.behavior,
1163
- rawInput: Object.freeze(structuredClone(rawInput)),
1164
- prepared,
1165
- });
1166
- }
1167
-
1168
- private async startDelegatedShort(
1169
- parent: Readonly<BehaviorActivationSnapshot>,
1170
- delegated: Readonly<{
1171
- behaviorId: string;
1172
- rawInput: Readonly<Record<string, unknown>>;
1173
- prepared: PreparedClawclawBehavior;
1174
- }>,
1175
- now: number,
1176
- ): Promise<void> {
1177
- if (!this.manager.isCurrent(parent.activationId, parent.instanceGeneration)) return;
1178
- const activationId = this.createActivationId();
1179
- const maxRuntimeMs = runtimeMs(delegated.prepared, delegated.rawInput)
1180
- ?? DEFAULT_SHORT_MAX_RUNTIME_MS;
1181
- const transitions = this.manager.startShort({
1182
- activationId,
1183
- behaviorId: delegated.behaviorId,
1184
- source: 'behavior',
1185
- input: delegated.prepared.input,
1186
- requestedAt: now,
1187
- maxRuntimeMs,
1188
- deadlineOutcome: deadlineOutcome(delegated.prepared, delegated.rawInput) ?? 'failed',
1189
- }, now);
1190
- this.runtimes.set(activationId, {
1191
- activationId,
1192
- behaviorId: delegated.behaviorId,
1193
- prepared: delegated.prepared,
1194
- decisionHistory: new BehaviorDecisionHistory(),
1195
- committedActionDedupeKeys: new Map(),
1196
- });
1197
- this.delegatedShorts.set(activationId, Object.freeze({
1198
- parentActivationId: parent.activationId,
1199
- }));
1200
- await this.applyTransitions(transitions);
1201
- }
1202
-
1203
- private async finishCurrent(
1204
- activation: Readonly<BehaviorActivationSnapshot>,
1205
- finish: Readonly<BehaviorFinish>,
1206
- now: number,
1207
- ): Promise<void> {
1208
- if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
1209
- if (finish.summary !== undefined) {
1210
- this.finishSummaries.set(activation.activationId, finish.summary);
1211
- }
1212
- await this.applyTransitions(this.manager.finish(
1213
- activation.activationId,
1214
- finish.outcome,
1215
- finish.reason,
1216
- now,
1217
- ));
1218
- }
1219
-
1220
- private async failCurrent(
1221
- activation: Readonly<BehaviorActivationSnapshot>,
1222
- reason: string,
1223
- now: number,
1224
- ): Promise<void> {
1225
- if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
1226
- await this.applyTransitions(this.manager.finish(activation.activationId, 'failed', reason, now));
1227
- }
1228
-
1229
- private async applyTransitions(
1230
- transitions: readonly BehaviorActivationTransition[],
1231
- ): Promise<void> {
1232
- this.captureDelegationResults(transitions);
1233
- for (const transition of transitions) {
1234
- const event = lifecycleEvent(transition);
1235
- if (event) this.pendingLifecycleEvents.push(event);
1236
- }
1237
- const failures: BehaviorActivationTransition[] = [];
1238
- // Reserve the incoming controller before releasing the outgoing layer.
1239
- // Equal-layer replacement is held until the old controller is released;
1240
- // a higher layer becomes active immediately, leaving no takeover gap.
1241
- for (const transition of transitions) {
1242
- if (transition.type !== 'started' && transition.type !== 'restarted') continue;
1243
- const snapshot = currentRuntimeSnapshot(this.manager, transition.activationId);
1244
- if (!snapshot) continue;
1245
- try {
1246
- const runtime = await this.ensureRuntime(snapshot);
1247
- if (!this.driver || !this.scope) throw new Error('behavior_control_driver_unavailable');
1248
- const handle = await this.driver.acquire(snapshot, this.scope);
1249
- if (
1250
- handle.caller.activationId !== snapshot.activationId
1251
- || handle.caller.layer !== snapshot.layer
1252
- || handle.caller.activationGeneration !== snapshot.instanceGeneration
1253
- ) throw new Error('behavior_control_handle_invalid');
1254
- this.controls.set(snapshot.activationId, handle);
1255
- runtime.instanceGeneration = snapshot.instanceGeneration;
1256
- } catch (error) {
1257
- this.diagnostic?.('behavior.activation.failed', {
1258
- behavior_id: snapshot.behaviorId,
1259
- activation_id: snapshot.activationId,
1260
- instance_generation: snapshot.instanceGeneration,
1261
- error_code: errorCode(error, 'BEHAVIOR_ACTIVATION_FAILED'),
1262
- }, 'error');
1263
- failures.push(...this.manager.finish(
1264
- snapshot.activationId,
1265
- 'failed',
1266
- errorCode(error, 'behavior_activation_failed'),
1267
- this.now(),
1268
- ));
1269
- }
1270
- }
1271
- for (const transition of transitions) {
1272
- if (
1273
- transition.type === 'suspended'
1274
- || transition.type === 'completed'
1275
- || transition.type === 'failed'
1276
- || transition.type === 'cancelled'
1277
- || transition.type === 'replaced'
1278
- ) {
1279
- this.controls.get(transition.activationId)?.release(`behavior_${transition.type}:${transition.reason}`);
1280
- this.controls.delete(transition.activationId);
1281
- const runtime = this.runtimes.get(transition.activationId);
1282
- await runtime?.runner?.stop('switched');
1283
- if (runtime) {
1284
- runtime.runner = undefined;
1285
- runtime.instanceGeneration = undefined;
1286
- }
1287
- if (transition.type !== 'suspended') this.runtimes.delete(transition.activationId);
1288
- }
1289
- }
1290
- if (failures.length > 0) await this.applyTransitions(failures);
1291
- }
1292
-
1293
- private captureDelegationResults(
1294
- transitions: readonly BehaviorActivationTransition[],
1295
- ): void {
1296
- for (const transition of transitions) {
1297
- if (
1298
- transition.type !== 'completed'
1299
- && transition.type !== 'failed'
1300
- && transition.type !== 'cancelled'
1301
- && transition.type !== 'replaced'
1302
- ) continue;
1303
- const delegated = this.delegatedShorts.get(transition.activationId);
1304
- const summary = this.finishSummaries.get(transition.activationId);
1305
- if (delegated) {
1306
- const parent = currentRuntimeSnapshot(this.manager, delegated.parentActivationId);
1307
- const parentRuntime = this.runtimes.get(delegated.parentActivationId);
1308
- if (parent?.layer === 'long' && parentRuntime) {
1309
- parentRuntime.pendingContinuation = Object.freeze({
1310
- delegatedBehavior: Object.freeze({
1311
- activationId: transition.activationId,
1312
- behavior: transition.behaviorId,
1313
- outcome: transition.type,
1314
- reason: transition.reason,
1315
- ...(summary === undefined ? {} : { summary }),
1316
- }),
1317
- });
1318
- }
1319
- this.delegatedShorts.delete(transition.activationId);
1320
- }
1321
- this.finishSummaries.delete(transition.activationId);
1322
- if (transition.layer === 'long') {
1323
- for (const [childActivationId, relation] of this.delegatedShorts) {
1324
- if (relation.parentActivationId === transition.activationId) {
1325
- this.delegatedShorts.delete(childActivationId);
1326
- }
1327
- }
1328
- }
1329
- }
1330
- }
1331
-
1332
- private async ensureRuntime(
1333
- activation: Readonly<BehaviorActivationSnapshot>,
1334
- ): Promise<ActivationRuntime> {
1335
- let runtime = this.runtimes.get(activation.activationId);
1336
- if (!runtime) {
1337
- let prepared: PreparedClawclawBehavior;
1338
- if (
1339
- activation.source === 'idle'
1340
- && this.fallbackPrepared?.manifest.id === activation.behaviorId
1341
- ) {
1342
- prepared = this.fallbackPreparedUsed
1343
- ? Object.freeze({
1344
- ...this.fallbackPrepared,
1345
- ...(this.fallbackPrepared.createModule
1346
- ? { module: this.fallbackPrepared.createModule() }
1347
- : {}),
1348
- })
1349
- : this.fallbackPrepared;
1350
- this.fallbackPreparedUsed = true;
1351
- } else {
1352
- prepared = await this.catalog.prepare(activation.behaviorId, activation.input);
1353
- }
1354
- runtime = {
1355
- activationId: activation.activationId,
1356
- behaviorId: activation.behaviorId,
1357
- prepared,
1358
- decisionHistory: new BehaviorDecisionHistory(),
1359
- committedActionDedupeKeys: new Map(),
1360
- };
1361
- this.runtimes.set(activation.activationId, runtime);
1362
- }
1363
- await runtime.runner?.stop('switched');
1364
- const prepared = runtime.instanceGeneration === undefined && activation.instanceGeneration === 1
1365
- ? runtime.prepared
1366
- : Object.freeze({
1367
- ...runtime.prepared,
1368
- ...(runtime.prepared.createModule
1369
- ? { module: runtime.prepared.createModule() }
1370
- : {}),
1371
- });
1372
- runtime.runner = new ClawclawBehaviorRunner({
1373
- snapshotStore: runtime.snapshotStore ??= new BehaviorSnapshotStore(),
1374
- behaviorId: activation.behaviorId,
1375
- activationId: activation.activationId,
1376
- instanceGeneration: activation.instanceGeneration,
1377
- prepared,
1378
- diagnostic: this.diagnostic,
1379
- diagnosticsEnabled: this.diagnosticsEnabled,
1380
- isActive: () => this.manager.isCurrent(
1381
- activation.activationId,
1382
- activation.instanceGeneration,
1383
- ),
1384
- });
1385
- runtime.instanceGeneration = activation.instanceGeneration;
1386
- await runtime.runner.prepare();
1387
- runtime.lastCommittedBackendTick = undefined;
1388
- runtime.lastStatus = undefined;
1389
- runtime.committedActionDedupeKeys.clear();
1390
- return runtime;
1391
- }
1392
-
1393
- private async syncRoleFallback(
1394
- role: string | undefined,
1395
- now: number,
1396
- ): Promise<void> {
1397
- if (this.manualFallbackOverride) return;
1398
- if (typeof role !== 'string' || !role) return;
1399
- const configured = this.fallbackBehaviors.get(role);
1400
- const key = `${this.fallbackConfigGeneration}:${role}:${configured?.behaviorId ?? ''}`;
1401
- if (this.appliedFallbackKey === key) return;
1402
- this.appliedFallbackKey = key;
1403
- if (!configured) {
1404
- this.fallbackPrepared = undefined;
1405
- this.fallbackPreparedUsed = false;
1406
- await this.applyTransitions(this.manager.bindFallback(undefined, now));
1407
- return;
1408
- }
1409
- try {
1410
- const prepared = await this.catalog.prepare(configured.behaviorId, configured.input ?? {});
1411
- this.fallbackPrepared = prepared;
1412
- this.fallbackPreparedUsed = false;
1413
- await this.applyTransitions(this.manager.bindFallback({
1414
- behaviorId: configured.behaviorId,
1415
- input: prepared.input,
1416
- }, now, true));
1417
- } catch (error) {
1418
- this.fallbackPrepared = undefined;
1419
- this.fallbackPreparedUsed = false;
1420
- await this.applyTransitions(this.manager.bindFallback(undefined, now));
1421
- this.diagnostic?.('behavior.fallback.invalid', {
1422
- role,
1423
- behavior_id: configured.behaviorId,
1424
- error_code: errorCode(error, 'BEHAVIOR_FALLBACK_INVALID'),
1425
- }, 'warn');
1426
- }
1427
- }
1428
-
1429
- /**
1430
- * The backend still calls this display-only field a Strategy. Report the
1431
- * current activation, including short/reflex overrides. A configured fallback
1432
- * or suspended long is not active until the manager gives it control.
1433
- */
1434
- private backendStrategyDescriptor(): ClawclawResolvedResourceMetadata | undefined {
1435
- const current = this.manager.current();
1436
- if (!current) return {
1437
- // The backend requires non-empty display text and has no clear action.
1438
- id: 'clawclaw:no-active-behavior',
1439
- name: '无策略在运行',
1440
- description: '当前没有活跃的策略。',
146
+ reportSucceeded: isSuccessfulBackendStrategyReport,
1441
147
  };
1442
- const prepared = this.runtimes.get(current.activationId)?.prepared;
1443
- if (!prepared || prepared.manifest.id !== current.behaviorId) return undefined;
1444
- return resolveClawclawResourceMetadata({
1445
- id: prepared.manifest.id,
1446
- name: prepared.manifest.name,
1447
- description: prepared.manifest.description,
1448
- display: prepared.display,
1449
- ...(prepared.manifest.localizations === undefined
1450
- ? {}
1451
- : { localizations: prepared.manifest.localizations }),
1452
- }, BACKEND_STRATEGY_REPORT_LOCALE);
1453
- }
1454
-
1455
- private refreshBackendStrategyReport(
1456
- input: RuntimeEpochPluginInput<Record<string, any>>,
1457
- context: RuntimeEpochPluginContext<Record<string, any>>,
1458
- ): void {
1459
- const wasEligible = this.backendStrategyReportEligible;
1460
- const state = input.epoch.state;
1461
- this.backendStrategyReportContext = context;
1462
- this.backendStrategyReportEligible = isClawclawRuntimeState(state)
1463
- && state.connection === 'connected'
1464
- && state.stage === 'game'
1465
- && state.game_snapshot.status === 'fresh'
1466
- && state.game_snapshot.state.phase === 'wandering'
1467
- && state.game_snapshot.state.you?.is_alive === true;
1468
-
1469
- const descriptor = this.backendStrategyDescriptor();
1470
- const nextTarget = descriptor
1471
- ? {
1472
- ...descriptor,
1473
- fingerprint: JSON.stringify([descriptor.id, descriptor.name, descriptor.description]),
1474
- }
1475
- : undefined;
1476
- const targetChanged = nextTarget?.fingerprint !== this.backendStrategyReportTarget?.fingerprint;
1477
- if (targetChanged) {
1478
- this.backendStrategyReportTarget = nextTarget;
1479
- // A prior target may still be in flight at the backend. Reconfirm even
1480
- // when the selection later returns to an older fingerprint.
1481
- this.backendStrategyReportAcknowledgedFingerprint = undefined;
1482
- this.clearBackendStrategyReportTimer();
1483
- }
1484
-
1485
- const target = this.backendStrategyReportTarget;
1486
- if (!this.backendStrategyReportEligible || !target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
1487
- this.clearBackendStrategyReportTimer();
1488
- return;
1489
- }
1490
- if (targetChanged || (!wasEligible && this.backendStrategyReportEligible)) {
1491
- this.scheduleBackendStrategyReport(0, true);
1492
- }
1493
- }
1494
-
1495
- private clearBackendStrategyReportTimer(): void {
1496
- if (!this.backendStrategyReportTimer) return;
1497
- clearTimeout(this.backendStrategyReportTimer);
1498
- this.backendStrategyReportTimer = undefined;
1499
- }
1500
-
1501
- private scheduleBackendStrategyReport(delayMs: number, replace = false): void {
1502
- const target = this.backendStrategyReportTarget;
1503
- if (
1504
- !target
1505
- || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
1506
- || this.backendStrategyReportInFlight
1507
- ) return;
1508
- if (this.backendStrategyReportTimer) {
1509
- if (!replace) return;
1510
- this.clearBackendStrategyReportTimer();
1511
- }
1512
- const lifecycleGeneration = this.backendStrategyReportLifecycleGeneration;
1513
- this.backendStrategyReportTimer = setTimeout(() => {
1514
- this.backendStrategyReportTimer = undefined;
1515
- if (lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration) return;
1516
- this.startBackendStrategyReportAttempt();
1517
- }, delayMs);
1518
- this.backendStrategyReportTimer.unref?.();
1519
- }
1520
-
1521
- private startBackendStrategyReportAttempt(): void {
1522
- const target = this.backendStrategyReportTarget;
1523
- const context = this.backendStrategyReportContext;
1524
- if (
1525
- !target
1526
- || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
1527
- || this.backendStrategyReportInFlight
1528
- ) return;
1529
- if (!this.backendStrategyReportEligible || !context || context.signal.aborted) {
1530
- return;
1531
- }
1532
-
1533
- const attempt: BackendStrategyReportAttempt = {
1534
- lifecycleGeneration: this.backendStrategyReportLifecycleGeneration,
1535
- fingerprint: target.fingerprint,
1536
- };
1537
- this.backendStrategyReportInFlight = attempt;
1538
- context.diagnostic('strategy.report.started', {
1539
- strategy_id: target.id,
1540
- }, 'debug');
1541
-
1542
- let pending: Promise<unknown>;
1543
- try {
1544
- pending = context.capabilities.performAction(
1545
- CLAWCLAW_ACTION_CAPABILITY,
1546
- {
1547
- route: 'game',
1548
- action: {
1549
- action: 'strategy',
1550
- name: target.name,
1551
- description: target.description,
1552
- },
1553
- },
1554
- );
1555
- } catch (error) {
1556
- this.finishBackendStrategyReportAttempt(attempt, false, error);
1557
- return;
1558
- }
1559
- void pending.then(
1560
- result => this.finishBackendStrategyReportAttempt(
1561
- attempt,
1562
- isSuccessfulBackendStrategyReport(result),
1563
- result,
1564
- ),
1565
- error => this.finishBackendStrategyReportAttempt(attempt, false, error),
1566
- );
1567
- }
1568
-
1569
- private finishBackendStrategyReportAttempt(
1570
- attempt: BackendStrategyReportAttempt,
1571
- successful: boolean,
1572
- result: unknown,
1573
- ): void {
1574
- if (
1575
- attempt.lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration
1576
- || this.backendStrategyReportInFlight?.fingerprint !== attempt.fingerprint
1577
- ) return;
1578
- this.backendStrategyReportInFlight = undefined;
1579
- const target = this.backendStrategyReportTarget;
1580
- if (successful && target?.fingerprint === attempt.fingerprint) {
1581
- this.backendStrategyReportAcknowledgedFingerprint = attempt.fingerprint;
1582
- this.clearBackendStrategyReportTimer();
1583
- this.backendStrategyReportContext?.diagnostic('strategy.report.completed', {
1584
- strategy_id: target.id,
1585
- }, 'info');
1586
- return;
1587
- }
1588
-
1589
- if (target?.fingerprint === attempt.fingerprint) {
1590
- if (!this.backendStrategyReportEligible) {
1591
- this.clearBackendStrategyReportTimer();
1592
- return;
1593
- }
1594
- this.backendStrategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
1595
- strategy_id: target.id,
1596
- retry_ms: BACKEND_STRATEGY_REPORT_RETRY_MS,
1597
- error_code: errorCode(result, 'STRATEGY_REPORT_RESPONSE_INVALID'),
1598
- }, 'warn');
1599
- this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
1600
- return;
1601
- }
1602
- if (
1603
- target
1604
- && this.backendStrategyReportAcknowledgedFingerprint !== target.fingerprint
1605
- ) this.scheduleBackendStrategyReport(0);
1606
- }
1607
-
1608
- private resetBackendStrategyReporting(): void {
1609
- this.backendStrategyReportLifecycleGeneration += 1;
1610
- this.clearBackendStrategyReportTimer();
1611
- this.backendStrategyReportTarget = undefined;
1612
- this.backendStrategyReportAcknowledgedFingerprint = undefined;
1613
- this.backendStrategyReportInFlight = undefined;
1614
- this.backendStrategyReportContext = undefined;
1615
- this.backendStrategyReportEligible = false;
1616
- }
1617
-
1618
- private output(
1619
- consumeEventsThroughCommitSeq?: number,
1620
- semanticStatus?: Readonly<BehaviorStatus>,
1621
- decisionEvents: readonly RuntimeEventProposal[] = [],
1622
- ): RuntimeEpochPluginResult {
1623
- const lifecycle = this.pendingLifecycleEvents.splice(0);
1624
- const trailingLifecycle = lifecycle.filter(event => (
1625
- event.type === 'behavior.completed'
1626
- || event.type === 'behavior.failed'
1627
- || event.type === 'behavior.cancelled'
1628
- ));
1629
- const leadingLifecycle = lifecycle.filter(event => !trailingLifecycle.includes(event));
1630
- const events = [...leadingLifecycle, ...decisionEvents, ...trailingLifecycle];
1631
- const status = this.status();
1632
- if (!status.running && events.length === 0 && semanticStatus === undefined) {
1633
- return {
1634
- outcome: 'noop',
1635
- reason: 'behavior_inactive',
1636
- ...(consumeEventsThroughCommitSeq === undefined
1637
- ? {}
1638
- : { consumeEventsThroughCommitSeq }),
1639
- };
148
+ }
149
+ /** Game policy and SDK adapter; activation/control/decision execution belongs to the shared runtime. */
150
+ export class ClawclawBehaviorPlugin extends StrategyHost {
151
+ constructor(options: ClawclawBehaviorPluginOptions) {
152
+ super({ ...options, id: CLAWCLAW_BEHAVIOR_PLUGIN_ID, stateTopic: CLAWCLAW_BEHAVIOR_STATE_TOPIC,
153
+ actionCapability: CLAWCLAW_ACTION_CAPABILITY, adapter: createAdapter(), captureActions: resolveDetailCapture().actions,
154
+ catalog: { has: id => options.catalog.has(id), prepare: async (id, input) => {
155
+ const prepared = await options.catalog.prepare(id, input);
156
+ return { ...prepared, value: prepared };
157
+ } }, after: options.after ?? [CLAWCLAW_ACTION_PLUGIN_ID, CLAWCLAW_GAME_QUERY_PLUGIN_ID, CLAWCLAW_PERCEPTION_PLUGIN_ID, CLAWCLAW_TRIGGER_PLUGIN_ID] });
1640
158
  }
1641
- const current = status.current;
1642
- const retainedStatus = semanticStatus
1643
- ?? (current === undefined ? undefined : this.runtimes.get(current.activationId)?.lastStatus);
1644
- const stateValue = {
1645
- running: status.running,
1646
- ...(current === undefined ? {} : {
1647
- activation_id: current.activationId,
1648
- behavior: current.behaviorId,
1649
- layer: current.layer,
1650
- source: current.source,
1651
- instance_generation: current.instanceGeneration,
1652
- }),
1653
- ...(retainedStatus === undefined ? {} : { status: retainedStatus }),
1654
- stack: status.stack,
1655
- };
1656
- return {
1657
- outcome: 'processed',
1658
- states: [{ topic: CLAWCLAW_BEHAVIOR_STATE_TOPIC, value: stateValue }],
1659
- ...(events.length === 0 ? {} : { events }),
1660
- ...(consumeEventsThroughCommitSeq === undefined
1661
- ? {}
1662
- : { consumeEventsThroughCommitSeq }),
1663
- };
1664
- }
1665
-
1666
- private withDecisionTimeout<T>(
1667
- operation: (signal: AbortSignal) => Promise<T>,
1668
- signal: AbortSignal,
1669
- activationId?: string,
1670
- ): Promise<T> {
1671
- if (signal.aborted) return Promise.reject(signal.reason);
1672
- return new Promise<T>((resolve, reject) => {
1673
- const controller = new AbortController();
1674
- let settled = false;
1675
- let timer: ReturnType<typeof setTimeout>;
1676
- const onAbort = (): void => {
1677
- const reason = signal.reason instanceof Error
1678
- ? signal.reason
1679
- : new Error('behavior_epoch_aborted');
1680
- controller.abort(reason);
1681
- complete(() => reject(reason));
1682
- };
1683
- const onInternalAbort = (): void => {
1684
- const reason = controller.signal.reason instanceof Error
1685
- ? controller.signal.reason
1686
- : new Error('behavior_decision_aborted');
1687
- complete(() => reject(reason));
1688
- };
1689
- const cleanup = (): void => {
1690
- clearTimeout(timer);
1691
- signal.removeEventListener('abort', onAbort);
1692
- controller.signal.removeEventListener('abort', onInternalAbort);
1693
- if (activationId) {
1694
- const controllers = this.decisionControllers.get(activationId);
1695
- controllers?.delete(controller);
1696
- if (controllers?.size === 0) this.decisionControllers.delete(activationId);
1697
- }
1698
- };
1699
- const complete = (callback: () => void): void => {
1700
- if (settled) return;
1701
- settled = true;
1702
- cleanup();
1703
- callback();
1704
- };
1705
- timer = setTimeout(() => {
1706
- const timeout = new Error('behavior_decision_timeout');
1707
- controller.abort(timeout);
1708
- complete(() => reject(timeout));
1709
- }, this.decisionTimeoutMs);
1710
- timer.unref?.();
1711
- controller.signal.addEventListener('abort', onInternalAbort, { once: true });
1712
- if (activationId) {
1713
- let controllers = this.decisionControllers.get(activationId);
1714
- if (!controllers) {
1715
- controllers = new Set();
1716
- this.decisionControllers.set(activationId, controllers);
1717
- }
1718
- controllers.add(controller);
1719
- }
1720
- signal.addEventListener('abort', onAbort, { once: true });
1721
- void operation(controller.signal).then(
1722
- value => complete(() => resolve(value)),
1723
- error => complete(() => reject(error)),
1724
- ).catch(() => {});
1725
- });
1726
- }
1727
-
1728
- private interruptDecisions(activationId: string, reason: string): void {
1729
- const controllers = this.decisionControllers.get(activationId);
1730
- if (!controllers) return;
1731
- const error = new Error(reason);
1732
- for (const controller of controllers) controller.abort(error);
1733
- }
1734
-
1735
- private enqueueControl<T>(operation: () => Promise<T>): Promise<T> {
1736
- const pending = this.controlTail.then(operation, operation);
1737
- this.controlTail = pending.then(() => undefined, () => undefined);
1738
- return pending;
1739
- }
1740
159
  }