@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -2
- package/dist/framework/action-diagnostics.d.ts +11 -0
- package/dist/framework/action-diagnostics.js +67 -0
- package/dist/framework/capability-registry.d.ts +58 -0
- package/dist/framework/capability-registry.js +325 -0
- package/dist/framework/contracts.d.ts +121 -0
- package/dist/framework/contracts.js +2 -0
- package/dist/framework/control/control-scheduler.d.ts +69 -0
- package/dist/framework/control/control-scheduler.js +1016 -0
- package/dist/framework/control/domain-set.d.ts +18 -0
- package/dist/framework/control/domain-set.js +70 -0
- package/dist/framework/control/index.d.ts +3 -0
- package/dist/framework/control/index.js +3 -0
- package/dist/framework/control/types.d.ts +142 -0
- package/dist/framework/control/types.js +13 -0
- package/dist/framework/control-coordinator.d.ts +7 -0
- package/dist/framework/control-coordinator.js +7 -0
- package/dist/framework/events/event-catalog.d.ts +23 -0
- package/dist/framework/events/event-catalog.js +52 -0
- package/dist/framework/events/event-delivery-service.d.ts +33 -0
- package/dist/framework/events/event-delivery-service.js +165 -0
- package/dist/framework/events/event-ingress.d.ts +28 -0
- package/dist/framework/events/event-ingress.js +76 -0
- package/dist/framework/events/event-repository.d.ts +38 -0
- package/dist/framework/events/event-repository.js +20 -0
- package/dist/framework/events/index.d.ts +7 -0
- package/dist/framework/events/index.js +7 -0
- package/dist/framework/events/memory-event-repository.d.ts +77 -0
- package/dist/framework/events/memory-event-repository.js +909 -0
- package/dist/framework/events/runtime-resume.d.ts +11 -0
- package/dist/framework/events/runtime-resume.js +7 -0
- package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
- package/dist/framework/events/sqlite-event-repository.js +2044 -0
- package/dist/framework/events/store-compatibility.d.ts +17 -0
- package/dist/framework/events/store-compatibility.js +17 -0
- package/dist/framework/events/types.d.ts +242 -0
- package/dist/framework/events/types.js +39 -0
- package/dist/framework/index.d.ts +7 -0
- package/dist/framework/index.js +7 -0
- package/dist/framework/load-node-sqlite.d.ts +5 -0
- package/dist/framework/load-node-sqlite.js +19 -0
- package/dist/framework/mailbox/coalescer.d.ts +30 -0
- package/dist/framework/mailbox/coalescer.js +45 -0
- package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
- package/dist/framework/mailbox/host-notification-sink.js +13 -0
- package/dist/framework/mailbox/identity.d.ts +15 -0
- package/dist/framework/mailbox/identity.js +28 -0
- package/dist/framework/mailbox/index.d.ts +7 -0
- package/dist/framework/mailbox/index.js +7 -0
- package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
- package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
- package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
- package/dist/framework/mailbox/mailbox-repository.js +9 -0
- package/dist/framework/mailbox/notification-projector.d.ts +25 -0
- package/dist/framework/mailbox/notification-projector.js +50 -0
- package/dist/framework/mailbox/types.d.ts +128 -0
- package/dist/framework/mailbox/types.js +1 -0
- package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
- package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
- package/dist/framework/modules/runtime-module-loader.js +64 -0
- package/dist/framework/modules/runtime-module-output.d.ts +7 -0
- package/dist/framework/modules/runtime-module-output.js +15 -0
- package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
- package/dist/framework/participation-manager.d.ts +94 -0
- package/dist/framework/participation-manager.js +185 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
- package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
- package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
- package/dist/framework/persistence/memory-first-persistence.js +459 -0
- package/dist/framework/plugins/contracts.d.ts +345 -0
- package/dist/framework/plugins/contracts.js +1 -0
- package/dist/framework/plugins/index.d.ts +4 -0
- package/dist/framework/plugins/index.js +4 -0
- package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
- package/dist/framework/plugins/runtime-event-identity.js +11 -0
- package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
- package/dist/framework/plugins/runtime-input-journal.js +716 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
- package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
- package/dist/framework/runtime.d.ts +264 -0
- package/dist/framework/runtime.js +1811 -0
- package/dist/framework/serial-task-queue.d.ts +6 -0
- package/dist/framework/serial-task-queue.js +12 -0
- package/dist/framework/state/contracts.d.ts +30 -0
- package/dist/framework/state/contracts.js +1 -0
- package/dist/framework/state/current-state-store.d.ts +17 -0
- package/dist/framework/state/current-state-store.js +153 -0
- package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
- package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
- package/dist/framework/state/freshness.d.ts +7 -0
- package/dist/framework/state/freshness.js +52 -0
- package/dist/framework/state/history/contracts.d.ts +133 -0
- package/dist/framework/state/history/contracts.js +1 -0
- package/dist/framework/state/history/history-writer.d.ts +55 -0
- package/dist/framework/state/history/history-writer.js +157 -0
- package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
- package/dist/framework/state/history/memory-state-history-repository.js +199 -0
- package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
- package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
- package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
- package/dist/framework/state/history/trajectory-projector.js +130 -0
- package/dist/framework/state/index.d.ts +12 -0
- package/dist/framework/state/index.js +12 -0
- package/dist/framework/state/state-ingress.d.ts +18 -0
- package/dist/framework/state/state-ingress.js +68 -0
- package/dist/framework/state/state-provider.d.ts +11 -0
- package/dist/framework/state/state-provider.js +56 -0
- package/dist/framework/state/types.d.ts +107 -0
- package/dist/framework/state/types.js +19 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
- package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
- package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
- package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
- package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
- package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
- package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
- package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
- package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
- package/dist/mailbox/host-monitor-rate-gate.js +93 -0
- package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
- package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
- package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
- package/dist/mailbox/mailbox-host-relay.js +299 -0
- package/dist/mailbox/mailbox-plugin.d.ts +56 -0
- package/dist/mailbox/mailbox-plugin.js +111 -0
- package/dist/mailbox/mailbox-service.d.ts +128 -0
- package/dist/mailbox/mailbox-service.js +582 -0
- package/dist/memory/contracts.d.ts +12 -0
- package/dist/memory/contracts.js +1 -0
- package/dist/memory/strategy-memory-rpc.d.ts +21 -0
- package/dist/memory/strategy-memory-rpc.js +86 -0
- package/dist/memory/strategy-memory.d.ts +15 -0
- package/dist/memory/strategy-memory.js +95 -0
- package/dist/observability/detail-capture.d.ts +25 -0
- package/dist/observability/detail-capture.js +136 -0
- package/dist/observability/index.d.ts +5 -0
- package/dist/observability/index.js +5 -0
- package/dist/observability/process-timing.d.ts +14 -0
- package/dist/observability/process-timing.js +56 -0
- package/dist/observability/recorder.d.ts +56 -0
- package/dist/observability/recorder.js +202 -0
- package/dist/observability/redaction.d.ts +30 -0
- package/dist/observability/redaction.js +166 -0
- package/dist/observability/reporter.d.ts +32 -0
- package/dist/observability/reporter.js +140 -0
- package/dist/observability/sinks.d.ts +36 -0
- package/dist/observability/sinks.js +121 -0
- package/dist/observability/types.d.ts +81 -0
- package/dist/observability/types.js +1 -0
- package/dist/owner/control-channel.d.ts +42 -0
- package/dist/owner/control-channel.js +188 -0
- package/dist/owner/parent-process-watch.d.ts +15 -0
- package/dist/owner/parent-process-watch.js +40 -0
- package/dist/owner/process-identity.d.ts +10 -0
- package/dist/owner/process-identity.js +65 -0
- package/dist/owner/runtime-lock.d.ts +5 -0
- package/dist/owner/runtime-lock.js +47 -0
- package/dist/perception/binding-resolution.d.ts +9 -0
- package/dist/perception/binding-resolution.js +14 -0
- package/dist/perception/contracts.d.ts +85 -0
- package/dist/perception/contracts.js +1 -0
- package/dist/perception/map-concurrent.d.ts +2 -0
- package/dist/perception/map-concurrent.js +12 -0
- package/dist/perception/perception-host.d.ts +114 -0
- package/dist/perception/perception-host.js +336 -0
- package/dist/perception/perception-worker-host.d.ts +11 -0
- package/dist/perception/perception-worker-host.js +44 -0
- package/dist/perception/perception-worker.d.ts +21 -0
- package/dist/perception/perception-worker.js +77 -0
- package/dist/perception/strategy-names.d.ts +7 -0
- package/dist/perception/strategy-names.js +22 -0
- package/dist/sdk/perception.d.ts +5 -0
- package/dist/sdk/perception.js +6 -0
- package/dist/sdk/strategy.d.ts +6 -0
- package/dist/sdk/strategy.js +3 -0
- package/dist/strategy/activation-manager.d.ts +105 -0
- package/dist/strategy/activation-manager.js +367 -0
- package/dist/strategy/behavior-decision-history.d.ts +20 -0
- package/dist/strategy/behavior-decision-history.js +59 -0
- package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
- package/dist/strategy/behavior-instance-snapshot.js +145 -0
- package/dist/strategy/contracts.d.ts +189 -0
- package/dist/strategy/contracts.js +1 -0
- package/dist/strategy/control-driver.d.ts +25 -0
- package/dist/strategy/control-driver.js +131 -0
- package/dist/strategy/in-process-runner.d.ts +25 -0
- package/dist/strategy/in-process-runner.js +40 -0
- package/dist/strategy/strategy-host.d.ts +165 -0
- package/dist/strategy/strategy-host.js +1456 -0
- package/dist/strategy/strategy-script-runner.d.ts +81 -0
- package/dist/strategy/strategy-script-runner.js +235 -0
- package/dist/strategy/strategy-worker-host.d.ts +27 -0
- package/dist/strategy/strategy-worker-host.js +96 -0
- package/dist/strategy/thread-strategy-executor.d.ts +120 -0
- package/dist/strategy/thread-strategy-executor.js +778 -0
- package/examples/grid-game.mjs +129 -0
- package/examples/grid-perception-worker.mjs +6 -0
- package/examples/grid-perception.mjs +12 -0
- package/examples/grid-strategy-worker.mjs +11 -0
- package/examples/grid-strategy.mjs +13 -0
- package/examples/run-grid-game.mjs +24 -0
- package/package.json +53 -4
|
@@ -0,0 +1,1456 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { performance } from 'node:perf_hooks';
|
|
3
|
+
import { StrategyMemoryStore } from '../memory/strategy-memory.js';
|
|
4
|
+
import { BehaviorActivationManager } from './activation-manager.js';
|
|
5
|
+
import { BehaviorDecisionHistory } from './behavior-decision-history.js';
|
|
6
|
+
import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
|
|
7
|
+
export const STRATEGY_LIFECYCLE_EVENT_TYPES = Object.freeze([
|
|
8
|
+
'behavior.started',
|
|
9
|
+
'behavior.suspended',
|
|
10
|
+
'behavior.restarted',
|
|
11
|
+
'behavior.completed',
|
|
12
|
+
'behavior.failed',
|
|
13
|
+
'behavior.cancelled',
|
|
14
|
+
'behavior.replaced',
|
|
15
|
+
]);
|
|
16
|
+
const BEHAVIOR_COMPUTATION_SCHEMA = 1;
|
|
17
|
+
const DEFAULT_DECISION_TIMEOUT_MS = 4_000;
|
|
18
|
+
const DEFAULT_SHORT_MAX_RUNTIME_MS = 120_000;
|
|
19
|
+
const BACKEND_STRATEGY_REPORT_RETRY_MS = 1_000;
|
|
20
|
+
function errorCode(error, fallback = 'BEHAVIOR_HOST_FAILED') {
|
|
21
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
22
|
+
return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message) ? message : fallback;
|
|
23
|
+
}
|
|
24
|
+
function proposal(value) {
|
|
25
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
26
|
+
throw new Error('behavior_computation_invalid');
|
|
27
|
+
}
|
|
28
|
+
const parsed = value;
|
|
29
|
+
if (parsed.schema !== BEHAVIOR_COMPUTATION_SCHEMA) {
|
|
30
|
+
throw new Error('behavior_computation_invalid');
|
|
31
|
+
}
|
|
32
|
+
return parsed;
|
|
33
|
+
}
|
|
34
|
+
function currentRuntimeSnapshot(manager, activationId) {
|
|
35
|
+
const snapshot = manager.snapshot();
|
|
36
|
+
return [snapshot.reflex, snapshot.short, snapshot.long]
|
|
37
|
+
.find((candidate) => candidate?.activationId === activationId);
|
|
38
|
+
}
|
|
39
|
+
function runtimeMs(prepared, rawInput, override) {
|
|
40
|
+
const base = override ?? prepared.timing?.duration_ms
|
|
41
|
+
?? prepared.timing?.timeout_ms
|
|
42
|
+
?? prepared.manifest.runtime?.defaultMs;
|
|
43
|
+
return base === undefined
|
|
44
|
+
? undefined
|
|
45
|
+
: base + (prepared.manifest.runtime?.controlGraceMs ?? 0);
|
|
46
|
+
}
|
|
47
|
+
function deadlineOutcome(prepared, rawInput) {
|
|
48
|
+
if (rawInput.duration_ms !== undefined)
|
|
49
|
+
return 'completed';
|
|
50
|
+
if (rawInput.timeout_ms !== undefined)
|
|
51
|
+
return 'failed';
|
|
52
|
+
return prepared.manifest.runtime?.deadlineOutcome;
|
|
53
|
+
}
|
|
54
|
+
function eventIds(input) {
|
|
55
|
+
return input.events.map((event) => event.eventId);
|
|
56
|
+
}
|
|
57
|
+
function sameStrings(left, right) {
|
|
58
|
+
return left.length === right.length && left.every((value, index) => value === right[index]);
|
|
59
|
+
}
|
|
60
|
+
function normalizeRoleFallbackBehaviors(value) {
|
|
61
|
+
const result = new Map();
|
|
62
|
+
for (const [role, binding] of Object.entries(value ?? {})) {
|
|
63
|
+
if (!role.trim() || !binding)
|
|
64
|
+
continue;
|
|
65
|
+
if (!/^[a-z0-9][a-z0-9._-]*$/.test(binding.behaviorId)) {
|
|
66
|
+
throw new Error('behavior_fallback_id_invalid');
|
|
67
|
+
}
|
|
68
|
+
result.set(role, Object.freeze({
|
|
69
|
+
behaviorId: binding.behaviorId,
|
|
70
|
+
input: Object.freeze(structuredClone(binding.input ?? {})),
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
function lifecycleEvent(transition) {
|
|
76
|
+
if (transition.type === 'ignored')
|
|
77
|
+
return undefined;
|
|
78
|
+
return {
|
|
79
|
+
type: `behavior.${transition.type}`,
|
|
80
|
+
dedupeKey: `${transition.activationId}:${transition.instanceGeneration}:${transition.type}`,
|
|
81
|
+
payload: {
|
|
82
|
+
activation_id: transition.activationId,
|
|
83
|
+
behavior: transition.behaviorId,
|
|
84
|
+
layer: transition.layer,
|
|
85
|
+
transition: transition.type,
|
|
86
|
+
reason: transition.reason,
|
|
87
|
+
instance_generation: transition.instanceGeneration,
|
|
88
|
+
...(transition.replacedByActivationId === undefined
|
|
89
|
+
? {}
|
|
90
|
+
: { replaced_by_activation_id: transition.replacedByActivationId }),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function asActionCaller(caller) {
|
|
95
|
+
return caller;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The sole long/short/reflex execution host. Activation policy is separate
|
|
99
|
+
* from module code; every layer runs the same ClawclawBehavior contract.
|
|
100
|
+
*/
|
|
101
|
+
export class StrategyHost {
|
|
102
|
+
options;
|
|
103
|
+
kind = 'epoch';
|
|
104
|
+
id;
|
|
105
|
+
version = '3';
|
|
106
|
+
after;
|
|
107
|
+
consumes = { events: ['*'] };
|
|
108
|
+
produces;
|
|
109
|
+
capabilities;
|
|
110
|
+
catchUp;
|
|
111
|
+
backlogPolicy = 'finish_started';
|
|
112
|
+
get maxInFlight() {
|
|
113
|
+
const current = this.manager.current();
|
|
114
|
+
return current && this.runtimes.get(current.activationId)?.prepared.manifest.execution === 'serial' ? 1 : 10;
|
|
115
|
+
}
|
|
116
|
+
maxPendingEpochs = 10;
|
|
117
|
+
timeoutMs;
|
|
118
|
+
failurePolicy = 'failed_completion';
|
|
119
|
+
catalog;
|
|
120
|
+
manager;
|
|
121
|
+
now;
|
|
122
|
+
createActivationId;
|
|
123
|
+
decisionTimeoutMs;
|
|
124
|
+
captureActions;
|
|
125
|
+
diagnosticsEnabled;
|
|
126
|
+
observationMemory;
|
|
127
|
+
adapter;
|
|
128
|
+
memory;
|
|
129
|
+
runtimes = new Map();
|
|
130
|
+
inputDefaults = new Map();
|
|
131
|
+
delegatedShorts = new Map();
|
|
132
|
+
finishSummaries = new Map();
|
|
133
|
+
controls = new Map();
|
|
134
|
+
pendingLifecycleEvents = [];
|
|
135
|
+
decisionControllers = new Map();
|
|
136
|
+
controlTail = Promise.resolve();
|
|
137
|
+
driver;
|
|
138
|
+
scope;
|
|
139
|
+
diagnostic;
|
|
140
|
+
boundaryActive = false;
|
|
141
|
+
stopped = false;
|
|
142
|
+
lastCommittedEpochSeq = 0;
|
|
143
|
+
fallbackPrepared;
|
|
144
|
+
fallbackBaseInput;
|
|
145
|
+
fallbackPreparedUsed = false;
|
|
146
|
+
fallbackBehaviors = new Map();
|
|
147
|
+
fallbackConfigGeneration = 1;
|
|
148
|
+
appliedFallbackKey;
|
|
149
|
+
manualFallbackOverride = false;
|
|
150
|
+
backendStrategyReportTarget;
|
|
151
|
+
backendStrategyReportAcknowledgedFingerprint;
|
|
152
|
+
backendStrategyReportInFlight;
|
|
153
|
+
backendStrategyReportTimer;
|
|
154
|
+
backendStrategyReportContext;
|
|
155
|
+
backendStrategyReportEligible = false;
|
|
156
|
+
backendStrategyReportSelection = 'active';
|
|
157
|
+
backendStrategyReportLifecycleGeneration = 0;
|
|
158
|
+
constructor(options) {
|
|
159
|
+
this.options = options;
|
|
160
|
+
this.id = options.id;
|
|
161
|
+
this.adapter = options.adapter;
|
|
162
|
+
this.observationMemory = options.adapter.observations;
|
|
163
|
+
this.captureActions = options.captureActions === true;
|
|
164
|
+
this.memory = options.memory ?? new StrategyMemoryStore();
|
|
165
|
+
this.capabilities = { uses: [this.options.actionCapability] };
|
|
166
|
+
this.catalog = options.catalog;
|
|
167
|
+
this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
|
|
168
|
+
this.manager = options.manager ?? new BehaviorActivationManager();
|
|
169
|
+
this.driver = options.driver;
|
|
170
|
+
this.now = options.now ?? Date.now;
|
|
171
|
+
this.createActivationId = options.createActivationId ?? randomUUID;
|
|
172
|
+
this.decisionTimeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
|
|
173
|
+
this.diagnosticsEnabled = options.diagnosticsEnabled === true;
|
|
174
|
+
this.after = [...(options.after ?? [])];
|
|
175
|
+
this.catchUp = options.catchUp ?? 'every_epoch';
|
|
176
|
+
this.timeoutMs = options.timeoutMs ?? Math.max(this.decisionTimeoutMs + 1_000, 5_000);
|
|
177
|
+
const eventTypes = new Set([
|
|
178
|
+
...STRATEGY_LIFECYCLE_EVENT_TYPES,
|
|
179
|
+
...(options.eventTypes ?? []),
|
|
180
|
+
]);
|
|
181
|
+
this.produces = {
|
|
182
|
+
states: [this.options.stateTopic],
|
|
183
|
+
events: [...eventTypes],
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
attachMemory(memory) {
|
|
187
|
+
if (this.scope)
|
|
188
|
+
throw Error('strategy_memory_already_started');
|
|
189
|
+
this.memory = memory;
|
|
190
|
+
}
|
|
191
|
+
attachDriver(driver) {
|
|
192
|
+
if (this.driver && this.driver !== driver)
|
|
193
|
+
throw new Error('behavior_control_driver_already_attached');
|
|
194
|
+
this.driver = driver;
|
|
195
|
+
}
|
|
196
|
+
async start(context) {
|
|
197
|
+
this.scope = context.scope;
|
|
198
|
+
this.memory.open(context.scope);
|
|
199
|
+
this.diagnostic = context.diagnostic;
|
|
200
|
+
this.stopped = false;
|
|
201
|
+
await this.applyTransitions(this.manager.leaveBoundary(this.now()));
|
|
202
|
+
}
|
|
203
|
+
status() {
|
|
204
|
+
const current = this.manager.current();
|
|
205
|
+
return Object.freeze({
|
|
206
|
+
running: current !== undefined,
|
|
207
|
+
...(current === undefined ? {} : { current }),
|
|
208
|
+
stack: this.manager.snapshot(),
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
diagnosticSnapshot() {
|
|
212
|
+
const status = this.status();
|
|
213
|
+
return Object.freeze({
|
|
214
|
+
running: status.running,
|
|
215
|
+
current_activation_id: status.current?.activationId ?? null,
|
|
216
|
+
current_behavior_id: status.current?.behaviorId ?? null,
|
|
217
|
+
current_layer: status.current?.layer ?? null,
|
|
218
|
+
runtime_count: this.runtimes.size,
|
|
219
|
+
runtimes: [...this.runtimes.values()].map((runtime) => ({
|
|
220
|
+
activation_id: runtime.activationId,
|
|
221
|
+
behavior_id: runtime.behaviorId,
|
|
222
|
+
instance_generation: runtime.instanceGeneration ?? null,
|
|
223
|
+
runner: runtime.runner?.diagnosticSnapshot() ?? null,
|
|
224
|
+
})),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
setIdleMs(idleMs) {
|
|
228
|
+
return this.enqueueControl(async () => {
|
|
229
|
+
await this.applyTransitions(this.manager.setIdleMs(idleMs, this.now()));
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
configureFallbackBehaviors(bindings, currentRole) {
|
|
233
|
+
return this.enqueueControl(async () => {
|
|
234
|
+
this.fallbackBehaviors = normalizeRoleFallbackBehaviors(bindings);
|
|
235
|
+
this.fallbackConfigGeneration += 1;
|
|
236
|
+
this.appliedFallbackKey = undefined;
|
|
237
|
+
this.manualFallbackOverride = false;
|
|
238
|
+
// A control receipt must reflect the current role's effective binding,
|
|
239
|
+
// including suspended boundaries with no fresh observation frame. The activation
|
|
240
|
+
// manager still owns boundary suspension and explicit long Behaviors.
|
|
241
|
+
await this.syncRoleFallback(currentRole, this.now());
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
bindFallback(behaviorId, input) {
|
|
245
|
+
return this.enqueueControl(async () => {
|
|
246
|
+
const prepared = await this.prepareInput(behaviorId, input);
|
|
247
|
+
this.manualFallbackOverride = true;
|
|
248
|
+
this.fallbackPrepared = prepared;
|
|
249
|
+
this.fallbackBaseInput = { behaviorId, input: structuredClone(input) };
|
|
250
|
+
this.fallbackPreparedUsed = false;
|
|
251
|
+
await this.applyTransitions(this.manager.bindFallback({
|
|
252
|
+
behaviorId,
|
|
253
|
+
input: prepared.input,
|
|
254
|
+
}, this.now()));
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
clearFallback() {
|
|
258
|
+
return this.enqueueControl(async () => {
|
|
259
|
+
this.manualFallbackOverride = true;
|
|
260
|
+
this.fallbackPrepared = undefined;
|
|
261
|
+
this.fallbackBaseInput = undefined;
|
|
262
|
+
this.fallbackPreparedUsed = false;
|
|
263
|
+
await this.applyTransitions(this.manager.bindFallback(undefined, this.now()));
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
startLong(behaviorId, input, options) {
|
|
267
|
+
return this.startLayer('long', behaviorId, input, options);
|
|
268
|
+
}
|
|
269
|
+
startShort(behaviorId, input, options) {
|
|
270
|
+
return this.startLayer('short', behaviorId, input, options);
|
|
271
|
+
}
|
|
272
|
+
cancel(activationId, reason = 'cancelled_by_control') {
|
|
273
|
+
return this.enqueueControl(async () => {
|
|
274
|
+
await this.applyTransitions(this.manager.cancel(activationId, reason, this.now()));
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
noteAgentActivity() {
|
|
278
|
+
return this.enqueueControl(async () => {
|
|
279
|
+
await this.applyTransitions(this.manager.noteAgentActivity(this.now()));
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
async updateReflex(triggerId, patch, guard = () => true) {
|
|
283
|
+
return this.enqueueControl(async () => {
|
|
284
|
+
if (!guard())
|
|
285
|
+
throw new Error('stale_runtime_scope');
|
|
286
|
+
const active = this.manager.snapshot().reflex;
|
|
287
|
+
if (!active || active.triggerId !== triggerId)
|
|
288
|
+
return false;
|
|
289
|
+
if (patch === undefined) {
|
|
290
|
+
this.interruptDecisions(active.activationId, 'reflex_disabled');
|
|
291
|
+
await this.applyTransitions(this.manager.cancel(active.activationId, 'reflex_disabled', this.now()));
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
await this.updateActivationInput(active.activationId, patch, guard);
|
|
295
|
+
return true;
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
/** Update one execution in any layer; background watch configuration is a separate target. */
|
|
299
|
+
updateInput(activationId, patch, guard = () => true) {
|
|
300
|
+
return this.enqueueControl(() => this.updateActivationInput(activationId, patch, guard));
|
|
301
|
+
}
|
|
302
|
+
/** Owner-controlled match-local inputs. Explicit start/delegation input and dynamic Trigger targets take precedence. */
|
|
303
|
+
configureInput(behaviorId, input, patch, guard = () => true, beforeApply) {
|
|
304
|
+
return this.enqueueControl(async () => {
|
|
305
|
+
if (!guard())
|
|
306
|
+
throw new Error('stale_runtime_scope');
|
|
307
|
+
const defaults = await this.catalog.prepare(behaviorId, input);
|
|
308
|
+
const stack = this.manager.snapshot();
|
|
309
|
+
const active = [stack.long, stack.short, stack.reflex].filter((entry) => entry?.behaviorId === behaviorId);
|
|
310
|
+
const updates = [];
|
|
311
|
+
for (const activation of active)
|
|
312
|
+
updates.push({ activation,
|
|
313
|
+
prepared: await this.catalog.prepare(behaviorId, {
|
|
314
|
+
...(this.runtimes.get(activation.activationId)?.prepared.rawInput ?? activation.input), ...patch
|
|
315
|
+
}) });
|
|
316
|
+
if (!guard())
|
|
317
|
+
throw new Error('stale_runtime_scope');
|
|
318
|
+
beforeApply?.();
|
|
319
|
+
await this.replacePreparedInputs(updates, guard);
|
|
320
|
+
this.inputDefaults.set(behaviorId, structuredClone(input));
|
|
321
|
+
if (this.manager.snapshot().fallback?.behaviorId === behaviorId) {
|
|
322
|
+
this.fallbackPrepared = defaults;
|
|
323
|
+
this.fallbackPreparedUsed = false;
|
|
324
|
+
this.manager.updateFallbackInput(behaviorId, defaults.input);
|
|
325
|
+
}
|
|
326
|
+
return updates.length;
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
prepareInput(behaviorId, input) {
|
|
330
|
+
return this.catalog.prepare(behaviorId, { ...this.inputDefaults.get(behaviorId), ...input });
|
|
331
|
+
}
|
|
332
|
+
async updateActivationInput(activationId, patch, guard) {
|
|
333
|
+
if (!guard())
|
|
334
|
+
throw new Error('stale_runtime_scope');
|
|
335
|
+
const active = currentRuntimeSnapshot(this.manager, activationId);
|
|
336
|
+
if (!active)
|
|
337
|
+
throw new Error('behavior_activation_not_found');
|
|
338
|
+
const prepared = await this.catalog.prepare(active.behaviorId, {
|
|
339
|
+
...(this.runtimes.get(activationId)?.prepared.rawInput ?? active.input), ...patch
|
|
340
|
+
});
|
|
341
|
+
if (!guard())
|
|
342
|
+
throw new Error('stale_runtime_scope');
|
|
343
|
+
await this.replacePreparedInputs([{ activation: active, prepared }], guard);
|
|
344
|
+
const updated = currentRuntimeSnapshot(this.manager, activationId);
|
|
345
|
+
if (!updated)
|
|
346
|
+
throw new Error('behavior_activation_update_failed');
|
|
347
|
+
return updated;
|
|
348
|
+
}
|
|
349
|
+
async replacePreparedInputs(updates, guard) {
|
|
350
|
+
if (!guard())
|
|
351
|
+
throw new Error('stale_runtime_scope');
|
|
352
|
+
for (const { activation } of updates) {
|
|
353
|
+
const latest = currentRuntimeSnapshot(this.manager, activation.activationId);
|
|
354
|
+
if (!latest || latest.instanceGeneration !== activation.instanceGeneration)
|
|
355
|
+
throw new Error('behavior_activation_changed');
|
|
356
|
+
}
|
|
357
|
+
for (const { activation } of updates) {
|
|
358
|
+
this.interruptDecisions(activation.activationId, 'behavior_input_updated');
|
|
359
|
+
this.controls.get(activation.activationId)?.release('behavior_input_updated');
|
|
360
|
+
this.controls.delete(activation.activationId);
|
|
361
|
+
await this.runtimes.get(activation.activationId)?.runner?.stop('switched');
|
|
362
|
+
}
|
|
363
|
+
if (!guard())
|
|
364
|
+
throw new Error('stale_runtime_scope');
|
|
365
|
+
const transitions = [];
|
|
366
|
+
for (const { activation, prepared } of updates) {
|
|
367
|
+
const activationId = activation.activationId, previous = this.runtimes.get(activationId);
|
|
368
|
+
this.runtimes.set(activationId, { activationId, behaviorId: activation.behaviorId, prepared,
|
|
369
|
+
pendingContinuation: previous?.pendingContinuation,
|
|
370
|
+
decisionHistory: new BehaviorDecisionHistory(), committedActionDedupeKeys: new Map() });
|
|
371
|
+
transitions.push(...this.manager.updateInput(activationId, prepared.input, this.now()));
|
|
372
|
+
}
|
|
373
|
+
await this.applyTransitions(transitions);
|
|
374
|
+
}
|
|
375
|
+
async requestReflex(request, guard) {
|
|
376
|
+
if (this.stopped || !this.scope)
|
|
377
|
+
return { accepted: false, reason: 'activation_ineligible' };
|
|
378
|
+
if (guard && !guard.isCurrent())
|
|
379
|
+
return { accepted: false, reason: 'stale_request' };
|
|
380
|
+
if (request.scope.sessionId !== this.scope.sessionId
|
|
381
|
+
|| request.scope.segmentId !== this.scope.segmentId
|
|
382
|
+
|| request.epochId <= this.lastCommittedEpochSeq)
|
|
383
|
+
return { accepted: false, reason: 'stale_request' };
|
|
384
|
+
if (!this.catalog.has(request.behavior))
|
|
385
|
+
return { accepted: false, reason: 'binding_invalid' };
|
|
386
|
+
let prepared;
|
|
387
|
+
try {
|
|
388
|
+
prepared = await this.prepareInput(request.behavior, request.behaviorInput);
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
return { accepted: false, reason: 'binding_invalid' };
|
|
392
|
+
}
|
|
393
|
+
if (guard && !guard.isCurrent())
|
|
394
|
+
return { accepted: false, reason: 'stale_request' };
|
|
395
|
+
const activeReflex = this.manager.snapshot().reflex;
|
|
396
|
+
if (activeReflex) {
|
|
397
|
+
if (activeReflex.triggerId === request.triggerId) {
|
|
398
|
+
return { accepted: false, reason: 'same_trigger_active' };
|
|
399
|
+
}
|
|
400
|
+
if ((activeReflex.reflexPriority ?? 0) >= request.reflexPriority) {
|
|
401
|
+
return { accepted: false, reason: 'reflex_priority_not_higher' };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const interrupted = this.manager.current();
|
|
405
|
+
if (interrupted)
|
|
406
|
+
this.interruptDecisions(interrupted.activationId, 'behavior_reflex_preempted');
|
|
407
|
+
return this.enqueueControl(async () => {
|
|
408
|
+
if (this.stopped || !this.scope)
|
|
409
|
+
return { accepted: false, reason: 'activation_ineligible' };
|
|
410
|
+
if (guard && !guard.isCurrent())
|
|
411
|
+
return { accepted: false, reason: 'stale_request' };
|
|
412
|
+
if (request.scope.sessionId !== this.scope.sessionId
|
|
413
|
+
|| request.scope.segmentId !== this.scope.segmentId
|
|
414
|
+
|| request.epochId <= this.lastCommittedEpochSeq)
|
|
415
|
+
return { accepted: false, reason: 'stale_request' };
|
|
416
|
+
const activationId = this.createActivationId();
|
|
417
|
+
const transitions = this.manager.requestReflex({
|
|
418
|
+
activationId,
|
|
419
|
+
behaviorId: request.behavior,
|
|
420
|
+
input: prepared.input,
|
|
421
|
+
requestedAt: this.now(),
|
|
422
|
+
maxRuntimeMs: request.maxRuntimeMs,
|
|
423
|
+
deadlineOutcome: 'failed',
|
|
424
|
+
source: request.source,
|
|
425
|
+
triggerId: request.triggerId,
|
|
426
|
+
reflexPriority: request.reflexPriority,
|
|
427
|
+
}, this.now());
|
|
428
|
+
const ignored = transitions.find((entry) => entry.type === 'ignored');
|
|
429
|
+
if (ignored) {
|
|
430
|
+
return {
|
|
431
|
+
accepted: false,
|
|
432
|
+
reason: ignored.reason === 'reflex_trigger_already_active'
|
|
433
|
+
? 'same_trigger_active'
|
|
434
|
+
: 'reflex_priority_not_higher',
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
this.runtimes.set(activationId, {
|
|
438
|
+
activationId,
|
|
439
|
+
behaviorId: request.behavior,
|
|
440
|
+
prepared,
|
|
441
|
+
decisionHistory: new BehaviorDecisionHistory(),
|
|
442
|
+
committedActionDedupeKeys: new Map(),
|
|
443
|
+
});
|
|
444
|
+
const replaced = transitions.find((entry) => entry.type === 'replaced');
|
|
445
|
+
await this.applyTransitions(transitions);
|
|
446
|
+
return {
|
|
447
|
+
accepted: true,
|
|
448
|
+
activationId,
|
|
449
|
+
...(replaced === undefined ? {} : { replacedActivationId: replaced.activationId }),
|
|
450
|
+
};
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
async update(input, context) {
|
|
454
|
+
if (this.adapter.boundary(input).notificationOnly)
|
|
455
|
+
return { outcome: 'noop', reason: 'notification_only' };
|
|
456
|
+
this.scope = context.scope;
|
|
457
|
+
const current = this.manager.current();
|
|
458
|
+
const base = {
|
|
459
|
+
schema: BEHAVIOR_COMPUTATION_SCHEMA,
|
|
460
|
+
...(current === undefined ? {} : {
|
|
461
|
+
activationId: current.activationId,
|
|
462
|
+
instanceGeneration: current.instanceGeneration,
|
|
463
|
+
}),
|
|
464
|
+
};
|
|
465
|
+
if (!current) {
|
|
466
|
+
return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } };
|
|
467
|
+
}
|
|
468
|
+
if (this.adapter.boundary(input).terminalReason) {
|
|
469
|
+
return { outcome: 'processed', proposal: { ...base, kind: 'scope_terminal' } };
|
|
470
|
+
}
|
|
471
|
+
const runtime = this.runtimes.get(current.activationId);
|
|
472
|
+
if (runtime
|
|
473
|
+
&& runtime.instanceGeneration === current.instanceGeneration
|
|
474
|
+
&& this.adapter.boundary(input).hasObservation) {
|
|
475
|
+
const tick = Number(input.epoch.domainTick
|
|
476
|
+
?? this.adapter.boundary(input).observationTick
|
|
477
|
+
?? input.epoch.epochSeq);
|
|
478
|
+
runtime.decisionHistory.begin({
|
|
479
|
+
epochId: input.epoch.epochSeq,
|
|
480
|
+
tick,
|
|
481
|
+
instanceGeneration: current.instanceGeneration,
|
|
482
|
+
});
|
|
483
|
+
const history = runtime.decisionHistory.snapshot();
|
|
484
|
+
context.diagnostic('behavior.decision_history.frame_pending', {
|
|
485
|
+
behavior_id: current.behaviorId,
|
|
486
|
+
activation_id: current.activationId,
|
|
487
|
+
instance_generation: current.instanceGeneration,
|
|
488
|
+
epoch_id: input.epoch.epochSeq,
|
|
489
|
+
tick,
|
|
490
|
+
retained_frame_count: history.length,
|
|
491
|
+
pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
|
|
492
|
+
}, 'debug');
|
|
493
|
+
}
|
|
494
|
+
const frame = this.adapter.input(input, current.input, runtime?.pendingContinuation, runtime?.decisionHistory.snapshot());
|
|
495
|
+
if (!frame) {
|
|
496
|
+
return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } };
|
|
497
|
+
}
|
|
498
|
+
const noDecision = (kind, reason) => {
|
|
499
|
+
const resolved = runtime?.decisionHistory.notComputed(frame.epochId, reason);
|
|
500
|
+
if (resolved) {
|
|
501
|
+
const history = runtime.decisionHistory.snapshot();
|
|
502
|
+
context.diagnostic('behavior.decision_history.frame_resolved', {
|
|
503
|
+
behavior_id: current.behaviorId,
|
|
504
|
+
activation_id: current.activationId,
|
|
505
|
+
instance_generation: current.instanceGeneration,
|
|
506
|
+
epoch_id: frame.epochId,
|
|
507
|
+
tick: resolved.tick,
|
|
508
|
+
status: resolved.status,
|
|
509
|
+
reason,
|
|
510
|
+
action_count: 0,
|
|
511
|
+
retained_frame_count: history.length,
|
|
512
|
+
pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
|
|
513
|
+
}, 'debug');
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
outcome: 'processed',
|
|
517
|
+
proposal: { ...base, kind },
|
|
518
|
+
};
|
|
519
|
+
};
|
|
520
|
+
const policy = this.adapter.policy(frame, current.layer);
|
|
521
|
+
if (policy.terminalReason)
|
|
522
|
+
return noDecision('scope_terminal', policy.terminalReason);
|
|
523
|
+
if (policy.inactiveReason)
|
|
524
|
+
return noDecision('participant_inactive', policy.inactiveReason);
|
|
525
|
+
if (policy.pauseReason)
|
|
526
|
+
return noDecision('boundary', policy.pauseReason);
|
|
527
|
+
const control = this.controls.get(current.activationId);
|
|
528
|
+
if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
|
|
529
|
+
return noDecision('control_held', 'runner_unavailable');
|
|
530
|
+
}
|
|
531
|
+
if (!control?.isAuthorized()) {
|
|
532
|
+
return noDecision('control_held', 'control_held');
|
|
533
|
+
}
|
|
534
|
+
const backendTick = Number(frame.tick ?? frame.epochId);
|
|
535
|
+
if (!frame.cycle && runtime.lastCommittedBackendTick !== undefined
|
|
536
|
+
&& backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks) {
|
|
537
|
+
return noDecision('cadence_skip', 'cadence_skip');
|
|
538
|
+
}
|
|
539
|
+
const observation = this.observationMemory.capture(frame);
|
|
540
|
+
try {
|
|
541
|
+
const decision = await this.withDecisionTimeout(signal => runtime.runner.execution === 'serial'
|
|
542
|
+
? runtime.runner.decideSerial(frame, signal, observation)
|
|
543
|
+
: runtime.runner.decideParallel(frame, signal, observation), context.signal, current.activationId);
|
|
544
|
+
const resolved = runtime.decisionHistory.complete(frame.epochId, decision.actions);
|
|
545
|
+
if (this.captureActions)
|
|
546
|
+
context.diagnostic('runtime.detail.actions.decision', {
|
|
547
|
+
behavior_id: current.behaviorId, activation_id: current.activationId,
|
|
548
|
+
instance_generation: current.instanceGeneration, epoch_id: frame.epochId,
|
|
549
|
+
tick: frame.tick, stage: 'computed_not_yet_committed', actions: decision.actions ?? [],
|
|
550
|
+
}, 'debug');
|
|
551
|
+
if (resolved) {
|
|
552
|
+
const history = runtime.decisionHistory.snapshot();
|
|
553
|
+
context.diagnostic('behavior.decision_history.frame_resolved', {
|
|
554
|
+
behavior_id: current.behaviorId,
|
|
555
|
+
activation_id: current.activationId,
|
|
556
|
+
instance_generation: current.instanceGeneration,
|
|
557
|
+
epoch_id: frame.epochId,
|
|
558
|
+
tick: resolved.tick,
|
|
559
|
+
status: resolved.status,
|
|
560
|
+
action_count: resolved.actions?.length ?? 0,
|
|
561
|
+
action_kinds: (resolved.actions ?? []).map((action) => action.action),
|
|
562
|
+
retained_frame_count: history.length,
|
|
563
|
+
pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
|
|
564
|
+
}, 'debug');
|
|
565
|
+
}
|
|
566
|
+
return {
|
|
567
|
+
outcome: 'processed',
|
|
568
|
+
proposal: {
|
|
569
|
+
...base,
|
|
570
|
+
kind: runtime.runner.execution,
|
|
571
|
+
eventIds: eventIds(frame),
|
|
572
|
+
observationRevision: observation.revision,
|
|
573
|
+
decision,
|
|
574
|
+
},
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
catch (error) {
|
|
578
|
+
const failure = errorCode(error, 'BEHAVIOR_DECIDE_FAILED');
|
|
579
|
+
const resolved = runtime.decisionHistory.fail(frame.epochId, failure);
|
|
580
|
+
if (resolved) {
|
|
581
|
+
const history = runtime.decisionHistory.snapshot();
|
|
582
|
+
context.diagnostic('behavior.decision_history.frame_resolved', {
|
|
583
|
+
behavior_id: current.behaviorId,
|
|
584
|
+
activation_id: current.activationId,
|
|
585
|
+
instance_generation: current.instanceGeneration,
|
|
586
|
+
epoch_id: frame.epochId,
|
|
587
|
+
tick: resolved.tick,
|
|
588
|
+
status: resolved.status,
|
|
589
|
+
reason: failure,
|
|
590
|
+
action_count: 0,
|
|
591
|
+
retained_frame_count: history.length,
|
|
592
|
+
pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
|
|
593
|
+
}, 'debug');
|
|
594
|
+
}
|
|
595
|
+
return {
|
|
596
|
+
outcome: 'processed',
|
|
597
|
+
proposal: {
|
|
598
|
+
...base,
|
|
599
|
+
kind: 'module_error',
|
|
600
|
+
errorCode: failure,
|
|
601
|
+
},
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
commit(input, computation, context) {
|
|
606
|
+
if (this.adapter.boundary(input).notificationOnly && !this.adapter.boundary(input).cycle)
|
|
607
|
+
return Promise.resolve(computation);
|
|
608
|
+
return this.enqueueControl(async () => {
|
|
609
|
+
// Cadence drains must advance deadlines and terminal/control transitions,
|
|
610
|
+
// but cannot run decide() or admit a Decision from another cycle.
|
|
611
|
+
const result = await this.commitOrdered(input, this.adapter.boundary(input).notificationOnly
|
|
612
|
+
? { schema: BEHAVIOR_COMPUTATION_SCHEMA, kind: 'waiting_for_state' }
|
|
613
|
+
: proposal(computation.proposal), context);
|
|
614
|
+
// Report the final activation after this epoch's advances, finishes and
|
|
615
|
+
// boundary transitions, rather than the activation it started with.
|
|
616
|
+
this.refreshBackendStrategyReport(input, context);
|
|
617
|
+
return result;
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
async stop(reason) {
|
|
621
|
+
await this.enqueueControl(async () => {
|
|
622
|
+
this.stopped = true;
|
|
623
|
+
if (this.scope)
|
|
624
|
+
this.memory.close(this.scope);
|
|
625
|
+
this.resetBackendStrategyReporting();
|
|
626
|
+
for (const controllers of this.decisionControllers.values()) {
|
|
627
|
+
for (const controller of controllers)
|
|
628
|
+
controller.abort(new Error(reason));
|
|
629
|
+
}
|
|
630
|
+
this.decisionControllers.clear();
|
|
631
|
+
const runnerReason = reason === 'shutdown' ? 'shutdown' : 'scope_ended';
|
|
632
|
+
const runners = [...this.runtimes.values()].flatMap((runtime) => {
|
|
633
|
+
const runner = runtime.runner;
|
|
634
|
+
runtime.runner = undefined;
|
|
635
|
+
runtime.instanceGeneration = undefined;
|
|
636
|
+
return runner ? [runner] : [];
|
|
637
|
+
});
|
|
638
|
+
await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
|
|
639
|
+
await this.applyTransitions(this.manager.clearScope(reason, this.now()));
|
|
640
|
+
this.runtimes.clear();
|
|
641
|
+
const parameterizedFallback = this.inputDefaults.has(this.manager.snapshot().fallback?.behaviorId ?? '');
|
|
642
|
+
this.inputDefaults.clear();
|
|
643
|
+
if (parameterizedFallback) {
|
|
644
|
+
if (this.fallbackBaseInput)
|
|
645
|
+
this.manager.updateFallbackInput(this.fallbackBaseInput.behaviorId, this.fallbackBaseInput.input);
|
|
646
|
+
this.fallbackPrepared = undefined;
|
|
647
|
+
this.fallbackPreparedUsed = false;
|
|
648
|
+
this.appliedFallbackKey = undefined;
|
|
649
|
+
}
|
|
650
|
+
this.delegatedShorts.clear();
|
|
651
|
+
this.finishSummaries.clear();
|
|
652
|
+
for (const handle of this.controls.values())
|
|
653
|
+
handle.release(reason);
|
|
654
|
+
this.controls.clear();
|
|
655
|
+
this.observationMemory.clear();
|
|
656
|
+
this.scope = undefined;
|
|
657
|
+
this.diagnostic = undefined;
|
|
658
|
+
this.boundaryActive = false;
|
|
659
|
+
this.pendingLifecycleEvents.length = 0;
|
|
660
|
+
this.lastCommittedEpochSeq = 0;
|
|
661
|
+
});
|
|
662
|
+
}
|
|
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(),
|
|
694
|
+
});
|
|
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;
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
async commitOrdered(input, computed, context) {
|
|
706
|
+
this.scope = context.scope;
|
|
707
|
+
this.diagnostic = context.diagnostic;
|
|
708
|
+
this.lastCommittedEpochSeq = Math.max(this.lastCommittedEpochSeq, input.epoch.epochSeq);
|
|
709
|
+
const cursor = input.pendingEvents.at(-1)?.commitSeq;
|
|
710
|
+
const frameForClock = this.adapter.input(input, Object.freeze({}));
|
|
711
|
+
const now = frameForClock?.nowMs ?? this.now();
|
|
712
|
+
const boundary = this.adapter.boundary(input);
|
|
713
|
+
const initialPolicy = this.adapter.policy(frameForClock);
|
|
714
|
+
if (boundary.terminalReason) {
|
|
715
|
+
await this.applyTransitions(this.manager.clearScope(initialPolicy.terminalReason ?? boundary.terminalReason, now));
|
|
716
|
+
if (this.scope)
|
|
717
|
+
this.memory.close(this.scope);
|
|
718
|
+
this.boundaryActive = true;
|
|
719
|
+
return this.output(cursor);
|
|
720
|
+
}
|
|
721
|
+
await this.syncRoleFallback(initialPolicy.fallbackKey, now);
|
|
722
|
+
if (!frameForClock && boundary.pendingPauseReason) {
|
|
723
|
+
await this.applyTransitions(this.manager.enterBoundary(boundary.pendingPauseReason, now));
|
|
724
|
+
this.boundaryActive = true;
|
|
725
|
+
return this.output(cursor);
|
|
726
|
+
}
|
|
727
|
+
await this.applyTransitions(this.manager.advance(now));
|
|
728
|
+
const currentForFrame = this.manager.current();
|
|
729
|
+
const currentFrameRuntime = currentForFrame
|
|
730
|
+
? this.runtimes.get(currentForFrame.activationId)
|
|
731
|
+
: undefined;
|
|
732
|
+
const frame = currentForFrame
|
|
733
|
+
? this.adapter.input(input, currentForFrame.input, currentFrameRuntime?.pendingContinuation, currentFrameRuntime?.decisionHistory.snapshot())
|
|
734
|
+
: frameForClock;
|
|
735
|
+
const policy = this.adapter.policy(frame, this.manager.current()?.layer);
|
|
736
|
+
if (policy.terminalReason || computed.kind === 'scope_terminal') {
|
|
737
|
+
await this.applyTransitions(this.manager.clearScope(policy.terminalReason ?? boundary.terminalReason ?? 'scope_ended', now));
|
|
738
|
+
if (this.scope)
|
|
739
|
+
this.memory.close(this.scope);
|
|
740
|
+
this.boundaryActive = true;
|
|
741
|
+
return this.output(cursor);
|
|
742
|
+
}
|
|
743
|
+
if (policy.inactiveReason || computed.kind === 'participant_inactive') {
|
|
744
|
+
await this.applyTransitions(this.manager.clearScope(policy.inactiveReason ?? 'participant_inactive', now));
|
|
745
|
+
this.boundaryActive = true;
|
|
746
|
+
return this.output(cursor);
|
|
747
|
+
}
|
|
748
|
+
if (policy.pauseReason) {
|
|
749
|
+
await this.applyTransitions(this.manager.enterBoundary(policy.pauseReason, now));
|
|
750
|
+
this.boundaryActive = true;
|
|
751
|
+
return this.output(cursor);
|
|
752
|
+
}
|
|
753
|
+
if (policy.resume && this.boundaryActive) {
|
|
754
|
+
this.boundaryActive = false;
|
|
755
|
+
await this.applyTransitions(this.manager.leaveBoundary(now));
|
|
756
|
+
return this.output(cursor);
|
|
757
|
+
}
|
|
758
|
+
const current = this.manager.current();
|
|
759
|
+
if (!current) {
|
|
760
|
+
const stack = this.manager.snapshot();
|
|
761
|
+
// An empty host has no activation that will consume this batch later.
|
|
762
|
+
// Drain only this plugin's cursor; canonical Events remain available to
|
|
763
|
+
// other consumers. A suspended long waiting for hand-back still owns
|
|
764
|
+
// its pending Events, even though current() temporarily returns nothing.
|
|
765
|
+
if (!stack.long && !stack.short && !stack.reflex)
|
|
766
|
+
return this.output(cursor);
|
|
767
|
+
}
|
|
768
|
+
if (!current
|
|
769
|
+
|| computed.activationId !== current.activationId
|
|
770
|
+
|| computed.instanceGeneration !== current.instanceGeneration
|
|
771
|
+
|| !this.manager.isCurrent(current.activationId, current.instanceGeneration)) {
|
|
772
|
+
if (computed.activationId) {
|
|
773
|
+
this.runtimes.get(computed.activationId)?.decisionHistory.notComputed(input.epoch.epochSeq, 'activation_superseded_before_commit');
|
|
774
|
+
}
|
|
775
|
+
return this.output(undefined);
|
|
776
|
+
}
|
|
777
|
+
if (!frame)
|
|
778
|
+
return this.output(undefined);
|
|
779
|
+
const runtime = this.runtimes.get(current.activationId);
|
|
780
|
+
const control = this.controls.get(current.activationId);
|
|
781
|
+
if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration || !control?.isAuthorized()) {
|
|
782
|
+
return this.output(undefined);
|
|
783
|
+
}
|
|
784
|
+
const backendTick = Number(frame.tick ?? frame.epochId);
|
|
785
|
+
if (!frame.cycle && runtime.lastCommittedBackendTick !== undefined
|
|
786
|
+
&& backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks)
|
|
787
|
+
return this.output(undefined);
|
|
788
|
+
if (computed.kind === 'cadence_skip' || computed.kind === 'control_held') {
|
|
789
|
+
return this.output(undefined);
|
|
790
|
+
}
|
|
791
|
+
if (computed.kind === 'module_error') {
|
|
792
|
+
await this.failCurrent(current, computed.errorCode ?? 'BEHAVIOR_DECIDE_FAILED', now);
|
|
793
|
+
return this.output(cursor);
|
|
794
|
+
}
|
|
795
|
+
if (computed.kind !== 'serial' && computed.kind !== 'parallel') {
|
|
796
|
+
return this.output(computed.kind === 'inactive' ? cursor : undefined);
|
|
797
|
+
}
|
|
798
|
+
const observation = this.observationMemory.snapshot(frame.epochId)
|
|
799
|
+
?? this.observationMemory.capture(frame);
|
|
800
|
+
const decision = computed.decision;
|
|
801
|
+
const proposalIsStale = !sameStrings(computed.eventIds ?? [], eventIds(frame))
|
|
802
|
+
|| computed.observationRevision !== observation.revision;
|
|
803
|
+
if (proposalIsStale) {
|
|
804
|
+
context.diagnostic('behavior.decision.stale_before_commit', {
|
|
805
|
+
behavior_id: current.behaviorId,
|
|
806
|
+
activation_id: current.activationId,
|
|
807
|
+
instance_generation: current.instanceGeneration,
|
|
808
|
+
epoch_id: frame.epochId,
|
|
809
|
+
tick: frame.tick,
|
|
810
|
+
event_input_changed: !sameStrings(computed.eventIds ?? [], eventIds(frame)),
|
|
811
|
+
observation_revision_changed: computed.observationRevision !== observation.revision,
|
|
812
|
+
}, 'debug');
|
|
813
|
+
return this.output(undefined);
|
|
814
|
+
}
|
|
815
|
+
if (!decision || !this.manager.isCurrent(current.activationId, current.instanceGeneration)) {
|
|
816
|
+
return this.output(undefined);
|
|
817
|
+
}
|
|
818
|
+
const resolvedDecision = runtime.decisionHistory.complete(frame.epochId, decision.actions);
|
|
819
|
+
if (resolvedDecision) {
|
|
820
|
+
const history = runtime.decisionHistory.snapshot();
|
|
821
|
+
context.diagnostic('behavior.decision_history.frame_resolved', {
|
|
822
|
+
behavior_id: current.behaviorId,
|
|
823
|
+
activation_id: current.activationId,
|
|
824
|
+
instance_generation: current.instanceGeneration,
|
|
825
|
+
epoch_id: frame.epochId,
|
|
826
|
+
tick: resolvedDecision.tick,
|
|
827
|
+
status: resolvedDecision.status,
|
|
828
|
+
action_count: resolvedDecision.actions?.length ?? 0,
|
|
829
|
+
action_kinds: (resolvedDecision.actions ?? []).map((action) => action.action),
|
|
830
|
+
retained_frame_count: history.length,
|
|
831
|
+
pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
|
|
832
|
+
}, 'debug');
|
|
833
|
+
}
|
|
834
|
+
runtime.lastCommittedBackendTick = backendTick;
|
|
835
|
+
let output;
|
|
836
|
+
try {
|
|
837
|
+
output = await this.applyDecision(current, runtime, frame, decision, input, context);
|
|
838
|
+
}
|
|
839
|
+
catch (error) {
|
|
840
|
+
await this.failCurrent(current, errorCode(error, 'BEHAVIOR_DECISION_INVALID'), now);
|
|
841
|
+
return this.output(cursor);
|
|
842
|
+
}
|
|
843
|
+
runtime.lastStatus = output.status ?? runtime.lastStatus;
|
|
844
|
+
if (policy.pauseAfterDecision) {
|
|
845
|
+
await this.applyTransitions(this.manager.enterBoundary(policy.pauseAfterDecision, now));
|
|
846
|
+
this.boundaryActive = true;
|
|
847
|
+
}
|
|
848
|
+
return this.output(cursor, output.status, output.events);
|
|
849
|
+
}
|
|
850
|
+
async applyDecision(activation, runtime, frame, decision, input, context) {
|
|
851
|
+
if (decision.finish && (decision.actions?.length ?? 0) > 0) {
|
|
852
|
+
throw new Error('behavior_finish_with_actions_invalid');
|
|
853
|
+
}
|
|
854
|
+
if (decision.delegate && (decision.actions?.length ?? 0) > 0) {
|
|
855
|
+
throw new Error('behavior_delegate_with_actions_invalid');
|
|
856
|
+
}
|
|
857
|
+
if (decision.delegate && decision.finish) {
|
|
858
|
+
throw new Error('behavior_delegate_with_finish_invalid');
|
|
859
|
+
}
|
|
860
|
+
if (decision.delegate && activation.layer !== 'long') {
|
|
861
|
+
throw new Error('behavior_delegate_layer_invalid');
|
|
862
|
+
}
|
|
863
|
+
const delegated = decision.delegate === undefined
|
|
864
|
+
? undefined
|
|
865
|
+
: await this.prepareDelegatedShort(decision.delegate);
|
|
866
|
+
const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
|
|
867
|
+
for (const event of decision.events ?? []) {
|
|
868
|
+
if (!declaredEvents.has(event.type))
|
|
869
|
+
throw new Error('behavior_event_output_invalid');
|
|
870
|
+
}
|
|
871
|
+
// A continuation belongs to the first Decision that actually reaches the
|
|
872
|
+
// ordered effect queue. Stale proposals and cadence skips never consume it.
|
|
873
|
+
runtime.pendingContinuation = undefined;
|
|
874
|
+
const safetyGeneration = this.adapter.boundary(input).actionGeneration;
|
|
875
|
+
for (const [index, rawAction] of (decision.actions ?? []).entries()) {
|
|
876
|
+
if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration))
|
|
877
|
+
break;
|
|
878
|
+
const control = this.controls.get(activation.activationId);
|
|
879
|
+
if (!control?.isAuthorized())
|
|
880
|
+
break;
|
|
881
|
+
const action = rawAction;
|
|
882
|
+
const dedupeKey = `${activation.instanceGeneration}:${frame.tick}:${index}:${JSON.stringify(action)}`;
|
|
883
|
+
if (runtime.committedActionDedupeKeys.has(dedupeKey))
|
|
884
|
+
continue;
|
|
885
|
+
const request = this.adapter.action(action, frame.epochId, safetyGeneration, activation.instanceGeneration, frame.tick);
|
|
886
|
+
const receiptStartedAt = performance.now();
|
|
887
|
+
try {
|
|
888
|
+
const result = await context.capabilities.performAction(this.options.actionCapability, { ...request, behaviorOriginId: activation.behaviorId }, asActionCaller(control.caller));
|
|
889
|
+
context.diagnostic('behavior.action.receipt', {
|
|
890
|
+
behavior_id: activation.behaviorId,
|
|
891
|
+
activation_id: activation.activationId,
|
|
892
|
+
instance_generation: activation.instanceGeneration,
|
|
893
|
+
epoch_id: frame.epochId,
|
|
894
|
+
tick: frame.tick,
|
|
895
|
+
action_index: index,
|
|
896
|
+
action_kind: action.action,
|
|
897
|
+
action_id: result.actionId,
|
|
898
|
+
status: result.status,
|
|
899
|
+
...(result.source ? { action_source: result.source } : {}),
|
|
900
|
+
...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
|
|
901
|
+
receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
|
|
902
|
+
}, result.status === 'failure' ? 'warn' : 'debug');
|
|
903
|
+
if (result.actionOutcome !== 'not_submitted') {
|
|
904
|
+
runtime.committedActionDedupeKeys.set(dedupeKey, frame.epochId);
|
|
905
|
+
while (runtime.committedActionDedupeKeys.size > 2_048) {
|
|
906
|
+
const oldest = runtime.committedActionDedupeKeys.keys().next().value;
|
|
907
|
+
if (oldest === undefined)
|
|
908
|
+
break;
|
|
909
|
+
runtime.committedActionDedupeKeys.delete(oldest);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
if (result.actionOutcome === 'not_submitted' && !control.isAuthorized())
|
|
913
|
+
break;
|
|
914
|
+
}
|
|
915
|
+
catch (error) {
|
|
916
|
+
context.diagnostic('behavior.action.failed', {
|
|
917
|
+
behavior_id: activation.behaviorId,
|
|
918
|
+
activation_id: activation.activationId,
|
|
919
|
+
instance_generation: activation.instanceGeneration,
|
|
920
|
+
epoch_id: frame.epochId,
|
|
921
|
+
tick: frame.tick,
|
|
922
|
+
action_index: index,
|
|
923
|
+
action_kind: action.action,
|
|
924
|
+
receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
|
|
925
|
+
error_code: errorCode(error, 'BEHAVIOR_ACTION_FAILED'),
|
|
926
|
+
}, 'error');
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) {
|
|
930
|
+
return { events: [] };
|
|
931
|
+
}
|
|
932
|
+
const events = (decision.events ?? []).map((event, index) => ({
|
|
933
|
+
type: event.type,
|
|
934
|
+
dedupeKey: `${activation.activationId}:${activation.instanceGeneration}:${frame.tick ?? frame.epochId}:${event.type}:${index}`,
|
|
935
|
+
payload: { ...event.payload },
|
|
936
|
+
...(event.occurredAt === undefined ? {} : { occurredAt: event.occurredAt }),
|
|
937
|
+
}));
|
|
938
|
+
if (delegated) {
|
|
939
|
+
// Keep the status on the suspended parent. Publishing it as the current
|
|
940
|
+
// semantic status would incorrectly attach it to the newly started child.
|
|
941
|
+
runtime.lastStatus = decision.status ?? runtime.lastStatus;
|
|
942
|
+
await this.startDelegatedShort(activation, delegated, frame.nowMs);
|
|
943
|
+
}
|
|
944
|
+
else if (decision.finish) {
|
|
945
|
+
await this.finishCurrent(activation, decision.finish, frame.nowMs);
|
|
946
|
+
}
|
|
947
|
+
return {
|
|
948
|
+
...(decision.status === undefined || delegated ? {} : { status: decision.status }),
|
|
949
|
+
events,
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
async prepareDelegatedShort(delegation) {
|
|
953
|
+
const rawInput = delegation.input ?? Object.freeze({});
|
|
954
|
+
const target = 'strategy' in delegation ? delegation.strategy : delegation.behavior;
|
|
955
|
+
const prepared = await this.prepareInput(target, rawInput);
|
|
956
|
+
return Object.freeze({
|
|
957
|
+
behaviorId: target,
|
|
958
|
+
rawInput: Object.freeze(structuredClone(rawInput)),
|
|
959
|
+
prepared,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
async startDelegatedShort(parent, delegated, now) {
|
|
963
|
+
if (!this.manager.isCurrent(parent.activationId, parent.instanceGeneration))
|
|
964
|
+
return;
|
|
965
|
+
const activationId = this.createActivationId();
|
|
966
|
+
const maxRuntimeMs = runtimeMs(delegated.prepared, delegated.rawInput)
|
|
967
|
+
?? DEFAULT_SHORT_MAX_RUNTIME_MS;
|
|
968
|
+
const transitions = this.manager.startShort({
|
|
969
|
+
activationId,
|
|
970
|
+
behaviorId: delegated.behaviorId,
|
|
971
|
+
source: 'behavior',
|
|
972
|
+
input: delegated.prepared.input,
|
|
973
|
+
requestedAt: now,
|
|
974
|
+
maxRuntimeMs,
|
|
975
|
+
deadlineOutcome: deadlineOutcome(delegated.prepared, delegated.rawInput) ?? 'failed',
|
|
976
|
+
}, now);
|
|
977
|
+
this.runtimes.set(activationId, {
|
|
978
|
+
activationId,
|
|
979
|
+
behaviorId: delegated.behaviorId,
|
|
980
|
+
prepared: delegated.prepared,
|
|
981
|
+
decisionHistory: new BehaviorDecisionHistory(),
|
|
982
|
+
committedActionDedupeKeys: new Map(),
|
|
983
|
+
});
|
|
984
|
+
this.delegatedShorts.set(activationId, Object.freeze({
|
|
985
|
+
parentActivationId: parent.activationId,
|
|
986
|
+
}));
|
|
987
|
+
await this.applyTransitions(transitions);
|
|
988
|
+
}
|
|
989
|
+
async finishCurrent(activation, finish, now) {
|
|
990
|
+
if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration))
|
|
991
|
+
return;
|
|
992
|
+
if (finish.summary !== undefined) {
|
|
993
|
+
this.finishSummaries.set(activation.activationId, finish.summary);
|
|
994
|
+
}
|
|
995
|
+
await this.applyTransitions(this.manager.finish(activation.activationId, finish.outcome, finish.reason, now));
|
|
996
|
+
}
|
|
997
|
+
async failCurrent(activation, reason, now) {
|
|
998
|
+
if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration))
|
|
999
|
+
return;
|
|
1000
|
+
await this.applyTransitions(this.manager.finish(activation.activationId, 'failed', reason, now));
|
|
1001
|
+
}
|
|
1002
|
+
async applyTransitions(transitions) {
|
|
1003
|
+
this.captureDelegationResults(transitions);
|
|
1004
|
+
for (const transition of transitions) {
|
|
1005
|
+
const event = lifecycleEvent(transition);
|
|
1006
|
+
if (event)
|
|
1007
|
+
this.pendingLifecycleEvents.push(event);
|
|
1008
|
+
}
|
|
1009
|
+
const failures = [];
|
|
1010
|
+
// Reserve the incoming controller before releasing the outgoing layer.
|
|
1011
|
+
// Equal-layer replacement is held until the old controller is released;
|
|
1012
|
+
// a higher layer becomes active immediately, leaving no takeover gap.
|
|
1013
|
+
for (const transition of transitions) {
|
|
1014
|
+
if (transition.type !== 'started' && transition.type !== 'restarted')
|
|
1015
|
+
continue;
|
|
1016
|
+
const snapshot = currentRuntimeSnapshot(this.manager, transition.activationId);
|
|
1017
|
+
if (!snapshot)
|
|
1018
|
+
continue;
|
|
1019
|
+
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;
|
|
1030
|
+
}
|
|
1031
|
+
catch (error) {
|
|
1032
|
+
this.diagnostic?.('behavior.activation.failed', {
|
|
1033
|
+
behavior_id: snapshot.behaviorId,
|
|
1034
|
+
activation_id: snapshot.activationId,
|
|
1035
|
+
instance_generation: snapshot.instanceGeneration,
|
|
1036
|
+
error_code: errorCode(error, 'BEHAVIOR_ACTIVATION_FAILED'),
|
|
1037
|
+
}, 'error');
|
|
1038
|
+
failures.push(...this.manager.finish(snapshot.activationId, 'failed', errorCode(error, 'behavior_activation_failed'), this.now()));
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
for (const transition of transitions) {
|
|
1042
|
+
if (transition.type === 'suspended'
|
|
1043
|
+
|| transition.type === 'completed'
|
|
1044
|
+
|| transition.type === 'failed'
|
|
1045
|
+
|| transition.type === 'cancelled'
|
|
1046
|
+
|| transition.type === 'replaced') {
|
|
1047
|
+
this.controls.get(transition.activationId)?.release(`behavior_${transition.type}:${transition.reason}`);
|
|
1048
|
+
this.controls.delete(transition.activationId);
|
|
1049
|
+
const runtime = this.runtimes.get(transition.activationId);
|
|
1050
|
+
await runtime?.runner?.stop('switched');
|
|
1051
|
+
if (runtime) {
|
|
1052
|
+
runtime.runner = undefined;
|
|
1053
|
+
runtime.instanceGeneration = undefined;
|
|
1054
|
+
}
|
|
1055
|
+
if (transition.type !== 'suspended')
|
|
1056
|
+
this.runtimes.delete(transition.activationId);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
if (failures.length > 0)
|
|
1060
|
+
await this.applyTransitions(failures);
|
|
1061
|
+
}
|
|
1062
|
+
captureDelegationResults(transitions) {
|
|
1063
|
+
for (const transition of transitions) {
|
|
1064
|
+
if (transition.type !== 'completed'
|
|
1065
|
+
&& transition.type !== 'failed'
|
|
1066
|
+
&& transition.type !== 'cancelled'
|
|
1067
|
+
&& transition.type !== 'replaced')
|
|
1068
|
+
continue;
|
|
1069
|
+
const delegated = this.delegatedShorts.get(transition.activationId);
|
|
1070
|
+
const summary = this.finishSummaries.get(transition.activationId);
|
|
1071
|
+
if (delegated) {
|
|
1072
|
+
const parent = currentRuntimeSnapshot(this.manager, delegated.parentActivationId);
|
|
1073
|
+
const parentRuntime = this.runtimes.get(delegated.parentActivationId);
|
|
1074
|
+
if (parent?.layer === 'long' && parentRuntime) {
|
|
1075
|
+
parentRuntime.pendingContinuation = Object.freeze({
|
|
1076
|
+
delegatedBehavior: Object.freeze({
|
|
1077
|
+
activationId: transition.activationId,
|
|
1078
|
+
behavior: transition.behaviorId,
|
|
1079
|
+
outcome: transition.type,
|
|
1080
|
+
reason: transition.reason,
|
|
1081
|
+
...(summary === undefined ? {} : { summary }),
|
|
1082
|
+
}),
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
this.delegatedShorts.delete(transition.activationId);
|
|
1086
|
+
}
|
|
1087
|
+
this.finishSummaries.delete(transition.activationId);
|
|
1088
|
+
if (transition.layer === 'long') {
|
|
1089
|
+
for (const [childActivationId, relation] of this.delegatedShorts) {
|
|
1090
|
+
if (relation.parentActivationId === transition.activationId) {
|
|
1091
|
+
this.delegatedShorts.delete(childActivationId);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
async ensureRuntime(activation) {
|
|
1098
|
+
let runtime = this.runtimes.get(activation.activationId);
|
|
1099
|
+
if (!runtime) {
|
|
1100
|
+
let prepared;
|
|
1101
|
+
if (activation.source === 'idle'
|
|
1102
|
+
&& this.fallbackPrepared?.manifest.id === activation.behaviorId) {
|
|
1103
|
+
prepared = this.fallbackPreparedUsed
|
|
1104
|
+
? Object.freeze({
|
|
1105
|
+
...this.fallbackPrepared,
|
|
1106
|
+
...(this.fallbackPrepared.createModule
|
|
1107
|
+
? { module: this.fallbackPrepared.createModule() }
|
|
1108
|
+
: {}),
|
|
1109
|
+
})
|
|
1110
|
+
: this.fallbackPrepared;
|
|
1111
|
+
this.fallbackPreparedUsed = true;
|
|
1112
|
+
}
|
|
1113
|
+
else {
|
|
1114
|
+
prepared = await this.prepareInput(activation.behaviorId, activation.input);
|
|
1115
|
+
}
|
|
1116
|
+
runtime = {
|
|
1117
|
+
activationId: activation.activationId,
|
|
1118
|
+
behaviorId: activation.behaviorId,
|
|
1119
|
+
prepared,
|
|
1120
|
+
decisionHistory: new BehaviorDecisionHistory(),
|
|
1121
|
+
committedActionDedupeKeys: new Map(),
|
|
1122
|
+
};
|
|
1123
|
+
this.runtimes.set(activation.activationId, runtime);
|
|
1124
|
+
}
|
|
1125
|
+
await runtime.runner?.stop('switched');
|
|
1126
|
+
const prepared = runtime.instanceGeneration === undefined && activation.instanceGeneration === 1
|
|
1127
|
+
? runtime.prepared
|
|
1128
|
+
: Object.freeze({
|
|
1129
|
+
...runtime.prepared,
|
|
1130
|
+
...(runtime.prepared.createModule
|
|
1131
|
+
? { module: runtime.prepared.createModule() }
|
|
1132
|
+
: {}),
|
|
1133
|
+
});
|
|
1134
|
+
runtime.runner = this.adapter.createRunner({
|
|
1135
|
+
memory: (input, active) => this.memory.bind(input.scope, `behavior:${activation.behaviorId}`, active),
|
|
1136
|
+
snapshotStore: runtime.snapshotStore ??= new BehaviorSnapshotStore(),
|
|
1137
|
+
behaviorId: activation.behaviorId,
|
|
1138
|
+
activationId: activation.activationId,
|
|
1139
|
+
instanceGeneration: activation.instanceGeneration,
|
|
1140
|
+
prepared,
|
|
1141
|
+
diagnostic: this.diagnostic,
|
|
1142
|
+
diagnosticsEnabled: this.diagnosticsEnabled,
|
|
1143
|
+
isActive: () => this.manager.isCurrent(activation.activationId, activation.instanceGeneration),
|
|
1144
|
+
});
|
|
1145
|
+
runtime.instanceGeneration = activation.instanceGeneration;
|
|
1146
|
+
await runtime.runner.prepare();
|
|
1147
|
+
runtime.lastCommittedBackendTick = undefined;
|
|
1148
|
+
runtime.lastStatus = undefined;
|
|
1149
|
+
runtime.committedActionDedupeKeys.clear();
|
|
1150
|
+
return runtime;
|
|
1151
|
+
}
|
|
1152
|
+
async syncRoleFallback(role, now) {
|
|
1153
|
+
if (this.manualFallbackOverride)
|
|
1154
|
+
return;
|
|
1155
|
+
if (typeof role !== 'string' || !role)
|
|
1156
|
+
return;
|
|
1157
|
+
const configured = this.fallbackBehaviors.get(role);
|
|
1158
|
+
const key = `${this.fallbackConfigGeneration}:${role}:${configured?.behaviorId ?? ''}`;
|
|
1159
|
+
if (this.appliedFallbackKey === key)
|
|
1160
|
+
return;
|
|
1161
|
+
this.appliedFallbackKey = key;
|
|
1162
|
+
if (!configured) {
|
|
1163
|
+
this.fallbackPrepared = undefined;
|
|
1164
|
+
this.fallbackBaseInput = undefined;
|
|
1165
|
+
this.fallbackPreparedUsed = false;
|
|
1166
|
+
await this.applyTransitions(this.manager.bindFallback(undefined, now));
|
|
1167
|
+
return;
|
|
1168
|
+
}
|
|
1169
|
+
try {
|
|
1170
|
+
const prepared = await this.prepareInput(configured.behaviorId, configured.input ?? {});
|
|
1171
|
+
this.fallbackPrepared = prepared;
|
|
1172
|
+
this.fallbackBaseInput = { behaviorId: configured.behaviorId, input: structuredClone(configured.input ?? {}) };
|
|
1173
|
+
this.fallbackPreparedUsed = false;
|
|
1174
|
+
await this.applyTransitions(this.manager.bindFallback({
|
|
1175
|
+
behaviorId: configured.behaviorId,
|
|
1176
|
+
input: prepared.input,
|
|
1177
|
+
}, now, true));
|
|
1178
|
+
}
|
|
1179
|
+
catch (error) {
|
|
1180
|
+
this.fallbackPrepared = undefined;
|
|
1181
|
+
this.fallbackBaseInput = undefined;
|
|
1182
|
+
this.fallbackPreparedUsed = false;
|
|
1183
|
+
await this.applyTransitions(this.manager.bindFallback(undefined, now));
|
|
1184
|
+
this.diagnostic?.('behavior.fallback.invalid', {
|
|
1185
|
+
role,
|
|
1186
|
+
behavior_id: configured.behaviorId,
|
|
1187
|
+
error_code: errorCode(error, 'BEHAVIOR_FALLBACK_INVALID'),
|
|
1188
|
+
}, 'warn');
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
/**
|
|
1192
|
+
* The backend still calls this display-only field a Strategy. Report the
|
|
1193
|
+
* current activation, including short/reflex overrides. The adapter may also
|
|
1194
|
+
* expose an inactive selection for display without giving it control.
|
|
1195
|
+
*/
|
|
1196
|
+
backendStrategyDescriptor() {
|
|
1197
|
+
const current = this.manager.current();
|
|
1198
|
+
const stack = this.manager.snapshot();
|
|
1199
|
+
const includeSelection = this.backendStrategyReportSelection === 'selected';
|
|
1200
|
+
const selected = current ?? (includeSelection ? stack.long : undefined);
|
|
1201
|
+
const prepared = selected
|
|
1202
|
+
? this.runtimes.get(selected.activationId)?.prepared
|
|
1203
|
+
: includeSelection && stack.fallback?.behaviorId === this.fallbackPrepared?.manifest.id
|
|
1204
|
+
? this.fallbackPrepared
|
|
1205
|
+
: undefined;
|
|
1206
|
+
if (!selected && !prepared)
|
|
1207
|
+
return this.adapter.display();
|
|
1208
|
+
if (!prepared || (selected && prepared.manifest.id !== selected.behaviorId))
|
|
1209
|
+
return undefined;
|
|
1210
|
+
return this.adapter.display(prepared);
|
|
1211
|
+
}
|
|
1212
|
+
refreshBackendStrategyReport(input, context) {
|
|
1213
|
+
const wasEligible = this.backendStrategyReportEligible;
|
|
1214
|
+
this.backendStrategyReportContext = context;
|
|
1215
|
+
this.backendStrategyReportEligible = this.adapter.reportEligible(input);
|
|
1216
|
+
this.backendStrategyReportSelection = this.adapter.reportSelection?.(input) ?? 'active';
|
|
1217
|
+
this.refreshBackendStrategyReportTarget(!wasEligible && this.backendStrategyReportEligible);
|
|
1218
|
+
}
|
|
1219
|
+
refreshBackendStrategyReportTarget(becameEligible = false) {
|
|
1220
|
+
const descriptor = this.backendStrategyDescriptor();
|
|
1221
|
+
const nextTarget = descriptor
|
|
1222
|
+
? {
|
|
1223
|
+
...descriptor,
|
|
1224
|
+
fingerprint: JSON.stringify([descriptor.id, descriptor.name, descriptor.description]),
|
|
1225
|
+
}
|
|
1226
|
+
: undefined;
|
|
1227
|
+
const targetChanged = nextTarget?.fingerprint !== this.backendStrategyReportTarget?.fingerprint;
|
|
1228
|
+
if (targetChanged) {
|
|
1229
|
+
this.backendStrategyReportTarget = nextTarget;
|
|
1230
|
+
// A prior target may still be in flight at the backend. Reconfirm even
|
|
1231
|
+
// when the selection later returns to an older fingerprint.
|
|
1232
|
+
this.backendStrategyReportAcknowledgedFingerprint = undefined;
|
|
1233
|
+
this.clearBackendStrategyReportTimer();
|
|
1234
|
+
}
|
|
1235
|
+
const target = this.backendStrategyReportTarget;
|
|
1236
|
+
if (!this.backendStrategyReportEligible || !target || this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint) {
|
|
1237
|
+
this.clearBackendStrategyReportTimer();
|
|
1238
|
+
return;
|
|
1239
|
+
}
|
|
1240
|
+
if (targetChanged || becameEligible) {
|
|
1241
|
+
this.scheduleBackendStrategyReport(0, true);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
clearBackendStrategyReportTimer() {
|
|
1245
|
+
if (!this.backendStrategyReportTimer)
|
|
1246
|
+
return;
|
|
1247
|
+
clearTimeout(this.backendStrategyReportTimer);
|
|
1248
|
+
this.backendStrategyReportTimer = undefined;
|
|
1249
|
+
}
|
|
1250
|
+
scheduleBackendStrategyReport(delayMs, replace = false) {
|
|
1251
|
+
const target = this.backendStrategyReportTarget;
|
|
1252
|
+
if (!target
|
|
1253
|
+
|| this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
|
|
1254
|
+
|| this.backendStrategyReportInFlight)
|
|
1255
|
+
return;
|
|
1256
|
+
if (this.backendStrategyReportTimer) {
|
|
1257
|
+
if (!replace)
|
|
1258
|
+
return;
|
|
1259
|
+
this.clearBackendStrategyReportTimer();
|
|
1260
|
+
}
|
|
1261
|
+
const lifecycleGeneration = this.backendStrategyReportLifecycleGeneration;
|
|
1262
|
+
this.backendStrategyReportTimer = setTimeout(() => {
|
|
1263
|
+
this.backendStrategyReportTimer = undefined;
|
|
1264
|
+
if (lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration)
|
|
1265
|
+
return;
|
|
1266
|
+
this.startBackendStrategyReportAttempt();
|
|
1267
|
+
}, delayMs);
|
|
1268
|
+
this.backendStrategyReportTimer.unref?.();
|
|
1269
|
+
}
|
|
1270
|
+
startBackendStrategyReportAttempt() {
|
|
1271
|
+
const target = this.backendStrategyReportTarget;
|
|
1272
|
+
const context = this.backendStrategyReportContext;
|
|
1273
|
+
if (!target
|
|
1274
|
+
|| this.backendStrategyReportAcknowledgedFingerprint === target.fingerprint
|
|
1275
|
+
|| this.backendStrategyReportInFlight)
|
|
1276
|
+
return;
|
|
1277
|
+
if (!this.backendStrategyReportEligible || !context || context.signal.aborted) {
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
const attempt = {
|
|
1281
|
+
lifecycleGeneration: this.backendStrategyReportLifecycleGeneration,
|
|
1282
|
+
fingerprint: target.fingerprint,
|
|
1283
|
+
};
|
|
1284
|
+
this.backendStrategyReportInFlight = attempt;
|
|
1285
|
+
context.diagnostic('strategy.report.started', {
|
|
1286
|
+
strategy_id: target.id,
|
|
1287
|
+
}, 'debug');
|
|
1288
|
+
let pending;
|
|
1289
|
+
try {
|
|
1290
|
+
pending = this.adapter.report(context, target);
|
|
1291
|
+
}
|
|
1292
|
+
catch (error) {
|
|
1293
|
+
this.finishBackendStrategyReportAttempt(attempt, false, error);
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
void pending.then(result => this.finishBackendStrategyReportAttempt(attempt, this.adapter.reportSucceeded(result), result), error => this.finishBackendStrategyReportAttempt(attempt, false, error));
|
|
1297
|
+
}
|
|
1298
|
+
finishBackendStrategyReportAttempt(attempt, successful, result) {
|
|
1299
|
+
if (attempt.lifecycleGeneration !== this.backendStrategyReportLifecycleGeneration
|
|
1300
|
+
|| this.backendStrategyReportInFlight?.fingerprint !== attempt.fingerprint)
|
|
1301
|
+
return;
|
|
1302
|
+
this.backendStrategyReportInFlight = undefined;
|
|
1303
|
+
const target = this.backendStrategyReportTarget;
|
|
1304
|
+
if (successful && target?.fingerprint === attempt.fingerprint) {
|
|
1305
|
+
this.backendStrategyReportAcknowledgedFingerprint = attempt.fingerprint;
|
|
1306
|
+
this.clearBackendStrategyReportTimer();
|
|
1307
|
+
this.backendStrategyReportContext?.diagnostic('strategy.report.completed', {
|
|
1308
|
+
strategy_id: target.id,
|
|
1309
|
+
}, 'info');
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
if (target?.fingerprint === attempt.fingerprint) {
|
|
1313
|
+
if (!this.backendStrategyReportEligible) {
|
|
1314
|
+
this.clearBackendStrategyReportTimer();
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
this.backendStrategyReportContext?.diagnostic('strategy.report.retry_scheduled', {
|
|
1318
|
+
strategy_id: target.id,
|
|
1319
|
+
retry_ms: BACKEND_STRATEGY_REPORT_RETRY_MS,
|
|
1320
|
+
error_code: errorCode(result, 'STRATEGY_REPORT_RESPONSE_INVALID'),
|
|
1321
|
+
}, 'warn');
|
|
1322
|
+
this.scheduleBackendStrategyReport(BACKEND_STRATEGY_REPORT_RETRY_MS);
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
if (target
|
|
1326
|
+
&& this.backendStrategyReportAcknowledgedFingerprint !== target.fingerprint)
|
|
1327
|
+
this.scheduleBackendStrategyReport(0);
|
|
1328
|
+
}
|
|
1329
|
+
resetBackendStrategyReporting() {
|
|
1330
|
+
this.backendStrategyReportLifecycleGeneration += 1;
|
|
1331
|
+
this.clearBackendStrategyReportTimer();
|
|
1332
|
+
this.backendStrategyReportTarget = undefined;
|
|
1333
|
+
this.backendStrategyReportAcknowledgedFingerprint = undefined;
|
|
1334
|
+
this.backendStrategyReportInFlight = undefined;
|
|
1335
|
+
this.backendStrategyReportContext = undefined;
|
|
1336
|
+
this.backendStrategyReportEligible = false;
|
|
1337
|
+
this.backendStrategyReportSelection = 'active';
|
|
1338
|
+
}
|
|
1339
|
+
output(consumeEventsThroughCommitSeq, semanticStatus, decisionEvents = []) {
|
|
1340
|
+
const lifecycle = this.pendingLifecycleEvents.splice(0);
|
|
1341
|
+
const trailingLifecycle = lifecycle.filter(event => (event.type === 'behavior.completed'
|
|
1342
|
+
|| event.type === 'behavior.failed'
|
|
1343
|
+
|| event.type === 'behavior.cancelled'));
|
|
1344
|
+
const leadingLifecycle = lifecycle.filter(event => !trailingLifecycle.includes(event));
|
|
1345
|
+
const events = [...leadingLifecycle, ...decisionEvents, ...trailingLifecycle];
|
|
1346
|
+
const status = this.status();
|
|
1347
|
+
if (!status.running && events.length === 0 && semanticStatus === undefined) {
|
|
1348
|
+
return {
|
|
1349
|
+
outcome: 'noop',
|
|
1350
|
+
reason: 'behavior_inactive',
|
|
1351
|
+
...(consumeEventsThroughCommitSeq === undefined
|
|
1352
|
+
? {}
|
|
1353
|
+
: { consumeEventsThroughCommitSeq }),
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
const current = status.current;
|
|
1357
|
+
const retainedStatus = semanticStatus
|
|
1358
|
+
?? (current === undefined ? undefined : this.runtimes.get(current.activationId)?.lastStatus);
|
|
1359
|
+
const stateValue = {
|
|
1360
|
+
running: status.running,
|
|
1361
|
+
...(current === undefined ? {} : {
|
|
1362
|
+
activation_id: current.activationId,
|
|
1363
|
+
behavior: current.behaviorId,
|
|
1364
|
+
layer: current.layer,
|
|
1365
|
+
source: current.source,
|
|
1366
|
+
instance_generation: current.instanceGeneration,
|
|
1367
|
+
}),
|
|
1368
|
+
...(retainedStatus === undefined ? {} : { status: retainedStatus }),
|
|
1369
|
+
stack: status.stack,
|
|
1370
|
+
};
|
|
1371
|
+
return {
|
|
1372
|
+
outcome: 'processed',
|
|
1373
|
+
states: [{ topic: this.options.stateTopic, value: stateValue }],
|
|
1374
|
+
...(events.length === 0 ? {} : { events }),
|
|
1375
|
+
...(consumeEventsThroughCommitSeq === undefined
|
|
1376
|
+
? {}
|
|
1377
|
+
: { consumeEventsThroughCommitSeq }),
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
withDecisionTimeout(operation, signal, activationId) {
|
|
1381
|
+
if (signal.aborted)
|
|
1382
|
+
return Promise.reject(signal.reason);
|
|
1383
|
+
return new Promise((resolve, reject) => {
|
|
1384
|
+
const controller = new AbortController();
|
|
1385
|
+
let settled = false;
|
|
1386
|
+
let timer;
|
|
1387
|
+
const onAbort = () => {
|
|
1388
|
+
const reason = signal.reason instanceof Error
|
|
1389
|
+
? signal.reason
|
|
1390
|
+
: new Error('behavior_epoch_aborted');
|
|
1391
|
+
controller.abort(reason);
|
|
1392
|
+
complete(() => reject(reason));
|
|
1393
|
+
};
|
|
1394
|
+
const onInternalAbort = () => {
|
|
1395
|
+
const reason = controller.signal.reason instanceof Error
|
|
1396
|
+
? controller.signal.reason
|
|
1397
|
+
: new Error('behavior_decision_aborted');
|
|
1398
|
+
complete(() => reject(reason));
|
|
1399
|
+
};
|
|
1400
|
+
const cleanup = () => {
|
|
1401
|
+
clearTimeout(timer);
|
|
1402
|
+
signal.removeEventListener('abort', onAbort);
|
|
1403
|
+
controller.signal.removeEventListener('abort', onInternalAbort);
|
|
1404
|
+
if (activationId) {
|
|
1405
|
+
const controllers = this.decisionControllers.get(activationId);
|
|
1406
|
+
controllers?.delete(controller);
|
|
1407
|
+
if (controllers?.size === 0)
|
|
1408
|
+
this.decisionControllers.delete(activationId);
|
|
1409
|
+
}
|
|
1410
|
+
};
|
|
1411
|
+
const complete = (callback) => {
|
|
1412
|
+
if (settled)
|
|
1413
|
+
return;
|
|
1414
|
+
settled = true;
|
|
1415
|
+
cleanup();
|
|
1416
|
+
callback();
|
|
1417
|
+
};
|
|
1418
|
+
timer = setTimeout(() => {
|
|
1419
|
+
const timeout = new Error('behavior_decision_timeout');
|
|
1420
|
+
controller.abort(timeout);
|
|
1421
|
+
complete(() => reject(timeout));
|
|
1422
|
+
}, this.decisionTimeoutMs);
|
|
1423
|
+
timer.unref?.();
|
|
1424
|
+
controller.signal.addEventListener('abort', onInternalAbort, { once: true });
|
|
1425
|
+
if (activationId) {
|
|
1426
|
+
let controllers = this.decisionControllers.get(activationId);
|
|
1427
|
+
if (!controllers) {
|
|
1428
|
+
controllers = new Set();
|
|
1429
|
+
this.decisionControllers.set(activationId, controllers);
|
|
1430
|
+
}
|
|
1431
|
+
controllers.add(controller);
|
|
1432
|
+
}
|
|
1433
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
1434
|
+
void operation(controller.signal).then(value => complete(() => resolve(value)), error => complete(() => reject(error))).catch(() => { });
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1437
|
+
interruptDecisions(activationId, reason) {
|
|
1438
|
+
const controllers = this.decisionControllers.get(activationId);
|
|
1439
|
+
if (!controllers)
|
|
1440
|
+
return;
|
|
1441
|
+
const error = new Error(reason);
|
|
1442
|
+
for (const controller of controllers)
|
|
1443
|
+
controller.abort(error);
|
|
1444
|
+
}
|
|
1445
|
+
enqueueControl(operation) {
|
|
1446
|
+
const run = async () => {
|
|
1447
|
+
const result = await operation();
|
|
1448
|
+
if (this.backendStrategyReportContext)
|
|
1449
|
+
this.refreshBackendStrategyReportTarget();
|
|
1450
|
+
return result;
|
|
1451
|
+
};
|
|
1452
|
+
const pending = this.controlTail.then(run, run);
|
|
1453
|
+
this.controlTail = pending.then(() => undefined, () => undefined);
|
|
1454
|
+
return pending;
|
|
1455
|
+
}
|
|
1456
|
+
}
|