@myclaw163/game-agent-runtime 0.1.1 → 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.
@@ -96,6 +96,19 @@ export function resolve(specifier, context, nextResolve) {
96
96
  url: target,
97
97
  });
98
98
  }
99
+ // A retained Strategy Worker evaluates validation and execution in separate
100
+ // module graphs. Carry the validation key through the local dependency tree.
101
+ if (context.parentURL?.includes('gar_strategy_prepare=1') && (specifier.startsWith('./') || specifier.startsWith('../'))) {
102
+ const parent = new URL(context.parentURL);
103
+ parent.searchParams.delete('gar_strategy_prepare');
104
+ const result = resolve(specifier, { ...context, parentURL: parent.href }, nextResolve);
105
+ const target = new URL(result.url);
106
+ if ([...esmModuleRoots].some(root => target.href.startsWith(root))) {
107
+ target.searchParams.set('gar_strategy_prepare', '1');
108
+ return { ...result, url: target.href, shortCircuit: true };
109
+ }
110
+ return result;
111
+ }
99
112
  // The CLI registers tsx before this hook. Letting tsx resolve a queried
100
113
  // user .ts/.tsx entry can percent-encode the query into a CommonJS virtual
101
114
  // URL, which then turns public SDK imports into unresolved require() calls.
@@ -1,4 +1,4 @@
1
- import type { RuntimeEpochPluginInput, RuntimeEventProposal } from '../framework/plugins/contracts.js';
1
+ import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext, RuntimeEventProposal } from '../framework/plugins/contracts.js';
2
2
  import type { EventNotificationContent } from '../framework/events/types.js';
3
3
  import type { StrategyMemory } from '../memory/contracts.js';
