@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0

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 (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +242 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +56 -0
  127. package/dist/mailbox/mailbox-plugin.js +111 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +336 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,778 @@
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 { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
7
+ import { serveStrategyMemoryRequest, unavailableStrategyMemory } from '../memory/strategy-memory-rpc.js';
8
+ export const PARALLEL_STRATEGY_THREAD_POOL_SIZE = 10;
9
+ const INITIAL_WORKER_COUNT = 2;
10
+ const MAX_POOL_SIZE = 10;
11
+ const IDLE_SCALE_DOWN_MS = 30_000;
12
+ const START_TIMEOUT_MS = 20_000;
13
+ const MAX_WORKER_ERROR_MESSAGE_LENGTH = 512;
14
+ const REPLACEMENT_RETRY_BASE_MS = 50;
15
+ const REPLACEMENT_RETRY_MAX_MS = 5_000;
16
+ const WORKER_BOOTSTRAP = realpathSync(fileURLToPath(new URL('../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url)));
17
+ function asError(value, fallback) {
18
+ return value instanceof Error ? value : new Error(typeof value === 'string' ? value : fallback);
19
+ }
20
+ function abortError(signal) {
21
+ return asError(signal.reason, 'behavior_thread_request_aborted');
22
+ }
23
+ function errorCode(error, fallback) {
24
+ const code = error && typeof error === 'object' && typeof error.code === 'string'
25
+ ? error.code.trim()
26
+ : '';
27
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code))
28
+ return code;
29
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
30
+ return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(message.trim())?.[1] ?? fallback;
31
+ }
32
+ function roundedElapsed(startedAt) {
33
+ return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
34
+ }
35
+ /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
36
+ export async function prepareStrategyInWorker(source, input, options) {
37
+ const pinned = options.bridge.pin(source);
38
+ const sourceUrl = options.bridge.sourceUrl(pinned);
39
+ const loader = options.bridge.loader();
40
+ const poolId = randomUUID();
41
+ const worker = new Worker(WORKER_BOOTSTRAP, {
42
+ execArgv: [],
43
+ resourceLimits: {
44
+ maxOldGenerationSizeMb: Math.max(16, Math.min(256, Math.floor(options.maxOldGenerationSizeMb ?? 64))),
45
+ },
46
+ stdout: true,
47
+ stderr: true,
48
+ workerData: {
49
+ runtimeModuleBootstrap: {
50
+ hostUrl: options.bridge.hostUrl,
51
+ hooksUrl: loader.hooksUrl,
52
+ sdkAliases: loader.sdkAliases,
53
+ esmModuleRoots: [new URL('.', sourceUrl).href],
54
+ },
55
+ poolId,
56
+ slotId: 0,
57
+ source: pinned,
58
+ sourceUrl,
59
+ prepareInput: structuredClone(input),
60
+ diagnosticsEnabled: options.diagnosticsEnabled === true,
61
+ },
62
+ });
63
+ try {
64
+ return await new Promise((resolve, reject) => {
65
+ let settled = false;
66
+ const finish = (callback) => {
67
+ if (settled)
68
+ return;
69
+ settled = true;
70
+ clearTimeout(timer);
71
+ callback();
72
+ };
73
+ const timer = setTimeout(() => finish(() => reject(new Error('behavior_thread_prepare_timeout'))), START_TIMEOUT_MS);
74
+ timer.unref?.();
75
+ worker.on('message', (value) => {
76
+ if (!value || typeof value !== 'object' || Array.isArray(value))
77
+ return;
78
+ const message = value;
79
+ if (message.poolId !== poolId || message.slotId !== 0)
80
+ return;
81
+ if (message.type === 'error') {
82
+ const detail = message.message?.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH);
83
+ finish(() => reject(new Error(detail ? `${message.code}: ${detail}` : message.code)));
84
+ return;
85
+ }
86
+ if (message.type !== 'ready'
87
+ || message.behaviorId !== pinned.id
88
+ || message.execution !== pinned.execution
89
+ || !message.manifest
90
+ || !message.input) {
91
+ finish(() => reject(new Error('behavior_thread_prepare_invalid')));
92
+ return;
93
+ }
94
+ finish(() => resolve({
95
+ manifest: structuredClone(message.manifest),
96
+ input: structuredClone(message.input),
97
+ ...(message.timing === undefined ? {} : { timing: structuredClone(message.timing) }),
98
+ source: pinned,
99
+ }));
100
+ });
101
+ worker.once('error', (error) => finish(() => reject(error)));
102
+ worker.once('exit', (code) => {
103
+ if (code !== 0)
104
+ finish(() => reject(new Error(`behavior_thread_worker_exited:${code}`)));
105
+ });
106
+ });
107
+ }
108
+ finally {
109
+ await worker.terminate().catch(() => -1);
110
+ }
111
+ }
112
+ /** Adaptive Worker Thread pool for cross-tick computations. */
113
+ export class ThreadStrategyExecutor {
114
+ snapshotStore;
115
+ runtimeInstanceId = randomUUID();
116
+ maxWorkerCount;
117
+ maxPendingRequestCount;
118
+ minWorkerCount;
119
+ idleWorkerTimeoutMs;
120
+ maxOldGenerationSizeMb;
121
+ state = 'new';
122
+ slots = new Set();
123
+ queue = [];
124
+ inFlight = new Set();
125
+ spawnTasks = new Set();
126
+ startTask;
127
+ stopTask;
128
+ replacementTask;
129
+ replacementRetryTimer;
130
+ idleScaleDownTimer;
131
+ replacementFailureCount = 0;
132
+ nextSlotId = 1;
133
+ startedWorkerCount = 0;
134
+ retiredWorkerCount = 0;
135
+ peakWorkerHeapUsedBytes = 0;
136
+ desiredWorkerCount;
137
+ options;
138
+ constructor(options) {
139
+ this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
140
+ this.options = Object.freeze({
141
+ ...options,
142
+ source: options.bridge.pin(options.source),
143
+ });
144
+ const execution = options.source.execution ?? 'parallel';
145
+ const maxWorkerCount = execution === 'serial'
146
+ ? 1
147
+ : options.poolSize ?? PARALLEL_STRATEGY_THREAD_POOL_SIZE;
148
+ if (!Number.isInteger(maxWorkerCount) || maxWorkerCount <= 0 || maxWorkerCount > MAX_POOL_SIZE) {
149
+ throw new TypeError(`poolSize must be between 1 and ${MAX_POOL_SIZE}.`);
150
+ }
151
+ const idleWorkerTimeoutMs = options.idleWorkerTimeoutMs ?? IDLE_SCALE_DOWN_MS;
152
+ if (!Number.isFinite(idleWorkerTimeoutMs) || idleWorkerTimeoutMs < 0) {
153
+ throw new TypeError('idleWorkerTimeoutMs must be a non-negative finite number.');
154
+ }
155
+ this.maxWorkerCount = maxWorkerCount;
156
+ this.maxPendingRequestCount = execution === 'serial'
157
+ ? PARALLEL_STRATEGY_THREAD_POOL_SIZE
158
+ : maxWorkerCount;
159
+ this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
160
+ this.desiredWorkerCount = this.minWorkerCount;
161
+ this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
162
+ this.maxOldGenerationSizeMb = Math.max(16, Math.min(256, Math.floor(options.maxOldGenerationSizeMb ?? 64)));
163
+ }
164
+ get isAlive() {
165
+ // A temporarily degraded pool remains the same live executor while it
166
+ // restores a retired slot. Capacity is reported separately by snapshot().
167
+ return this.state === 'running';
168
+ }
169
+ start(signal) {
170
+ if (this.state === 'running')
171
+ return Promise.resolve();
172
+ if (this.state === 'starting')
173
+ return this.awaitStart(signal);
174
+ if (this.state === 'stopping' || this.state === 'stopped') {
175
+ return Promise.reject(new Error('behavior_thread_pool_stopped'));
176
+ }
177
+ if (signal.aborted)
178
+ return Promise.reject(abortError(signal));
179
+ this.state = 'starting';
180
+ const startedAt = performance.now();
181
+ this.startTask = Promise.all(Array.from({ length: this.minWorkerCount }, () => this.spawnSlot('initial'))).then(() => {
182
+ if (this.state !== 'starting')
183
+ throw new Error('behavior_thread_pool_stopped');
184
+ this.state = 'running';
185
+ this.diagnostic('behavior.thread_pool.started', {
186
+ behavior_id: this.options.source.id,
187
+ execution: this.options.source.execution,
188
+ runtime_instance_id: this.runtimeInstanceId,
189
+ worker_count: this.slots.size,
190
+ min_worker_count: this.minWorkerCount,
191
+ max_worker_count: this.maxWorkerCount,
192
+ worker_max_old_generation_mb: this.maxOldGenerationSizeMb,
193
+ started_worker_count: this.startedWorkerCount,
194
+ retired_worker_count: this.retiredWorkerCount,
195
+ ...(this.options.diagnosticsEnabled === true ? {
196
+ worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
197
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
198
+ } : {}),
199
+ duration_ms: roundedElapsed(startedAt),
200
+ }, 'info');
201
+ }).catch(async (error) => {
202
+ if (this.state === 'starting')
203
+ this.state = 'stopped';
204
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, 'start_failed')));
205
+ throw error;
206
+ });
207
+ return this.awaitStart(signal).catch(async (error) => {
208
+ if (signal.aborted)
209
+ await this.stop('switched');
210
+ throw error;
211
+ });
212
+ }
213
+ update(frame, signal, observationSnapshot) {
214
+ return this.submit('decide', frame, signal, observationSnapshot);
215
+ }
216
+ async reset(_signal) {
217
+ this.snapshotStore.reset();
218
+ }
219
+ stop(reason) {
220
+ if (this.stopTask)
221
+ return this.stopTask;
222
+ this.stopTask = this.performStop(reason);
223
+ return this.stopTask;
224
+ }
225
+ async performStop(reason) {
226
+ if (this.state === 'stopped')
227
+ return;
228
+ if (this.state === 'new') {
229
+ this.state = 'stopped';
230
+ return;
231
+ }
232
+ this.state = 'stopping';
233
+ if (this.replacementRetryTimer) {
234
+ clearTimeout(this.replacementRetryTimer);
235
+ this.replacementRetryTimer = undefined;
236
+ }
237
+ this.cancelIdleScaleDown();
238
+ const error = new Error('behavior_thread_pool_stopped');
239
+ for (const request of [...this.inFlight])
240
+ this.rejectRequest(request, error);
241
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
242
+ await Promise.allSettled([...this.spawnTasks]);
243
+ await this.startTask?.catch(() => { });
244
+ await Promise.allSettled([...this.slots].map((slot) => this.retireSlot(slot, reason)));
245
+ this.state = 'stopped';
246
+ this.diagnostic('behavior.thread_pool.stopped', {
247
+ behavior_id: this.options.source.id,
248
+ runtime_instance_id: this.runtimeInstanceId,
249
+ reason,
250
+ min_worker_count: this.minWorkerCount,
251
+ max_worker_count: this.maxWorkerCount,
252
+ started_worker_count: this.startedWorkerCount,
253
+ retired_worker_count: this.retiredWorkerCount,
254
+ ...(this.options.diagnosticsEnabled === true ? {
255
+ worker_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
256
+ peak_worker_heap_used_bytes: this.peakWorkerHeapUsedBytes,
257
+ } : {}),
258
+ }, 'info');
259
+ }
260
+ snapshot() {
261
+ const slots = [...this.slots];
262
+ return {
263
+ state: this.state,
264
+ workerCount: slots.length,
265
+ idleWorkerCount: slots.filter(({ state }) => state === 'idle').length,
266
+ busyWorkerCount: slots.filter(({ state }) => state === 'busy').length,
267
+ queuedRequestCount: this.queue.length,
268
+ inFlightRequestCount: this.inFlight.size,
269
+ startedWorkerCount: this.startedWorkerCount,
270
+ retiredWorkerCount: this.retiredWorkerCount,
271
+ workerHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
272
+ peakWorkerHeapUsedBytes: this.peakWorkerHeapUsedBytes,
273
+ };
274
+ }
275
+ awaitStart(signal) {
276
+ const task = this.startTask;
277
+ if (signal.aborted)
278
+ return Promise.reject(abortError(signal));
279
+ return new Promise((resolve, reject) => {
280
+ const onAbort = () => reject(abortError(signal));
281
+ signal.addEventListener('abort', onAbort, { once: true });
282
+ void task.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort));
283
+ });
284
+ }
285
+ async submit(operation, frame, signal, observationSnapshot) {
286
+ if (signal.aborted)
287
+ throw abortError(signal);
288
+ await this.awaitStart(signal);
289
+ if (this.state !== 'running')
290
+ throw new Error('behavior_thread_pool_not_running');
291
+ if (this.inFlight.size >= this.maxPendingRequestCount) {
292
+ throw new Error('behavior_thread_window_full');
293
+ }
294
+ return new Promise((resolve, reject) => {
295
+ const request = {
296
+ requestId: randomUUID(),
297
+ operation,
298
+ // Frame is already recursively frozen. Keep the Owner snapshot
299
+ // until postMessage performs the one unavoidable Worker-boundary clone.
300
+ frame,
301
+ ...(observationSnapshot === undefined
302
+ ? {}
303
+ : { observationSnapshot: structuredClone(observationSnapshot) }),
304
+ signal,
305
+ enqueuedAt: performance.now(),
306
+ resolve,
307
+ reject,
308
+ settled: false,
309
+ onAbort: () => this.abortRequest(request),
310
+ };
311
+ signal.addEventListener('abort', request.onAbort, { once: true });
312
+ this.inFlight.add(request);
313
+ this.queue.push(request);
314
+ this.diagnostic(`behavior.${operation}.started`, {
315
+ behavior_id: this.options.source.id,
316
+ executor: 'worker_thread',
317
+ runtime_instance_id: this.runtimeInstanceId,
318
+ request_id: request.requestId,
319
+ epoch_id: frame.epochId,
320
+ ...(this.options.inputMetadata?.(frame) ?? {}),
321
+ }, 'debug');
322
+ this.pump();
323
+ this.growForPressure();
324
+ });
325
+ }
326
+ async spawnSlot(reason) {
327
+ const source = this.options.bridge.resolve(this.options.source);
328
+ const sourceUrl = this.options.bridge.sourceUrl(source);
329
+ const slotId = this.nextSlotId++;
330
+ const loader = this.options.bridge.loader();
331
+ const worker = new Worker(WORKER_BOOTSTRAP, {
332
+ execArgv: [],
333
+ resourceLimits: { maxOldGenerationSizeMb: this.maxOldGenerationSizeMb },
334
+ stdout: true,
335
+ stderr: true,
336
+ workerData: {
337
+ runtimeModuleBootstrap: {
338
+ hostUrl: this.options.bridge.hostUrl,
339
+ hooksUrl: loader.hooksUrl,
340
+ sdkAliases: loader.sdkAliases,
341
+ esmModuleRoots: [new URL('.', sourceUrl).href],
342
+ },
343
+ poolId: this.runtimeInstanceId,
344
+ slotId,
345
+ source,
346
+ sourceUrl,
347
+ diagnosticsEnabled: this.options.diagnosticsEnabled === true,
348
+ },
349
+ });
350
+ const slot = { id: slotId, worker, state: 'starting' };
351
+ this.slots.add(slot);
352
+ worker.stdout?.on('data', (chunk) => this.diagnostic('behavior.thread.stdout', { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length }, 'debug'));
353
+ worker.stderr?.on('data', (chunk) => this.diagnostic('behavior.thread.stderr', { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length }, 'debug'));
354
+ worker.on('message', (message) => this.handleMessage(slot, message));
355
+ worker.once('error', (error) => this.failSlot(slot, error));
356
+ worker.once('exit', (code) => {
357
+ if (slot.state !== 'retiring') {
358
+ this.failSlot(slot, new Error(`behavior_thread_worker_exited:${code}`));
359
+ }
360
+ });
361
+ let timer;
362
+ try {
363
+ await new Promise((resolve, reject) => {
364
+ slot.readyResolve = resolve;
365
+ slot.readyReject = reject;
366
+ timer = setTimeout(() => reject(new Error('behavior_thread_worker_start_timeout')), START_TIMEOUT_MS);
367
+ timer.unref?.();
368
+ });
369
+ if (this.state !== 'starting' && this.state !== 'running') {
370
+ throw new Error('behavior_thread_pool_stopped');
371
+ }
372
+ slot.state = 'idle';
373
+ slot.idleSince = performance.now();
374
+ this.startedWorkerCount += 1;
375
+ this.diagnostic('behavior.thread.started', {
376
+ behavior_id: source.id,
377
+ runtime_instance_id: this.runtimeInstanceId,
378
+ slot_id: slot.id,
379
+ worker_count: this.activeWorkerCount(),
380
+ min_worker_count: this.minWorkerCount,
381
+ max_worker_count: this.maxWorkerCount,
382
+ reason,
383
+ }, 'info');
384
+ }
385
+ catch (error) {
386
+ await this.retireSlot(slot, 'start_failed');
387
+ throw error;
388
+ }
389
+ finally {
390
+ if (timer)
391
+ clearTimeout(timer);
392
+ slot.readyResolve = undefined;
393
+ slot.readyReject = undefined;
394
+ }
395
+ }
396
+ pump() {
397
+ if (this.state !== 'running')
398
+ return;
399
+ while (this.queue.length > 0) {
400
+ const slot = [...this.slots].find((candidate) => candidate.state === 'idle');
401
+ if (!slot)
402
+ return;
403
+ const request = this.queue.shift();
404
+ if (request.settled || request.signal.aborted) {
405
+ if (!request.settled)
406
+ this.rejectRequest(request, abortError(request.signal));
407
+ continue;
408
+ }
409
+ slot.state = 'busy';
410
+ slot.idleSince = undefined;
411
+ slot.current = request;
412
+ request.slot = slot;
413
+ request.assignedAt = performance.now();
414
+ const inherited = this.options.source.stateMode === 'snapshot' ? this.snapshotStore.latest : undefined;
415
+ request.snapshotEpoch = inherited?.epochId;
416
+ request.snapshotGeneration = this.snapshotStore.generation;
417
+ try {
418
+ slot.worker.postMessage({
419
+ type: 'run',
420
+ poolId: this.runtimeInstanceId,
421
+ requestId: request.requestId,
422
+ operation: request.operation,
423
+ frame: request.frame,
424
+ ...(inherited ? { instanceSnapshot: inherited.value } : {}),
425
+ ...(request.observationSnapshot === undefined
426
+ ? {}
427
+ : { observationSnapshot: request.observationSnapshot }),
428
+ });
429
+ }
430
+ catch (error) {
431
+ this.rejectRequest(request, asError(error, 'behavior_thread_submit_failed'));
432
+ void this.retireSlot(slot, 'submit_failed');
433
+ }
434
+ }
435
+ }
436
+ handleMessage(slot, value) {
437
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
438
+ this.failSlot(slot, new Error('behavior_thread_protocol_invalid'));
439
+ return;
440
+ }
441
+ const message = value;
442
+ if (message.poolId !== this.runtimeInstanceId || message.slotId !== slot.id) {
443
+ this.failSlot(slot, new Error('behavior_thread_protocol_identity_mismatch'));
444
+ return;
445
+ }
446
+ if (message.type === 'strategy_memory') {
447
+ const request = slot.current;
448
+ const isActive = () => this.state === 'running' && !!request && request === slot.current
449
+ && message.requestId === request.requestId && !request.settled && !request.signal.aborted;
450
+ void serveStrategyMemoryRequest(message, () => request && this.options.memory
451
+ ? this.options.memory(request.frame, isActive) : unavailableStrategyMemory, reply => slot.worker.postMessage(reply));
452
+ return;
453
+ }
454
+ if (message.type === 'ready') {
455
+ if (slot.state !== 'starting'
456
+ || message.behaviorId !== this.options.source.id
457
+ || message.execution !== this.options.source.execution
458
+ || (this.options.diagnosticsEnabled === true && (!Number.isFinite(message.heapUsedBytes)
459
+ || Number(message.heapUsedBytes) < 0))) {
460
+ this.failSlot(slot, new Error('behavior_thread_ready_invalid'));
461
+ return;
462
+ }
463
+ if (typeof message.heapUsedBytes === 'number')
464
+ this.updateWorkerHeap(slot, message.heapUsedBytes);
465
+ slot.readyResolve?.();
466
+ return;
467
+ }
468
+ if (message.type === 'error') {
469
+ if (Number.isFinite(message.heapUsedBytes) && Number(message.heapUsedBytes) >= 0) {
470
+ this.updateWorkerHeap(slot, Number(message.heapUsedBytes));
471
+ }
472
+ const code = typeof message.code === 'string'
473
+ ? message.code
474
+ : 'behavior_thread_worker_failed';
475
+ const detail = typeof message.message === 'string'
476
+ ? message.message.trim().slice(0, MAX_WORKER_ERROR_MESSAGE_LENGTH)
477
+ : '';
478
+ const error = new Error(detail ? `${code}: ${detail}` : code);
479
+ if (slot.current && (!message.requestId || message.requestId === slot.current.requestId)) {
480
+ this.rejectRequest(slot.current, error);
481
+ }
482
+ else {
483
+ slot.readyReject?.(error);
484
+ }
485
+ void this.retireSlot(slot, 'worker_error');
486
+ return;
487
+ }
488
+ const request = slot.current;
489
+ if (!request || message.requestId !== request.requestId) {
490
+ this.failSlot(slot, new Error('behavior_thread_request_mismatch'));
491
+ return;
492
+ }
493
+ if (message.type !== 'result') {
494
+ this.rejectRequest(request, new Error('behavior_thread_response_invalid'));
495
+ void this.retireSlot(slot, 'invalid_response');
496
+ return;
497
+ }
498
+ if (this.options.diagnosticsEnabled === true && (!Number.isFinite(message.heapUsedBytes)
499
+ || Number(message.heapUsedBytes) < 0)) {
500
+ this.rejectRequest(request, new Error('behavior_thread_worker_memory_invalid'));
501
+ void this.retireSlot(slot, 'invalid_response');
502
+ return;
503
+ }
504
+ if (typeof message.heapUsedBytes === 'number')
505
+ this.updateWorkerHeap(slot, message.heapUsedBytes);
506
+ slot.current = undefined;
507
+ slot.state = 'idle';
508
+ slot.idleSince = performance.now();
509
+ request.slot = undefined;
510
+ this.resolveRequest(request, structuredClone(message.result), message);
511
+ this.pump();
512
+ }
513
+ resolveRequest(request, value, message) {
514
+ if (request.settled)
515
+ return;
516
+ const published = this.options.source.stateMode === 'snapshot' && message.instanceSnapshot
517
+ && !request.signal.aborted && this.state === 'running'
518
+ ? this.snapshotStore.publish(request.frame.epochId, message.instanceSnapshot, request.snapshotGeneration)
519
+ : false;
520
+ if (this.options.source.stateMode === 'snapshot')
521
+ this.diagnostic('behavior.snapshot.completed', {
522
+ behavior_id: this.options.source.id, epoch_id: request.frame.epochId,
523
+ inherited_epoch_id: request.snapshotEpoch ?? null, published,
524
+ latest_completed_epoch_id: this.snapshotStore.latest?.epochId ?? null,
525
+ }, 'debug');
526
+ request.settled = true;
527
+ request.signal.removeEventListener('abort', request.onAbort);
528
+ this.inFlight.delete(request);
529
+ this.diagnostic(`behavior.${request.operation}.completed`, {
530
+ behavior_id: this.options.source.id,
531
+ executor: 'worker_thread',
532
+ runtime_instance_id: this.runtimeInstanceId,
533
+ request_id: request.requestId,
534
+ epoch_id: request.frame.epochId,
535
+ duration_ms: roundedElapsed(request.enqueuedAt),
536
+ queue_duration_ms: Math.round(Math.max(0, (request.assignedAt ?? performance.now()) - request.enqueuedAt) * 1_000) / 1_000,
537
+ worker_duration_ms: message.durationMs,
538
+ read_query_count: message.queryCount,
539
+ ...(this.options.diagnosticsEnabled === true ? {
540
+ worker_heap_used_bytes: message.heapUsedBytes,
541
+ worker_pool_heap_used_bytes: this.currentWorkerHeapUsedBytes(),
542
+ peak_worker_pool_heap_used_bytes: this.peakWorkerHeapUsedBytes,
543
+ } : {}),
544
+ }, 'debug');
545
+ request.resolve(value);
546
+ this.scheduleIdleScaleDown();
547
+ }
548
+ rejectRequest(request, error) {
549
+ if (request.settled)
550
+ return;
551
+ request.settled = true;
552
+ request.signal.removeEventListener('abort', request.onAbort);
553
+ this.inFlight.delete(request);
554
+ const index = this.queue.indexOf(request);
555
+ if (index >= 0)
556
+ this.queue.splice(index, 1);
557
+ if (request.slot?.current === request)
558
+ request.slot.current = undefined;
559
+ request.slot = undefined;
560
+ this.diagnostic(request.signal.aborted
561
+ ? `behavior.${request.operation}.cancelled`
562
+ : `behavior.${request.operation}.failed`, {
563
+ behavior_id: this.options.source.id,
564
+ executor: 'worker_thread',
565
+ runtime_instance_id: this.runtimeInstanceId,
566
+ request_id: request.requestId,
567
+ epoch_id: request.frame.epochId,
568
+ duration_ms: roundedElapsed(request.enqueuedAt),
569
+ aborted: request.signal.aborted,
570
+ error_code: errorCode(error, `BEHAVIOR_${request.operation.toUpperCase()}_FAILED`),
571
+ }, request.signal.aborted ? 'debug' : 'error');
572
+ request.reject(error);
573
+ this.scheduleIdleScaleDown();
574
+ }
575
+ abortRequest(request) {
576
+ if (request.settled)
577
+ return;
578
+ const slot = request.slot;
579
+ this.rejectRequest(request, abortError(request.signal));
580
+ // Synchronous behavior code cannot be interrupted inside one isolate.
581
+ // Replace only its slot; computations in the other Workers remain in flight.
582
+ if (slot)
583
+ void this.retireSlot(slot, 'request_aborted');
584
+ }
585
+ failSlot(slot, error) {
586
+ slot.readyReject?.(error);
587
+ if (slot.current)
588
+ this.rejectRequest(slot.current, error);
589
+ void this.retireSlot(slot, 'failed');
590
+ }
591
+ retireSlot(slot, reason) {
592
+ if (slot.retirement)
593
+ return slot.retirement;
594
+ slot.readyReject?.(new Error(`behavior_thread_worker_retired:${reason}`));
595
+ slot.state = 'retiring';
596
+ if (slot.current) {
597
+ this.rejectRequest(slot.current, new Error(`behavior_thread_worker_retired:${reason}`));
598
+ }
599
+ const retirement = Promise.resolve(slot.worker.terminate()).catch(() => -1).then(() => {
600
+ this.slots.delete(slot);
601
+ this.retiredWorkerCount += 1;
602
+ this.diagnostic('behavior.thread.retired', {
603
+ behavior_id: this.options.source.id,
604
+ runtime_instance_id: this.runtimeInstanceId,
605
+ slot_id: slot.id,
606
+ reason,
607
+ worker_count: this.activeWorkerCount(),
608
+ min_worker_count: this.minWorkerCount,
609
+ max_worker_count: this.maxWorkerCount,
610
+ }, reason === 'request_aborted' ? 'debug' : 'info');
611
+ if (this.state === 'running')
612
+ this.ensureReplacement('replacement');
613
+ });
614
+ slot.retirement = retirement;
615
+ return retirement;
616
+ }
617
+ ensureReplacement(reason) {
618
+ if (this.state !== 'running'
619
+ || this.activeWorkerCount() >= this.desiredWorkerCount
620
+ || this.replacementTask
621
+ || this.replacementRetryTimer) {
622
+ this.pump();
623
+ return;
624
+ }
625
+ const task = this.spawnSlot(reason).then(() => {
626
+ this.replacementFailureCount = 0;
627
+ this.pump();
628
+ this.scheduleIdleScaleDown();
629
+ }).catch((error) => {
630
+ this.replacementFailureCount += 1;
631
+ const retryDelayMs = Math.min(REPLACEMENT_RETRY_MAX_MS, REPLACEMENT_RETRY_BASE_MS * (2 ** Math.min(10, this.replacementFailureCount - 1)));
632
+ this.diagnostic('behavior.thread.replacement_failed', {
633
+ behavior_id: this.options.source.id,
634
+ runtime_instance_id: this.runtimeInstanceId,
635
+ error_code: errorCode(error, 'BEHAVIOR_THREAD_REPLACEMENT_FAILED'),
636
+ reason,
637
+ retry_delay_ms: retryDelayMs,
638
+ }, 'error');
639
+ if (this.state === 'running') {
640
+ this.replacementRetryTimer = setTimeout(() => {
641
+ this.replacementRetryTimer = undefined;
642
+ this.ensureReplacement(reason);
643
+ }, retryDelayMs);
644
+ this.replacementRetryTimer.unref?.();
645
+ }
646
+ }).finally(() => {
647
+ this.spawnTasks.delete(task);
648
+ this.replacementTask = undefined;
649
+ if (this.state === 'running'
650
+ && this.activeWorkerCount() < this.desiredWorkerCount
651
+ && !this.replacementRetryTimer)
652
+ this.ensureReplacement(reason);
653
+ });
654
+ this.replacementTask = task;
655
+ this.spawnTasks.add(task);
656
+ }
657
+ growForPressure() {
658
+ const target = Math.min(this.maxWorkerCount, Math.max(this.minWorkerCount, this.inFlight.size));
659
+ if (target <= this.desiredWorkerCount)
660
+ return;
661
+ const previous = this.desiredWorkerCount;
662
+ this.desiredWorkerCount = target;
663
+ this.diagnostic('behavior.thread_pool.scale_requested', {
664
+ behavior_id: this.options.source.id,
665
+ runtime_instance_id: this.runtimeInstanceId,
666
+ trigger: 'queue_pressure',
667
+ previous_worker_count: previous,
668
+ desired_worker_count: target,
669
+ worker_count: this.activeWorkerCount(),
670
+ min_worker_count: this.minWorkerCount,
671
+ max_worker_count: this.maxWorkerCount,
672
+ queued_request_count: this.queue.length,
673
+ in_flight_request_count: this.inFlight.size,
674
+ }, 'info');
675
+ this.ensureReplacement('queue_pressure');
676
+ this.scheduleIdleScaleDown();
677
+ }
678
+ scheduleIdleScaleDown() {
679
+ if (this.state !== 'running' || this.idleScaleDownTimer)
680
+ return;
681
+ const delayMs = this.nextIdleScaleDownDelayMs();
682
+ if (delayMs === undefined)
683
+ return;
684
+ this.idleScaleDownTimer = setTimeout(() => {
685
+ this.idleScaleDownTimer = undefined;
686
+ if (this.state !== 'running')
687
+ return;
688
+ // inFlight already contains both assigned and queued requests, so it is the current
689
+ // concurrency demand. Never retire a busy Worker or shrink below that demand.
690
+ const demand = Math.min(this.maxWorkerCount, Math.max(this.minWorkerCount, this.inFlight.size));
691
+ const previous = this.desiredWorkerCount;
692
+ this.desiredWorkerCount = demand;
693
+ const activeWorkerCount = this.activeWorkerCount();
694
+ const retiredWorkerCount = this.trimIdleWorkers(demand);
695
+ this.diagnostic(retiredWorkerCount > 0 || previous !== demand
696
+ ? 'behavior.thread_pool.scale_requested'
697
+ : 'behavior.thread_pool.scale_deferred', {
698
+ behavior_id: this.options.source.id,
699
+ runtime_instance_id: this.runtimeInstanceId,
700
+ trigger: retiredWorkerCount > 0 ? 'idle' : 'current_demand',
701
+ previous_worker_count: previous,
702
+ desired_worker_count: demand,
703
+ worker_count: activeWorkerCount,
704
+ min_worker_count: this.minWorkerCount,
705
+ max_worker_count: this.maxWorkerCount,
706
+ in_flight_request_count: this.inFlight.size,
707
+ queued_request_count: this.queue.length,
708
+ idle_timeout_ms: this.idleWorkerTimeoutMs,
709
+ retired_worker_count: retiredWorkerCount,
710
+ }, 'info');
711
+ if (this.activeWorkerCount() < this.desiredWorkerCount) {
712
+ this.ensureReplacement('queue_pressure');
713
+ }
714
+ this.scheduleIdleScaleDown();
715
+ }, delayMs);
716
+ this.idleScaleDownTimer.unref?.();
717
+ }
718
+ nextIdleScaleDownDelayMs() {
719
+ const excess = this.activeWorkerCount() - this.currentWorkerDemand();
720
+ if (excess <= 0)
721
+ return undefined;
722
+ const oldestIdleSince = [...this.slots].reduce((oldest, slot) => {
723
+ if (slot.state !== 'idle' || slot.idleSince === undefined)
724
+ return oldest;
725
+ return oldest === undefined ? slot.idleSince : Math.min(oldest, slot.idleSince);
726
+ }, undefined);
727
+ if (oldestIdleSince === undefined)
728
+ return undefined;
729
+ return Math.max(0, Math.ceil(oldestIdleSince + this.idleWorkerTimeoutMs - performance.now()));
730
+ }
731
+ cancelIdleScaleDown() {
732
+ if (!this.idleScaleDownTimer)
733
+ return;
734
+ clearTimeout(this.idleScaleDownTimer);
735
+ this.idleScaleDownTimer = undefined;
736
+ }
737
+ trimIdleWorkers(demand = this.currentWorkerDemand()) {
738
+ let excess = this.activeWorkerCount() - demand;
739
+ if (excess <= 0)
740
+ return 0;
741
+ const cutoff = performance.now() - this.idleWorkerTimeoutMs;
742
+ const candidates = [...this.slots]
743
+ .filter((slot) => (slot.state === 'idle'
744
+ && slot.idleSince !== undefined
745
+ && slot.idleSince <= cutoff))
746
+ .sort((left, right) => left.idleSince - right.idleSince);
747
+ let retired = 0;
748
+ for (const slot of candidates) {
749
+ if (excess <= 0)
750
+ break;
751
+ excess -= 1;
752
+ retired += 1;
753
+ void this.retireSlot(slot, 'idle');
754
+ }
755
+ return retired;
756
+ }
757
+ currentWorkerDemand() {
758
+ return Math.min(this.maxWorkerCount, Math.max(this.minWorkerCount, this.inFlight.size));
759
+ }
760
+ activeWorkerCount() {
761
+ return [...this.slots].filter((slot) => slot.state !== 'retiring').length;
762
+ }
763
+ currentWorkerHeapUsedBytes() {
764
+ return [...this.slots].reduce((total, slot) => total + (slot.state === 'retiring' ? 0 : slot.heapUsedBytes ?? 0), 0);
765
+ }
766
+ updateWorkerHeap(slot, heapUsedBytes) {
767
+ slot.heapUsedBytes = Math.max(0, heapUsedBytes);
768
+ this.peakWorkerHeapUsedBytes = Math.max(this.peakWorkerHeapUsedBytes, this.currentWorkerHeapUsedBytes());
769
+ }
770
+ diagnostic(name, attributes, severity) {
771
+ try {
772
+ this.options.diagnostic?.(name, attributes, severity);
773
+ }
774
+ catch {
775
+ // Diagnostics are observability only and must never alter pool lifecycle.
776
+ }
777
+ }
778
+ }