@myclaw163/game-agent-runtime 0.1.0 → 0.1.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.
@@ -1,3 +1,4 @@
1
+ import { Worker } from 'node:worker_threads';
1
2
  import type { RuntimeDiagnosticSeverity } from '../framework/plugins/index.js';
2
3
  import type { RuntimeModuleThreadLoaderConfig } from '../framework/modules/runtime-module-loader.js';
3
4
  import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
@@ -13,6 +14,7 @@ export interface StrategyThreadFrame {
13
14
  export interface StrategyThreadBridge<Source extends StrategyThreadSource> {
14
15
  readonly hostUrl: string;
15
16
  pin(source: Source): Source;
17
+ pinAsync?(source: Source): Promise<Source>;
16
18
  resolve(source: Source): Source;
17
19
  sourceUrl(source: Source): string;
18
20
  loader(): RuntimeModuleThreadLoaderConfig;
@@ -27,6 +29,8 @@ export interface ThreadStrategyExecutorOptions<Source extends StrategyThreadSour
27
29
  readonly inputMetadata?: (frame: Frame) => Readonly<Record<string, unknown>>;
28
30
  readonly memory?: (frame: Readonly<Frame>, isActive: () => boolean) => StrategyMemory;
29
31
  readonly fixedWorkers?: boolean;
32
+ readonly initialWorkers?: number;
33
+ readonly preparedWorker?: StrategyWorkerLease;
30
34
  readonly snapshotStore?: BehaviorSnapshotStore;
31
35
  readonly source: Source;
32
36
  /** Maximum Worker count and in-flight request window. Tests may reduce it. */
@@ -50,22 +54,34 @@ export interface ThreadStrategyExecutorSnapshot {
50
54
  readonly workerHeapUsedBytes: number;
51
55
  readonly peakWorkerHeapUsedBytes: number;
52
56
  }
57
+ /** A prepared slot belongs to its original source until a runner takes it. */
58
+ export declare class StrategyWorkerLease {
59
+ private readonly worker;
60
+ readonly poolId: string;
61
+ private available;
62
+ private readonly ignoreError;
63
+ constructor(worker: Worker, poolId: string);
64
+ take(): Worker | undefined;
65
+ dispose(): void;
66
+ }
53
67
  export interface StrategyThreadPreparation<Source extends StrategyThreadSource, Manifest> {
54
68
  readonly manifest: Readonly<Manifest>;
55
69
  readonly input: Readonly<Record<string, unknown>>;
56
70
  readonly timing?: Readonly<BehaviorTiming>;
57
71
  readonly source: Source;
72
+ readonly worker?: StrategyWorkerLease;
58
73
  }
59
74
  /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
60
75
  export declare function prepareStrategyInWorker<Source extends StrategyThreadSource, Manifest = unknown>(source: Source, input: Readonly<Record<string, unknown>>, options: Readonly<{
61
76
  bridge: StrategyThreadBridge<Source>;
62
77
  maxOldGenerationSizeMb?: number;
63
78
  diagnosticsEnabled?: boolean;
79
+ retainWorker?: boolean;
64
80
  }>): Promise<StrategyThreadPreparation<Source, Manifest>>;
65
81
  /** Adaptive Worker Thread pool for cross-tick computations. */
66
82
  export declare class ThreadStrategyExecutor<Source extends StrategyThreadSource, Frame extends StrategyThreadFrame, Decision, Observation = unknown> {
67
83
  private readonly snapshotStore;
68
- readonly runtimeInstanceId: `${string}-${string}-${string}-${string}-${string}`;
84
+ readonly runtimeInstanceId: string;
69
85
  private readonly maxWorkerCount;
70
86
  private readonly maxPendingRequestCount;
71
87
  private readonly minWorkerCount;
@@ -99,6 +115,8 @@ export declare class ThreadStrategyExecutor<Source extends StrategyThreadSource,
99
115
  private awaitStart;
100
116
  private submit;
101
117
  private spawnSlot;
118
+ private attachSlot;
119
+ private waitForSlot;
102
120
  private pump;
103
121
  private handleMessage;
104
122
  private resolveRequest;
@@ -32,9 +32,38 @@ function errorCode(error, fallback) {
32
32
  function roundedElapsed(startedAt) {
33
33
  return Math.round(Math.max(0, performance.now() - startedAt) * 1_000) / 1_000;
34
34
  }
35
+ /** A prepared slot belongs to its original source until a runner takes it. */
36
+ export class StrategyWorkerLease {
37
+ worker;
38
+ poolId;
39
+ available = true;
40
+ ignoreError = () => { };
41
+ constructor(worker, poolId) {
42
+ this.worker = worker;
43
+ this.poolId = poolId;
44
+ worker.on('error', this.ignoreError);
45
+ worker.unref();
46
+ }
47
+ take() {
48
+ if (!this.available)
49
+ return undefined;
50
+ this.available = false;
51
+ this.worker.off('error', this.ignoreError);
52
+ if (this.worker.threadId === -1)
53
+ return undefined;
54
+ this.worker.ref();
55
+ return this.worker;
56
+ }
57
+ dispose() {
58
+ if (!this.available)
59
+ return;
60
+ this.available = false;
61
+ void this.worker.terminate().catch(() => -1);
62
+ }
63
+ }
35
64
  /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
36
65
  export async function prepareStrategyInWorker(source, input, options) {
37
- const pinned = options.bridge.pin(source);
66
+ const pinned = options.bridge.pinAsync ? await options.bridge.pinAsync(source) : options.bridge.pin(source);
38
67
  const sourceUrl = options.bridge.sourceUrl(pinned);
39
68
  const loader = options.bridge.loader();
40
69
  const poolId = randomUUID();
@@ -57,9 +86,11 @@ export async function prepareStrategyInWorker(source, input, options) {
57
86
  source: pinned,
58
87
  sourceUrl,
59
88
  prepareInput: structuredClone(input),
89
+ retainWorker: options.retainWorker === true,
60
90
  diagnosticsEnabled: options.diagnosticsEnabled === true,
61
91
  },
62
92
  });
93
+ let lease;
63
94
  try {
64
95
  return await new Promise((resolve, reject) => {
65
96
  let settled = false;
@@ -72,7 +103,7 @@ export async function prepareStrategyInWorker(source, input, options) {
72
103
  };
73
104
  const timer = setTimeout(() => finish(() => reject(new Error('behavior_thread_prepare_timeout'))), START_TIMEOUT_MS);
74
105
  timer.unref?.();
75
- worker.on('message', (value) => {
106
+ const onMessage = (value) => {
76
107
  if (!value || typeof value !== 'object' || Array.isArray(value))
77
108
  return;
78
109
  const message = value;
@@ -91,28 +122,37 @@ export async function prepareStrategyInWorker(source, input, options) {
91
122
  finish(() => reject(new Error('behavior_thread_prepare_invalid')));
92
123
  return;
93
124
  }
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
- });
125
+ finish(() => {
126
+ worker.off('message', onMessage);
127
+ worker.off('error', onError);
128
+ worker.off('exit', onExit);
129
+ if (options.retainWorker)
130
+ lease = new StrategyWorkerLease(worker, poolId);
131
+ resolve({
132
+ manifest: structuredClone(message.manifest),
133
+ input: structuredClone(message.input),
134
+ ...(message.timing === undefined ? {} : { timing: structuredClone(message.timing) }),
135
+ source: pinned,
136
+ ...(lease ? { worker: lease } : {}),
137
+ });
138
+ });
139
+ };
140
+ const onError = (error) => finish(() => reject(error));
141
+ const onExit = (code) => finish(() => reject(new Error(`behavior_thread_worker_exited:${code}`)));
142
+ worker.on('message', onMessage);
143
+ worker.once('error', onError);
144
+ worker.once('exit', onExit);
106
145
  });
107
146
  }
108
147
  finally {
109
- await worker.terminate().catch(() => -1);
148
+ if (!lease)
149
+ await worker.terminate().catch(() => -1);
110
150
  }
111
151
  }
112
152
  /** Adaptive Worker Thread pool for cross-tick computations. */
113
153
  export class ThreadStrategyExecutor {
114
154
  snapshotStore;
115
- runtimeInstanceId = randomUUID();
155
+ runtimeInstanceId;
116
156
  maxWorkerCount;
117
157
  maxPendingRequestCount;
118
158
  minWorkerCount;
@@ -136,6 +176,9 @@ export class ThreadStrategyExecutor {
136
176
  desiredWorkerCount;
137
177
  options;
138
178
  constructor(options) {
179
+ this.runtimeInstanceId = options.preparedWorker?.poolId ?? randomUUID();
180
+ if (options.preparedWorker)
181
+ this.nextSlotId = 1;
139
182
  this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
140
183
  this.options = Object.freeze({
141
184
  ...options,
@@ -148,6 +191,9 @@ export class ThreadStrategyExecutor {
148
191
  if (!Number.isInteger(maxWorkerCount) || maxWorkerCount <= 0 || maxWorkerCount > MAX_POOL_SIZE) {
149
192
  throw new TypeError(`poolSize must be between 1 and ${MAX_POOL_SIZE}.`);
150
193
  }
194
+ if (options.initialWorkers !== undefined && (!Number.isInteger(options.initialWorkers) || options.initialWorkers < 1)) {
195
+ throw new Error('behavior_thread_initial_workers_invalid');
196
+ }
151
197
  const idleWorkerTimeoutMs = options.idleWorkerTimeoutMs ?? IDLE_SCALE_DOWN_MS;
152
198
  if (!Number.isFinite(idleWorkerTimeoutMs) || idleWorkerTimeoutMs < 0) {
153
199
  throw new TypeError('idleWorkerTimeoutMs must be a non-negative finite number.');
@@ -156,7 +202,7 @@ export class ThreadStrategyExecutor {
156
202
  this.maxPendingRequestCount = execution === 'serial'
157
203
  ? PARALLEL_STRATEGY_THREAD_POOL_SIZE
158
204
  : maxWorkerCount;
159
- this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
205
+ this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(options.initialWorkers ?? INITIAL_WORKER_COUNT, maxWorkerCount);
160
206
  this.desiredWorkerCount = this.minWorkerCount;
161
207
  this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
162
208
  this.maxOldGenerationSizeMb = Math.max(16, Math.min(256, Math.floor(options.maxOldGenerationSizeMb ?? 64)));
@@ -178,7 +224,13 @@ export class ThreadStrategyExecutor {
178
224
  return Promise.reject(abortError(signal));
179
225
  this.state = 'starting';
180
226
  const startedAt = performance.now();
181
- this.startTask = Promise.all(Array.from({ length: this.minWorkerCount }, () => this.spawnSlot('initial'))).then(() => {
227
+ const prepared = this.options.preparedWorker?.take();
228
+ if (prepared) {
229
+ const slot = { id: 0, worker: prepared, state: 'idle', idleSince: performance.now() };
230
+ this.attachSlot(slot, this.options.source);
231
+ this.startedWorkerCount += 1;
232
+ }
233
+ this.startTask = Promise.all(Array.from({ length: this.minWorkerCount - this.slots.size }, () => this.spawnSlot('initial'))).then(() => {
182
234
  if (this.state !== 'starting')
183
235
  throw new Error('behavior_thread_pool_stopped');
184
236
  this.state = 'running';
@@ -226,6 +278,7 @@ export class ThreadStrategyExecutor {
226
278
  if (this.state === 'stopped')
227
279
  return;
228
280
  if (this.state === 'new') {
281
+ this.options.preparedWorker?.dispose();
229
282
  this.state = 'stopped';
230
283
  return;
231
284
  }
@@ -348,6 +401,11 @@ export class ThreadStrategyExecutor {
348
401
  },
349
402
  });
350
403
  const slot = { id: slotId, worker, state: 'starting' };
404
+ this.attachSlot(slot, source);
405
+ await this.waitForSlot(slot, source, reason);
406
+ }
407
+ attachSlot(slot, source) {
408
+ const { worker, id: slotId } = slot;
351
409
  this.slots.add(slot);
352
410
  worker.stdout?.on('data', (chunk) => this.diagnostic('behavior.thread.stdout', { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length }, 'debug'));
353
411
  worker.stderr?.on('data', (chunk) => this.diagnostic('behavior.thread.stderr', { behavior_id: source.id, slot_id: slot.id, bytes: chunk.length }, 'debug'));
@@ -358,6 +416,8 @@ export class ThreadStrategyExecutor {
358
416
  this.failSlot(slot, new Error(`behavior_thread_worker_exited:${code}`));
359
417
  }
360
418
  });
419
+ }
420
+ async waitForSlot(slot, source, reason) {
361
421
  let timer;
362
422
  try {
363
423
  await new Promise((resolve, reject) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myclaw163/game-agent-runtime",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Game-neutral local agent runtime",
6
6
  "engines": {