4
4
  export interface PerceptionBinding {
@@ -35,6 +35,10 @@ export interface PerceptionResult {
35
35
  readonly key: string;
36
36
  readonly wakeAgent?: boolean;
37
37
  readonly payload: Readonly<Record<string, unknown>>;
38
+ readonly occurredAt?: string;
39
+ }[];
40
+ readonly forwards?: readonly {
41
+ readonly eventId: string;
38
42
  }[];
39
43
  readonly activations?: readonly (PerceptionActivation | {
40
44
  readonly strategy: string;
@@ -58,11 +62,13 @@ export interface PerceptionBoundary {
58
62
  readonly state: unknown;
59
63
  readonly identity?: string;
60
64
  readonly resetModules: boolean;
65
+ readonly resetBindings?: boolean;
61
66
  readonly resetScope: boolean;
62
67
  readonly notificationOnly: boolean;
63
68
  readonly nowMs: number;
64
69
  readonly reflexAllowed: boolean;
65
70
  readonly value: unknown;
71
+ readonly consumeEventsThroughCommitSeq?: number;
66
72
  }
67
73
  export interface PerceptionBindingInput {
68
74
  readonly availableBehaviors: readonly string[];
@@ -72,7 +78,8 @@ export interface PerceptionBindingInput {
72
78
  export interface PerceptionAdapter {
73
79
  reset(): void;
74
80
  recover(checkpoint: unknown): unknown;
75
- prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown): PerceptionBoundary;
81
+ prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown, context?: RuntimeEpochPluginContext<Record<string, any>>): PerceptionBoundary;
82
+ forward?(eventId: string, boundary: PerceptionBoundary, source: PerceptionSource): RuntimeEventProposal;
76
83
  input(source: PerceptionSource, boundary: PerceptionBoundary, inputState: unknown, state: unknown, config: Readonly<Record<string, unknown>>, bindings: PerceptionBindingInput): {
77
84
  invocation: PerceptionInvocation;
78
85
  inputState: unknown;
@@ -10,6 +10,12 @@ export interface PerceptionHostOptions {
10
10
  after: readonly string[];
11
11
  behaviors?: () => readonly ReactionBehaviorCandidate[];
12
12
  adapter: PerceptionAdapter;
13
+ notificationRelay?: RuntimeEpochPlugin['notificationRelay'];
14
+ /** Registration-owned budgets; script manifests cannot change these. */
15
+ resultLimits?: {
16
+ events?: number;
17
+ bytes?: number;
18
+ };
13
19
  }
14
20
  /** Observing and notifications remain active independently of fixed Reflex admission. */
15
21
  export declare class PerceptionHost implements RuntimeEpochPlugin<Record<string, any>> {
@@ -27,9 +33,11 @@ export declare class PerceptionHost implements RuntimeEpochPlugin<Record<string,
27
33
  readonly produces: {
28
34
  events: readonly string[];
29
35
  };
36
+ readonly notificationRelay?: RuntimeEpochPlugin['notificationRelay'];
30
37
  private readonly sources;
31
38
  private readonly runners;
32
39
  private readonly failed;
40
+ private readonly reflexWarnings;
33
41
  private checkpoint;
34
42
  constructor(options: PerceptionHostOptions);
35
43
  private driver?;
@@ -16,13 +16,16 @@ export class PerceptionHost {
16
16
  after;
17
17
  consumes;
18
18
  produces;
19
+ notificationRelay;
19
20
  sources;
20
21
  runners = new Map();
21
22
  failed = new Set();
23
+ reflexWarnings = [];
22
24
  checkpoint = { modules: {}, failures: [] };
23
25
  constructor(options) {
24
26
  this.options = options;
25
27
  this.id = options.id;
28
+ this.notificationRelay = options.notificationRelay;
26
29
  this.sources = options.sources.filter(s => s.module).map(source => ({ ...source, module: normalizePerceptionManifestNames(source.module) })).sort((a, b) => a.id.localeCompare(b.id));
27
30
  this.after = options.after;
28
31
  this.consumes = { events: [...new Set(this.sources.flatMap(source => [...(source.module.consumes ?? [])]))] };
@@ -116,6 +119,7 @@ export class PerceptionHost {
116
119
  this.watches.clear();
117
120
  this.configs.clear();
118
121
  this.checkpoint = { modules: {}, failures: [] };
122
+ this.reflexWarnings.length = 0;
119
123
  this.failed.clear();
120
124
  this.options.adapter.reset();
121
125
  await Promise.all(this.sources.map(async (source, index) => {
@@ -158,26 +162,29 @@ export class PerceptionHost {
158
162
  return this.sources.filter(source => !this.failed.has(source.id)).map(source => this.options.adapter.describe(source, locale));
159
163
  }
160
164
  async update(input, context) {
161
- const prepared = this.options.adapter.prepare(input, this.checkpoint.adapterState);
165
+ const prepared = this.options.adapter.prepare(input, this.checkpoint.adapterState, context);
162
166
  if (prepared.notificationOnly)
163
167
  return { outcome: 'noop', reason: 'notification_only' };
164
168
  this.scope = { ...input.epoch.scope };
165
169
  if (prepared.resetScope)
166
170
  this.checkpoint = { modules: {}, failures: [] };
167
- if (prepared.resetModules)
168
- for (const state of Object.values(this.checkpoint.modules)) {
171
+ for (const state of Object.values(this.checkpoint.modules)) {
172
+ if (prepared.resetModules)
169
173
  state.value = undefined;
170
- for (const binding of Object.values(state.bindings)) {
171
- binding.armed = true;
172
- binding.lastAcceptedAt = undefined;
173
- binding.failedAttempt = undefined;
174
- }
174
+ if (!(prepared.resetBindings ?? prepared.resetModules))
175
+ continue;
176
+ for (const binding of Object.values(state.bindings)) {
177
+ binding.armed = true;
178
+ binding.lastAcceptedAt = undefined;
179
+ binding.failedAttempt = undefined;
175
180
  }
181
+ }
176
182
  this.checkpoint.adapterState = prepared.state;
177
183
  const nowMs = prepared.nowMs;
178
184
  this.lastNow = nowMs;
179
185
  const candidates = this.options.behaviors?.() ?? [];
180
- const events = [];
186
+ const events = this.reflexWarnings.splice(0)
187
+ .filter(warning => warning.current()).map(warning => warning.event);
181
188
  const requests = [];
182
189
  const results = await mapConcurrent(this.sources, 4, async (source) => {
183
190
  const events = [];
@@ -213,7 +220,11 @@ export class PerceptionHost {
213
220
  for (const event of result.events ?? []) {
214
221
  const proposal = { type: event.type,
215
222
  dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
216
- payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() };
223
+ payload: { ...event.payload }, occurredAt: event.occurredAt ?? new Date(nowMs).toISOString() };
224
+ events.push({ ...proposal, notificationContent: this.options.adapter.notification(proposal, prepared, source) });
225
+ }
226
+ for (const forward of result.forwards ?? []) {
227
+ const proposal = this.options.adapter.forward(forward.eventId, prepared, source);
217
228
  events.push({ ...proposal, notificationContent: this.options.adapter.notification(proposal, prepared, source) });
218
229
  }
219
230
  const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
@@ -270,6 +281,8 @@ export class PerceptionHost {
270
281
  const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
271
282
  if (state.failedAttempt === attempt)
272
283
  continue;
284
+ const current = () => !this.stopped && !context.signal.aborted && generation === this.generation
285
+ && !!behavior && this.watches.has(behavior) && this.sameScope(input.epoch.scope);
273
286
  let result = { accepted: false, reason: 'behavior_not_loaded' };
274
287
  if (behavior && this.watches.has(behavior)) {
275
288
  try {
@@ -278,53 +291,81 @@ export class PerceptionHost {
278
291
  epochId: input.epoch.epochSeq, configGeneration: generation, behavior,
279
292
  behaviorInput: { ...binding.input, ...activation.input }, reflexPriority: binding.reflexPriority ?? 0,
280
293
  maxRuntimeMs: binding.maxRuntimeMs ?? 10_000,
281
- reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` }, { isCurrent: () => !this.stopped && !context.signal.aborted && generation === this.generation
282
- && this.watches.has(behavior) && this.sameScope(input.epoch.scope) })
294
+ reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` }, { isCurrent: current })
283
295
  ?? { accepted: false, reason: 'activation_unavailable' };
284
296
  }
285
297
  catch {
286
298
  result = { accepted: false, reason: 'activation_unavailable' };
287
299
  }
288
300
  }
289
- if (result.accepted) {
301
+ const accept = (acceptedAt) => {
290
302
  state.armed = false;
291
- state.lastAcceptedAt = nowMs;
303
+ state.lastAcceptedAt = acceptedAt;
292
304
  state.warning = undefined;
293
305
  state.failedAttempt = undefined;
294
- }
295
- else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
296
- const reason = result.reason ?? 'activation_unavailable';
306
+ };
307
+ const reject = (reason) => {
297
308
  state.failedAttempt = attempt;
298
- if (state.warning !== reason) {
299
- state.warning = reason;
300
- state.warningSequence++;
301
- events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
302
- dedupeKey: JSON.stringify([prepared.identity, source.id, activation.behavior, state.warningSequence]),
303
- payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
304
- ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
305
- ...(behavior ? { behavior_id: behavior } : {}), reason,
306
- text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
307
- }
309
+ if (state.warning === reason)
310
+ return undefined;
311
+ state.warning = reason;
312
+ state.warningSequence++;
313
+ return { type: 'perception.behavior_unavailable', wakeAgent: true,
314
+ dedupeKey: JSON.stringify([prepared.identity, source.id, activation.behavior, state.warningSequence]),
315
+ payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
316
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
317
+ ...(behavior ? { behavior_id: behavior } : {}), reason,
318
+ text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } };
319
+ };
320
+ if (result.accepted && result.ready) {
321
+ void result.ready.then(outcome => {
322
+ if (!current())
323
+ return;
324
+ if (outcome === 'ready')
325
+ accept(this.lastNow ?? nowMs);
326
+ if (outcome === 'invalid') {
327
+ const event = reject('binding_invalid');
328
+ if (event)
329
+ this.reflexWarnings.push({ event, current });
330
+ }
331
+ });
332
+ }
333
+ else if (result.accepted) {
334
+ accept(nowMs);
335
+ }
336
+ else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason)) {
337
+ const event = reject(result.reason);
338
+ if (event)
339
+ events.push(event);
308
340
  }
309
341
  }
310
342
  return { outcome: 'processed', events: events.map(event => ({ ...event,
311
343
  notificationContent: event.notificationContent ?? this.options.adapter.notification(event, prepared) })), checkpoint: structuredClone(this.checkpoint),
312
- ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1).commitSeq } : {}) };
344
+ ...(prepared.consumeEventsThroughCommitSeq !== undefined
345
+ ? { consumeEventsThroughCommitSeq: prepared.consumeEventsThroughCommitSeq }
346
+ : input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1).commitSeq } : {}) };
313
347
  }
314
348
  validate(result, source) {
315
- if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
349
+ if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'forwards', 'activations'].includes(key))
316
350
  || result.events !== undefined && !Array.isArray(result.events)
317
351
  || result.activations !== undefined && !Array.isArray(result.activations)
318
- || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
319
- || Buffer.byteLength(JSON.stringify(result)) > 128_000)
352
+ || result.forwards !== undefined && (!this.notificationRelay || !this.options.adapter.forward || !Array.isArray(result.forwards))
353
+ || (result.events?.length ?? 0) > (this.options.resultLimits?.events ?? 32) || (result.activations?.length ?? 0) > 16
354
+ || Buffer.byteLength(JSON.stringify(result)) > (this.options.resultLimits?.bytes ?? 128_000))
320
355
  throw new Error('REACTION_OUTPUT_INVALID');
321
356
  for (const event of result.events ?? []) {
322
357
  if (!record(event) || !source.module.produces?.includes(event.type)
323
358
  || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
324
359
  || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
360
+ || event.occurredAt !== undefined && (typeof event.occurredAt !== 'string' || !Number.isFinite(Date.parse(event.occurredAt)))
325
361
  || !record(event.payload))
326
362
  throw new Error('REACTION_EVENT_INVALID');
327
363
  }
364
+ for (const forward of result.forwards ?? []) {
365
+ if (!record(forward) || typeof forward.eventId !== 'string' || !forward.eventId
366
+ || Object.keys(forward).some(key => key !== 'eventId'))
367
+ throw Error('PERCEPTION_FORWARD_INVALID');
368
+ }
328
369
  const bindings = new Set();
329
370
  for (const activation of result.activations ?? []) {
330
371
  if (!record(activation) || typeof activation.behavior !== 'string' || !Object.hasOwn(source.module.behaviors ?? {}, activation.behavior)
@@ -83,6 +83,8 @@ export declare class BehaviorActivationManager {
83
83
  cancel(activationId: string, reason: string, now: number): readonly BehaviorActivationTransition[];
84
84
  advance(now: number): readonly BehaviorActivationTransition[];
85
85
  current(): BehaviorActivationSnapshot | undefined;
86
+ /** Install normalized input before an asynchronously prepared activation gets control. */
87
+ setPreparedInput(activationId: string, generation: number, input: Readonly<Record<string, unknown>>, now: number): void;
86
88
  /** New immutable input, same activation and deadline; old decision generations expire. */
87
89
  updateInput(activationId: string, input: Readonly<Record<string, unknown>>, now: number): readonly BehaviorActivationTransition[];
88
90
  updateFallbackInput(behaviorId: string, input: Readonly<Record<string, unknown>>): void;
@@ -255,6 +255,17 @@ export class BehaviorActivationManager {
255
255
  current() {
256
256
  return this.snapshotActivation(this.reflex ?? this.short ?? (this.long?.state === 'running' ? this.long : undefined));
257
257
  }
258
+ /** Install normalized input before an asynchronously prepared activation gets control. */
259
+ setPreparedInput(activationId, generation, input, now) {
260
+ const layer = this.findLayer(activationId);
261
+ const activation = layer ? this[layer] : undefined;
262
+ if (!activation || activation.instanceGeneration !== generation)
263
+ return;
264
+ activation.spec = { ...activation.spec, input: cloneInput(input) };
265
+ activation.startedAt = now;
266
+ if (activation.spec.maxRuntimeMs !== undefined)
267
+ activation.deadlineAt = now + activation.spec.maxRuntimeMs;
268
+ }
258
269
  /** New immutable input, same activation and deadline; old decision generations expire. */
259
270
  updateInput(activationId, input, now) {
260
271
  const active = [this.long, this.short, this.reflex].find(entry => entry?.spec.activationId === activationId);
@@ -99,6 +99,7 @@ export interface PreparedStrategy {
99
99
  readonly createModule?: () => object;
100
100
  readonly source?: unknown;
101
101
  readonly value: unknown;
102
+ readonly discardWorker?: () => void;
102
103
  }
103
104
  export interface StrategyObservation {
104
105
  readonly revision: number;
@@ -178,6 +179,7 @@ export type ReflexResult = Readonly<{
178
179
  accepted: true;
179
180
  activationId: string;
180
181
  replacedActivationId?: string;
182
+ ready?: Promise<'ready' | 'invalid' | 'cancelled'>;
181
183
  }> | Readonly<{
182
184
  accepted: false;
183
185
  reason: string;
@@ -1,5 +1,5 @@
1
1
  import { StrategyMemoryStore } from '../memory/strategy-memory.js';
2
- import type { RuntimeEpochCatchUp, RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../framework/plugins/contracts.js';
2
+ import type { RuntimeEpochCatchUp, RuntimeEpochFlushReason, RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../framework/plugins/contracts.js';
3
3
  import { BehaviorActivationManager, type BehaviorActivationSnapshot, type BehaviorActivationSource } from './activation-manager.js';
4
4
  import type { StrategyControlDriver } from './control-driver.js';
5
5
  import type { StrategyAdapter, PreparedStrategy, ReflexDriver, ReflexRequest, ReflexResult } from './contracts.js';
@@ -19,6 +19,7 @@ export interface StrategyHostOptions {
19
19
  readonly catalog: {
20
20
  has(id: string): boolean;
21
21
  prepare(id: string, input: Readonly<Record<string, unknown>>): PreparedStrategy | Promise<PreparedStrategy>;
22
+ prepareForActivation?(id: string, input: Readonly<Record<string, unknown>>): Promise<PreparedStrategy>;
22
23
  };
23
24
  readonly fallbackBehaviors?: StrategyFallbackBindings;
24
25
  readonly manager?: BehaviorActivationManager;
@@ -85,8 +86,13 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
85
86
  private readonly pendingLifecycleEvents;
86
87
  private readonly decisionControllers;
87
88
  private controlTail;
89
+ private readonly startRequests;
90
+ private readonly deferredDelegations;
91
+ private readonly deferredReflexes;
92
+ private pendingPreparations;
88
93
  private driver?;
89
94
  private scope?;
95
+ private scopeClosing;
90
96
  private diagnostic?;
91
97
  private boundaryActive;
92
98
  private stopped;
@@ -133,16 +139,22 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
133
139
  }>): Promise<ReflexResult>;
134
140
  update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult>;
135
141
  commit(input: RuntimeEpochPluginInput<Record<string, any>>, computation: Readonly<RuntimeEpochPluginResult>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult>;
142
+ flush(reason: RuntimeEpochFlushReason): void;
136
143
  stop(reason: 'segment_ending' | 'shutdown'): Promise<void>;
137
144
  private startLayer;
145
+ private sameScope;
146
+ private activateLayer;
138
147
  private commitOrdered;
139
148
  private applyDecision;
149
+ private deferDelegation;
140
150
  private prepareDelegatedShort;
141
151
  private startDelegatedShort;
142
152
  private finishCurrent;
143
153
  private failCurrent;
144
154
  private applyTransitions;
145
155
  private captureDelegationResults;
156
+ private deferRunner;
157
+ private acquireControl;
146
158
  private ensureRuntime;
147
159
  private syncRoleFallback;
148
160
  /**
@@ -161,5 +173,6 @@ export declare class StrategyHost implements RuntimeEpochPlugin<Record<string, a
161
173
  private output;
162
174
  private withDecisionTimeout;
163
175
  private interruptDecisions;
176
+ private inBackground;
164
177
  private enqueueControl;
165
178
  }
@@ -134,8 +134,13 @@ export class StrategyHost {
134
134
  pendingLifecycleEvents = [];
135
135
  decisionControllers = new Map();
136
136
  controlTail = Promise.resolve();
137
+ startRequests = new Map();
138
+ deferredDelegations = new Map();
139
+ deferredReflexes = new Map();
140
+ pendingPreparations = 0;
137
141
  driver;
138
142
  scope;
143
+ scopeClosing = false;
139
144
  diagnostic;
140
145
  boundaryActive = false;
141
146
  stopped = false;
@@ -195,6 +200,7 @@ export class StrategyHost {
195
200
  }
196
201
  async start(context) {
197
202
  this.scope = context.scope;
203
+ this.scopeClosing = false;
198
204
  this.memory.open(context.scope);
199
205
  this.diagnostic = context.diagnostic;
200
206
  this.stopped = false;
@@ -216,6 +222,7 @@ export class StrategyHost {
216
222
  current_behavior_id: status.current?.behaviorId ?? null,
217
223
  current_layer: status.current?.layer ?? null,
218
224
  runtime_count: this.runtimes.size,
225
+ pending_preparations: this.pendingPreparations,
219
226
  runtimes: [...this.runtimes.values()].map((runtime) => ({
220
227
  activation_id: runtime.activationId,
221
228
  behavior_id: runtime.behaviorId,
@@ -244,6 +251,7 @@ export class StrategyHost {
244
251
  bindFallback(behaviorId, input) {
245
252
  return this.enqueueControl(async () => {
246
253
  const prepared = await this.prepareInput(behaviorId, input);
254
+ this.fallbackPrepared?.discardWorker?.();
247
255
  this.manualFallbackOverride = true;
248
256
  this.fallbackPrepared = prepared;
249
257
  this.fallbackBaseInput = { behaviorId, input: structuredClone(input) };
@@ -257,6 +265,7 @@ export class StrategyHost {
257
265
  clearFallback() {
258
266
  return this.enqueueControl(async () => {
259
267
  this.manualFallbackOverride = true;
268
+ this.fallbackPrepared?.discardWorker?.();
260
269
  this.fallbackPrepared = undefined;
261
270
  this.fallbackBaseInput = undefined;
262
271
  this.fallbackPreparedUsed = false;
@@ -319,6 +328,7 @@ export class StrategyHost {
319
328
  await this.replacePreparedInputs(updates, guard);
320
329
  this.inputDefaults.set(behaviorId, structuredClone(input));
321
330
  if (this.manager.snapshot().fallback?.behaviorId === behaviorId) {
331
+ this.fallbackPrepared?.discardWorker?.();
322
332
  this.fallbackPrepared = defaults;
323
333
  this.fallbackPreparedUsed = false;
324
334
  this.manager.updateFallbackInput(behaviorId, defaults.input);
@@ -326,8 +336,11 @@ export class StrategyHost {
326
336
  return updates.length;
327
337
  });
328
338
  }
329
- prepareInput(behaviorId, input) {
330
- return this.catalog.prepare(behaviorId, { ...this.inputDefaults.get(behaviorId), ...input });
339
+ prepareInput(behaviorId, input, activation = false) {
340
+ const parameters = { ...this.inputDefaults.get(behaviorId), ...input };
341
+ return activation && this.catalog.prepareForActivation
342
+ ? this.catalog.prepareForActivation(behaviorId, parameters)
343
+ : this.catalog.prepare(behaviorId, parameters);
331
344
  }
332
345
  async updateActivationInput(activationId, patch, guard) {
333
346
  if (!guard())
@@ -384,11 +397,13 @@ export class StrategyHost {
384
397
  if (!this.catalog.has(request.behavior))
385
398
  return { accepted: false, reason: 'binding_invalid' };
386
399
  let prepared;
387
- try {
388
- prepared = await this.prepareInput(request.behavior, request.behaviorInput);
389
- }
390
- catch {
391
- return { accepted: false, reason: 'binding_invalid' };
400
+ if (!this.catalog.prepareForActivation) {
401
+ try {
402
+ prepared = await this.prepareInput(request.behavior, request.behaviorInput);
403
+ }
404
+ catch {
405
+ return { accepted: false, reason: 'binding_invalid' };
406
+ }
392
407
  }
393
408
  if (guard && !guard.isCurrent())
394
409
  return { accepted: false, reason: 'stale_request' };
@@ -417,7 +432,7 @@ export class StrategyHost {
417
432
  const transitions = this.manager.requestReflex({
418
433
  activationId,
419
434
  behaviorId: request.behavior,
420
- input: prepared.input,
435
+ input: prepared?.input ?? request.behaviorInput,
421
436
  requestedAt: this.now(),
422
437
  maxRuntimeMs: request.maxRuntimeMs,
423
438
  deadlineOutcome: 'failed',
@@ -434,18 +449,22 @@ export class StrategyHost {
434
449
  : 'reflex_priority_not_higher',
435
450
  };
436
451
  }
437
- this.runtimes.set(activationId, {
438
- activationId,
439
- behaviorId: request.behavior,
440
- prepared,
441
- decisionHistory: new BehaviorDecisionHistory(),
442
- committedActionDedupeKeys: new Map(),
443
- });
452
+ let ready;
453
+ if (prepared) {
454
+ this.runtimes.set(activationId, {
455
+ activationId, behaviorId: request.behavior, prepared,
456
+ decisionHistory: new BehaviorDecisionHistory(), committedActionDedupeKeys: new Map(),
457
+ });
458
+ }
459
+ else {
460
+ ready = new Promise(settle => this.deferredReflexes.set(activationId, { guard, settle }));
461
+ }
444
462
  const replaced = transitions.find((entry) => entry.type === 'replaced');
445
463
  await this.applyTransitions(transitions);
446
464
  return {
447
465
  accepted: true,
448
466
  activationId,
467
+ ...(ready ? { ready } : {}),
449
468
  ...(replaced === undefined ? {} : { replacedActivationId: replaced.activationId }),
450
469
  };
451
470
  });
@@ -617,12 +636,17 @@ export class StrategyHost {
617
636
  return result;
618
637
  });
619
638
  }
639
+ flush(reason) {
640
+ if (reason === 'segment_ending' || reason === 'shutdown')
641
+ this.scopeClosing = true;
642
+ }
620
643
  async stop(reason) {
621
644
  await this.enqueueControl(async () => {
622
645
  this.stopped = true;
623
646
  if (this.scope)
624
647
  this.memory.close(this.scope);
625
648
  this.resetBackendStrategyReporting();
649
+ this.fallbackPrepared?.discardWorker?.();
626
650
  for (const controllers of this.decisionControllers.values()) {
627
651
  for (const controller of controllers)
628
652
  controller.abort(new Error(reason));
@@ -630,6 +654,7 @@ export class StrategyHost {
630
654
  this.decisionControllers.clear();
631
655
  const runnerReason = reason === 'shutdown' ? 'shutdown' : 'scope_ended';
632
656
  const runners = [...this.runtimes.values()].flatMap((runtime) => {
657
+ runtime.prepared.discardWorker?.();
633
658
  const runner = runtime.runner;
634
659
  runtime.runner = undefined;
635
660
  runtime.instanceGeneration = undefined;
@@ -648,6 +673,11 @@ export class StrategyHost {
648
673
  this.appliedFallbackKey = undefined;
649
674
  }
650
675
  this.delegatedShorts.clear();
676
+ this.deferredDelegations.clear();
677
+ for (const pending of this.deferredReflexes.values())
678
+ pending.settle('cancelled');
679
+ this.deferredReflexes.clear();
680
+ this.startRequests.clear();
651
681
  this.finishSummaries.clear();
652
682
  for (const handle of this.controls.values())
653
683
  handle.release(reason);
@@ -660,47 +690,74 @@ export class StrategyHost {
660
690
  this.lastCommittedEpochSeq = 0;
661
691
  });
662
692
  }
663
- startLayer(layer, behaviorId, input, options) {
664
- return this.enqueueControl(async () => {
665
- if (this.stopped || !this.scope)
666
- throw new Error('behavior_host_not_active');
667
- const prepared = await this.prepareInput(behaviorId, input);
668
- if (options.isCurrent && !options.isCurrent())
669
- throw new Error('perception_activation_stale');
670
- const activationId = this.createActivationId();
671
- const maxRuntimeMs = layer === 'short'
672
- ? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
673
- : options.maxRuntimeMs;
674
- const outcome = maxRuntimeMs === undefined
675
- ? undefined
676
- : deadlineOutcome(prepared, input) ?? 'failed';
677
- const spec = {
678
- activationId,
679
- behaviorId,
680
- source: options.source,
681
- input: prepared.input,
682
- requestedAt: this.now(),
683
- ...(maxRuntimeMs === undefined ? {} : {
684
- maxRuntimeMs,
685
- deadlineOutcome: outcome,
686
- }),
687
- };
688
- this.runtimes.set(activationId, {
689
- activationId,
690
- behaviorId,
691
- prepared,
692
- decisionHistory: new BehaviorDecisionHistory(),
693
- committedActionDedupeKeys: new Map(),
693
+ async startLayer(layer, behaviorId, input, options) {
694
+ const scope = this.scope;
695
+ if (this.stopped || this.scopeClosing || !scope)
696
+ throw new Error('behavior_host_not_active');
697
+ if (!this.catalog.prepareForActivation) {
698
+ return this.enqueueControl(async () => this.activateLayer(layer, behaviorId, input, options, await this.prepareInput(behaviorId, input)));
699
+ }
700
+ const request = {};
701
+ this.startRequests.set(layer, request);
702
+ let prepared;
703
+ try {
704
+ const ready = prepared = await this.prepareInput(behaviorId, input, true);
705
+ return await this.enqueueControl(() => {
706
+ if (!this.sameScope(scope) || this.startRequests.get(layer) !== request)
707
+ throw new Error('behavior_start_superseded');
708
+ return this.activateLayer(layer, behaviorId, input, options, ready);
694
709
  });
695
- const transitions = layer === 'long'
696
- ? this.manager.startLong(spec, this.now())
697
- : this.manager.startShort(spec, this.now());
698
- await this.applyTransitions(transitions);
699
- const snapshot = currentRuntimeSnapshot(this.manager, activationId);
700
- if (!snapshot)
701
- throw new Error('behavior_activation_start_failed');
702
- return snapshot;
710
+ }
711
+ catch (error) {
712
+ prepared?.discardWorker?.();
713
+ throw error;
714
+ }
715
+ finally {
716
+ if (this.startRequests.get(layer) === request)
717
+ this.startRequests.delete(layer);
718
+ }
719
+ }
720
+ sameScope(scope) {
721
+ return !this.stopped && !this.scopeClosing && this.scope?.sessionId === scope.sessionId && this.scope.segmentId === scope.segmentId;
722
+ }
723
+ async activateLayer(layer, behaviorId, input, options, prepared) {
724
+ if (this.stopped || !this.scope)
725
+ throw new Error('behavior_host_not_active');
726
+ if (options.isCurrent && !options.isCurrent())
727
+ throw new Error('perception_activation_stale');
728
+ const activationId = this.createActivationId();
729
+ const maxRuntimeMs = layer === 'short'
730
+ ? runtimeMs(prepared, input, options.maxRuntimeMs) ?? DEFAULT_SHORT_MAX_RUNTIME_MS
731
+ : options.maxRuntimeMs;
732
+ const outcome = maxRuntimeMs === undefined
733
+ ? undefined
734
+ : deadlineOutcome(prepared, input) ?? 'failed';
735
+ const spec = {
736
+ activationId,
737
+ behaviorId,
738
+ source: options.source,
739
+ input: prepared.input,
740
+ requestedAt: this.now(),
741
+ ...(maxRuntimeMs === undefined ? {} : {
742
+ maxRuntimeMs,
743
+ deadlineOutcome: outcome,
744
+ }),
745
+ };
746
+ this.runtimes.set(activationId, {
747
+ activationId,
748
+ behaviorId,
749
+ prepared,
750
+ decisionHistory: new BehaviorDecisionHistory(),
751
+ committedActionDedupeKeys: new Map(),
703
752
  });
753
+ const transitions = layer === 'long'
754
+ ? this.manager.startLong(spec, this.now())
755
+ : this.manager.startShort(spec, this.now());
756
+ await this.applyTransitions(transitions);
757
+ const snapshot = currentRuntimeSnapshot(this.manager, activationId);
758
+ if (!snapshot)
759
+ throw new Error('behavior_activation_start_failed');
760
+ return snapshot;
704
761
  }
705
762
  async commitOrdered(input, computed, context) {
706
763
  this.scope = context.scope;
@@ -860,7 +917,7 @@ export class StrategyHost {
860
917
  if (decision.delegate && activation.layer !== 'long') {
861
918
  throw new Error('behavior_delegate_layer_invalid');
862
919
  }
863
- const delegated = decision.delegate === undefined
920
+ const delegated = decision.delegate === undefined || this.catalog.prepareForActivation
864
921
  ? undefined
865
922
  : await this.prepareDelegatedShort(decision.delegate);
866
923
  const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
@@ -941,6 +998,9 @@ export class StrategyHost {
941
998
  runtime.lastStatus = decision.status ?? runtime.lastStatus;
942
999
  await this.startDelegatedShort(activation, delegated, frame.nowMs);
943
1000
  }
1001
+ else if (decision.delegate) {
1002
+ this.deferDelegation(activation, decision.delegate, context.scope);
1003
+ }
944
1004
  else if (decision.finish) {
945
1005
  await this.finishCurrent(activation, decision.finish, frame.nowMs);
946
1006
  }
@@ -949,10 +1009,36 @@ export class StrategyHost {
949
1009
  events,
950
1010
  };
951
1011
  }
952
- async prepareDelegatedShort(delegation) {
1012
+ deferDelegation(parent, delegation, scope) {
1013
+ const { activationId, instanceGeneration } = parent;
1014
+ if (this.deferredDelegations.get(activationId) === instanceGeneration)
1015
+ return;
1016
+ this.deferredDelegations.set(activationId, instanceGeneration);
1017
+ const current = () => this.sameScope(scope) && this.manager.isCurrent(activationId, instanceGeneration);
1018
+ setImmediate(() => {
1019
+ if (!current()) {
1020
+ if (this.deferredDelegations.get(activationId) === instanceGeneration)
1021
+ this.deferredDelegations.delete(activationId);
1022
+ return;
1023
+ }
1024
+ void this.prepareDelegatedShort(delegation, true).then(delegated => this.enqueueControl(async () => {
1025
+ if (!current())
1026
+ delegated.prepared.discardWorker?.();
1027
+ else
1028
+ await this.startDelegatedShort(parent, delegated, this.now());
1029
+ })).catch(error => this.enqueueControl(async () => {
1030
+ if (current())
1031
+ await this.failCurrent(parent, errorCode(error, 'BEHAVIOR_DECISION_INVALID'), this.now());
1032
+ })).finally(() => {
1033
+ if (this.deferredDelegations.get(activationId) === instanceGeneration)
1034
+ this.deferredDelegations.delete(activationId);
1035
+ }).catch(error => this.diagnostic?.('behavior.delegation.failed', { error_code: errorCode(error) }, 'warn'));
1036
+ });
1037
+ }
1038
+ async prepareDelegatedShort(delegation, activation = false) {
953
1039
  const rawInput = delegation.input ?? Object.freeze({});
954
1040
  const target = 'strategy' in delegation ? delegation.strategy : delegation.behavior;
955
- const prepared = await this.prepareInput(target, rawInput);
1041
+ const prepared = await this.prepareInput(target, rawInput, activation);
956
1042
  return Object.freeze({
957
1043
  behaviorId: target,
958
1044
  rawInput: Object.freeze(structuredClone(rawInput)),
@@ -1002,6 +1088,8 @@ export class StrategyHost {
1002
1088
  async applyTransitions(transitions) {
1003
1089
  this.captureDelegationResults(transitions);
1004
1090
  for (const transition of transitions) {
1091
+ if (this.catalog.prepareForActivation && (transition.type === 'started' || transition.type === 'restarted'))
1092
+ continue;
1005
1093
  const event = lifecycleEvent(transition);
1006
1094
  if (event)
1007
1095
  this.pendingLifecycleEvents.push(event);
@@ -1016,17 +1104,13 @@ export class StrategyHost {
1016
1104
  const snapshot = currentRuntimeSnapshot(this.manager, transition.activationId);
1017
1105
  if (!snapshot)
1018
1106
  continue;
1107
+ if (this.catalog.prepareForActivation && this.scope) {
1108
+ this.deferRunner(snapshot, transition, this.scope);
1109
+ continue;
1110
+ }
1019
1111
  try {
1020
- const runtime = await this.ensureRuntime(snapshot);
1021
- if (!this.driver || !this.scope)
1022
- throw new Error('behavior_control_driver_unavailable');
1023
- const handle = await this.driver.acquire(snapshot, this.scope);
1024
- if (handle.caller.activationId !== snapshot.activationId
1025
- || handle.caller.layer !== snapshot.layer
1026
- || handle.caller.activationGeneration !== snapshot.instanceGeneration)
1027
- throw new Error('behavior_control_handle_invalid');
1028
- this.controls.set(snapshot.activationId, handle);
1029
- runtime.instanceGeneration = snapshot.instanceGeneration;
1112
+ await this.ensureRuntime(snapshot);
1113
+ await this.acquireControl(snapshot);
1030
1114
  }
1031
1115
  catch (error) {
1032
1116
  this.diagnostic?.('behavior.activation.failed', {
@@ -1047,13 +1131,22 @@ export class StrategyHost {
1047
1131
  this.controls.get(transition.activationId)?.release(`behavior_${transition.type}:${transition.reason}`);
1048
1132
  this.controls.delete(transition.activationId);
1049
1133
  const runtime = this.runtimes.get(transition.activationId);
1050
- await runtime?.runner?.stop('switched');
1134
+ const stopped = runtime?.runner?.stop('switched');
1135
+ runtime?.prepared.discardWorker?.();
1136
+ if (this.catalog.prepareForActivation) {
1137
+ void stopped?.catch(error => this.diagnostic?.('behavior.runner.stop_failed', { error_code: errorCode(error) }, 'warn'));
1138
+ }
1139
+ else
1140
+ await stopped;
1051
1141
  if (runtime) {
1052
1142
  runtime.runner = undefined;
1053
1143
  runtime.instanceGeneration = undefined;
1054
1144
  }
1055
- if (transition.type !== 'suspended')
1145
+ if (transition.type !== 'suspended') {
1056
1146
  this.runtimes.delete(transition.activationId);
1147
+ this.deferredReflexes.get(transition.activationId)?.settle('cancelled');
1148
+ this.deferredReflexes.delete(transition.activationId);
1149
+ }
1057
1150
  }
1058
1151
  }
1059
1152
  if (failures.length > 0)
@@ -1094,7 +1187,58 @@ export class StrategyHost {
1094
1187
  }
1095
1188
  }
1096
1189
  }
1097
- async ensureRuntime(activation) {
1190
+ deferRunner(snapshot, transition, scope) {
1191
+ const current = () => this.sameScope(scope) && this.manager.isCurrent(snapshot.activationId, snapshot.instanceGeneration);
1192
+ this.inBackground(async () => {
1193
+ if (!current())
1194
+ return;
1195
+ try {
1196
+ const runtime = await this.ensureRuntime(snapshot, current);
1197
+ await this.enqueueControl(async () => {
1198
+ if (!current() || this.runtimes.get(snapshot.activationId) !== runtime
1199
+ || runtime.instanceGeneration !== snapshot.instanceGeneration)
1200
+ return;
1201
+ const pending = this.deferredReflexes.get(snapshot.activationId);
1202
+ if (pending?.guard && !pending.guard.isCurrent()) {
1203
+ await this.applyTransitions(this.manager.cancel(snapshot.activationId, 'behavior_reflex_superseded', this.now()));
1204
+ return;
1205
+ }
1206
+ if (pending)
1207
+ this.manager.setPreparedInput(snapshot.activationId, snapshot.instanceGeneration, runtime.prepared.input, this.now());
1208
+ await this.acquireControl(snapshot);
1209
+ pending?.settle('ready');
1210
+ this.deferredReflexes.delete(snapshot.activationId);
1211
+ const event = lifecycleEvent(transition);
1212
+ if (event)
1213
+ this.pendingLifecycleEvents.push(event);
1214
+ });
1215
+ }
1216
+ catch (error) {
1217
+ await this.enqueueControl(async () => {
1218
+ if (!current())
1219
+ return;
1220
+ this.deferredReflexes.get(snapshot.activationId)?.settle('invalid');
1221
+ this.deferredReflexes.delete(snapshot.activationId);
1222
+ const reason = errorCode(error, 'BEHAVIOR_ACTIVATION_FAILED');
1223
+ this.diagnostic?.('behavior.activation.failed', { behavior_id: snapshot.behaviorId,
1224
+ activation_id: snapshot.activationId, instance_generation: snapshot.instanceGeneration, error_code: reason }, 'error');
1225
+ await this.failCurrent(snapshot, reason, this.now());
1226
+ });
1227
+ }
1228
+ });
1229
+ }
1230
+ async acquireControl(snapshot) {
1231
+ if (!this.driver || !this.scope)
1232
+ throw new Error('behavior_control_driver_unavailable');
1233
+ const handle = await this.driver.acquire(snapshot, this.scope);
1234
+ if (handle.caller.activationId !== snapshot.activationId || handle.caller.layer !== snapshot.layer
1235
+ || handle.caller.activationGeneration !== snapshot.instanceGeneration) {
1236
+ handle.release('behavior_control_handle_invalid');
1237
+ throw new Error('behavior_control_handle_invalid');
1238
+ }
1239
+ this.controls.set(snapshot.activationId, handle);
1240
+ }
1241
+ async ensureRuntime(activation, current = () => true) {
1098
1242
  let runtime = this.runtimes.get(activation.activationId);
1099
1243
  if (!runtime) {
1100
1244
  let prepared;
@@ -1111,7 +1255,11 @@ export class StrategyHost {
1111
1255
  this.fallbackPreparedUsed = true;
1112
1256
  }
1113
1257
  else {
1114
- prepared = await this.prepareInput(activation.behaviorId, activation.input);
1258
+ prepared = await this.prepareInput(activation.behaviorId, activation.input, true);
1259
+ }
1260
+ if (!current()) {
1261
+ prepared.discardWorker?.();
1262
+ throw new Error('behavior_activation_superseded');
1115
1263
  }
1116
1264
  runtime = {
1117
1265
  activationId: activation.activationId,
@@ -1122,7 +1270,10 @@ export class StrategyHost {
1122
1270
  };
1123
1271
  this.runtimes.set(activation.activationId, runtime);
1124
1272
  }
1125
- await runtime.runner?.stop('switched');
1273
+ if (runtime.runner)
1274
+ await runtime.runner.stop('switched');
1275
+ if (!current())
1276
+ throw new Error('behavior_activation_superseded');
1126
1277
  const prepared = runtime.instanceGeneration === undefined && activation.instanceGeneration === 1
1127
1278
  ? runtime.prepared
1128
1279
  : Object.freeze({
@@ -1160,23 +1311,25 @@ export class StrategyHost {
1160
1311
  return;
1161
1312
  this.appliedFallbackKey = key;
1162
1313
  if (!configured) {
1314
+ this.fallbackPrepared?.discardWorker?.();
1163
1315
  this.fallbackPrepared = undefined;
1164
1316
  this.fallbackBaseInput = undefined;
1165
1317
  this.fallbackPreparedUsed = false;
1166
1318
  await this.applyTransitions(this.manager.bindFallback(undefined, now));
1167
1319
  return;
1168
1320
  }
1169
- try {
1170
- const prepared = await this.prepareInput(configured.behaviorId, configured.input ?? {});
1321
+ const apply = async (prepared) => {
1322
+ this.fallbackPrepared?.discardWorker?.();
1171
1323
  this.fallbackPrepared = prepared;
1172
1324
  this.fallbackBaseInput = { behaviorId: configured.behaviorId, input: structuredClone(configured.input ?? {}) };
1173
1325
  this.fallbackPreparedUsed = false;
1174
1326
  await this.applyTransitions(this.manager.bindFallback({
1175
1327
  behaviorId: configured.behaviorId,
1176
1328
  input: prepared.input,
1177
- }, now, true));
1178
- }
1179
- catch (error) {
1329
+ }, this.now(), true));
1330
+ };
1331
+ const reject = async (error) => {
1332
+ this.fallbackPrepared?.discardWorker?.();
1180
1333
  this.fallbackPrepared = undefined;
1181
1334
  this.fallbackBaseInput = undefined;
1182
1335
  this.fallbackPreparedUsed = false;
@@ -1186,6 +1339,34 @@ export class StrategyHost {
1186
1339
  behavior_id: configured.behaviorId,
1187
1340
  error_code: errorCode(error, 'BEHAVIOR_FALLBACK_INVALID'),
1188
1341
  }, 'warn');
1342
+ };
1343
+ const scope = this.scope;
1344
+ if (this.catalog.prepareForActivation && scope) {
1345
+ const current = () => this.sameScope(scope) && !this.manualFallbackOverride && this.appliedFallbackKey === key;
1346
+ this.inBackground(async () => {
1347
+ if (!current())
1348
+ return;
1349
+ try {
1350
+ const prepared = await this.prepareInput(configured.behaviorId, configured.input ?? {}, true);
1351
+ await this.enqueueControl(async () => {
1352
+ if (current())
1353
+ await apply(prepared);
1354
+ else
1355
+ prepared.discardWorker?.();
1356
+ });
1357
+ }
1358
+ catch (error) {
1359
+ await this.enqueueControl(async () => { if (current())
1360
+ await reject(error); });
1361
+ }
1362
+ });
1363
+ return;
1364
+ }
1365
+ try {
1366
+ await apply(await this.prepareInput(configured.behaviorId, configured.input ?? {}));
1367
+ }
1368
+ catch (error) {
1369
+ await reject(error);
1189
1370
  }
1190
1371
  }
1191
1372
  /**
@@ -1442,6 +1623,13 @@ export class StrategyHost {
1442
1623
  for (const controller of controllers)
1443
1624
  controller.abort(error);
1444
1625
  }
1626
+ inBackground(operation) {
1627
+ this.pendingPreparations += 1;
1628
+ setImmediate(() => {
1629
+ void operation().catch(error => this.diagnostic?.('behavior.preparation.failed', { error_code: errorCode(error) }, 'warn'))
1630
+ .finally(() => { this.pendingPreparations -= 1; });
1631
+ });
1632
+ }
1445
1633
  enqueueControl(operation) {
1446
1634
  const run = async () => {
1447
1635
  const result = await operation();
@@ -1,7 +1,7 @@
1
1
  import type { StrategyDecision } from './contracts.js';
2
2
  import type { StrategyMemory } from '../memory/contracts.js';
3
3
  import type { RuntimeDiagnosticSeverity } from '../framework/plugins/contracts.js';
4
- import { type StrategyThreadSource, type StrategyThreadBridge } from './thread-strategy-executor.js';
4
+ import { type StrategyThreadSource, type StrategyThreadBridge, type StrategyWorkerLease } from './thread-strategy-executor.js';
5
5
  import { type DetailCaptureConfig } from '../observability/detail-capture.js';
6
6
  import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
7
7
  export interface ScriptFrame {
@@ -21,6 +21,7 @@ export interface PreparedStrategyScript<Frame, Decision, Api, Source extends Str
21
21
  readonly everyTicks?: number;
22
22
  };
23
23
  readonly source?: Source;
24
+ readonly worker?: StrategyWorkerLease;
24
25
  }
25
26
  export interface ScriptApiContext<Observation> {
26
27
  readonly memory?: StrategyMemory;
@@ -43,6 +44,7 @@ export interface StrategyScriptRunnerOptions<Frame extends ScriptFrame, Decision
43
44
  readonly diagnostic?: (name: string, attributes?: Readonly<Record<string, unknown>>, severity?: RuntimeDiagnosticSeverity) => void;
44
45
  readonly isActive: () => boolean;
45
46
  readonly diagnosticsEnabled?: boolean;
47
+ readonly initialWorkers?: number;
46
48
  }
47
49
  /**
48
50
  * One Activation-generation runner. Serial retains one instance; parallel
@@ -103,6 +103,8 @@ export class StrategyScriptRunner {
103
103
  this.stopped = true;
104
104
  this.parallelLifecycle.abort(new Error(`behavior_runner_stopped:${reason}`));
105
105
  const executor = this.parallelExecutor;
106
+ if (!executor)
107
+ this.prepared.worker?.dispose();
106
108
  this.parallelExecutor = undefined;
107
109
  this.parallelReady = undefined;
108
110
  this.parallelStop = executor?.stop(reason) ?? Promise.resolve();
@@ -142,7 +144,9 @@ export class StrategyScriptRunner {
142
144
  const executor = new ThreadStrategyExecutor({
143
145
  bridge: this.options.bridge, inputMetadata: this.options.inputMetadata,
144
146
  memory: this.options.memory && ((frame, active) => this.options.memory(frame, () => active() && !this.stopped && this.options.isActive())),
145
- fixedWorkers: true,
147
+ fixedWorkers: this.options.initialWorkers === undefined,
148
+ initialWorkers: this.options.initialWorkers,
149
+ preparedWorker: this.prepared.worker,
146
150
  snapshotStore: this.options.snapshotStore,
147
151
  source,
148
152
  diagnostic: this.options.diagnostic,
@@ -7,6 +7,7 @@ export interface StrategyWorkerData<Source extends StrategyThreadSource> {
7
7
  readonly sourceUrl: string;
8
8
  readonly diagnosticsEnabled?: boolean;
9
9
  readonly prepareInput?: Readonly<Record<string, unknown>>;
10
+ readonly retainWorker?: boolean;
10
11
  }
11
12
  export interface StrategyWorkerModule<Frame, Decision, Api> {
12
13
  readonly execution: 'serial' | 'parallel';
@@ -34,10 +34,16 @@ export async function runStrategyWorker(adapter) {
34
34
  let preparation;
35
35
  let serialInstance;
36
36
  try {
37
- loaded = await adapter.load(data);
37
+ const validationUrl = new URL(data.sourceUrl);
38
+ if (data.retainWorker && validationUrl.protocol === 'file:') {
39
+ validationUrl.searchParams.set('gar_strategy_prepare', '1');
40
+ }
41
+ loaded = await adapter.load({ ...data, sourceUrl: validationUrl.href });
38
42
  if (data.prepareInput !== undefined) {
39
43
  preparation = loaded.prepare(data.prepareInput);
40
44
  assertRuntimeModuleOutputSize(preparation.input, 'behavior_normalize_output');
45
+ if (data.retainWorker)
46
+ loaded = await adapter.load(data);
41
47
  }
42
48
  if (loaded.execution === 'serial' && data.prepareInput === undefined)
43
49
  serialInstance = loaded.create();
@@ -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.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Game-neutral local agent runtime",
6
6
  "engines": {