@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.
- package/dist/framework/events/types.d.ts +2 -0
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +13 -0
- package/dist/mailbox/mailbox-plugin.d.ts +2 -0
- package/dist/mailbox/mailbox-plugin.js +18 -1
- package/dist/perception/contracts.d.ts +10 -3
- package/dist/perception/perception-host.d.ts +8 -0
- package/dist/perception/perception-host.js +77 -34
- package/dist/strategy/activation-manager.d.ts +2 -0
- package/dist/strategy/activation-manager.js +11 -0
- package/dist/strategy/contracts.d.ts +2 -0
- package/dist/strategy/strategy-host.d.ts +14 -1
- package/dist/strategy/strategy-host.js +265 -77
- package/dist/strategy/strategy-script-runner.d.ts +3 -1
- package/dist/strategy/strategy-script-runner.js +5 -1
- package/dist/strategy/strategy-worker-host.d.ts +1 -0
- package/dist/strategy/strategy-worker-host.js +7 -1
- package/dist/strategy/thread-strategy-executor.d.ts +19 -1
- package/dist/strategy/thread-strategy-executor.js +78 -18
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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.
|
|
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
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
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
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
const
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
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
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1021
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1170
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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();
|