@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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