@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,974 +1,15 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { realpathSync } from 'node:fs';
3
- import { fileURLToPath } from 'node:url';
4
- import { performance } from 'node:perf_hooks';
5
- import { Worker } from 'node:worker_threads';
6
- import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
7
- import type {
8
- BehaviorDecision,
9
- BehaviorInput,
10
- BehaviorTiming,
11
- ClawclawBehaviorManifest,
12
- } from '../../../../sdk/behavior-plugin/index.js';
13
- import {
14
- behaviorSourceUrl,
15
- behaviorThreadLoaderConfig,
16
- pinBehaviorSource,
17
- resolveBehaviorSource,
18
- } from './behavior-module-loader.js';
19
- import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
1
+ import { ThreadStrategyExecutor, prepareStrategyInWorker, type ThreadStrategyExecutorOptions, type StrategyThreadPreparation } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
2
+ import type { BehaviorInput, BehaviorDecision, ClawclawBehaviorManifest } from '../../../../sdk/behavior-plugin/index.js';
20
3
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
21
- import { BehaviorSnapshotStore, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
22
- import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
23
- import { serveStrategyMemoryRequest, unavailableStrategyMemory, type StrategyMemoryRequest } from '../../strategy-memory-rpc.js';
24
-
25
- export const PARALLEL_BEHAVIOR_THREAD_POOL_SIZE = 10;
26
- const INITIAL_WORKER_COUNT = 2;
27
- const MAX_POOL_SIZE = 10;
28
- const IDLE_SCALE_DOWN_MS = 30_000;
29
- const START_TIMEOUT_MS = 20_000;
30
- const MAX_WORKER_ERROR_MESSAGE_LENGTH = 512;
31
- const REPLACEMENT_RETRY_BASE_MS = 50;
32
- const REPLACEMENT_RETRY_MAX_MS = 5_000;
33
- const WORKER_BOOTSTRAP = realpathSync(fileURLToPath(
34
- new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url),
35
- ));
36
- const WORKER_HOST_URL = new URL('./behavior-analysis-thread-host.ts', import.meta.url).href;
37
-
38
- export interface ThreadBehaviorExecutorOptions {
39
- readonly memory?: (frame: Readonly<BehaviorInput>, isActive: () => boolean) => StrategyMemory;
40
- readonly fixedWorkers?: boolean;
41
- readonly snapshotStore?: BehaviorSnapshotStore;
42
- readonly source: ResolvedClawclawBehaviorSource;
43
- /** Maximum Worker count and in-flight request window. Tests may reduce it. */
44
- readonly poolSize?: number;
45
- /** How long an expanded, idle pool is retained before returning to two Workers. */
46
- readonly idleWorkerTimeoutMs?: number;
47
- readonly maxOldGenerationSizeMb?: number;
48
- /** Samples Worker heaps only for explicit full diagnostics. */
49
- readonly diagnosticsEnabled?: boolean;
50
- readonly diagnostic?: (
51
- name: string,
52
- attributes?: Readonly<Record<string, unknown>>,
53
- severity?: RuntimeDiagnosticSeverity,
54
- ) => void;
55
- }
56
-
57
- export interface ThreadBehaviorExecutorSnapshot {
58
- readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped';
59
- readonly workerCount: number;
60
- readonly idleWorkerCount: number;
61
- readonly busyWorkerCount: number;
62
- readonly queuedRequestCount: number;
63
- readonly inFlightRequestCount: number;
64
- readonly startedWorkerCount: number;
65
- readonly retiredWorkerCount: number;
66
- readonly workerHeapUsedBytes: number;
67
- readonly peakWorkerHeapUsedBytes: number;
68
- }
69
-
70
- interface PendingRequest {
71
- snapshotEpoch?: number;
72
- snapshotGeneration?: number;
73
- readonly requestId: string;
74
- readonly operation: 'decide';
75
- readonly frame: BehaviorInput;
76
- readonly observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>;
77
- readonly signal: AbortSignal;
78
- readonly enqueuedAt: number;
79
- readonly resolve: (value: unknown) => void;
80
- readonly reject: (error: Error) => void;
81
- readonly onAbort: () => void;
82
- settled: boolean;
83
- assignedAt?: number;
84
- slot?: WorkerSlot;
85
- }
86
-
87
- interface WorkerSlot {
88
- readonly id: number;
89
- readonly worker: Worker;
90
- state: 'starting' | 'idle' | 'busy' | 'retiring';
91
- idleSince?: number;
92
- current?: PendingRequest;
93
- readyResolve?: () => void;
94
- readyReject?: (error: Error) => void;
95
- heapUsedBytes?: number;
96
- retirement?: Promise<void>;
97
- }
98
-
99
- interface WorkerMessageBase {
100
- readonly type: string;
101
- readonly poolId: string;
102
- readonly slotId: number;
103
- readonly requestId?: string;
104
- }
105
-
106
- interface WorkerReadyMessage extends WorkerMessageBase {
107
- readonly type: 'ready';
108
- readonly behaviorId: string;
109
- readonly execution: ResolvedClawclawBehaviorSource['execution'];
110
- readonly manifest?: Readonly<ClawclawBehaviorManifest>;
111
- readonly input?: Readonly<Record<string, unknown>>;
112
- readonly timing?: Readonly<BehaviorTiming>;
113
- readonly heapUsedBytes?: number;
114
- }
115
-
116
- interface WorkerResultMessage extends WorkerMessageBase {
117
- readonly instanceSnapshot?: BehaviorInstanceSnapshot;
118
- readonly type: 'result';
119
- readonly requestId: string;
120
- readonly result: BehaviorDecision;
121
- readonly queryCount: number;
122
- readonly durationMs: number;
123
- readonly heapUsedBytes?: number;
124
- }
125
-
126
- interface WorkerErrorMessage extends WorkerMessageBase {
127
- readonly type: 'error';
128
- readonly code: string;
129
- readonly message?: string;
130
- readonly heapUsedBytes?: number;
131
- }
132
-
133
- function asError(value: unknown, fallback: string): Error {
134
- return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback);
135
- }
136
-
137
- function abortError(signal: AbortSignal): Error {
138
- return asError(signal.reason, 'behavior_thread_request_aborted');
139
- }
140
-
141
- function errorCode(error: unknown, fallback: string): string {
142
- const code = error && typeof error === 'object' && typeof (error as any).code === 'string'
143
- ? (error as any).code.trim()
144
- : '';
145
- if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)) return code;
146
- const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
147
- return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
148
- }
149
-
150
- function roundedElapsed(startedAt: number): number {
151
- return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
152
- }
153
-
154
- export interface BehaviorThreadPreparation {
155
- readonly manifest: Readonly<ClawclawBehaviorManifest>;
156
- readonly input: Readonly<Record<string, unknown>>;
157
- readonly timing?: Readonly<BehaviorTiming>;
158
- readonly source: ResolvedClawclawBehaviorSource;
159
- }
160
-
161
- /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
162
- export async function prepareBehaviorInWorker(
163
- source: ResolvedClawclawBehaviorSource,
164
- input: Readonly<Record<string, unknown>>,
165
- options: Readonly<{
166
- maxOldGenerationSizeMb?: number;
167
- diagnosticsEnabled?: boolean;
168
- }> = {},
169
- ): Promise<BehaviorThreadPreparation> {
170
- const pinned = pinBehaviorSource(source);
171
- const sourceUrl = behaviorSourceUrl(pinned);
172
- const loader = behaviorThreadLoaderConfig();
173
- const poolId = randomUUID();
174
- const worker = new Worker(WORKER_BOOTSTRAP, {
175
- execArgv: [],
176
- resourceLimits: {
177
- maxOldGenerationSizeMb: Math.max(16, Math.min(
178
- 256,
179
- Math.floor(options.maxOldGenerationSizeMb ?? 64),
180
- )),
181
- },
182
- stdout: true,
183
- stderr: true,
184
- workerData: {
185
- runtimeModuleBootstrap: {
186
- hostUrl: WORKER_HOST_URL,
187
- hooksUrl: loader.hooksUrl,
188
- sdkAliases: loader.sdkAliases,
189
- esmModuleRoots: [new URL('.', sourceUrl).href],
190
- },
191
- poolId,
192
- slotId: 0,
193
- source: pinned,
194
- sourceUrl,
195
- prepareInput: structuredClone(input),
196
- diagnosticsEnabled: options.diagnosticsEnabled === true,
197
- },
198
- });
199
- try {
200
- return await new Promise<BehaviorThreadPreparation>((resolve, reject) => {
201
- let settled = false;
202
- const finish = (callback: () => void): void => {
203
- if (settled) return;
204
- settled = true;
205
- clearTimeout(timer);
206
- callback();
207
- };
208
- const timer = setTimeout(() => finish(() => reject(
209
- new Error('behavior_thread_prepare_timeout'),
210
- )), START_TIMEOUT_MS);
211
- timer.unref?.();
212
- worker.on('message', (value: unknown) => {
213
- if (!value || typeof value !== 'object' || Array.isArray(value)) return;
214
- const message = value as WorkerReadyMessage | WorkerErrorMessage;
215
- if (message.poolId !== poolId || message.slotId !== 0) return;
216
- if (message.type === 'error') {
217
- const detail = message.message?.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH);
218
- finish(() => reject(new Error(detail ? `${message.code}: ${detail}` : message.code)));
219
- return;
220
- }
221
- if (
222
- message.type !== 'ready'
223
- || message.behaviorId !== pinned.id
224
- || message.execution !== pinned.execution
225
- || !message.manifest
226
- || !message.input
227
- ) {
228
- finish(() => reject(new Error('behavior_thread_prepare_invalid')));
229
- return;
230
- }
231
- finish(() => resolve({
232
- manifest: structuredClone(message.manifest!),
233
- input: structuredClone(message.input!),
234
- ...(message.timing === undefined ? {} : { timing: structuredClone(message.timing) }),
235
- source: pinned,
236
- }));
237
- });
238
- worker.once('error', (error) => finish(() => reject(error)));
239
- worker.once('exit', (code) => {
240
- if (code !== 0) finish(() => reject(new Error(`behavior_thread_worker_exited:${code}`)));
241
- });
242
- });
243
- } finally {
244
- await worker.terminate().catch(() => -1);
245
- }
246
- }
247
-
248
- /** Adaptive Worker Thread pool for cross-tick computations. */
249
- export class ThreadBehaviorExecutor {
250
- private readonly snapshotStore: BehaviorSnapshotStore;
251
- readonly runtimeInstanceId = randomUUID();
252
-
253
- private readonly maxWorkerCount: number;
254
- private readonly maxPendingRequestCount: number;
255
- private readonly minWorkerCount: number;
256
- private readonly idleWorkerTimeoutMs: number;
257
- private readonly maxOldGenerationSizeMb: number;
258
- private state: ThreadBehaviorExecutorSnapshot['state'] = 'new';
259
- private readonly slots = new Set<WorkerSlot>();
260
- private readonly queue: PendingRequest[] = [];
261
- private readonly inFlight = new Set<PendingRequest>();
262
- private readonly spawnTasks = new Set<Promise<void>>();
263
- private startTask?: Promise<void>;
264
- private stopTask?: Promise<void>;
265
- private replacementTask?: Promise<void>;
266
- private replacementRetryTimer?: ReturnType<typeof setTimeout>;
267
- private idleScaleDownTimer?: ReturnType<typeof setTimeout>;
268
- private replacementFailureCount = 0;
269
- private nextSlotId = 1;
270
- private startedWorkerCount = 0;
271
- private retiredWorkerCount = 0;
272
- private peakWorkerHeapUsedBytes = 0;
273
- private desiredWorkerCount: number;
274
-
275
- private readonly options: ThreadBehaviorExecutorOptions;
276
-
277
- constructor(options: ThreadBehaviorExecutorOptions) {
278
- this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
279
- this.options = Object.freeze({
280
- ...options,
281
- source: pinBehaviorSource(options.source),
282
- });
283
- const execution = options.source.execution ?? 'parallel';
284
- const maxWorkerCount = execution === 'serial'
285
- ? 1
286
- : options.poolSize ?? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE;
287
- if (!Number.isInteger(maxWorkerCount) || maxWorkerCount <= 0 || maxWorkerCount > MAX_POOL_SIZE) {
288
- throw new TypeError(`poolSize must be between 1 and ${MAX_POOL_SIZE}.`);
289
- }
290
- const idleWorkerTimeoutMs = options.idleWorkerTimeoutMs ?? IDLE_SCALE_DOWN_MS;
291
- if (!Number.isFinite(idleWorkerTimeoutMs) || idleWorkerTimeoutMs < 0) {
292
- throw new TypeError('idleWorkerTimeoutMs must be a non-negative finite number.');
293
- }
294
- this.maxWorkerCount = maxWorkerCount;
295
- this.maxPendingRequestCount = execution === 'serial'
296
- ? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE
297
- : maxWorkerCount;
298
- this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
299
- this.desiredWorkerCount = this.minWorkerCount;
300
- this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
301
- this.maxOldGenerationSizeMb = Math.max(16, Math.min(
302
- 256,
303
- Math.floor(options.maxOldGenerationSizeMb ?? 64),
304
- ));
305
- }
306
-
307
- get isAlive(): boolean {
308
- // A temporarily degraded pool remains the same live executor while it
309
- // restores a retired slot. Capacity is reported separately by snapshot().
310
- return this.state === 'running';
311
- }
312
-
313
- start(signal: AbortSignal): Promise<void> {
314
- if (this.state === 'running') return Promise.resolve();
315
- if (this.state === 'starting') return this.awaitStart(signal);
316
- if (this.state === 'stopping' || this.state === 'stopped') {
317
- return Promise.reject(new Error('behavior_thread_pool_stopped'));
318
- }
319
- if (signal.aborted) return Promise.reject(abortError(signal));
320
- this.state = 'starting';
321
- const startedAt = performance.now();
322
- this.startTask = Promise.all(
323
- Array.from({ length: this.minWorkerCount }, () => this.spawnSlot('initial')),
324
- ).then(() => {
325
- if (this.state !== 'starting') throw new Error('behavior_thread_pool_stopped');
326
- this.state = 'running';
327
- this.diagnostic('behavior.thread_pool.started', {
328
- behavior_id: this.options.source.id,
329
- execution: this.options.source.execution,
330
- runtime_instance_id: this.runtimeInstanceId,
331
- worker_count: this.slots.size,
332
- min_worker_count: this.minWorkerCount,
333
- max_worker_count: this.maxWorkerCount,
334
- worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
335
- started_worker_count: this.startedWorkerCount,
336
- retired_worker_count: this.retiredWorkerCount,
337
- ...(this.options.diagnosticsEnabled === true ? {
338
- worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
339
- peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
340
- } : {}),
341
- duration_ms: roundedElapsed(startedAt),
342
- }, 'info');
343
- }).catch(async (error) => {
344
- if (this.state === 'starting') this.state = 'stopped';
345
- await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'start_failed')));
346
- throw error;
347
- });
348
- return this.awaitStart(signal).catch(async (error) => {
349
- if (signal.aborted) await this.stop('switched');
350
- throw error;
351
- });
352
- }
353
-
354
- update(
355
- frame: BehaviorInput,
356
- signal: AbortSignal,
357
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
358
- ): Promise<BehaviorDecision> {
359
- return this.submit('decide', frame, signal, observationSnapshot) as Promise<BehaviorDecision>;
360
- }
361
-
362
- async reset(_signal: AbortSignal): Promise<void> {
363
- this.snapshotStore.reset();
364
- }
365
-
366
- stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
367
- if (this.stopTask) return this.stopTask;
368
- this.stopTask = this.performStop(reason);
369
- return this.stopTask;
370
- }
371
-
372
- private async performStop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
373
- if (this.state === 'stopped') return;
374
- if (this.state === 'new') {
375
- this.state = 'stopped';
376
- return;
377
- }
378
- this.state = 'stopping';
379
- if (this.replacementRetryTimer) {
380
- clearTimeout(this.replacementRetryTimer);
381
- this.replacementRetryTimer = undefined;
382
- }
383
- this.cancelIdleScaleDown();
384
- const error = new Error('behavior_thread_pool_stopped');
385
- for (const request of [...this.inFlight]) this.rejectRequest(request, error);
386
- await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
387
- await Promise.allSettled([...this.spawnTasks]);
388
- await this.startTask?.catch(() => {});
389
- await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
390
- this.state = 'stopped';
391
- this.diagnostic('behavior.thread_pool.stopped', {
392
- behavior_id: this.options.source.id,
393
- runtime_instance_id: this.runtimeInstanceId,
394
- reason,
395
- min_worker_count: this.minWorkerCount,
396
- max_worker_count: this.maxWorkerCount,
397
- started_worker_count: this.startedWorkerCount,
398
- retired_worker_count: this.retiredWorkerCount,
399
- ...(this.options.diagnosticsEnabled === true ? {
400
- worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
401
- peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
402
- } : {}),
403
- }, 'info');
404
- }
405
-
406
- snapshot(): ThreadBehaviorExecutorSnapshot {
407
- const slots = [...this.slots];
408
- return {
409
- state: this.state,
410
- workerCount: slots.length,
411
- idleWorkerCount: slots.filter(({ state }) => state === 'idle').length,
412
- busyWorkerCount: slots.filter(({ state }) => state === 'busy').length,
413
- queuedRequestCount: this.queue.length,
414
- inFlightRequestCount: this.inFlight.size,
415
- startedWorkerCount: this.startedWorkerCount,
416
- retiredWorkerCount: this.retiredWorkerCount,
417
- workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
418
- peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
419
- };
420
- }
421
-
422
- private awaitStart(signal: AbortSignal): Promise<void> {
423
- const task = this.startTask!;
424
- if (signal.aborted) return Promise.reject(abortError(signal));
425
- return new Promise<void>((resolve, reject) => {
426
- const onAbort = (): void => reject(abortError(signal));
427
- signal.addEventListener('abort', onAbort, { once: true });
428
- void task.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
429
- });
430
- }
431
-
432
- private async submit(
433
- operation: 'decide',
434
- frame: BehaviorInput,
435
- signal: AbortSignal,
436
- observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
437
- ): Promise<unknown> {
438
- if (signal.aborted) throw abortError(signal);
439
- await this.awaitStart(signal);
440
- if (this.state !== 'running') throw new Error('behavior_thread_pool_not_running');
441
- if (this.inFlight.size >= this.maxPendingRequestCount) {
442
- throw new Error('behavior_thread_window_full');
443
- }
444
- return new Promise<unknown>((resolve, reject) => {
445
- const request: PendingRequest = {
446
- requestId: randomUUID(),
447
- operation,
448
- // BehaviorInput is already recursively frozen. Keep the Owner snapshot
449
- // until postMessage performs the one unavoidable Worker-boundary clone.
450
- frame,
451
- ...(observationSnapshot === undefined
452
- ? {}
453
- : { observationSnapshot: structuredClone(observationSnapshot) }),
454
- signal,
455
- enqueuedAt: performance.now(),
456
- resolve,
457
- reject,
458
- settled: false,
459
- onAbort: () => this.abortRequest(request),
460
- };
461
- signal.addEventListener('abort', request.onAbort, { once: true });
462
- this.inFlight.add(request);
463
- this.queue.push(request);
464
- this.diagnostic(`behavior.${operation}.started`, {
465
- behavior_id: this.options.source.id,
466
- executor: 'worker_thread',
467
- runtime_instance_id: this.runtimeInstanceId,
468
- request_id: request.requestId,
469
- epoch_id: frame.epochId,
470
- ...(frame.gameState.tick === undefined ? {} : { tick: frame.gameState.tick }),
471
- }, 'debug');
472
- this.pump();
473
- this.growForPressure();
474
- });
475
- }
476
-
477
- private async spawnSlot(reason: 'initial' | 'queue_pressure' | 'replacement'): Promise<void> {
478
- const source = resolveBehaviorSource(this.options.source);
479
- const sourceUrl = behaviorSourceUrl(source);
480
- const slotId = this.nextSlotId++;
481
- const loader = behaviorThreadLoaderConfig();
482
- const worker = new Worker(WORKER_BOOTSTRAP, {
483
- execArgv: [],
484
- resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
485
- stdout: true,
486
- stderr: true,
487
- workerData: {
488
- runtimeModuleBootstrap: {
489
- hostUrl: WORKER_HOST_URL,
490
- hooksUrl: loader.hooksUrl,
491
- sdkAliases: loader.sdkAliases,
492
- esmModuleRoots: [new URL('.', sourceUrl).href],
493
- },
494
- poolId: this.runtimeInstanceId,
495
- slotId,
496
- source,
497
- sourceUrl,
498
- diagnosticsEnabled: this.options.diagnosticsEnabled === true,
499
- },
500
- });
501
- const slot: WorkerSlot = { id: slotId, worker, state: 'starting' };
502
- this.slots.add(slot);
503
- worker.stdout?.on('data', (chunk: Buffer) => this.diagnostic(
504
- 'behavior.thread.stdout',
505
- { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length },
506
- 'debug',
507
- ));
508
- worker.stderr?.on('data', (chunk: Buffer) => this.diagnostic(
509
- 'behavior.thread.stderr',
510
- { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length },
511
- 'debug',
512
- ));
513
- worker.on('message', (message: unknown) => this.handleMessage(slot, message));
514
- worker.once('error', (error) => this.failSlot(slot, error));
515
- worker.once('exit', (code) => {
516
- if (slot.state !== 'retiring') {
517
- this.failSlot(slot, new Error(`behavior_thread_worker_exited:${code}`));
518
- }
519
- });
520
- let timer: ReturnType<typeof setTimeout> | undefined;
521
- try {
522
- await new Promise<void>((resolve, reject) => {
523
- slot.readyResolve = resolve;
524
- slot.readyReject = reject;
525
- timer = setTimeout(() => reject(new Error('behavior_thread_worker_start_timeout')), START_TIMEOUT_MS);
526
- timer.unref?.();
527
- });
528
- if (this.state !== 'starting' && this.state !== 'running') {
529
- throw new Error('behavior_thread_pool_stopped');
530
- }
531
- slot.state = 'idle';
532
- slot.idleSince = performance.now();
533
- this.startedWorkerCount += 1;
534
- this.diagnostic('behavior.thread.started', {
535
- behavior_id: source.id,
536
- runtime_instance_id: this.runtimeInstanceId,
537
- slot_id: slot.id,
538
- worker_count: this.activeWorkerCount(),
539
- min_worker_count: this.minWorkerCount,
540
- max_worker_count: this.maxWorkerCount,
541
- reason,
542
- }, 'info');
543
- } catch (error) {
544
- await this.retireSlot(slot, 'start_failed');
545
- throw error;
546
- } finally {
547
- if (timer) clearTimeout(timer);
548
- slot.readyResolve = undefined;
549
- slot.readyReject = undefined;
550
- }
551
- }
552
-
553
- private pump(): void {
554
- if (this.state !== 'running') return;
555
- while (this.queue.length > 0) {
556
- const slot = [...this.slots].find((candidate) => candidate.state === 'idle');
557
- if (!slot) return;
558
- const request = this.queue.shift()!;
559
- if (request.settled || request.signal.aborted) {
560
- if (!request.settled) this.rejectRequest(request, abortError(request.signal));
561
- continue;
562
- }
563
- slot.state = 'busy';
564
- slot.idleSince = undefined;
565
- slot.current = request;
566
- request.slot = slot;
567
- request.assignedAt = performance.now();
568
- const inherited = this.options.source.stateMode === 'snapshot' ? this.snapshotStore.latest : undefined;
569
- request.snapshotEpoch = inherited?.epochId;
570
- request.snapshotGeneration = this.snapshotStore.generation;
571
- try {
572
- slot.worker.postMessage({
573
- type: 'run',
574
- poolId: this.runtimeInstanceId,
575
- requestId: request.requestId,
576
- operation: request.operation,
577
- frame: request.frame,
578
- ...(inherited ? { instanceSnapshot: inherited.value } : {}),
579
- ...(request.observationSnapshot === undefined
580
- ? {}
581
- : { observationSnapshot: request.observationSnapshot }),
582
- });
583
- } catch (error) {
584
- this.rejectRequest(request, asError(error, 'behavior_thread_submit_failed'));
585
- void this.retireSlot(slot, 'submit_failed');
586
- }
587
- }
588
- }
589
-
590
- private handleMessage(slot: WorkerSlot, value: unknown): void {
591
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
592
- this.failSlot(slot, new Error('behavior_thread_protocol_invalid'));
593
- return;
594
- }
595
- const message = value as WorkerReadyMessage
596
- | WorkerResultMessage
597
- | WorkerErrorMessage
598
- | (StrategyMemoryRequest & WorkerMessageBase & { readonly heapUsedBytes?: number });
599
- if (message.poolId !== this.runtimeInstanceId || message.slotId !== slot.id) {
600
- this.failSlot(slot, new Error('behavior_thread_protocol_identity_mismatch'));
601
- return;
602
- }
603
- if (message.type === 'strategy_memory') {
604
- const request = slot.current;
605
- const isActive = () => this.state === 'running' && !!request && request === slot.current
606
- && message.requestId === request.requestId && !request.settled && !request.signal.aborted;
607
- void serveStrategyMemoryRequest(message, () => request && this.options.memory
608
- ? this.options.memory(request.frame, isActive) : unavailableStrategyMemory, reply => slot.worker.postMessage(reply));
609
- return;
610
- }
611
- if (message.type === 'ready') {
612
- if (
613
- slot.state !== 'starting'
614
- || message.behaviorId !== this.options.source.id
615
- || message.execution !== this.options.source.execution
616
- || (this.options.diagnosticsEnabled === true && (
617
- !Number.isFinite(message.heapUsedBytes)
618
- || Number(message.heapUsedBytes) < 0
619
- ))
620
- ) {
621
- this.failSlot(slot, new Error('behavior_thread_ready_invalid'));
622
- return;
623
- }
624
- if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
625
- slot.readyResolve?.();
626
- return;
627
- }
628
- if (message.type === 'error') {
629
- if (Number.isFinite(message.heapUsedBytes) && Number(message.heapUsedBytes) >= 0) {
630
- this.updateWorkerHeap(slot, Number(message.heapUsedBytes));
631
- }
632
- const code = typeof message.code === 'string'
633
- ? message.code
634
- : 'behavior_thread_worker_failed';
635
- const detail = typeof message.message === 'string'
636
- ? message.message.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH)
637
- : '';
638
- const error = new Error(detail ? `${code}: ${detail}` : code);
639
- if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) {
640
- this.rejectRequest(slot.current, error);
641
- } else {
642
- slot.readyReject?.(error);
643
- }
644
- void this.retireSlot(slot, 'worker_error');
645
- return;
646
- }
647
- const request = slot.current;
648
- if (!request || message.requestId !== request.requestId) {
649
- this.failSlot(slot, new Error('behavior_thread_request_mismatch'));
650
- return;
651
- }
652
- if (message.type !== 'result') {
653
- this.rejectRequest(request, new Error('behavior_thread_response_invalid'));
654
- void this.retireSlot(slot, 'invalid_response');
655
- return;
656
- }
657
- if (this.options.diagnosticsEnabled === true && (
658
- !Number.isFinite(message.heapUsedBytes)
659
- || Number(message.heapUsedBytes) < 0
660
- )) {
661
- this.rejectRequest(request, new Error('behavior_thread_worker_memory_invalid'));
662
- void this.retireSlot(slot, 'invalid_response');
663
- return;
664
- }
665
- if (typeof message.heapUsedBytes === 'number') this.updateWorkerHeap(slot, message.heapUsedBytes);
666
- slot.current = undefined;
667
- slot.state = 'idle';
668
- slot.idleSince = performance.now();
669
- request.slot = undefined;
670
- this.resolveRequest(request, structuredClone(message.result), message);
671
- this.pump();
672
- }
673
-
674
- private resolveRequest(
675
- request: PendingRequest,
676
- value: unknown,
677
- message: WorkerResultMessage,
678
- ): void {
679
- if (request.settled) return;
680
- const published = this.options.source.stateMode === 'snapshot' && message.instanceSnapshot
681
- && !request.signal.aborted && this.state === 'running'
682
- ? this.snapshotStore.publish(request.frame.epochId, message.instanceSnapshot, request.snapshotGeneration!)
683
- : false;
684
- if (this.options.source.stateMode === 'snapshot') this.diagnostic('behavior.snapshot.completed', {
685
- behavior_id: this.options.source.id, epoch_id: request.frame.epochId,
686
- inherited_epoch_id: request.snapshotEpoch ?? null, published,
687
- latest_completed_epoch_id: this.snapshotStore.latest?.epochId ?? null,
688
- }, 'debug');
689
- request.settled = true;
690
- request.signal.removeEventListener('abort', request.onAbort);
691
- this.inFlight.delete(request);
692
- this.diagnostic(`behavior.${request.operation}.completed`, {
693
- behavior_id: this.options.source.id,
694
- executor: 'worker_thread',
695
- runtime_instance_id: this.runtimeInstanceId,
696
- request_id: request.requestId,
697
- epoch_id: request.frame.epochId,
698
- duration_ms: roundedElapsed(request.enqueuedAt),
699
- queue_duration_ms: Math.round(
700
- Math.max(0, (request.assignedAt ?? performance.now()) - request.enqueuedAt) * 1_000,
701
- ) / 1_000,
702
- worker_duration_ms: message.durationMs,
703
- read_query_count: message.queryCount,
704
- ...(this.options.diagnosticsEnabled === true ? {
705
- worker_heap_used_bytes: message.heapUsedBytes,
706
- worker_pool_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
707
- peak_worker_pool_heap_used_bytes: this.peakWorkerHeapUsedBytes,
708
- } : {}),
709
- }, 'debug');
710
- request.resolve(value);
711
- this.scheduleIdleScaleDown();
712
- }
713
-
714
- private rejectRequest(request: PendingRequest, error: Error): void {
715
- if (request.settled) return;
716
- request.settled = true;
717
- request.signal.removeEventListener('abort', request.onAbort);
718
- this.inFlight.delete(request);
719
- const index = this.queue.indexOf(request);
720
- if (index >= 0) this.queue.splice(index, 1);
721
- if (request.slot?.current === request) request.slot.current = undefined;
722
- request.slot = undefined;
723
- this.diagnostic(
724
- request.signal.aborted
725
- ? `behavior.${request.operation}.cancelled`
726
- : `behavior.${request.operation}.failed`,
727
- {
728
- behavior_id: this.options.source.id,
729
- executor: 'worker_thread',
730
- runtime_instance_id: this.runtimeInstanceId,
731
- request_id: request.requestId,
732
- epoch_id: request.frame.epochId,
733
- duration_ms: roundedElapsed(request.enqueuedAt),
734
- aborted: request.signal.aborted,
735
- error_code: errorCode(error, `BEHAVIOR_${request.operation.toUpperCase()}_FAILED`),
736
- },
737
- request.signal.aborted ? 'debug' : 'error',
738
- );
739
- request.reject(error);
740
- this.scheduleIdleScaleDown();
741
- }
742
-
743
- private abortRequest(request: PendingRequest): void {
744
- if (request.settled) return;
745
- const slot = request.slot;
746
- this.rejectRequest(request, abortError(request.signal));
747
- // Synchronous behavior code cannot be interrupted inside one isolate.
748
- // Replace only its slot; computations in the other Workers remain in flight.
749
- if (slot) void this.retireSlot(slot, 'request_aborted');
750
- }
751
-
752
- private failSlot(slot: WorkerSlot, error: Error): void {
753
- slot.readyReject?.(error);
754
- if (slot.current) this.rejectRequest(slot.current, error);
755
- void this.retireSlot(slot, 'failed');
756
- }
757
-
758
- private retireSlot(slot: WorkerSlot, reason: string): Promise<void> {
759
- if (slot.retirement) return slot.retirement;
760
- slot.readyReject?.(new Error(`behavior_thread_worker_retired:${reason}`));
761
- slot.state = 'retiring';
762
- if (slot.current) {
763
- this.rejectRequest(slot.current, new Error(`behavior_thread_worker_retired:${reason}`));
764
- }
765
- const retirement = Promise.resolve(slot.worker.terminate()).catch(() => -1).then(() => {
766
- this.slots.delete(slot);
767
- this.retiredWorkerCount += 1;
768
- this.diagnostic('behavior.thread.retired', {
769
- behavior_id: this.options.source.id,
770
- runtime_instance_id: this.runtimeInstanceId,
771
- slot_id: slot.id,
772
- reason,
773
- worker_count: this.activeWorkerCount(),
774
- min_worker_count: this.minWorkerCount,
775
- max_worker_count: this.maxWorkerCount,
776
- }, reason === 'request_aborted' ? 'debug' : 'info');
777
- if (this.state === 'running') this.ensureReplacement('replacement');
778
- });
779
- slot.retirement = retirement;
780
- return retirement;
781
- }
782
-
783
- private ensureReplacement(reason: 'queue_pressure' | 'replacement'): void {
784
- if (
785
- this.state !== 'running'
786
- || this.activeWorkerCount() >= this.desiredWorkerCount
787
- || this.replacementTask
788
- || this.replacementRetryTimer
789
- ) {
790
- this.pump();
791
- return;
792
- }
793
- const task = this.spawnSlot(reason).then(() => {
794
- this.replacementFailureCount = 0;
795
- this.pump();
796
- this.scheduleIdleScaleDown();
797
- }).catch((error) => {
798
- this.replacementFailureCount += 1;
799
- const retryDelayMs = Math.min(
800
- REPLACEMENT_RETRY_MAX_MS,
801
- REPLACEMENT_RETRY_BASE_MS * (2 ** Math.min(10, this.replacementFailureCount - 1)),
802
- );
803
- this.diagnostic('behavior.thread.replacement_failed', {
804
- behavior_id: this.options.source.id,
805
- runtime_instance_id: this.runtimeInstanceId,
806
- error_code: errorCode(error, 'BEHAVIOR_THREAD_REPLACEMENT_FAILED'),
807
- reason,
808
- retry_delay_ms: retryDelayMs,
809
- }, 'error');
810
- if (this.state === 'running') {
811
- this.replacementRetryTimer = setTimeout(() => {
812
- this.replacementRetryTimer = undefined;
813
- this.ensureReplacement(reason);
814
- }, retryDelayMs);
815
- this.replacementRetryTimer.unref?.();
816
- }
817
- }).finally(() => {
818
- this.spawnTasks.delete(task);
819
- this.replacementTask = undefined;
820
- if (
821
- this.state === 'running'
822
- && this.activeWorkerCount() < this.desiredWorkerCount
823
- && !this.replacementRetryTimer
824
- ) this.ensureReplacement(reason);
825
- });
826
- this.replacementTask = task;
827
- this.spawnTasks.add(task);
828
- }
829
-
830
- private growForPressure(): void {
831
- const target = Math.min(this.maxWorkerCount, Math.max(this.minWorkerCount, this.inFlight.size));
832
- if (target <= this.desiredWorkerCount) return;
833
- const previous = this.desiredWorkerCount;
834
- this.desiredWorkerCount = target;
835
- this.diagnostic('behavior.thread_pool.scale_requested', {
836
- behavior_id: this.options.source.id,
837
- runtime_instance_id: this.runtimeInstanceId,
838
- trigger: 'queue_pressure',
839
- previous_worker_count: previous,
840
- desired_worker_count: target,
841
- worker_count: this.activeWorkerCount(),
842
- min_worker_count: this.minWorkerCount,
843
- max_worker_count: this.maxWorkerCount,
844
- queued_request_count: this.queue.length,
845
- in_flight_request_count: this.inFlight.size,
846
- }, 'info');
847
- this.ensureReplacement('queue_pressure');
848
- this.scheduleIdleScaleDown();
849
- }
850
-
851
- private scheduleIdleScaleDown(): void {
852
- if (this.state !== 'running' || this.idleScaleDownTimer) return;
853
- const delayMs = this.nextIdleScaleDownDelayMs();
854
- if (delayMs === undefined) return;
855
- this.idleScaleDownTimer = setTimeout(() => {
856
- this.idleScaleDownTimer = undefined;
857
- if (this.state !== 'running') return;
858
- // inFlight already contains both assigned and queued requests, so it is the current
859
- // concurrency demand. Never retire a busy Worker or shrink below that demand.
860
- const demand = Math.min(
861
- this.maxWorkerCount,
862
- Math.max(this.minWorkerCount, this.inFlight.size),
863
- );
864
- const previous = this.desiredWorkerCount;
865
- this.desiredWorkerCount = demand;
866
- const activeWorkerCount = this.activeWorkerCount();
867
- const retiredWorkerCount = this.trimIdleWorkers(demand);
868
- this.diagnostic(
869
- retiredWorkerCount > 0 || previous !== demand
870
- ? 'behavior.thread_pool.scale_requested'
871
- : 'behavior.thread_pool.scale_deferred',
872
- {
873
- behavior_id: this.options.source.id,
874
- runtime_instance_id: this.runtimeInstanceId,
875
- trigger: retiredWorkerCount > 0 ? 'idle' : 'current_demand',
876
- previous_worker_count: previous,
877
- desired_worker_count: demand,
878
- worker_count: activeWorkerCount,
879
- min_worker_count: this.minWorkerCount,
880
- max_worker_count: this.maxWorkerCount,
881
- in_flight_request_count: this.inFlight.size,
882
- queued_request_count: this.queue.length,
883
- idle_timeout_ms: this.idleWorkerTimeoutMs,
884
- retired_worker_count: retiredWorkerCount,
885
- },
886
- 'info',
887
- );
888
- if (this.activeWorkerCount() < this.desiredWorkerCount) {
889
- this.ensureReplacement('queue_pressure');
890
- }
891
- this.scheduleIdleScaleDown();
892
- }, delayMs);
893
- this.idleScaleDownTimer.unref?.();
894
- }
895
-
896
- private nextIdleScaleDownDelayMs(): number | undefined {
897
- const excess = this.activeWorkerCount() - this.currentWorkerDemand();
898
- if (excess <= 0) return undefined;
899
- const oldestIdleSince = [...this.slots].reduce<number | undefined>((oldest, slot) => {
900
- if (slot.state !== 'idle' || slot.idleSince === undefined) return oldest;
901
- return oldest === undefined ? slot.idleSince : Math.min(oldest, slot.idleSince);
902
- }, undefined);
903
- if (oldestIdleSince === undefined) return undefined;
904
- return Math.max(
905
- 0,
906
- Math.ceil(oldestIdleSince + this.idleWorkerTimeoutMs - performance.now()),
907
- );
908
- }
909
-
910
- private cancelIdleScaleDown(): void {
911
- if (!this.idleScaleDownTimer) return;
912
- clearTimeout(this.idleScaleDownTimer);
913
- this.idleScaleDownTimer = undefined;
914
- }
915
-
916
- private trimIdleWorkers(demand = this.currentWorkerDemand()): number {
917
- let excess = this.activeWorkerCount() - demand;
918
- if (excess <= 0) return 0;
919
- const cutoff = performance.now() - this.idleWorkerTimeoutMs;
920
- const candidates = [...this.slots]
921
- .filter((slot) => (
922
- slot.state === 'idle'
923
- && slot.idleSince !== undefined
924
- && slot.idleSince <= cutoff
925
- ))
926
- .sort((left, right) => left.idleSince! - right.idleSince!);
927
- let retired = 0;
928
- for (const slot of candidates) {
929
- if (excess <= 0) break;
930
- excess -= 1;
931
- retired += 1;
932
- void this.retireSlot(slot, 'idle');
933
- }
934
- return retired;
935
- }
936
-
937
- private currentWorkerDemand(): number {
938
- return Math.min(
939
- this.maxWorkerCount,
940
- Math.max(this.minWorkerCount, this.inFlight.size),
941
- );
942
- }
943
-
944
- private activeWorkerCount(): number {
945
- return [...this.slots].filter((slot) => slot.state !== 'retiring').length;
946
- }
947
-
948
- private currentWorkerHeapUsedBytes(): number {
949
- return [...this.slots].reduce(
950
- (total, slot) => total + (slot.state === 'retiring' ? 0 : slot.heapUsedBytes ?? 0),
951
- 0,
952
- );
953
- }
954
-
955
- private updateWorkerHeap(slot: WorkerSlot, heapUsedBytes: number): void {
956
- slot.heapUsedBytes = Math.max(0, heapUsedBytes);
957
- this.peakWorkerHeapUsedBytes = Math.max(
958
- this.peakWorkerHeapUsedBytes,
959
- this.currentWorkerHeapUsedBytes(),
960
- );
961
- }
962
-
963
- private diagnostic(
964
- name: string,
965
- attributes?: Readonly<Record<string, unknown>>,
966
- severity?: RuntimeDiagnosticSeverity,
967
- ): void {
968
- try {
969
- this.options.diagnostic?.(name, attributes, severity);
970
- } catch {
971
- // Diagnostics are observability only and must never alter pool lifecycle.
972
- }
973
- }
4
+ import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
5
+ import { CLAWCLAW_STRATEGY_WORKER_BRIDGE } from './behavior-worker-bridge.js';
6
+ export { PARALLEL_STRATEGY_THREAD_POOL_SIZE as PARALLEL_BEHAVIOR_THREAD_POOL_SIZE } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
7
+ export type { ThreadStrategyExecutorSnapshot as ThreadBehaviorExecutorSnapshot } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
8
+ export type ThreadBehaviorExecutorOptions = Omit<ThreadStrategyExecutorOptions<ResolvedClawclawBehaviorSource, BehaviorInput, ClawclawBehaviorObservationSnapshot>, 'bridge' | 'inputMetadata'>;
9
+ export type BehaviorThreadPreparation = StrategyThreadPreparation<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>;
10
+ export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
11
+ prepareStrategyInWorker<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>(source, input, {...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE});
12
+ export class ThreadBehaviorExecutor extends ThreadStrategyExecutor<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, ClawclawBehaviorObservationSnapshot> {
13
+ constructor(options: ThreadBehaviorExecutorOptions) { super({...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE,
14
+ inputMetadata: frame => frame.gameState.tick === undefined ? {} : {tick: frame.gameState.tick} }); }
974
15
  }