@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.1
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 +244 -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 +58 -0
- package/dist/mailbox/mailbox-plugin.js +128 -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 +338 -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,582 @@
|
|
|
1
|
+
import { DEFAULT_EVENT_CONSUMER_ID } from '../framework/events/index.js';
|
|
2
|
+
import { stableMailboxItemId } from '../framework/mailbox/index.js';
|
|
3
|
+
import { AgentMailboxCoordinator } from './agent-mailbox-coordinator.js';
|
|
4
|
+
const CCL_EVENTS_LEASE_TTL_MS = 30_000;
|
|
5
|
+
const MONITOR_OVERFLOW_LEASE_TTL_MS = 30_000;
|
|
6
|
+
const MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE = 200;
|
|
7
|
+
const MONITOR_PROTECTED_PRIORITY = 80;
|
|
8
|
+
const MONITOR_PRIORITY_BYPASS_ITEM_LIMIT = 4;
|
|
9
|
+
export const DEFAULT_MONITOR_PENDING_ITEM_LIMIT = 10;
|
|
10
|
+
/** Rolling admission window for ordinary Monitor output. */
|
|
11
|
+
export const DEFAULT_MONITOR_ADMISSION_WINDOW_MS = 60_000;
|
|
12
|
+
/** Ordinary short items admitted during one rolling window. */
|
|
13
|
+
export const DEFAULT_MONITOR_ORDINARY_WINDOW_ITEM_BUDGET = 12;
|
|
14
|
+
/** Additional ordinary-only backlog wake-ups admitted during one rolling window. */
|
|
15
|
+
export const DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET = 4;
|
|
16
|
+
/** Minimum spacing between directly presented visual telemetry items. */
|
|
17
|
+
export const DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS = 5_000;
|
|
18
|
+
/** Monitor direct-notification and the explicit event query detail adapters over the Agent Mailbox core. */
|
|
19
|
+
export class MailboxService {
|
|
20
|
+
adapter;
|
|
21
|
+
repository;
|
|
22
|
+
readyView;
|
|
23
|
+
agentMailbox;
|
|
24
|
+
ownsAgentMailbox;
|
|
25
|
+
consumerId;
|
|
26
|
+
monitorEnabled;
|
|
27
|
+
monitorPendingItemLimit;
|
|
28
|
+
monitorOrdinaryWindowItemBudget;
|
|
29
|
+
monitorBacklogHintWindowItemBudget;
|
|
30
|
+
monitorAdmissionWindowMs;
|
|
31
|
+
monitorVisualMinIntervalMs;
|
|
32
|
+
monitorOrdinaryAdmissionTimesMs = [];
|
|
33
|
+
monitorBacklogHintAdmissionTimesMs = [];
|
|
34
|
+
monitorLastVisualAdmissionAtMs;
|
|
35
|
+
delegatedDetailsConsumerId;
|
|
36
|
+
now;
|
|
37
|
+
diagnostic;
|
|
38
|
+
lastObservedReadyEpochSeq = 0;
|
|
39
|
+
backlogHintEventId;
|
|
40
|
+
stopped = false;
|
|
41
|
+
policy;
|
|
42
|
+
notificationOnly;
|
|
43
|
+
constructor(options) {
|
|
44
|
+
this.policy = options.policy;
|
|
45
|
+
this.notificationOnly = options.notificationOnly ?? false;
|
|
46
|
+
this.repository = options.repository;
|
|
47
|
+
this.readyView = options.readyView;
|
|
48
|
+
this.consumerId = options.consumerId ?? DEFAULT_EVENT_CONSUMER_ID;
|
|
49
|
+
this.monitorEnabled = options.monitorEnabled ?? true;
|
|
50
|
+
this.monitorPendingItemLimit = options.monitorPendingItemLimit
|
|
51
|
+
?? DEFAULT_MONITOR_PENDING_ITEM_LIMIT;
|
|
52
|
+
if (!Number.isInteger(this.monitorPendingItemLimit) || this.monitorPendingItemLimit <= 0) {
|
|
53
|
+
throw new Error('monitor_pending_item_limit_invalid');
|
|
54
|
+
}
|
|
55
|
+
this.monitorOrdinaryWindowItemBudget = options.monitorOrdinaryWindowItemBudget
|
|
56
|
+
?? DEFAULT_MONITOR_ORDINARY_WINDOW_ITEM_BUDGET;
|
|
57
|
+
if (!Number.isInteger(this.monitorOrdinaryWindowItemBudget)
|
|
58
|
+
|| this.monitorOrdinaryWindowItemBudget < 0) {
|
|
59
|
+
throw new Error('monitor_ordinary_window_item_budget_invalid');
|
|
60
|
+
}
|
|
61
|
+
this.monitorBacklogHintWindowItemBudget = options.monitorBacklogHintWindowItemBudget
|
|
62
|
+
?? DEFAULT_MONITOR_BACKLOG_HINT_WINDOW_ITEM_BUDGET;
|
|
63
|
+
if (!Number.isInteger(this.monitorBacklogHintWindowItemBudget)
|
|
64
|
+
|| this.monitorBacklogHintWindowItemBudget < 0) {
|
|
65
|
+
throw new Error('monitor_backlog_hint_window_item_budget_invalid');
|
|
66
|
+
}
|
|
67
|
+
this.monitorAdmissionWindowMs = options.monitorAdmissionWindowMs
|
|
68
|
+
?? DEFAULT_MONITOR_ADMISSION_WINDOW_MS;
|
|
69
|
+
if (!Number.isInteger(this.monitorAdmissionWindowMs) || this.monitorAdmissionWindowMs <= 0) {
|
|
70
|
+
throw new Error('monitor_admission_window_ms_invalid');
|
|
71
|
+
}
|
|
72
|
+
this.monitorVisualMinIntervalMs = options.monitorVisualMinIntervalMs
|
|
73
|
+
?? DEFAULT_MONITOR_VISUAL_MIN_INTERVAL_MS;
|
|
74
|
+
if (!Number.isInteger(this.monitorVisualMinIntervalMs)
|
|
75
|
+
|| this.monitorVisualMinIntervalMs < 0) {
|
|
76
|
+
throw new Error('monitor_visual_min_interval_ms_invalid');
|
|
77
|
+
}
|
|
78
|
+
this.delegatedDetailsConsumerId = options.delegatedDetailsConsumerId ?? this.consumerId;
|
|
79
|
+
this.adapter = this.monitorEnabled ? {
|
|
80
|
+
id: this.policy.monitorAdapterId,
|
|
81
|
+
acknowledgement: 'explicit',
|
|
82
|
+
consumerId: this.consumerId,
|
|
83
|
+
} : undefined;
|
|
84
|
+
this.now = options.now ?? Date.now;
|
|
85
|
+
this.diagnostic = options.diagnostic;
|
|
86
|
+
this.ownsAgentMailbox = !options.agentMailbox;
|
|
87
|
+
this.agentMailbox = options.agentMailbox ?? new AgentMailboxCoordinator({
|
|
88
|
+
repository: options.repository,
|
|
89
|
+
readyView: options.readyView,
|
|
90
|
+
presentEvent: this.policy.presentEvent,
|
|
91
|
+
compactState: this.policy.compactState,
|
|
92
|
+
projectState: this.policy.projectState,
|
|
93
|
+
admitEvent: this.notificationOnly ? this.policy.admitEvent : undefined,
|
|
94
|
+
eventFilter: this.policy.requiresDetails,
|
|
95
|
+
delegatedMonitorConsumerId: this.consumerId,
|
|
96
|
+
consumerId: this.consumerId,
|
|
97
|
+
now: this.now,
|
|
98
|
+
diagnostic: this.diagnostic,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
prepareEvents(request = {}, readyView) {
|
|
102
|
+
this.assertRunning();
|
|
103
|
+
const ready = this.captureReadyView(readyView);
|
|
104
|
+
if (ready.epochSeq <= 0)
|
|
105
|
+
return { output: { schema: this.policy.querySchema, state: null, events: [] } };
|
|
106
|
+
if (request.eventType) {
|
|
107
|
+
const event = this.repository.listCommittedEvents({
|
|
108
|
+
sessionId: ready.scope.sessionId,
|
|
109
|
+
types: [request.eventType],
|
|
110
|
+
maxCommitSeq: ready.eventWatermark,
|
|
111
|
+
maxEpochSeq: ready.epochSeq,
|
|
112
|
+
order: 'desc',
|
|
113
|
+
limit: 1,
|
|
114
|
+
})[0];
|
|
115
|
+
const visible = event && event.deliveryClass !== 'internal_only'
|
|
116
|
+
&& (!this.notificationOnly || this.policy.admitEvent(event)) ? event : undefined;
|
|
117
|
+
const presented = visible
|
|
118
|
+
? this.policy.presentEvent(visible, ready.state.state)
|
|
119
|
+
: null;
|
|
120
|
+
return {
|
|
121
|
+
output: {
|
|
122
|
+
schema: this.policy.querySchema,
|
|
123
|
+
query: { type: request.eventType },
|
|
124
|
+
state: this.agentMailbox.stateForReadyView(ready),
|
|
125
|
+
found: !!presented,
|
|
126
|
+
event: presented,
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
let prepared;
|
|
131
|
+
try {
|
|
132
|
+
prepared = this.agentMailbox.prepareEvents({
|
|
133
|
+
readyView: ready,
|
|
134
|
+
bypassDelay: true,
|
|
135
|
+
deliveryVia: request.mode === 'backlog' ? `${this.policy.detailPrefix}_backlog` : this.policy.detailPrefix,
|
|
136
|
+
ownerIdPrefix: this.policy.detailPrefix,
|
|
137
|
+
leaseTtlMs: CCL_EVENTS_LEASE_TTL_MS,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
return this.policy.mapError(error);
|
|
142
|
+
}
|
|
143
|
+
return {
|
|
144
|
+
output: {
|
|
145
|
+
schema: this.policy.querySchema,
|
|
146
|
+
...prepared.batch,
|
|
147
|
+
},
|
|
148
|
+
...(prepared.deliveryToken ? { deliveryToken: prepared.deliveryToken } : {}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/** Serializes pull delivery while preserving the caller's immutable Ready View. */
|
|
152
|
+
async prepareEventsWhenAvailable(request = {}, readyView, timeoutMs = 5_000) {
|
|
153
|
+
if (request.eventType)
|
|
154
|
+
return this.prepareEvents(request, readyView);
|
|
155
|
+
this.assertRunning();
|
|
156
|
+
const ready = this.captureReadyView(readyView);
|
|
157
|
+
if (ready.epochSeq <= 0)
|
|
158
|
+
return { output: { schema: this.policy.querySchema, state: null, events: [] } };
|
|
159
|
+
let prepared;
|
|
160
|
+
try {
|
|
161
|
+
prepared = await this.agentMailbox.prepareEventsWhenAvailable({
|
|
162
|
+
readyView: ready,
|
|
163
|
+
bypassDelay: true,
|
|
164
|
+
deliveryVia: request.mode === 'backlog' ? `${this.policy.detailPrefix}_backlog` : this.policy.detailPrefix,
|
|
165
|
+
ownerIdPrefix: this.policy.detailPrefix,
|
|
166
|
+
leaseTtlMs: CCL_EVENTS_LEASE_TTL_MS,
|
|
167
|
+
}, timeoutMs);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
return this.policy.mapError(error);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
output: {
|
|
174
|
+
schema: this.policy.querySchema,
|
|
175
|
+
...prepared.batch,
|
|
176
|
+
},
|
|
177
|
+
...(prepared.deliveryToken ? { deliveryToken: prepared.deliveryToken } : {}),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
ackEvents(deliveryToken) {
|
|
181
|
+
return this.agentMailbox.ack(deliveryToken);
|
|
182
|
+
}
|
|
183
|
+
releaseEvents(deliveryToken) {
|
|
184
|
+
return this.agentMailbox.release(deliveryToken);
|
|
185
|
+
}
|
|
186
|
+
/** Called by the Monitor Driver at its own cadence, never by each epoch. */
|
|
187
|
+
prepareMonitor(_force = false) {
|
|
188
|
+
this.assertRunning();
|
|
189
|
+
if (!this.monitorEnabled)
|
|
190
|
+
return 0;
|
|
191
|
+
const ready = this.captureReadyView();
|
|
192
|
+
if (this.notificationOnly) {
|
|
193
|
+
// A recovered queue may contain envelopes created by an older producer policy.
|
|
194
|
+
// Do not let those stored envelopes bypass current notification admission.
|
|
195
|
+
const rejected = this.repository.peekMailbox({ consumerId: this.consumerId,
|
|
196
|
+
sessionId: ready.scope.sessionId, modes: ['short'], states: ['pending', 'claimed'], order: 'asc' })
|
|
197
|
+
.filter(item => {
|
|
198
|
+
const event = this.repository.eventById(item.eventId);
|
|
199
|
+
return !event || !this.policy.admitEvent(event);
|
|
200
|
+
}).map(item => item.eventId);
|
|
201
|
+
if (rejected.length)
|
|
202
|
+
this.repository.suppressMailboxItems({ consumerId: this.consumerId,
|
|
203
|
+
sessionId: ready.scope.sessionId, eventIds: rejected, modes: ['short'], includeExpiredClaims: true, nowMs: this.now() });
|
|
204
|
+
}
|
|
205
|
+
if (ready.epochSeq <= 0)
|
|
206
|
+
return 0;
|
|
207
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.consumerId, ['monitor']);
|
|
208
|
+
const rows = this.repository.listEvents({
|
|
209
|
+
sessionId: ready.scope.sessionId,
|
|
210
|
+
deliveryClasses: ['monitor_and_events'],
|
|
211
|
+
monitorStates: ['pending'],
|
|
212
|
+
maxCommitSeq: ready.eventWatermark,
|
|
213
|
+
maxEpochSeq: ready.epochSeq,
|
|
214
|
+
order: 'asc',
|
|
215
|
+
}, this.consumerId, ['monitor']).filter(row => !this.notificationOnly || this.policy.admitEvent(row.event));
|
|
216
|
+
const unprojected = rows.filter((row) => !this.repository.mailboxItemForEvent(this.consumerId, row.event.eventId, 'short'));
|
|
217
|
+
if (unprojected.length === 0 || !unprojected.some(({ event }) => event.wakeAgent !== false))
|
|
218
|
+
return 0;
|
|
219
|
+
const nowMs = this.now();
|
|
220
|
+
this.pruneMonitorAdmissionWindows(nowMs);
|
|
221
|
+
const ordinaryWindowItemsRemaining = Math.max(0, this.monitorOrdinaryWindowItemBudget - this.monitorOrdinaryAdmissionTimesMs.length);
|
|
222
|
+
const backlogHintWindowItemsRemaining = Math.max(0, this.monitorBacklogHintWindowItemBudget - this.monitorBacklogHintAdmissionTimesMs.length);
|
|
223
|
+
const visualAdmissionAvailable = this.monitorLastVisualAdmissionAtMs === undefined
|
|
224
|
+
|| nowMs - this.monitorLastVisualAdmissionAtMs >= this.monitorVisualMinIntervalMs;
|
|
225
|
+
const queuedItems = this.repository.peekMailbox({
|
|
226
|
+
consumerId: this.consumerId,
|
|
227
|
+
sessionId: ready.scope.sessionId,
|
|
228
|
+
modes: ['short'],
|
|
229
|
+
states: ['pending', 'claimed'],
|
|
230
|
+
order: 'asc',
|
|
231
|
+
limit: this.monitorPendingItemLimit + MONITOR_PRIORITY_BYPASS_ITEM_LIMIT + 1,
|
|
232
|
+
});
|
|
233
|
+
const queuedItemCount = queuedItems.length;
|
|
234
|
+
const delegatedUnreadBefore = this.delegatedUnreadCount(ready);
|
|
235
|
+
if (delegatedUnreadBefore === 0)
|
|
236
|
+
this.backlogHintEventId = undefined;
|
|
237
|
+
const queuedBacklogHint = queuedItems.find((item) => (!!item.payload.backlog && typeof item.payload.backlog === 'object'));
|
|
238
|
+
if (queuedBacklogHint)
|
|
239
|
+
this.backlogHintEventId = queuedBacklogHint.eventId;
|
|
240
|
+
const storedBacklogHint = this.backlogHintEventId
|
|
241
|
+
? this.repository.mailboxItemForEvent(this.consumerId, this.backlogHintEventId, 'short')
|
|
242
|
+
: null;
|
|
243
|
+
const backlogHintOutstanding = !!queuedBacklogHint || (delegatedUnreadBefore > 0
|
|
244
|
+
&& !!storedBacklogHint
|
|
245
|
+
&& storedBacklogHint.state !== 'suppressed');
|
|
246
|
+
const queuedBaseItemCount = queuedItems.filter((item) => (!item.payload.backlog || typeof item.payload.backlog !== 'object')).length;
|
|
247
|
+
const availableBaseItemCount = Math.max(0, this.monitorPendingItemLimit - queuedBaseItemCount);
|
|
248
|
+
const usedPriorityBypassItemCount = Math.max(0, queuedBaseItemCount - this.monitorPendingItemLimit);
|
|
249
|
+
const availablePriorityBypassItemCount = Math.max(0, MONITOR_PRIORITY_BYPASS_ITEM_LIMIT - usedPriorityBypassItemCount);
|
|
250
|
+
const protectedEvents = unprojected
|
|
251
|
+
.filter((row) => this.policy.mustRemainDirect(row.event))
|
|
252
|
+
.sort((left, right) => (this.policy.admissionPriority(right.event)
|
|
253
|
+
- this.policy.admissionPriority(left.event)
|
|
254
|
+
|| left.event.commitSeq - right.event.commitSeq));
|
|
255
|
+
const protectedCapacity = availableBaseItemCount + availablePriorityBypassItemCount;
|
|
256
|
+
const directProtected = protectedEvents.slice(0, protectedCapacity);
|
|
257
|
+
const remainingBaseItemCount = Math.max(0, availableBaseItemCount - Math.min(directProtected.length, availableBaseItemCount));
|
|
258
|
+
const allOrdinaryEvents = unprojected
|
|
259
|
+
.filter((row) => !this.policy.mustRemainDirect(row.event));
|
|
260
|
+
const noisyVisualEvents = allOrdinaryEvents
|
|
261
|
+
.filter((row) => this.policy.isRateLimited(row.event))
|
|
262
|
+
.sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
263
|
+
const directVisualCandidate = visualAdmissionAvailable ? [...noisyVisualEvents].sort((left, right) => (this.policy.priority(right.event) - this.policy.priority(left.event)
|
|
264
|
+
|| right.event.commitSeq - left.event.commitSeq))[0] : undefined;
|
|
265
|
+
const coalescedVisualOverflow = directVisualCandidate
|
|
266
|
+
? noisyVisualEvents.filter((row) => row !== directVisualCandidate)
|
|
267
|
+
: noisyVisualEvents;
|
|
268
|
+
const ordinaryEvents = allOrdinaryEvents
|
|
269
|
+
.filter((row) => !this.policy.isRateLimited(row.event))
|
|
270
|
+
.concat(directVisualCandidate ? [directVisualCandidate] : [])
|
|
271
|
+
.sort((left, right) => (this.policy.priority(right.event) - this.policy.priority(left.event)
|
|
272
|
+
|| this.policy.retentionRank(left.event) - this.policy.retentionRank(right.event)
|
|
273
|
+
|| left.event.commitSeq - right.event.commitSeq));
|
|
274
|
+
const ordinaryDirectAdmissionCount = Math.min(remainingBaseItemCount, ordinaryWindowItemsRemaining);
|
|
275
|
+
const directOrdinary = ordinaryEvents.slice(0, ordinaryDirectAdmissionCount);
|
|
276
|
+
const ordinaryBudgetEventIds = new Set(directOrdinary.map((row) => row.event.eventId));
|
|
277
|
+
let overflow = [
|
|
278
|
+
...ordinaryEvents.slice(ordinaryDirectAdmissionCount),
|
|
279
|
+
...coalescedVisualOverflow,
|
|
280
|
+
].sort((left, right) => left.event.commitSeq - right.event.commitSeq);
|
|
281
|
+
let direct = [...directProtected, ...directOrdinary]
|
|
282
|
+
.sort((left, right) => (this.policy.admissionPriority(right.event) - this.policy.admissionPriority(left.event)
|
|
283
|
+
|| left.event.commitSeq - right.event.commitSeq));
|
|
284
|
+
let dedicatedBacklogHintEventId;
|
|
285
|
+
// A full ordinary queue still needs one durable signal. Use the first new
|
|
286
|
+
// Event as that signal's factual anchor and allow one separately-budgeted
|
|
287
|
+
// item. The same bounded hint lane becomes available again as its rolling
|
|
288
|
+
// admission window advances after the explicit event query drains an earlier backlog.
|
|
289
|
+
if (direct.length === 0
|
|
290
|
+
&& !backlogHintOutstanding
|
|
291
|
+
&& backlogHintWindowItemsRemaining > 0
|
|
292
|
+
&& (queuedBaseItemCount >= this.monitorPendingItemLimit
|
|
293
|
+
|| ordinaryWindowItemsRemaining === 0)
|
|
294
|
+
&& (overflow.length > 1 || (overflow.length > 0 && delegatedUnreadBefore > 0))) {
|
|
295
|
+
const highestPriority = Math.max(...overflow.map(({ event }) => this.policy.priority(event)));
|
|
296
|
+
const preferred = overflow.filter(({ event }) => this.policy.priority(event) === highestPriority);
|
|
297
|
+
const firstNonVisualIndex = preferred.findIndex((row) => (!this.policy.isTelemetry(row.event)));
|
|
298
|
+
const hintAnchorIndex = firstNonVisualIndex >= 0
|
|
299
|
+
? firstNonVisualIndex
|
|
300
|
+
: preferred.length - 1;
|
|
301
|
+
const hintAnchor = preferred[hintAnchorIndex];
|
|
302
|
+
direct = [hintAnchor];
|
|
303
|
+
dedicatedBacklogHintEventId = hintAnchor.event.eventId;
|
|
304
|
+
overflow = overflow.filter((row) => row !== hintAnchor);
|
|
305
|
+
}
|
|
306
|
+
if (direct.length === 0 && overflow.length === 0)
|
|
307
|
+
return 0;
|
|
308
|
+
// With only one newly blocked Event there is no factual anchor plus
|
|
309
|
+
// durable remainder yet. Keep it pending/unprojected until either the
|
|
310
|
+
// ordinary queue gains capacity or a second Event forms a real backlog.
|
|
311
|
+
// A temporally eligible item blocked only by queue capacity remains
|
|
312
|
+
// pending until a second Event can anchor a durable backlog signal. An
|
|
313
|
+
// exhausted rolling window or visual rate limit recovers only with time,
|
|
314
|
+
// so delegate a quiet tail immediately instead of retaining stale output.
|
|
315
|
+
if (direct.length === 0
|
|
316
|
+
&& !backlogHintOutstanding
|
|
317
|
+
&& delegatedUnreadBefore === 0
|
|
318
|
+
&& ordinaryWindowItemsRemaining > 0
|
|
319
|
+
&& ordinaryEvents.length > 0)
|
|
320
|
+
return 0;
|
|
321
|
+
const coalesceBase = `ready:${ready.scope.sessionId}:${ready.scope.segmentId}:${ready.epochSeq}`;
|
|
322
|
+
const payloads = direct.map((row) => this.policy.item(row.event, ready));
|
|
323
|
+
const anticipatedDelegatedUnreadCount = delegatedUnreadBefore + overflow.length;
|
|
324
|
+
const createsBacklogHint = (!backlogHintOutstanding
|
|
325
|
+
&& payloads.length > 0
|
|
326
|
+
&& anticipatedDelegatedUnreadCount > 0);
|
|
327
|
+
if (createsBacklogHint) {
|
|
328
|
+
payloads[0] = {
|
|
329
|
+
...payloads[0],
|
|
330
|
+
backlog: {
|
|
331
|
+
remaining_events: anticipatedDelegatedUnreadCount,
|
|
332
|
+
through_event_commit_seq: ready.eventWatermark,
|
|
333
|
+
command: this.policy.detailsCommand,
|
|
334
|
+
},
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const chunks = this.policy.partition(payloads);
|
|
338
|
+
const rowByEventId = new Map(direct.map((row) => [row.event.eventId, row]));
|
|
339
|
+
const entries = chunks.flatMap((chunk, chunkIndex) => {
|
|
340
|
+
const coalesceKey = chunks.length === 1
|
|
341
|
+
? coalesceBase
|
|
342
|
+
: `${coalesceBase}:chunk:${chunkIndex}`;
|
|
343
|
+
return chunk.map((payload) => {
|
|
344
|
+
const row = rowByEventId.get(payload.event_id);
|
|
345
|
+
if (!row)
|
|
346
|
+
throw new Error(`mailbox_monitor_event_missing:${payload.event_id}`);
|
|
347
|
+
return { coalesceKey, payload, row };
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
// Reassign only delivery slots within this batch; canonical sequence is unchanged.
|
|
351
|
+
const slots = entries.map(({ row }) => row.event.commitSeq).sort((a, b) => a - b);
|
|
352
|
+
const deliveryOrder = new Map(entries.map((entry, index) => [entry.row.event.eventId, slots[index]]));
|
|
353
|
+
const enqueue = (entry) => {
|
|
354
|
+
const event = entry.row.event;
|
|
355
|
+
return this.repository.enqueueMailboxItem({
|
|
356
|
+
itemId: stableMailboxItemId({
|
|
357
|
+
consumerId: this.consumerId,
|
|
358
|
+
sessionId: event.sessionId,
|
|
359
|
+
eventId: event.eventId,
|
|
360
|
+
mode: 'short',
|
|
361
|
+
}),
|
|
362
|
+
schemaVersion: 1,
|
|
363
|
+
formatterVersion: `${this.policy.formatterVersion}:short`,
|
|
364
|
+
consumerId: this.consumerId,
|
|
365
|
+
sessionId: event.sessionId,
|
|
366
|
+
segmentId: event.segmentId,
|
|
367
|
+
eventId: event.eventId,
|
|
368
|
+
eventCommitSeq: event.commitSeq,
|
|
369
|
+
deliveryOrder: deliveryOrder.get(event.eventId),
|
|
370
|
+
mode: 'short',
|
|
371
|
+
coalesceKey: entry.coalesceKey,
|
|
372
|
+
payload: entry.payload,
|
|
373
|
+
availableAtMs: nowMs,
|
|
374
|
+
createdAt: new Date(nowMs).toISOString(),
|
|
375
|
+
});
|
|
376
|
+
};
|
|
377
|
+
let inserted = 0;
|
|
378
|
+
const accountInserted = (entry, wasInserted) => {
|
|
379
|
+
if (!wasInserted)
|
|
380
|
+
return;
|
|
381
|
+
inserted += 1;
|
|
382
|
+
if (ordinaryBudgetEventIds.has(entry.row.event.eventId)) {
|
|
383
|
+
this.monitorOrdinaryAdmissionTimesMs.push(nowMs);
|
|
384
|
+
}
|
|
385
|
+
if (entry.row.event.eventId === dedicatedBacklogHintEventId) {
|
|
386
|
+
this.monitorBacklogHintAdmissionTimesMs.push(nowMs);
|
|
387
|
+
}
|
|
388
|
+
if (this.policy.isRateLimited(entry.row.event)) {
|
|
389
|
+
this.monitorLastVisualAdmissionAtMs = nowMs;
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
let persistedHintEntry;
|
|
393
|
+
if (createsBacklogHint) {
|
|
394
|
+
const hintEntry = entries.find((entry) => (!!entry.payload.backlog && typeof entry.payload.backlog === 'object'));
|
|
395
|
+
if (!hintEntry)
|
|
396
|
+
throw new Error('mailbox_monitor_backlog_hint_missing');
|
|
397
|
+
const result = enqueue(hintEntry);
|
|
398
|
+
const persisted = result.inserted || (!!result.item.payload.backlog && typeof result.item.payload.backlog === 'object');
|
|
399
|
+
if (!persisted)
|
|
400
|
+
return 0;
|
|
401
|
+
accountInserted(hintEntry, result.inserted);
|
|
402
|
+
persistedHintEntry = hintEntry;
|
|
403
|
+
this.backlogHintEventId = hintEntry.row.event.eventId;
|
|
404
|
+
}
|
|
405
|
+
// The unique hint anchor is now durable (or an older accepted/pending hint
|
|
406
|
+
// is still outstanding), so suppressing the remainder cannot orphan it.
|
|
407
|
+
const delegatedCount = this.delegateMonitorOverflow(overflow.map((row) => row.event.eventId), nowMs);
|
|
408
|
+
if (createsBacklogHint) {
|
|
409
|
+
const delegatedUnreadCount = this.delegatedUnreadCount(ready);
|
|
410
|
+
this.diagnostic?.('runtime.mailbox.monitor_backlog_delegated', {
|
|
411
|
+
consumer_id: this.consumerId,
|
|
412
|
+
session_id: ready.scope.sessionId,
|
|
413
|
+
segment_id: ready.scope.segmentId,
|
|
414
|
+
ready_epoch_seq: ready.epochSeq,
|
|
415
|
+
event_watermark: ready.eventWatermark,
|
|
416
|
+
pending_item_limit: this.monitorPendingItemLimit,
|
|
417
|
+
queued_item_count: queuedItemCount,
|
|
418
|
+
direct_event_count: direct.length,
|
|
419
|
+
delegated_event_count: delegatedCount,
|
|
420
|
+
unread_delegated_event_count: delegatedUnreadCount,
|
|
421
|
+
}, 'info');
|
|
422
|
+
}
|
|
423
|
+
for (const entry of entries) {
|
|
424
|
+
if (entry === persistedHintEntry)
|
|
425
|
+
continue;
|
|
426
|
+
const result = enqueue(entry);
|
|
427
|
+
accountInserted(entry, result.inserted);
|
|
428
|
+
}
|
|
429
|
+
if (payloads.length === 0) {
|
|
430
|
+
// This path uses an already durable backlog hint and only delegates new
|
|
431
|
+
// ordinary Events, so there is intentionally no new Mailbox item.
|
|
432
|
+
return 0;
|
|
433
|
+
}
|
|
434
|
+
if (inserted > 0 && chunks.length > 1) {
|
|
435
|
+
const eventTypeCounts = {};
|
|
436
|
+
for (const payload of payloads) {
|
|
437
|
+
const type = String(payload.event.type ?? 'event');
|
|
438
|
+
eventTypeCounts[type] = (eventTypeCounts[type] ?? 0) + 1;
|
|
439
|
+
}
|
|
440
|
+
this.diagnostic?.('runtime.mailbox.monitor_batch_split', {
|
|
441
|
+
consumer_id: this.consumerId,
|
|
442
|
+
session_id: ready.scope.sessionId,
|
|
443
|
+
segment_id: ready.scope.segmentId,
|
|
444
|
+
ready_epoch_seq: ready.epochSeq,
|
|
445
|
+
event_watermark: ready.eventWatermark,
|
|
446
|
+
event_count: payloads.length,
|
|
447
|
+
inserted_event_count: inserted,
|
|
448
|
+
notification_count: chunks.length,
|
|
449
|
+
events_per_notification: chunks.map((chunk) => chunk.length),
|
|
450
|
+
notification_char_counts: chunks.map((chunk) => (JSON.stringify(this.policy.compose(chunk)).length)),
|
|
451
|
+
event_type_counts: eventTypeCounts,
|
|
452
|
+
}, 'info');
|
|
453
|
+
}
|
|
454
|
+
return inserted;
|
|
455
|
+
}
|
|
456
|
+
/** Monitor delivery reports every perception covered by the accepted Ready batch.
|
|
457
|
+
* A backlog hint counts as delivery for display; detail ACK is independent.
|
|
458
|
+
*/
|
|
459
|
+
monitorDeliveredEvents(eventIds) {
|
|
460
|
+
const bounds = new Map();
|
|
461
|
+
for (const id of eventIds) {
|
|
462
|
+
const item = this.repository.mailboxItemForEvent(this.consumerId, id, 'short');
|
|
463
|
+
if (!item || item.state !== 'accepted')
|
|
464
|
+
continue;
|
|
465
|
+
const through = Number(item.payload.ready?.event_commit_seq ?? item.eventCommitSeq);
|
|
466
|
+
bounds.set(item.sessionId, Math.max(bounds.get(item.sessionId) ?? 0, through));
|
|
467
|
+
}
|
|
468
|
+
const events = [];
|
|
469
|
+
for (const [sessionId, through] of bounds) {
|
|
470
|
+
events.push(...this.repository.listCommittedEvents({ sessionId, maxCommitSeq: through, order: 'asc' }));
|
|
471
|
+
}
|
|
472
|
+
return events;
|
|
473
|
+
}
|
|
474
|
+
composeMonitor(values) {
|
|
475
|
+
const hasBacklog = values.some((value) => (!!value.backlog && typeof value.backlog === 'object'));
|
|
476
|
+
if (!hasBacklog)
|
|
477
|
+
return this.policy.compose(values);
|
|
478
|
+
const ready = this.captureReadyView();
|
|
479
|
+
const remainingEvents = this.delegatedUnreadCount(ready);
|
|
480
|
+
const refreshed = values.map((value) => {
|
|
481
|
+
if (!value.backlog || typeof value.backlog !== 'object')
|
|
482
|
+
return value;
|
|
483
|
+
const { backlog: _backlog, ...withoutBacklog } = value;
|
|
484
|
+
if (remainingEvents === 0)
|
|
485
|
+
return withoutBacklog;
|
|
486
|
+
return {
|
|
487
|
+
...withoutBacklog,
|
|
488
|
+
backlog: {
|
|
489
|
+
remaining_events: remainingEvents,
|
|
490
|
+
through_event_commit_seq: ready.eventWatermark,
|
|
491
|
+
command: this.policy.detailsCommand,
|
|
492
|
+
},
|
|
493
|
+
};
|
|
494
|
+
});
|
|
495
|
+
return this.policy.compose(refreshed);
|
|
496
|
+
}
|
|
497
|
+
async flush() {
|
|
498
|
+
if (!this.stopped)
|
|
499
|
+
this.prepareMonitor(true);
|
|
500
|
+
}
|
|
501
|
+
async stop() {
|
|
502
|
+
if (this.stopped)
|
|
503
|
+
return;
|
|
504
|
+
await this.flush();
|
|
505
|
+
this.stopped = true;
|
|
506
|
+
if (this.ownsAgentMailbox)
|
|
507
|
+
await this.agentMailbox.stop();
|
|
508
|
+
}
|
|
509
|
+
delegateMonitorOverflow(eventIds, nowMs) {
|
|
510
|
+
if (eventIds.length === 0)
|
|
511
|
+
return 0;
|
|
512
|
+
const lease = this.repository.acquireLease({
|
|
513
|
+
consumerId: this.consumerId,
|
|
514
|
+
channel: 'monitor',
|
|
515
|
+
ownerId: `${this.consumerId}:monitor-overflow`,
|
|
516
|
+
ttlMs: MONITOR_OVERFLOW_LEASE_TTL_MS,
|
|
517
|
+
nowMs,
|
|
518
|
+
});
|
|
519
|
+
if (!lease)
|
|
520
|
+
return 0;
|
|
521
|
+
let changed = 0;
|
|
522
|
+
try {
|
|
523
|
+
for (let offset = 0; offset < eventIds.length; offset += MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE) {
|
|
524
|
+
changed += this.repository.transitionMonitor({
|
|
525
|
+
eventIds: eventIds.slice(offset, offset + MONITOR_OVERFLOW_TRANSITION_BATCH_SIZE),
|
|
526
|
+
consumerId: this.consumerId,
|
|
527
|
+
from: ['pending'],
|
|
528
|
+
to: 'suppressed',
|
|
529
|
+
lease,
|
|
530
|
+
nowMs,
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
return changed;
|
|
534
|
+
}
|
|
535
|
+
finally {
|
|
536
|
+
this.repository.releaseLease(lease);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
delegatedUnreadCount(ready) {
|
|
540
|
+
const suppressed = this.repository.listEvents({
|
|
541
|
+
sessionId: ready.scope.sessionId,
|
|
542
|
+
deliveryClasses: ['monitor_and_events'],
|
|
543
|
+
monitorStates: ['suppressed'],
|
|
544
|
+
maxCommitSeq: ready.eventWatermark,
|
|
545
|
+
maxEpochSeq: ready.epochSeq,
|
|
546
|
+
order: 'asc',
|
|
547
|
+
}, this.consumerId, ['monitor']).filter(row => !this.notificationOnly || this.policy.admitEvent(row.event));
|
|
548
|
+
if (suppressed.length === 0)
|
|
549
|
+
return 0;
|
|
550
|
+
this.repository.ensureDeliveries(ready.scope.sessionId, this.delegatedDetailsConsumerId, ['details']);
|
|
551
|
+
return suppressed.filter((row) => {
|
|
552
|
+
const state = this.repository.delivery(row.event.eventId, this.delegatedDetailsConsumerId)?.detailState;
|
|
553
|
+
return state === 'pending' || state === 'deferred';
|
|
554
|
+
}).length;
|
|
555
|
+
}
|
|
556
|
+
pruneMonitorAdmissionWindows(nowMs) {
|
|
557
|
+
const cutoffMs = nowMs - this.monitorAdmissionWindowMs;
|
|
558
|
+
while (this.monitorOrdinaryAdmissionTimesMs.length > 0
|
|
559
|
+
&& this.monitorOrdinaryAdmissionTimesMs[0] <= cutoffMs)
|
|
560
|
+
this.monitorOrdinaryAdmissionTimesMs.shift();
|
|
561
|
+
while (this.monitorBacklogHintAdmissionTimesMs.length > 0
|
|
562
|
+
&& this.monitorBacklogHintAdmissionTimesMs[0] <= cutoffMs)
|
|
563
|
+
this.monitorBacklogHintAdmissionTimesMs.shift();
|
|
564
|
+
}
|
|
565
|
+
captureReadyView(readyView) {
|
|
566
|
+
const ready = structuredClone(readyView ?? this.readyView());
|
|
567
|
+
if (ready.epochSeq > this.lastObservedReadyEpochSeq) {
|
|
568
|
+
this.diagnostic?.('runtime.mailbox.ready_advanced', {
|
|
569
|
+
previous_ready_epoch_seq: this.lastObservedReadyEpochSeq,
|
|
570
|
+
ready_epoch_seq: ready.epochSeq,
|
|
571
|
+
event_commit_seq: ready.eventWatermark,
|
|
572
|
+
frame_seq: ready.frameSeq,
|
|
573
|
+
});
|
|
574
|
+
this.lastObservedReadyEpochSeq = ready.epochSeq;
|
|
575
|
+
}
|
|
576
|
+
return ready;
|
|
577
|
+
}
|
|
578
|
+
assertRunning() {
|
|
579
|
+
if (this.stopped)
|
|
580
|
+
throw new Error(this.policy.stoppedError);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** JSON data owned by one strategy resource in the current game and Owner process. */
|
|
2
|
+
export type StrategyMemoryValue = null | boolean | number | string | readonly StrategyMemoryValue[] | {
|
|
3
|
+
readonly [key: string]: StrategyMemoryValue;
|
|
4
|
+
};
|
|
5
|
+
/** Immediate, resource-scoped memory shared by a Behavior and its explicitly bound Perception.
|
|
6
|
+
* Values are detached copies; writes are independent of Decision or backend Action success.
|
|
7
|
+
*/
|
|
8
|
+
export interface StrategyMemory {
|
|
9
|
+
get<T extends StrategyMemoryValue = StrategyMemoryValue>(key: string): Promise<T | undefined>;
|
|
10
|
+
set(key: string, value: StrategyMemoryValue): Promise<void>;
|
|
11
|
+
delete(key: string): Promise<void>;
|
|
12
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { StrategyMemory, StrategyMemoryValue } from './contracts.js';
|
|
2
|
+
export interface StrategyMemoryRequest {
|
|
3
|
+
readonly type: 'strategy_memory';
|
|
4
|
+
readonly requestId: string;
|
|
5
|
+
readonly memoryRequestId: number;
|
|
6
|
+
readonly operation: 'get' | 'set' | 'delete';
|
|
7
|
+
readonly key: string;
|
|
8
|
+
readonly value?: StrategyMemoryValue;
|
|
9
|
+
}
|
|
10
|
+
export declare const unavailableStrategyMemory: StrategyMemory;
|
|
11
|
+
/** Replies are handled outside the computation queue, so an awaited memory call cannot deadlock it. */
|
|
12
|
+
export declare class StrategyMemoryRpcClient {
|
|
13
|
+
private readonly send;
|
|
14
|
+
private sequence;
|
|
15
|
+
private pending;
|
|
16
|
+
constructor(send: (value: Readonly<Record<string, unknown>>) => void);
|
|
17
|
+
receive(message: any): boolean;
|
|
18
|
+
bind(requestId: string, isActive: () => boolean): StrategyMemory;
|
|
19
|
+
}
|
|
20
|
+
/** The parent supplies an already-bound capability; messages cannot choose another resource or scope. */
|
|
21
|
+
export declare function serveStrategyMemoryRequest(message: StrategyMemoryRequest, binding: StrategyMemory | (() => StrategyMemory), send: (value: Readonly<Record<string, unknown>>) => void): Promise<void>;
|