@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.
Files changed (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +244 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +58 -0
  127. package/dist/mailbox/mailbox-plugin.js +128 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +338 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,1660 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { cloneCanonical, runtimeScopeKey } from '../state/types.js';
3
+ const DEFAULT_PLUGIN_TIMEOUT_MS = 1_000;
4
+ const PLUGIN_START_TIMEOUT_MS = 10_000;
5
+ const DEFAULT_MAX_CATCH_UP_EPOCHS = 10;
6
+ const MAX_PLUGIN_IN_FLIGHT = 10;
7
+ const DEFAULT_RETRY_ATTEMPTS = 3;
8
+ const DEFAULT_DIAGNOSTIC_TIMING_WINDOW_MS = 10_000;
9
+ const DEFAULT_SLOW_PLUGIN_MS = 250;
10
+ const DEFAULT_SLOW_BEHAVIOR_PLUGIN_MS = 1_000;
11
+ const DEFAULT_SLOW_EPOCH_MS = 1_000;
12
+ const DEGRADED_LAG_EPOCHS = 3;
13
+ const CRITICAL_LAG_EPOCHS = 10;
14
+ function rounded(value) {
15
+ return Math.round(value * 1_000) / 1_000;
16
+ }
17
+ function deepFreeze(value, seen = new WeakSet()) {
18
+ if (!value || typeof value !== 'object' || Object.isFrozen(value))
19
+ return value;
20
+ const object = value;
21
+ if (seen.has(object))
22
+ return value;
23
+ seen.add(object);
24
+ for (const child of Object.values(object))
25
+ deepFreeze(child, seen);
26
+ return Object.freeze(value);
27
+ }
28
+ function percentile(sorted, fraction) {
29
+ if (sorted.length === 0)
30
+ return 0;
31
+ return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)];
32
+ }
33
+ function lagBand(lagEpochCount) {
34
+ if (lagEpochCount >= CRITICAL_LAG_EPOCHS)
35
+ return 'critical';
36
+ if (lagEpochCount >= DEGRADED_LAG_EPOCHS)
37
+ return 'degraded';
38
+ return 'healthy';
39
+ }
40
+ function slowPluginThresholdMs(pluginId) {
41
+ return /(?:^|\.)behavior$/.test(pluginId)
42
+ ? DEFAULT_SLOW_BEHAVIOR_PLUGIN_MS
43
+ : DEFAULT_SLOW_PLUGIN_MS;
44
+ }
45
+ function forbidsCoalescing(work) {
46
+ return work.epoch.coalescing === 'forbidden';
47
+ }
48
+ function unavailableCapabilities(pluginId) {
49
+ const unavailable = () => {
50
+ throw new Error(`Runtime capability access is unavailable for Plugin ${pluginId}.`);
51
+ };
52
+ return {
53
+ provideObservation: unavailable,
54
+ provideAction: unavailable,
55
+ queryObservation: unavailable,
56
+ performAction: unavailable,
57
+ };
58
+ }
59
+ function computationCapabilities(pluginId, capabilities) {
60
+ const registrationUnavailable = () => {
61
+ throw new Error(`Runtime Epoch Plugin ${pluginId} cannot register capabilities from a parallel update.`);
62
+ };
63
+ return {
64
+ provideObservation: registrationUnavailable,
65
+ provideAction: registrationUnavailable,
66
+ queryObservation: capabilities.queryObservation.bind(capabilities),
67
+ performAction: async () => {
68
+ throw new Error(`Runtime Epoch Plugin ${pluginId} cannot perform Action from a parallel update; return a proposal and act from ordered commit.`);
69
+ },
70
+ };
71
+ }
72
+ function assertNonEmpty(value, field) {
73
+ if (typeof value !== 'string' || !value.trim())
74
+ throw new TypeError(`${field} must not be empty.`);
75
+ }
76
+ function normalizedFailurePolicy(plugin) {
77
+ const configured = plugin.failurePolicy;
78
+ const policy = typeof configured === 'string' ? { mode: configured } : configured;
79
+ const normalized = policy ?? { mode: 'failed_completion' };
80
+ if (!['failed_completion', 'retry', 'pause', 'terminate'].includes(normalized.mode)) {
81
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} has invalid failurePolicy mode.`);
82
+ }
83
+ if (normalized.maxAttempts !== undefined
84
+ && (!Number.isInteger(normalized.maxAttempts) || normalized.maxAttempts <= 0)) {
85
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} failurePolicy.maxAttempts must be positive.`);
86
+ }
87
+ return normalized.mode === 'retry'
88
+ ? { mode: 'retry', maxAttempts: normalized.maxAttempts ?? DEFAULT_RETRY_ATTEMPTS }
89
+ : { mode: normalized.mode };
90
+ }
91
+ function normalizedMaxInFlight(plugin) {
92
+ const maxInFlight = plugin.maxInFlight ?? 1;
93
+ if (!Number.isInteger(maxInFlight) || maxInFlight <= 0 || maxInFlight > MAX_PLUGIN_IN_FLIGHT) {
94
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} maxInFlight must be an integer between 1 and ${MAX_PLUGIN_IN_FLIGHT}.`);
95
+ }
96
+ return maxInFlight;
97
+ }
98
+ function normalizedMaxPendingEpochs(plugin, fallback) {
99
+ const maxPendingEpochs = plugin.maxPendingEpochs ?? fallback;
100
+ if (!Number.isInteger(maxPendingEpochs) || maxPendingEpochs <= 0 || maxPendingEpochs > 10_000) {
101
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} maxPendingEpochs must be an integer between 1 and 10000.`);
102
+ }
103
+ return maxPendingEpochs;
104
+ }
105
+ function pluginLayers(plugins) {
106
+ const byId = new Map();
107
+ const stateOwners = new Map();
108
+ const capabilityOwners = new Map();
109
+ for (const plugin of plugins) {
110
+ if (plugin.kind !== 'epoch')
111
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} has invalid kind.`);
112
+ assertNonEmpty(plugin.id, 'Runtime Epoch Plugin id');
113
+ assertNonEmpty(plugin.version, `Runtime Epoch Plugin ${plugin.id} version`);
114
+ if (byId.has(plugin.id))
115
+ throw new Error(`Duplicate Runtime Epoch Plugin id: ${plugin.id}`);
116
+ byId.set(plugin.id, plugin);
117
+ normalizedFailurePolicy(plugin);
118
+ normalizedMaxInFlight(plugin);
119
+ if (plugin.maxPendingEpochs !== undefined)
120
+ normalizedMaxPendingEpochs(plugin, 1);
121
+ for (const topic of plugin.produces?.states ?? []) {
122
+ assertNonEmpty(topic, `Runtime Epoch Plugin ${plugin.id} State output`);
123
+ const owner = stateOwners.get(topic);
124
+ if (owner)
125
+ throw new Error(`Runtime State topic ${topic} is owned by both ${owner} and ${plugin.id}`);
126
+ stateOwners.set(topic, plugin.id);
127
+ }
128
+ for (const capability of plugin.capabilities?.provides ?? []) {
129
+ assertNonEmpty(capability, `Runtime Epoch Plugin ${plugin.id} capability`);
130
+ const owner = capabilityOwners.get(capability);
131
+ if (owner)
132
+ throw new Error(`Runtime capability ${capability} is provided by both ${owner} and ${plugin.id}`);
133
+ capabilityOwners.set(capability, plugin.id);
134
+ }
135
+ for (const capability of plugin.capabilities?.uses ?? []) {
136
+ assertNonEmpty(capability, `Runtime Epoch Plugin ${plugin.id} capability dependency`);
137
+ }
138
+ if (plugin.timeoutMs !== undefined && (!Number.isInteger(plugin.timeoutMs) || plugin.timeoutMs <= 0)) {
139
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} timeoutMs must be a positive integer.`);
140
+ }
141
+ if (plugin.recoveryTimeoutMs !== undefined
142
+ && (!Number.isInteger(plugin.recoveryTimeoutMs) || plugin.recoveryTimeoutMs <= 0)) {
143
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} recoveryTimeoutMs must be a positive integer.`);
144
+ }
145
+ }
146
+ for (const plugin of plugins) {
147
+ for (const dependency of plugin.after ?? []) {
148
+ if (!byId.has(dependency)) {
149
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} depends on missing ${dependency}`);
150
+ }
151
+ }
152
+ }
153
+ const remaining = new Map(byId);
154
+ const completed = new Set();
155
+ const layers = [];
156
+ while (remaining.size > 0) {
157
+ const layer = [...remaining.values()]
158
+ .filter((plugin) => (plugin.after ?? []).every((id) => completed.has(id)))
159
+ .sort((a, b) => a.id.localeCompare(b.id));
160
+ if (layer.length === 0) {
161
+ throw new Error(`Runtime Epoch Plugin dependency cycle: ${[...remaining.keys()].sort().join(', ')}`);
162
+ }
163
+ layers.push(layer);
164
+ for (const plugin of layer) {
165
+ remaining.delete(plugin.id);
166
+ completed.add(plugin.id);
167
+ }
168
+ }
169
+ return layers;
170
+ }
171
+ function validateResult(plugin, result) {
172
+ if (result.outcome !== 'processed' && result.outcome !== 'noop') {
173
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} returned an invalid outcome.`);
174
+ }
175
+ const stateOutputs = new Set(plugin.produces?.states ?? []);
176
+ for (const state of result.states ?? []) {
177
+ if (!stateOutputs.has(state.topic)) {
178
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} did not declare State output ${state.topic}.`);
179
+ }
180
+ }
181
+ const eventOutputs = new Set(plugin.produces?.events ?? []);
182
+ for (const event of result.events ?? []) {
183
+ if (!eventOutputs.has(event.type)) {
184
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} did not declare Event output ${event.type}.`);
185
+ }
186
+ }
187
+ if (result.proposal !== undefined) {
188
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} commit output must not contain a proposal.`);
189
+ }
190
+ }
191
+ function validateComputationResult(plugin, result) {
192
+ if (result.outcome !== 'processed' && result.outcome !== 'noop') {
193
+ throw new TypeError(`Runtime Epoch Plugin ${plugin.id} returned an invalid outcome.`);
194
+ }
195
+ if (result.states !== undefined
196
+ || result.eventDeliveries !== undefined
197
+ || result.events !== undefined
198
+ || result.checkpoint !== undefined
199
+ || result.consumeEventsThroughCommitSeq !== undefined) {
200
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} update must return only outcome, reason and proposal when commit is declared.`);
201
+ }
202
+ }
203
+ function validateParallelFinalResult(plugin, result) {
204
+ validateResult(plugin, result);
205
+ if (result.checkpoint !== undefined || result.consumeEventsThroughCommitSeq !== undefined) {
206
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} with maxInFlight > 1 must use commit for checkpoint or Event cursor output.`);
207
+ }
208
+ }
209
+ export class RuntimeEpochPluginTimeoutError extends Error {
210
+ pluginId;
211
+ timeoutMs;
212
+ constructor(pluginId, timeoutMs) {
213
+ super(`Runtime Epoch Plugin "${pluginId}" exceeded ${timeoutMs}ms.`);
214
+ this.pluginId = pluginId;
215
+ this.timeoutMs = timeoutMs;
216
+ this.name = 'RuntimeEpochPluginTimeoutError';
217
+ }
218
+ }
219
+ export class RuntimeEpochPluginSupersededError extends Error {
220
+ pluginId;
221
+ epochSeq;
222
+ newerEpochSeq;
223
+ reasonCode;
224
+ constructor(pluginId, epochSeq, newerEpochSeq, reasonCode = 'newer_epoch_available') {
225
+ super(`Runtime Epoch Plugin "${pluginId}" epoch ${epochSeq} was superseded by epoch ${newerEpochSeq}.`);
226
+ this.pluginId = pluginId;
227
+ this.epochSeq = epochSeq;
228
+ this.newerEpochSeq = newerEpochSeq;
229
+ this.reasonCode = reasonCode;
230
+ this.name = 'RuntimeEpochPluginSupersededError';
231
+ }
232
+ }
233
+ export class RuntimeEpochPluginFatalError extends Error {
234
+ pluginId;
235
+ cause;
236
+ constructor(pluginId, cause) {
237
+ super(`Runtime Epoch Plugin "${pluginId}" terminated the Runtime: ${cause instanceof Error ? cause.message : String(cause)}`);
238
+ this.pluginId = pluginId;
239
+ this.cause = cause;
240
+ this.name = 'RuntimeEpochPluginFatalError';
241
+ }
242
+ }
243
+ function pluginDiagnosticErrorCode(error, fallback) {
244
+ const code = error && typeof error === 'object' && typeof error.code === 'string'
245
+ ? error.code.trim()
246
+ : '';
247
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code))
248
+ return code;
249
+ if (error instanceof Error && error.name !== 'Error') {
250
+ const name = error.name.trim();
251
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(name))
252
+ return name;
253
+ }
254
+ return fallback;
255
+ }
256
+ /**
257
+ * Advances each plugin on its own durable cursor. Dependencies gate only the
258
+ * affected plugin, so an unrelated slow branch cannot stall the whole graph.
259
+ */
260
+ export class RuntimePluginScheduler {
261
+ layers;
262
+ plugins;
263
+ pluginOrder = new Map();
264
+ pending = new Map();
265
+ inputJournal;
266
+ pluginStore;
267
+ stateHistory;
268
+ commitInputEvents;
269
+ publishEvent;
270
+ resolveEventDelivery;
271
+ listEvents;
272
+ highWaterCommitSeq;
273
+ currentSegment;
274
+ capabilitiesFor;
275
+ onEpochClosed;
276
+ onFatalError;
277
+ onDiagnostic;
278
+ pluginTimeoutMs;
279
+ maxCatchUpEpochs;
280
+ diagnosticTimingWindowMs;
281
+ nowMs;
282
+ processingIntervalMs;
283
+ activeInvocations = new Map();
284
+ bufferedInvocations = new Map();
285
+ activeCommits = new Map();
286
+ inputEventCommits = new Map();
287
+ inputEventCommitTail = Promise.resolve();
288
+ catchUpCounts = new Map();
289
+ drainingBatches = new Set();
290
+ pluginTimingWindows = new Map();
291
+ lagBands = new Map();
292
+ pausedPlugins = new Set();
293
+ activeScope = null;
294
+ pumping = false;
295
+ pumpRequested = false;
296
+ closing = false;
297
+ stopped = false;
298
+ fatalError;
299
+ lastWork = null;
300
+ idleWaiters = [];
301
+ constructor(options) {
302
+ this.layers = pluginLayers(options.plugins ?? []);
303
+ this.plugins = this.layers.flat();
304
+ this.plugins.forEach((plugin, index) => this.pluginOrder.set(plugin.id, index));
305
+ this.processingIntervalMs = options.processingIntervalMs;
306
+ this.inputJournal = options.inputJournal;
307
+ this.pluginStore = options.pluginStore;
308
+ this.stateHistory = options.stateHistory;
309
+ this.commitInputEvents = options.commitInputEvents;
310
+ this.publishEvent = options.publishEvent;
311
+ this.resolveEventDelivery = options.resolveEventDelivery;
312
+ this.listEvents = options.listEvents;
313
+ this.highWaterCommitSeq = options.highWaterCommitSeq;
314
+ this.currentSegment = options.currentSegment ?? (() => ({ kind: 'unknown' }));
315
+ this.capabilitiesFor = options.capabilitiesFor;
316
+ this.onEpochClosed = options.onEpochClosed;
317
+ this.onFatalError = options.onFatalError;
318
+ this.onDiagnostic = options.onDiagnostic;
319
+ this.pluginTimeoutMs = options.pluginTimeoutMs ?? DEFAULT_PLUGIN_TIMEOUT_MS;
320
+ this.maxCatchUpEpochs = options.maxCatchUpEpochs ?? DEFAULT_MAX_CATCH_UP_EPOCHS;
321
+ this.diagnosticTimingWindowMs = options.diagnosticTimingWindowMs
322
+ ?? DEFAULT_DIAGNOSTIC_TIMING_WINDOW_MS;
323
+ this.nowMs = options.nowMs ?? Date.now;
324
+ if (!Number.isInteger(this.pluginTimeoutMs) || this.pluginTimeoutMs <= 0) {
325
+ throw new TypeError('pluginTimeoutMs must be a positive integer.');
326
+ }
327
+ if (!Number.isInteger(this.maxCatchUpEpochs)
328
+ || this.maxCatchUpEpochs <= 0
329
+ || this.maxCatchUpEpochs > MAX_PLUGIN_IN_FLIGHT) {
330
+ throw new TypeError(`maxCatchUpEpochs must be an integer between 1 and ${MAX_PLUGIN_IN_FLIGHT}.`);
331
+ }
332
+ if (!Number.isInteger(this.diagnosticTimingWindowMs) || this.diagnosticTimingWindowMs <= 0) {
333
+ throw new TypeError('diagnosticTimingWindowMs must be a positive integer.');
334
+ }
335
+ }
336
+ descriptors() {
337
+ return this.plugins.map((plugin) => ({
338
+ kind: 'epoch',
339
+ id: plugin.id,
340
+ version: plugin.version,
341
+ after: [...(plugin.after ?? [])],
342
+ catchUp: plugin.catchUp ?? 'every_epoch',
343
+ maxInFlight: normalizedMaxInFlight(plugin),
344
+ maxPendingEpochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
345
+ consumes: cloneCanonical(plugin.consumes ?? {}),
346
+ produces: cloneCanonical(plugin.produces ?? {}),
347
+ capabilities: cloneCanonical(plugin.capabilities ?? {}),
348
+ failurePolicy: cloneCanonical(normalizedFailurePolicy(plugin)),
349
+ ...(plugin.timeoutMs === undefined ? {} : { timeoutMs: plugin.timeoutMs }),
350
+ ...(plugin.recoveryTimeoutMs === undefined
351
+ ? {}
352
+ : { recoveryTimeoutMs: plugin.recoveryTimeoutMs }),
353
+ }));
354
+ }
355
+ /**
356
+ * Exact, on-demand scheduler state for full local diagnostics.
357
+ * The Owner calls this only while full observability is enabled so the
358
+ * per-plugin backlog scan has zero cost in the default runtime path.
359
+ */
360
+ diagnosticSnapshot(scope = this.activeScope ?? undefined) {
361
+ const pending = scope
362
+ ? [...this.pending.values()].filter(({ work }) => (runtimeScopeKey(work.epoch.scope) === runtimeScopeKey(scope)))
363
+ : [...this.pending.values()];
364
+ let oldest;
365
+ let oldestEpochSeq = null;
366
+ let newestEpochSeq = null;
367
+ for (const entry of pending) {
368
+ if (!oldest || entry.queuedAtMs < oldest.queuedAtMs)
369
+ oldest = entry;
370
+ const epochSeq = entry.work.epoch.epochSeq;
371
+ oldestEpochSeq = oldestEpochSeq === null ? epochSeq : Math.min(oldestEpochSeq, epochSeq);
372
+ newestEpochSeq = newestEpochSeq === null ? epochSeq : Math.max(newestEpochSeq, epochSeq);
373
+ }
374
+ const effectiveScope = scope ?? pending[0]?.work.epoch.scope;
375
+ const progressByPlugin = effectiveScope
376
+ ? new Map(this.plugins.map((plugin) => [
377
+ plugin.id,
378
+ this.pluginStore.pluginProgress(plugin.id, effectiveScope),
379
+ ]))
380
+ : new Map();
381
+ const latestEpochSeq = newestEpochSeq ?? 0;
382
+ const plugins = this.plugins.map((plugin) => {
383
+ const progress = progressByPlugin.get(plugin.id);
384
+ const completedThroughEpochSeq = progress?.completedThroughEpochSeq ?? 0;
385
+ const dependencies = (plugin.after ?? []).map((id) => (progressByPlugin.get(id)?.completedThroughEpochSeq ?? 0));
386
+ const readyThroughEpochSeq = dependencies.length === 0
387
+ ? latestEpochSeq
388
+ : Math.min(latestEpochSeq, ...dependencies);
389
+ return {
390
+ plugin_id: plugin.id,
391
+ catch_up: plugin.catchUp ?? 'every_epoch',
392
+ max_in_flight: normalizedMaxInFlight(plugin),
393
+ max_pending_epochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
394
+ completed_through_epoch_seq: completedThroughEpochSeq,
395
+ ready_through_epoch_seq: readyThroughEpochSeq,
396
+ lag_epoch_count: pending.filter(({ work }) => (work.epoch.epochSeq > completedThroughEpochSeq)).length,
397
+ active_invocation_count: [...this.activeInvocations.values()]
398
+ .filter(({ pluginId }) => pluginId === plugin.id).length,
399
+ buffered_invocation_count: this.bufferedInvocations.get(plugin.id)?.size ?? 0,
400
+ active_commit: this.activeCommits.has(plugin.id),
401
+ paused: this.pausedPlugins.has(plugin.id),
402
+ };
403
+ });
404
+ return {
405
+ pending_epoch_count: pending.length,
406
+ oldest_pending_epoch_seq: oldestEpochSeq,
407
+ newest_pending_epoch_seq: newestEpochSeq,
408
+ oldest_pending_age_ms: oldest
409
+ ? Math.max(0, this.nowMs() - oldest.queuedAtMs)
410
+ : 0,
411
+ active_invocation_count: this.activeInvocations.size,
412
+ active_commit_count: this.activeCommits.size,
413
+ buffered_invocation_count: this.bufferedInvocationCount(),
414
+ input_event_commit_count: this.inputEventCommits.size,
415
+ plugins,
416
+ };
417
+ }
418
+ async activateScope(scope) {
419
+ if (this.activeScope && runtimeScopeKey(this.activeScope) === runtimeScopeKey(scope))
420
+ return;
421
+ if (this.activeInvocations.size > 0 || this.activeCommits.size > 0 || this.bufferedInvocationCount() > 0) {
422
+ throw new Error('Cannot switch Runtime plugin scope while invocations are active.');
423
+ }
424
+ if (this.activeScope)
425
+ await this.stopScope('segment_ending');
426
+ this.activeScope = cloneCanonical(scope);
427
+ this.pausedPlugins.clear();
428
+ this.catchUpCounts.clear();
429
+ this.drainingBatches.clear();
430
+ for (const layer of this.layers) {
431
+ await Promise.all(layer.map(async (plugin) => {
432
+ const startController = new AbortController();
433
+ await this.withDeadline(plugin, startController, () => plugin.start?.(this.context(plugin, scope, startController.signal, 0)), undefined, false, undefined, PLUGIN_START_TIMEOUT_MS);
434
+ const recoverController = new AbortController();
435
+ await this.withDeadline(plugin, recoverController, () => plugin.recover?.(this.context(plugin, scope, recoverController.signal, this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq)), undefined, false, undefined, plugin.recoveryTimeoutMs);
436
+ }));
437
+ }
438
+ }
439
+ enqueue(work) {
440
+ if (this.stopped || this.closing || this.fatalError) {
441
+ return Promise.reject(this.fatalError ?? new Error('Runtime Epoch Plugin Host is stopped.'));
442
+ }
443
+ if (this.pending.has(work.epoch.epochSeq)) {
444
+ return Promise.reject(new Error(`Runtime epoch ${work.epoch.epochSeq} is already queued.`));
445
+ }
446
+ this.ensureRecoveredRecords(work);
447
+ const queuedAtMs = this.nowMs();
448
+ // Clone once at admission, then share the recursively immutable epoch core
449
+ // across plugins. Per-plugin inputs still own filtered Event/State views.
450
+ const immutableWork = deepFreeze(cloneCanonical(work));
451
+ const completion = new Promise((resolve, reject) => {
452
+ this.pending.set(work.epoch.epochSeq, {
453
+ work: immutableWork,
454
+ queuedAtMs,
455
+ resolve,
456
+ reject,
457
+ });
458
+ });
459
+ this.reportLagTransition(work.epoch.scope, work.epoch.epochSeq);
460
+ this.requestPump();
461
+ return completion;
462
+ }
463
+ async flush(reason) {
464
+ await this.waitForIdle();
465
+ const scope = this.activeScope;
466
+ if (!scope)
467
+ return;
468
+ for (const layer of this.layers) {
469
+ await Promise.all(layer.map(async (plugin) => {
470
+ if (!plugin.flush)
471
+ return;
472
+ const controller = new AbortController();
473
+ try {
474
+ const result = await this.withDeadline(plugin, controller, () => plugin.flush(reason, this.context(plugin, scope, controller.signal, this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq)));
475
+ if (result !== undefined) {
476
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} lifecycle flush must not return output.`);
477
+ }
478
+ this.onDiagnostic?.('runtime.plugin.flush_completed', {
479
+ plugin_id: plugin.id,
480
+ reason,
481
+ }, scope);
482
+ }
483
+ catch (error) {
484
+ this.onDiagnostic?.('runtime.plugin.flush_failed', {
485
+ plugin_id: plugin.id,
486
+ reason,
487
+ error_code: pluginDiagnosticErrorCode(error, 'RUNTIME_PLUGIN_FLUSH_FAILED'),
488
+ }, scope, 'error');
489
+ }
490
+ }));
491
+ }
492
+ }
493
+ waitForIdle() {
494
+ if (this.isIdle())
495
+ return Promise.resolve();
496
+ return new Promise((resolve) => this.idleWaiters.push(resolve));
497
+ }
498
+ async close() {
499
+ if (this.stopped)
500
+ return;
501
+ this.closing = true;
502
+ this.requestPump();
503
+ await this.waitForIdle();
504
+ let flushError;
505
+ try {
506
+ if (!this.fatalError)
507
+ await this.flush('shutdown');
508
+ }
509
+ catch (error) {
510
+ flushError = error;
511
+ }
512
+ finally {
513
+ await this.stopScope('shutdown');
514
+ this.stopped = true;
515
+ }
516
+ if (flushError)
517
+ throw flushError;
518
+ }
519
+ requestPump() {
520
+ this.pumpRequested = true;
521
+ if (this.pumping || this.stopped)
522
+ return;
523
+ this.pumping = true;
524
+ // Yield to transport/Worker message delivery before launching more CPU work.
525
+ // A self-renewing microtask pump can otherwise prevent newly received State
526
+ // from reaching admission, hiding the backlog from bounded catch-up.
527
+ setImmediate(() => {
528
+ void this.pump().catch((error) => this.failRuntime(error, 'runtime.scheduler')).finally(() => {
529
+ this.pumping = false;
530
+ if (this.pumpRequested && !this.stopped && !this.fatalError)
531
+ this.requestPump();
532
+ else
533
+ this.resolveIdle();
534
+ });
535
+ });
536
+ }
537
+ async pump() {
538
+ while (!this.fatalError) {
539
+ this.pumpRequested = false;
540
+ const first = this.pendingInOrder()[0];
541
+ if (!first)
542
+ return;
543
+ if (!this.activeScope || runtimeScopeKey(this.activeScope) !== runtimeScopeKey(first.work.epoch.scope)) {
544
+ if (this.activeInvocations.size > 0 || this.activeCommits.size > 0)
545
+ return;
546
+ await this.activateScope(first.work.epoch.scope);
547
+ }
548
+ this.abortSupersededInvocations();
549
+ if (await this.closeReadyEpochs()) {
550
+ continue;
551
+ }
552
+ const commits = this.launchReadyCommits();
553
+ const launched = this.launchReadyPlugins();
554
+ if (commits > 0 || launched > 0)
555
+ return;
556
+ return;
557
+ }
558
+ }
559
+ launchReadyPlugins() {
560
+ const scope = this.activeScope;
561
+ if (!scope)
562
+ return 0;
563
+ let launched = 0;
564
+ for (const plugin of this.plugins) {
565
+ const maxInFlight = normalizedMaxInFlight(plugin);
566
+ let candidates = this.launchCandidates(plugin, scope);
567
+ if (candidates.length === 0)
568
+ continue;
569
+ if (this.pausedPlugins.has(plugin.id)) {
570
+ if (maxInFlight > 1) {
571
+ if (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id))
572
+ continue;
573
+ const earliest = this.readyCandidates(plugin, scope)[0];
574
+ if (!earliest || this.isInvocationScheduled(plugin.id, earliest.work.epoch.epochSeq))
575
+ continue;
576
+ this.recordPausedCompletion(plugin, earliest.work);
577
+ launched += 1;
578
+ }
579
+ else {
580
+ for (const pending of candidates)
581
+ this.recordPausedCompletion(plugin, pending.work);
582
+ launched += candidates.length;
583
+ }
584
+ this.requestPump();
585
+ continue;
586
+ }
587
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
588
+ this.trimBoundedBacklog(plugin, scope);
589
+ candidates = this.launchCandidates(plugin, scope);
590
+ if (candidates.length === 0)
591
+ continue;
592
+ }
593
+ if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0)
594
+ continue;
595
+ if (this.drainingBatches.has(plugin.id)
596
+ && (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id)))
597
+ continue;
598
+ if (maxInFlight > 1) {
599
+ const reorderCapacity = (plugin.catchUp ?? 'every_epoch') === 'strict_ordered'
600
+ ? maxInFlight
601
+ : Math.min(maxInFlight, normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs));
602
+ let slots = reorderCapacity - this.scheduledInvocationCount(plugin.id);
603
+ for (const candidate of candidates) {
604
+ if (slots <= 0)
605
+ break;
606
+ this.runPlugin(plugin, candidate.work, candidates.length > 1);
607
+ launched += 1;
608
+ slots -= 1;
609
+ }
610
+ continue;
611
+ }
612
+ const catchUp = plugin.catchUp ?? 'every_epoch';
613
+ const count = this.catchUpCounts.get(plugin.id) ?? 0;
614
+ const requiredIndex = candidates.findIndex((candidate) => forbidsCoalescing(candidate.work));
615
+ // A required boundary must not discard earlier strict-ordered inputs.
616
+ const shouldJump = catchUp !== 'strict_ordered' && (requiredIndex > 0 || (requiredIndex < 0 && (catchUp === 'latest_only' || (catchUp === 'every_epoch'
617
+ && count >= normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs)
618
+ && candidates.length > 1))));
619
+ if (shouldJump && candidates.length > 1) {
620
+ const targetIndex = requiredIndex >= 0 ? requiredIndex : candidates.length - 1;
621
+ const skipped = candidates.slice(0, targetIndex);
622
+ const target = candidates[targetIndex];
623
+ this.recordCoalesced(plugin, skipped.map((entry) => entry.work), requiredIndex >= 0
624
+ ? 'required_epoch_boundary'
625
+ : catchUp === 'latest_only'
626
+ ? 'newer_epoch_available'
627
+ : 'catch_up_limit');
628
+ candidates = [target];
629
+ this.catchUpCounts.set(plugin.id, 0);
630
+ }
631
+ const target = candidates[0];
632
+ const hadBacklog = candidates.length > 1 || this.readyCandidates(plugin, scope).length > 1;
633
+ this.runPlugin(plugin, target.work, hadBacklog);
634
+ launched += 1;
635
+ }
636
+ return launched;
637
+ }
638
+ runPlugin(plugin, work, hadBacklog) {
639
+ const activeKey = this.invocationKey(plugin.id, work.epoch.epochSeq);
640
+ void this.invokeWithPolicy(plugin, work).then((invocation) => {
641
+ void invocation.settlement.then(() => {
642
+ this.activeInvocations.delete(activeKey);
643
+ this.requestPump();
644
+ });
645
+ const buffer = this.bufferFor(plugin.id);
646
+ if (buffer.has(work.epoch.epochSeq)) {
647
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} epoch ${work.epoch.epochSeq} completed twice.`);
648
+ }
649
+ buffer.set(work.epoch.epochSeq, {
650
+ invocation,
651
+ work: cloneCanonical(work),
652
+ hadBacklog,
653
+ });
654
+ this.requestPump();
655
+ }).catch((error) => {
656
+ this.activeInvocations.delete(activeKey);
657
+ this.failRuntime(error, plugin.id, work.epoch.scope);
658
+ });
659
+ }
660
+ launchReadyCommits() {
661
+ const scope = this.activeScope;
662
+ if (!scope)
663
+ return 0;
664
+ let launched = 0;
665
+ for (const plugin of this.plugins) {
666
+ // A parallel update may finish while an earlier ordered commit is still
667
+ // performing effects. Apply the same catch-up window to those completed
668
+ // proposals before granting the next commit lease; otherwise buffered
669
+ // results can bypass trimBoundedBacklog and replay an arbitrarily stale
670
+ // sequence of Actions after the head commit settles.
671
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
672
+ this.trimBoundedBacklog(plugin, scope);
673
+ }
674
+ if (this.activeCommits.has(plugin.id))
675
+ continue;
676
+ const progress = this.pluginStore.pluginProgress(plugin.id, scope);
677
+ const next = this.pendingInOrder().find((pending) => (runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope)
678
+ && pending.work.epoch.epochSeq > progress.completedThroughEpochSeq));
679
+ if (!next)
680
+ continue;
681
+ const buffered = this.bufferFor(plugin.id).get(next.work.epoch.epochSeq);
682
+ if (!buffered)
683
+ continue;
684
+ const controller = new AbortController();
685
+ this.activeCommits.set(plugin.id, controller);
686
+ void this.commitBufferedInvocation(buffered, controller).catch((error) => {
687
+ this.failRuntime(error, plugin.id, buffered.work.epoch.scope);
688
+ }).finally(() => {
689
+ this.bufferFor(plugin.id).delete(buffered.work.epoch.epochSeq);
690
+ this.activeCommits.delete(plugin.id);
691
+ this.requestPump();
692
+ });
693
+ launched += 1;
694
+ }
695
+ return launched;
696
+ }
697
+ async commitBufferedInvocation(buffered, controller) {
698
+ const { plugin } = buffered.invocation;
699
+ const policy = normalizedFailurePolicy(plugin);
700
+ if (buffered.invocation.error && policy.mode === 'terminate') {
701
+ throw new RuntimeEpochPluginFatalError(plugin.id, buffered.invocation.error);
702
+ }
703
+ if (buffered.invocation.error && policy.mode === 'pause')
704
+ this.pausedPlugins.add(plugin.id);
705
+ if (this.pausedPlugins.has(plugin.id) && !buffered.invocation.error) {
706
+ this.recordPausedCompletion(plugin, buffered.work);
707
+ return;
708
+ }
709
+ const progress = this.pluginStore.pluginProgress(plugin.id, buffered.work.epoch.scope);
710
+ let invocation = {
711
+ ...buffered.invocation,
712
+ cursorBefore: progress.eventCursor,
713
+ ...(progress.checkpoint === undefined
714
+ ? { checkpointBefore: undefined }
715
+ : { checkpointBefore: cloneCanonical(progress.checkpoint) }),
716
+ };
717
+ // Decide whether a latest-only proposal is stale at the ordered-commit
718
+ // boundary. Once commit starts, its reducer/Action side effects and its
719
+ // published output must remain one atomic decision; rechecking afterwards
720
+ // could execute an old Action and then silently discard the matching
721
+ // State/Event output.
722
+ const latestReadyBeforeCommit = this.readyCandidates(plugin, buffered.work.epoch.scope).at(-1)?.work.epoch.epochSeq ?? buffered.work.epoch.epochSeq;
723
+ const supersededBeforeCommit = !invocation.error
724
+ && !forbidsCoalescing(buffered.work)
725
+ && (plugin.catchUp ?? 'every_epoch') === 'latest_only'
726
+ && plugin.backlogPolicy !== 'finish_started'
727
+ && latestReadyBeforeCommit > buffered.work.epoch.epochSeq
728
+ ? latestReadyBeforeCommit
729
+ : null;
730
+ if (!invocation.error && plugin.commit && supersededBeforeCommit === null) {
731
+ const commitStartedAt = this.nowMs();
732
+ const maxEventWatermark = this.inputJournal.eventWatermarkThrough(buffered.work.epoch.scope, buffered.work.epoch.epochSeq);
733
+ const input = this.pluginInput(plugin, buffered.work, this.epochEventsFor(buffered.work), this.upstreamStatesFor(buffered.work.epoch.epochSeq), progress.eventCursor, maxEventWatermark);
734
+ try {
735
+ const result = await this.withDeadline(plugin, controller, () => plugin.commit(input, cloneCanonical(invocation.result), this.context(plugin, buffered.work.epoch.scope, controller.signal, buffered.work.epoch.epochSeq)), undefined, true);
736
+ validateResult(plugin, result);
737
+ invocation = {
738
+ ...invocation,
739
+ result: cloneCanonical(result),
740
+ maxEventWatermark,
741
+ durationMs: invocation.durationMs + Math.max(0, this.nowMs() - commitStartedAt),
742
+ };
743
+ }
744
+ catch (error) {
745
+ invocation = {
746
+ ...invocation,
747
+ error,
748
+ result: undefined,
749
+ maxEventWatermark,
750
+ durationMs: invocation.durationMs + Math.max(0, this.nowMs() - commitStartedAt),
751
+ };
752
+ }
753
+ }
754
+ if (invocation.error && policy.mode === 'terminate') {
755
+ throw new RuntimeEpochPluginFatalError(plugin.id, invocation.error);
756
+ }
757
+ if (invocation.error && policy.mode === 'pause')
758
+ this.pausedPlugins.add(plugin.id);
759
+ await this.commitInvocation(invocation, buffered.work, supersededBeforeCommit);
760
+ if (normalizedMaxInFlight(plugin) === 1 && (plugin.catchUp ?? 'every_epoch') === 'every_epoch') {
761
+ const backlogRemains = this.readyCandidates(plugin, buffered.work.epoch.scope).length > 0;
762
+ this.catchUpCounts.set(plugin.id, buffered.hadBacklog || backlogRemains ? (this.catchUpCounts.get(plugin.id) ?? 0) + 1 : 0);
763
+ }
764
+ }
765
+ async invokeWithPolicy(plugin, work) {
766
+ const policy = normalizedFailurePolicy(plugin);
767
+ const maxAttempts = policy.mode === 'retry' ? policy.maxAttempts ?? DEFAULT_RETRY_ATTEMPTS : 1;
768
+ let invocation;
769
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
770
+ invocation = await this.invoke(plugin, work, attempt);
771
+ if (!invocation.error || invocation.error instanceof RuntimeEpochPluginSupersededError)
772
+ return invocation;
773
+ if (attempt < maxAttempts) {
774
+ this.onDiagnostic?.('runtime.plugin.invocation_retrying', {
775
+ plugin_id: plugin.id,
776
+ epoch_seq: work.epoch.epochSeq,
777
+ attempt,
778
+ max_attempts: maxAttempts,
779
+ error_code: pluginDiagnosticErrorCode(invocation.error, 'RUNTIME_PLUGIN_INVOCATION_FAILED'),
780
+ }, work.epoch.scope, 'warn');
781
+ await invocation.settlement;
782
+ }
783
+ }
784
+ return invocation;
785
+ }
786
+ async invoke(plugin, work, attempt) {
787
+ const invocationId = randomUUID();
788
+ const controller = new AbortController();
789
+ const startedAt = this.nowMs();
790
+ this.activeInvocations.set(this.invocationKey(plugin.id, work.epoch.epochSeq), {
791
+ pluginId: plugin.id,
792
+ epochSeq: work.epoch.epochSeq,
793
+ controller,
794
+ });
795
+ await this.ensureInputEventsCommitted(work);
796
+ const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
797
+ const maxEventWatermark = this.inputJournal.eventWatermarkThrough(work.epoch.scope, work.epoch.epochSeq);
798
+ const input = this.pluginInput(plugin, work, this.epochEventsFor(work), this.upstreamStatesFor(work.epoch.epochSeq), progress.eventCursor, maxEventWatermark);
799
+ let settlement = Promise.resolve();
800
+ try {
801
+ const result = await this.withDeadline(plugin, controller, () => plugin.update(input, this.context(plugin, work.epoch.scope, controller.signal, work.epoch.epochSeq, {
802
+ progress,
803
+ allowActions: normalizedMaxInFlight(plugin) === 1,
804
+ snapshotSegment: normalizedMaxInFlight(plugin) > 1,
805
+ })), (settlement) => {
806
+ this.onDiagnostic?.('runtime.plugin.stale_output_rejected', {
807
+ plugin_id: plugin.id,
808
+ invocation_id: invocationId,
809
+ epoch_seq: work.epoch.epochSeq,
810
+ settlement,
811
+ reason: controller.signal.reason instanceof RuntimeEpochPluginSupersededError
812
+ ? controller.signal.reason.reasonCode
813
+ : 'invocation_timed_out',
814
+ }, work.epoch.scope, 'warn');
815
+ }, false, (operationSettlement) => { settlement = operationSettlement; });
816
+ if (plugin.commit)
817
+ validateComputationResult(plugin, result);
818
+ else if (normalizedMaxInFlight(plugin) > 1)
819
+ validateParallelFinalResult(plugin, result);
820
+ else
821
+ validateResult(plugin, result);
822
+ return {
823
+ plugin,
824
+ invocationId,
825
+ startedAt,
826
+ durationMs: Math.max(0, this.nowMs() - startedAt),
827
+ settlement,
828
+ attempt,
829
+ result: cloneCanonical(result),
830
+ cursorBefore: progress.eventCursor,
831
+ ...(progress.checkpoint === undefined ? {} : { checkpointBefore: cloneCanonical(progress.checkpoint) }),
832
+ maxEventWatermark,
833
+ };
834
+ }
835
+ catch (error) {
836
+ if (error instanceof RuntimeEpochPluginTimeoutError) {
837
+ this.onDiagnostic?.('runtime.plugin.invocation_cancelled', {
838
+ plugin_id: plugin.id,
839
+ invocation_id: invocationId,
840
+ epoch_seq: work.epoch.epochSeq,
841
+ reason: 'timeout',
842
+ timeout_ms: error.timeoutMs,
843
+ }, work.epoch.scope, 'warn');
844
+ }
845
+ else if (error instanceof RuntimeEpochPluginSupersededError) {
846
+ this.onDiagnostic?.('runtime.plugin.invocation_cancelled', {
847
+ plugin_id: plugin.id,
848
+ invocation_id: invocationId,
849
+ epoch_seq: work.epoch.epochSeq,
850
+ newer_epoch_seq: error.newerEpochSeq,
851
+ reason: error.reasonCode,
852
+ }, work.epoch.scope);
853
+ }
854
+ return {
855
+ plugin,
856
+ invocationId,
857
+ startedAt,
858
+ durationMs: Math.max(0, this.nowMs() - startedAt),
859
+ settlement,
860
+ attempt,
861
+ error,
862
+ cursorBefore: progress.eventCursor,
863
+ ...(progress.checkpoint === undefined ? {} : { checkpointBefore: cloneCanonical(progress.checkpoint) }),
864
+ maxEventWatermark,
865
+ };
866
+ }
867
+ }
868
+ async commitInvocation(invocation, work, supersededBeforeCommit = null) {
869
+ const { plugin } = invocation;
870
+ let outcome;
871
+ let reason;
872
+ let stateRows = [];
873
+ let eventCount = 0;
874
+ let cursorAfter = invocation.cursorBefore;
875
+ if (invocation.error instanceof RuntimeEpochPluginSupersededError) {
876
+ outcome = 'coalesced';
877
+ reason = invocation.error.reasonCode;
878
+ }
879
+ else if (invocation.error) {
880
+ outcome = 'failed';
881
+ reason = invocation.error instanceof Error ? invocation.error.message : String(invocation.error);
882
+ }
883
+ else {
884
+ const result = invocation.result;
885
+ const superseded = supersededBeforeCommit !== null;
886
+ outcome = superseded ? 'coalesced' : result.outcome;
887
+ reason = superseded ? 'newer_epoch_available_before_commit' : result.reason;
888
+ if (superseded) {
889
+ this.onDiagnostic?.('runtime.plugin.stale_output_rejected', {
890
+ plugin_id: plugin.id,
891
+ invocation_id: invocation.invocationId,
892
+ epoch_seq: work.epoch.epochSeq,
893
+ newer_epoch_seq: supersededBeforeCommit,
894
+ reason,
895
+ }, work.epoch.scope);
896
+ }
897
+ else {
898
+ if (result.consumeEventsThroughCommitSeq !== undefined) {
899
+ const requested = result.consumeEventsThroughCommitSeq;
900
+ if (!Number.isInteger(requested)
901
+ || requested < invocation.cursorBefore
902
+ || requested > invocation.maxEventWatermark) {
903
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} returned invalid Event cursor ${requested}.`);
904
+ }
905
+ cursorAfter = requested;
906
+ }
907
+ stateRows = (result.states ?? []).map((state) => ({
908
+ epochSeq: work.epoch.epochSeq,
909
+ pluginId: plugin.id,
910
+ topic: state.topic,
911
+ value: cloneCanonical(state.value),
912
+ }));
913
+ const deliveryFacts = result.eventDeliveries?.length ? this.listEvents({
914
+ scope: work.epoch.scope, afterCommitSeq: invocation.cursorBefore,
915
+ maxCommitSeq: invocation.maxEventWatermark, maxEpochSeq: work.epoch.epochSeq,
916
+ }) : [];
917
+ for (const decision of result.eventDeliveries ?? []) {
918
+ const fact = deliveryFacts.find(event => event.eventId === decision.eventId);
919
+ if (!fact || !plugin.controlsEventDelivery?.includes(fact.type)
920
+ || !['monitor_and_events', 'internal_only'].includes(decision.deliveryClass)) {
921
+ throw new Error(`Runtime Epoch Plugin ${plugin.id} returned an unauthorized delivery decision.`);
922
+ }
923
+ }
924
+ for (const decision of result.eventDeliveries ?? []) {
925
+ if (!this.resolveEventDelivery)
926
+ throw new Error('Event delivery decisions are unsupported.');
927
+ this.resolveEventDelivery(decision);
928
+ }
929
+ for (const [proposalIndex, proposal] of (result.events ?? []).entries()) {
930
+ await this.publishEvent(plugin.id, work.epoch, proposal, proposalIndex);
931
+ eventCount += 1;
932
+ }
933
+ if (eventCount > 0) {
934
+ this.inputJournal.markEventWatermark(work.epoch.epochSeq, this.highWaterCommitSeq(work.epoch.scope));
935
+ }
936
+ }
937
+ }
938
+ if (stateRows.length > 0)
939
+ this.pluginStore.saveStates(stateRows);
940
+ const recordedAtMs = this.nowMs();
941
+ const now = new Date(recordedAtMs).toISOString();
942
+ const record = {
943
+ epochSeq: work.epoch.epochSeq,
944
+ pluginId: plugin.id,
945
+ invocationId: invocation.invocationId,
946
+ outcome,
947
+ ...(reason ? { reason } : {}),
948
+ durationMs: invocation.durationMs,
949
+ stateCount: stateRows.length,
950
+ eventCount,
951
+ eventCursorBefore: invocation.cursorBefore,
952
+ eventCursorAfter: cursorAfter,
953
+ recordedAt: now,
954
+ };
955
+ this.pluginStore.recordPlugin(record);
956
+ this.pluginStore.savePluginProgress({
957
+ pluginId: plugin.id,
958
+ completedThroughEpochSeq: work.epoch.epochSeq,
959
+ eventCursor: cursorAfter,
960
+ ...(invocation.result?.checkpoint === undefined || outcome === 'coalesced'
961
+ ? (invocation.checkpointBefore === undefined ? {} : { checkpoint: cloneCanonical(invocation.checkpointBefore) })
962
+ : { checkpoint: cloneCanonical(invocation.result.checkpoint) }),
963
+ updatedAt: now,
964
+ }, work.epoch.scope);
965
+ this.recordPluginTiming(record, work.epoch.scope, recordedAtMs);
966
+ if (outcome === 'failed') {
967
+ this.onDiagnostic?.('runtime.plugin.invocation_failed', {
968
+ plugin_id: plugin.id,
969
+ invocation_id: invocation.invocationId,
970
+ epoch_seq: work.epoch.epochSeq,
971
+ attempt: invocation.attempt,
972
+ outcome,
973
+ error_code: pluginDiagnosticErrorCode(invocation.error, 'RUNTIME_PLUGIN_INVOCATION_FAILED'),
974
+ duration_ms: record.durationMs,
975
+ state_count: record.stateCount,
976
+ event_count: record.eventCount,
977
+ event_cursor_before: record.eventCursorBefore,
978
+ event_cursor_after: record.eventCursorAfter,
979
+ }, work.epoch.scope, 'error');
980
+ }
981
+ else {
982
+ const slowThresholdMs = slowPluginThresholdMs(plugin.id);
983
+ if (record.durationMs >= slowThresholdMs) {
984
+ this.onDiagnostic?.('runtime.plugin.slow', {
985
+ plugin_id: plugin.id,
986
+ invocation_id: invocation.invocationId,
987
+ epoch_seq: work.epoch.epochSeq,
988
+ attempt: invocation.attempt,
989
+ outcome,
990
+ ...(reason === undefined ? {} : { reason }),
991
+ duration_ms: record.durationMs,
992
+ threshold_ms: slowThresholdMs,
993
+ state_count: record.stateCount,
994
+ event_count: record.eventCount,
995
+ }, work.epoch.scope, 'warn');
996
+ }
997
+ }
998
+ }
999
+ recordCoalesced(plugin, works, reason) {
1000
+ if (works.length === 0)
1001
+ return;
1002
+ for (const work of works) {
1003
+ const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
1004
+ const recordedAtMs = this.nowMs();
1005
+ const recordedAt = new Date(recordedAtMs).toISOString();
1006
+ const record = {
1007
+ epochSeq: work.epoch.epochSeq,
1008
+ pluginId: plugin.id,
1009
+ invocationId: randomUUID(),
1010
+ outcome: 'coalesced',
1011
+ reason,
1012
+ durationMs: 0,
1013
+ stateCount: 0,
1014
+ eventCount: 0,
1015
+ eventCursorBefore: progress.eventCursor,
1016
+ eventCursorAfter: progress.eventCursor,
1017
+ recordedAt,
1018
+ };
1019
+ this.pluginStore.recordPlugin(record);
1020
+ this.pluginStore.savePluginProgress({
1021
+ ...progress,
1022
+ completedThroughEpochSeq: work.epoch.epochSeq,
1023
+ updatedAt: recordedAt,
1024
+ }, work.epoch.scope);
1025
+ this.recordPluginTiming(record, work.epoch.scope, recordedAtMs, false);
1026
+ }
1027
+ this.onDiagnostic?.('runtime.plugin.invocations_coalesced', {
1028
+ plugin_id: plugin.id,
1029
+ reason,
1030
+ skipped_from_epoch_seq: works[0].epoch.epochSeq,
1031
+ skipped_through_epoch_seq: works.at(-1).epoch.epochSeq,
1032
+ coalesced_epoch_count: works.length,
1033
+ }, works[0].epoch.scope);
1034
+ }
1035
+ recordPausedCompletion(plugin, work) {
1036
+ const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
1037
+ const recordedAtMs = this.nowMs();
1038
+ const recordedAt = new Date(recordedAtMs).toISOString();
1039
+ const record = {
1040
+ epochSeq: work.epoch.epochSeq,
1041
+ pluginId: plugin.id,
1042
+ invocationId: randomUUID(),
1043
+ outcome: 'failed',
1044
+ reason: 'plugin_paused',
1045
+ durationMs: 0,
1046
+ stateCount: 0,
1047
+ eventCount: 0,
1048
+ eventCursorBefore: progress.eventCursor,
1049
+ eventCursorAfter: progress.eventCursor,
1050
+ recordedAt,
1051
+ };
1052
+ this.pluginStore.recordPlugin(record);
1053
+ this.pluginStore.savePluginProgress({
1054
+ ...progress,
1055
+ completedThroughEpochSeq: work.epoch.epochSeq,
1056
+ updatedAt: recordedAt,
1057
+ }, work.epoch.scope);
1058
+ this.recordPluginTiming(record, work.epoch.scope, recordedAtMs, false);
1059
+ this.onDiagnostic?.('runtime.plugin.invocation_failed', {
1060
+ plugin_id: plugin.id,
1061
+ epoch_seq: work.epoch.epochSeq,
1062
+ outcome: 'failed',
1063
+ reason: 'plugin_paused',
1064
+ }, work.epoch.scope, 'warn');
1065
+ }
1066
+ async closeReadyEpochs() {
1067
+ const scope = this.activeScope;
1068
+ if (!scope)
1069
+ return false;
1070
+ let progressed = false;
1071
+ while (true) {
1072
+ const pending = this.pendingInOrder()[0];
1073
+ if (!pending || runtimeScopeKey(pending.work.epoch.scope) !== runtimeScopeKey(scope))
1074
+ break;
1075
+ const epochSeq = pending.work.epoch.epochSeq;
1076
+ await this.ensureInputEventsCommitted(pending.work);
1077
+ const complete = this.plugins.every((plugin) => (this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq >= epochSeq));
1078
+ if (!complete)
1079
+ break;
1080
+ const outcomes = this.pluginStore.pluginRecords(epochSeq)
1081
+ .sort((a, b) => this.orderOfId(a.pluginId) - this.orderOfId(b.pluginId));
1082
+ const eventWatermark = this.inputJournal.eventWatermarkThrough(scope, epochSeq);
1083
+ const eventCount = this.listEvents({
1084
+ scope,
1085
+ afterCommitSeq: 0,
1086
+ maxCommitSeq: eventWatermark,
1087
+ epochSeq,
1088
+ }).length;
1089
+ const closedAtMs = this.nowMs();
1090
+ const durationMs = Math.max(0, closedAtMs - pending.queuedAtMs);
1091
+ const result = {
1092
+ epochSeq,
1093
+ durationMs,
1094
+ outcomes,
1095
+ stateCount: this.pluginStore.states(epochSeq).length,
1096
+ eventCount,
1097
+ eventWatermark,
1098
+ };
1099
+ this.inputJournal.markClosed(epochSeq, new Date(closedAtMs).toISOString(), durationMs);
1100
+ this.lastWork = cloneCanonical(pending.work);
1101
+ await this.onEpochClosed?.(cloneCanonical(pending.work), cloneCanonical(result));
1102
+ this.pending.delete(epochSeq);
1103
+ pending.resolve(cloneCanonical(result));
1104
+ if (durationMs >= DEFAULT_SLOW_EPOCH_MS) {
1105
+ this.onDiagnostic?.('runtime.epoch.slow', {
1106
+ epoch_seq: epochSeq,
1107
+ domain_tick: pending.work.epoch.domainTick,
1108
+ source_id: pending.work.epoch.sourceId,
1109
+ duration_ms: durationMs,
1110
+ threshold_ms: DEFAULT_SLOW_EPOCH_MS,
1111
+ plugin_count: outcomes.length,
1112
+ state_count: result.stateCount,
1113
+ event_count: result.eventCount,
1114
+ }, scope, 'warn');
1115
+ }
1116
+ this.reportLagTransition(scope, this.latestPendingEpochSeq(scope, epochSeq));
1117
+ progressed = true;
1118
+ }
1119
+ return progressed;
1120
+ }
1121
+ readyCandidates(plugin, scope) {
1122
+ const progress = this.pluginStore.pluginProgress(plugin.id, scope);
1123
+ const dependencies = (plugin.after ?? []).map((id) => (this.pluginStore.pluginProgress(id, scope).completedThroughEpochSeq));
1124
+ const readyThrough = dependencies.length === 0
1125
+ ? Number.MAX_SAFE_INTEGER
1126
+ : Math.min(...dependencies);
1127
+ return this.pendingInOrder().filter((pending) => (runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope)
1128
+ && pending.work.epoch.epochSeq > progress.completedThroughEpochSeq
1129
+ && pending.work.epoch.epochSeq <= readyThrough));
1130
+ }
1131
+ launchCandidates(plugin, scope) {
1132
+ return this.readyCandidates(plugin, scope).filter((pending) => (!this.isInvocationScheduled(plugin.id, pending.work.epoch.epochSeq)));
1133
+ }
1134
+ trimBoundedBacklog(plugin, scope) {
1135
+ const maxInFlight = normalizedMaxInFlight(plugin);
1136
+ const catchUpWindow = Math.min(normalizedMaxPendingEpochs(plugin, maxInFlight > 1
1137
+ ? Math.min(maxInFlight, this.maxCatchUpEpochs)
1138
+ : this.maxCatchUpEpochs), 10_000);
1139
+ if (plugin.backlogPolicy === 'finish_started') {
1140
+ const ready = this.readyCandidates(plugin, scope);
1141
+ if (ready.length > catchUpWindow)
1142
+ this.drainingBatches.add(plugin.id);
1143
+ if (!this.drainingBatches.has(plugin.id))
1144
+ return;
1145
+ // Do not replace active/buffered work. Stop refilling the current batch
1146
+ // until its ordered effects have completed, then skip only unstarted work.
1147
+ if (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id))
1148
+ return;
1149
+ const boundary = ready.findIndex(({ work }) => forbidsCoalescing(work));
1150
+ const target = boundary >= 0 ? boundary : ready.length - 1;
1151
+ if (target > 0)
1152
+ this.recordCoalesced(plugin, ready.slice(0, target).map(x => x.work), boundary >= 0 ? 'required_epoch_boundary' : 'catch_up_limit');
1153
+ this.drainingBatches.delete(plugin.id);
1154
+ return;
1155
+ }
1156
+ while (true) {
1157
+ const ready = this.readyCandidates(plugin, scope);
1158
+ const earliest = ready[0];
1159
+ const latest = ready.at(-1);
1160
+ const requiredIndex = ready.findIndex(({ work }) => forbidsCoalescing(work));
1161
+ if (!earliest
1162
+ || !latest
1163
+ || ready.length <= catchUpWindow)
1164
+ return;
1165
+ if (requiredIndex === 0 || forbidsCoalescing(earliest.work))
1166
+ return;
1167
+ const reason = requiredIndex > 0 ? 'required_epoch_boundary' : 'catch_up_limit';
1168
+ // commit() is the atomic reducer/effect boundary. Once it has started we
1169
+ // must let it finish; only a completed proposal that has not obtained the
1170
+ // commit lease may be discarded.
1171
+ if (this.activeCommits.has(plugin.id))
1172
+ return;
1173
+ const buffer = this.bufferFor(plugin.id);
1174
+ const buffered = buffer.get(earliest.work.epoch.epochSeq);
1175
+ if (buffered) {
1176
+ // invokeWithPolicy can return before the underlying Promise settles
1177
+ // after cancellation/timeout. It can also carry a real failure whose
1178
+ // failure policy must remain observable. In either case use the normal
1179
+ // ordered completion path instead of silently rewriting it as catch-up.
1180
+ if (this.activeInvocations.has(this.invocationKey(plugin.id, earliest.work.epoch.epochSeq))
1181
+ || buffered.invocation.error !== undefined)
1182
+ return;
1183
+ buffer.delete(earliest.work.epoch.epochSeq);
1184
+ this.recordCoalesced(plugin, [earliest.work], reason);
1185
+ continue;
1186
+ }
1187
+ const active = this.activeInvocations.get(this.invocationKey(plugin.id, earliest.work.epoch.epochSeq));
1188
+ if (active) {
1189
+ if (!active.controller.signal.aborted) {
1190
+ active.controller.abort(new RuntimeEpochPluginSupersededError(plugin.id, earliest.work.epoch.epochSeq, latest.work.epoch.epochSeq, reason));
1191
+ }
1192
+ return;
1193
+ }
1194
+ this.recordCoalesced(plugin, [earliest.work], reason);
1195
+ }
1196
+ }
1197
+ invocationKey(pluginId, epochSeq) {
1198
+ return `${pluginId}\u0000${epochSeq}`;
1199
+ }
1200
+ bufferFor(pluginId) {
1201
+ let buffer = this.bufferedInvocations.get(pluginId);
1202
+ if (!buffer) {
1203
+ buffer = new Map();
1204
+ this.bufferedInvocations.set(pluginId, buffer);
1205
+ }
1206
+ return buffer;
1207
+ }
1208
+ bufferedInvocationCount() {
1209
+ let count = 0;
1210
+ for (const buffer of this.bufferedInvocations.values())
1211
+ count += buffer.size;
1212
+ return count;
1213
+ }
1214
+ scheduledInvocationCount(pluginId) {
1215
+ const epochs = new Set(this.bufferedInvocations.get(pluginId)?.keys() ?? []);
1216
+ for (const invocation of this.activeInvocations.values()) {
1217
+ if (invocation.pluginId === pluginId)
1218
+ epochs.add(invocation.epochSeq);
1219
+ }
1220
+ return epochs.size;
1221
+ }
1222
+ isInvocationScheduled(pluginId, epochSeq) {
1223
+ return this.activeInvocations.has(this.invocationKey(pluginId, epochSeq))
1224
+ || (this.bufferedInvocations.get(pluginId)?.has(epochSeq) ?? false);
1225
+ }
1226
+ abortSupersededInvocations() {
1227
+ const scope = this.activeScope;
1228
+ if (!scope)
1229
+ return;
1230
+ for (const plugin of this.plugins) {
1231
+ if ((plugin.catchUp ?? 'every_epoch') !== 'latest_only')
1232
+ continue;
1233
+ for (const active of this.activeInvocations.values()) {
1234
+ if (active.pluginId !== plugin.id || active.controller.signal.aborted)
1235
+ continue;
1236
+ const activeWork = this.pending.get(active.epochSeq)?.work;
1237
+ if (activeWork && forbidsCoalescing(activeWork))
1238
+ continue;
1239
+ const latestReady = this.readyCandidates(plugin, scope).at(-1)?.work.epoch.epochSeq;
1240
+ if (latestReady !== undefined && latestReady > active.epochSeq) {
1241
+ active.controller.abort(new RuntimeEpochPluginSupersededError(plugin.id, active.epochSeq, latestReady));
1242
+ }
1243
+ }
1244
+ }
1245
+ }
1246
+ epochEventsFor(work) {
1247
+ const watermark = this.inputJournal.eventWatermarkThrough(work.epoch.scope, work.epoch.epochSeq);
1248
+ const committedCurrentEvents = this.listEvents({
1249
+ scope: work.epoch.scope,
1250
+ afterCommitSeq: 0,
1251
+ maxCommitSeq: watermark,
1252
+ epochSeq: work.epoch.epochSeq,
1253
+ });
1254
+ const events = [
1255
+ ...work.epochEvents,
1256
+ ...committedCurrentEvents,
1257
+ ];
1258
+ const unique = new Map(events.map((event) => [event.eventId, event]));
1259
+ return [...unique.values()];
1260
+ }
1261
+ upstreamStatesFor(epochSeq) {
1262
+ return Object.fromEntries(this.pluginStore.states(epochSeq).map((row) => [row.topic, cloneCanonical(row.value)]));
1263
+ }
1264
+ pluginInput(plugin, work, epochEvents, upstreamStates, eventCursor, maxEventWatermark) {
1265
+ const subscribedTypes = plugin.consumes?.events ?? [];
1266
+ const allEvents = subscribedTypes.includes('*');
1267
+ const eventTypes = new Set(subscribedTypes);
1268
+ const committedPendingEvents = subscribedTypes.length === 0 ? [] : this.listEvents({
1269
+ scope: work.epoch.scope,
1270
+ afterCommitSeq: eventCursor,
1271
+ maxCommitSeq: maxEventWatermark,
1272
+ maxEpochSeq: work.epoch.epochSeq,
1273
+ ...(allEvents ? {} : { types: subscribedTypes }),
1274
+ });
1275
+ const pendingEvents = new Map(committedPendingEvents.map((event) => [event.eventId, event]));
1276
+ for (const event of epochEvents) {
1277
+ if (event.commitSeq > eventCursor
1278
+ && (allEvents || eventTypes.has(event.type)))
1279
+ pendingEvents.set(event.eventId, event);
1280
+ }
1281
+ const stateTopics = new Set(plugin.consumes?.states ?? []);
1282
+ const allStates = stateTopics.has('*');
1283
+ return deepFreeze({
1284
+ epoch: work.epoch,
1285
+ frame: work.frame,
1286
+ currentState: work.currentState,
1287
+ previousState: work.previousState,
1288
+ epochEvents: epochEvents.filter((event) => allEvents || eventTypes.has(event.type)),
1289
+ pendingEvents: [...pendingEvents.values()].sort((a, b) => a.commitSeq - b.commitSeq),
1290
+ upstreamStates: Object.fromEntries(Object.entries(upstreamStates).filter(([topic]) => allStates || stateTopics.has(topic))),
1291
+ });
1292
+ }
1293
+ context(plugin, scope, signal, epochSeq, options = {}) {
1294
+ const progress = options.progress;
1295
+ const capabilities = this.capabilitiesFor?.(plugin, scope, signal, epochSeq)
1296
+ ?? unavailableCapabilities(plugin.id);
1297
+ const segment = options.snapshotSegment ? cloneCanonical(this.currentSegment()) : null;
1298
+ return Object.freeze({
1299
+ scope: cloneCanonical(scope),
1300
+ ...(this.processingIntervalMs === undefined ? {} : { processingIntervalMs: this.processingIntervalMs }),
1301
+ stateHistory: this.stateHistoryThrough(scope, epochSeq),
1302
+ sourceEventsAt: (requestedEpoch) => {
1303
+ if (!Number.isSafeInteger(requestedEpoch) || requestedEpoch < 1 || requestedEpoch > epochSeq)
1304
+ return [];
1305
+ const input = this.inputJournal.epoch(requestedEpoch);
1306
+ if (!input || runtimeScopeKey(input.scope) !== runtimeScopeKey(scope))
1307
+ return [];
1308
+ const types = new Set(plugin.consumes?.events ?? []);
1309
+ return cloneCanonical(input.events.filter(event => types.has('*') || types.has(event.type)));
1310
+ },
1311
+ currentSegment: segment
1312
+ ? () => cloneCanonical(segment)
1313
+ : this.currentSegment,
1314
+ checkpoint: () => cloneCanonical(progress
1315
+ ? progress.checkpoint
1316
+ : this.pluginStore.pluginProgress(plugin.id, scope).checkpoint),
1317
+ progress: () => cloneCanonical(progress ?? this.pluginStore.pluginProgress(plugin.id, scope)),
1318
+ capabilities: options.allowActions === false
1319
+ ? computationCapabilities(plugin.id, capabilities)
1320
+ : capabilities,
1321
+ diagnostic: (name, attributes = {}, severity = 'debug') => {
1322
+ this.onDiagnostic?.(name, {
1323
+ plugin_id: plugin.id,
1324
+ epoch_seq: epochSeq,
1325
+ ...attributes,
1326
+ }, scope, severity);
1327
+ },
1328
+ signal,
1329
+ });
1330
+ }
1331
+ async stopScope(reason) {
1332
+ const scope = this.activeScope;
1333
+ if (!scope)
1334
+ return;
1335
+ for (const layer of [...this.layers].reverse()) {
1336
+ await Promise.all(layer.map(async (plugin) => {
1337
+ if (!plugin.stop)
1338
+ return;
1339
+ const controller = new AbortController();
1340
+ await this.withDeadline(plugin, controller, () => plugin.stop(reason, this.context(plugin, scope, controller.signal, this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq))).catch((error) => {
1341
+ this.onDiagnostic?.('runtime.plugin.stop_failed', {
1342
+ plugin_id: plugin.id,
1343
+ reason,
1344
+ error_code: pluginDiagnosticErrorCode(error, 'RUNTIME_PLUGIN_STOP_FAILED'),
1345
+ }, scope, 'warn');
1346
+ });
1347
+ }));
1348
+ }
1349
+ this.flushPluginTimingWindows(scope, this.nowMs());
1350
+ this.lagBands.delete(runtimeScopeKey(scope));
1351
+ this.activeScope = null;
1352
+ }
1353
+ stateHistoryThrough(scope, epochSeq) {
1354
+ const boundedQuery = (query) => ({
1355
+ ...query,
1356
+ scope: cloneCanonical(scope),
1357
+ toEpochSeq: Math.min(query.toEpochSeq ?? epochSeq, epochSeq),
1358
+ });
1359
+ return Object.freeze({
1360
+ queryStateFrames: (query) => this.stateHistory.queryStateFrames(boundedQuery(query)),
1361
+ latestStateFrame: (_requestedScope) => this.stateHistory.queryStateFrames({
1362
+ scope: cloneCanonical(scope),
1363
+ toEpochSeq: epochSeq,
1364
+ order: 'desc',
1365
+ limit: 1,
1366
+ }).frames[0] ?? null,
1367
+ });
1368
+ }
1369
+ ensureInputEventsCommitted(work) {
1370
+ const epochSeq = work.epoch.epochSeq;
1371
+ if (this.inputJournal.inputEventsCommitted(epochSeq))
1372
+ return Promise.resolve();
1373
+ const existing = this.inputEventCommits.get(epochSeq);
1374
+ if (existing)
1375
+ return existing;
1376
+ const committing = this.inputEventCommitTail.then(async () => {
1377
+ await this.commitInputEvents(cloneCanonical(work));
1378
+ const watermark = this.highWaterCommitSeq(work.epoch.scope);
1379
+ this.inputJournal.markInputEventsCommitted(epochSeq, watermark);
1380
+ });
1381
+ this.inputEventCommitTail = committing.catch(() => { });
1382
+ void committing.then(() => this.inputEventCommits.delete(epochSeq), () => this.inputEventCommits.delete(epochSeq));
1383
+ this.inputEventCommits.set(epochSeq, committing);
1384
+ return committing;
1385
+ }
1386
+ ensureRecoveredRecords(work) {
1387
+ const existing = new Set(this.pluginStore.pluginRecords(work.epoch.epochSeq).map((row) => row.pluginId));
1388
+ for (const plugin of this.plugins) {
1389
+ const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
1390
+ if (progress.completedThroughEpochSeq < work.epoch.epochSeq || existing.has(plugin.id))
1391
+ continue;
1392
+ this.pluginStore.recordPlugin({
1393
+ epochSeq: work.epoch.epochSeq,
1394
+ pluginId: plugin.id,
1395
+ invocationId: randomUUID(),
1396
+ outcome: 'noop',
1397
+ reason: 'recovered:already_completed',
1398
+ durationMs: 0,
1399
+ stateCount: this.pluginStore.states(work.epoch.epochSeq)
1400
+ .filter((row) => row.pluginId === plugin.id).length,
1401
+ eventCount: this.listEvents({
1402
+ scope: work.epoch.scope,
1403
+ afterCommitSeq: 0,
1404
+ maxCommitSeq: this.inputJournal.eventWatermarkThrough(work.epoch.scope, work.epoch.epochSeq),
1405
+ epochSeq: work.epoch.epochSeq,
1406
+ }).filter((event) => event.sourceId === `runtime-plugin:${plugin.id}`).length,
1407
+ eventCursorBefore: progress.eventCursor,
1408
+ eventCursorAfter: progress.eventCursor,
1409
+ recordedAt: new Date().toISOString(),
1410
+ });
1411
+ }
1412
+ }
1413
+ async withDeadline(plugin, controller, run, onStaleSettlement, awaitSettlementAfterCancellation = false, onOperationSettlement, timeoutMsOverride) {
1414
+ const timeoutMs = timeoutMsOverride ?? plugin.timeoutMs ?? this.pluginTimeoutMs;
1415
+ let timer;
1416
+ let abandoned = false;
1417
+ let removeAbortListener;
1418
+ const operation = Promise.resolve().then(() => {
1419
+ if (controller.signal.aborted) {
1420
+ const reason = controller.signal.reason;
1421
+ throw reason instanceof Error
1422
+ ? reason
1423
+ : new Error('Runtime Epoch Plugin invocation was cancelled.');
1424
+ }
1425
+ return run();
1426
+ });
1427
+ const operationSettlement = operation.then(() => { }, () => { });
1428
+ onOperationSettlement?.(operationSettlement);
1429
+ void operation.then(() => { if (abandoned)
1430
+ onStaleSettlement?.('resolved'); }, () => { if (abandoned)
1431
+ onStaleSettlement?.('rejected'); });
1432
+ const cancellation = new Promise((_resolve, reject) => {
1433
+ const onAbort = () => {
1434
+ abandoned = true;
1435
+ const reason = controller.signal.reason;
1436
+ reject(reason instanceof Error ? reason : new Error('Runtime Epoch Plugin invocation was cancelled.'));
1437
+ };
1438
+ if (controller.signal.aborted) {
1439
+ onAbort();
1440
+ return;
1441
+ }
1442
+ controller.signal.addEventListener('abort', onAbort, { once: true });
1443
+ removeAbortListener = () => controller.signal.removeEventListener('abort', onAbort);
1444
+ });
1445
+ const timeout = new Promise((_resolve, reject) => {
1446
+ timer = setTimeout(() => {
1447
+ abandoned = true;
1448
+ const error = new RuntimeEpochPluginTimeoutError(plugin.id, timeoutMs);
1449
+ controller.abort(error);
1450
+ reject(error);
1451
+ }, timeoutMs);
1452
+ });
1453
+ try {
1454
+ return await Promise.race([operation, timeout, cancellation]);
1455
+ }
1456
+ catch (error) {
1457
+ if (awaitSettlementAfterCancellation && abandoned) {
1458
+ await operation.then(() => { }, () => { });
1459
+ }
1460
+ throw error;
1461
+ }
1462
+ finally {
1463
+ if (timer)
1464
+ clearTimeout(timer);
1465
+ removeAbortListener?.();
1466
+ }
1467
+ }
1468
+ pendingInOrder() {
1469
+ return [...this.pending.values()].sort((a, b) => a.work.epoch.epochSeq - b.work.epoch.epochSeq);
1470
+ }
1471
+ latestPendingEpochSeq(scope, fallback = 0) {
1472
+ return this.pendingInOrder()
1473
+ .filter((pending) => runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope))
1474
+ .reduce((latest, pending) => Math.max(latest, pending.work.epoch.epochSeq), fallback);
1475
+ }
1476
+ orderOf(plugin) {
1477
+ return this.orderOfId(plugin.id);
1478
+ }
1479
+ orderOfId(pluginId) {
1480
+ return this.pluginOrder.get(pluginId) ?? Number.MAX_SAFE_INTEGER;
1481
+ }
1482
+ recordPluginTiming(record, scope, nowMs, invoked = true) {
1483
+ if (!this.onDiagnostic)
1484
+ return;
1485
+ const key = `${runtimeScopeKey(scope)}:${record.pluginId}`;
1486
+ let window = this.pluginTimingWindows.get(key);
1487
+ if (window && nowMs - window.startedAtMs >= this.diagnosticTimingWindowMs) {
1488
+ this.emitPluginTimingWindow(window, nowMs);
1489
+ this.pluginTimingWindows.delete(key);
1490
+ window = undefined;
1491
+ }
1492
+ if (!window) {
1493
+ window = {
1494
+ scope: cloneCanonical(scope),
1495
+ pluginId: record.pluginId,
1496
+ startedAtMs: nowMs,
1497
+ fromEpochSeq: record.epochSeq,
1498
+ throughEpochSeq: record.epochSeq,
1499
+ durationsMs: [],
1500
+ processedCount: 0,
1501
+ noopCount: 0,
1502
+ failedCount: 0,
1503
+ coalescedCount: 0,
1504
+ slowCount: 0,
1505
+ };
1506
+ this.pluginTimingWindows.set(key, window);
1507
+ }
1508
+ window.fromEpochSeq = Math.min(window.fromEpochSeq, record.epochSeq);
1509
+ window.throughEpochSeq = Math.max(window.throughEpochSeq, record.epochSeq);
1510
+ if (record.outcome === 'processed')
1511
+ window.processedCount += 1;
1512
+ else if (record.outcome === 'noop')
1513
+ window.noopCount += 1;
1514
+ else if (record.outcome === 'failed')
1515
+ window.failedCount += 1;
1516
+ else
1517
+ window.coalescedCount += 1;
1518
+ if (invoked) {
1519
+ window.durationsMs.push(record.durationMs);
1520
+ if (record.durationMs >= slowPluginThresholdMs(record.pluginId))
1521
+ window.slowCount += 1;
1522
+ }
1523
+ }
1524
+ emitPluginTimingWindow(window, endedAtMs) {
1525
+ if (!this.onDiagnostic)
1526
+ return;
1527
+ const sorted = [...window.durationsMs].sort((a, b) => a - b);
1528
+ const total = sorted.reduce((sum, value) => sum + value, 0);
1529
+ this.onDiagnostic('runtime.plugin.timing_window', {
1530
+ plugin_id: window.pluginId,
1531
+ window_ms: Math.max(0, endedAtMs - window.startedAtMs),
1532
+ from_epoch_seq: window.fromEpochSeq,
1533
+ through_epoch_seq: window.throughEpochSeq,
1534
+ invocation_count: sorted.length,
1535
+ processed_count: window.processedCount,
1536
+ noop_count: window.noopCount,
1537
+ failed_count: window.failedCount,
1538
+ coalesced_count: window.coalescedCount,
1539
+ slow_count: window.slowCount,
1540
+ duration_avg_ms: sorted.length === 0 ? 0 : rounded(total / sorted.length),
1541
+ duration_p50_ms: percentile(sorted, 0.5),
1542
+ duration_p95_ms: percentile(sorted, 0.95),
1543
+ duration_max_ms: sorted.at(-1) ?? 0,
1544
+ }, window.scope);
1545
+ }
1546
+ flushPluginTimingWindows(scope, endedAtMs) {
1547
+ const scopePrefix = `${runtimeScopeKey(scope)}:`;
1548
+ for (const [key, window] of this.pluginTimingWindows) {
1549
+ if (!key.startsWith(scopePrefix))
1550
+ continue;
1551
+ this.emitPluginTimingWindow(window, endedAtMs);
1552
+ this.pluginTimingWindows.delete(key);
1553
+ }
1554
+ }
1555
+ boundedPendingLag(scope, completedThroughEpochSeq, latestEpochSeq) {
1556
+ let count = 0;
1557
+ for (const pending of this.pending.values()) {
1558
+ if (runtimeScopeKey(pending.work.epoch.scope) !== runtimeScopeKey(scope))
1559
+ continue;
1560
+ const epochSeq = pending.work.epoch.epochSeq;
1561
+ if (epochSeq <= completedThroughEpochSeq || epochSeq > latestEpochSeq)
1562
+ continue;
1563
+ count += 1;
1564
+ if (count >= CRITICAL_LAG_EPOCHS) {
1565
+ return { count: CRITICAL_LAG_EPOCHS, capped: true };
1566
+ }
1567
+ }
1568
+ return { count, capped: false };
1569
+ }
1570
+ lagSnapshot(scope, latestEpochSeq) {
1571
+ const progressByPlugin = new Map(this.plugins.map((plugin) => [
1572
+ plugin.id,
1573
+ this.pluginStore.pluginProgress(plugin.id, scope),
1574
+ ]));
1575
+ const pluginProgress = this.plugins.map((plugin) => {
1576
+ const progress = progressByPlugin.get(plugin.id);
1577
+ const dependencies = (plugin.after ?? []).map((id) => (progressByPlugin.get(id)?.completedThroughEpochSeq ?? 0));
1578
+ const readyThroughEpochSeq = dependencies.length === 0
1579
+ ? latestEpochSeq
1580
+ : Math.min(latestEpochSeq, ...dependencies);
1581
+ const lag = this.boundedPendingLag(scope, progress.completedThroughEpochSeq, latestEpochSeq);
1582
+ return {
1583
+ plugin_id: plugin.id,
1584
+ completed_through_epoch_seq: progress.completedThroughEpochSeq,
1585
+ ready_through_epoch_seq: readyThroughEpochSeq,
1586
+ lag_epoch_count: lag.count,
1587
+ lag_count_capped: lag.capped,
1588
+ };
1589
+ });
1590
+ const maxLagEpochCount = Math.max(0, ...pluginProgress.map((progress) => progress.lag_epoch_count));
1591
+ return {
1592
+ band: lagBand(maxLagEpochCount),
1593
+ latestEpochSeq,
1594
+ maxLagEpochCount,
1595
+ lagCountCapped: pluginProgress.some((progress) => progress.lag_count_capped),
1596
+ pluginProgress,
1597
+ };
1598
+ }
1599
+ reportLagTransition(scope, latestEpochSeq) {
1600
+ if (!this.onDiagnostic || this.plugins.length === 0)
1601
+ return;
1602
+ const snapshot = this.lagSnapshot(scope, latestEpochSeq);
1603
+ const scopeKey = runtimeScopeKey(scope);
1604
+ const previous = this.lagBands.get(scopeKey) ?? 'healthy';
1605
+ this.lagBands.set(scopeKey, snapshot.band);
1606
+ if (snapshot.band === previous)
1607
+ return;
1608
+ const common = {
1609
+ previous_band: previous,
1610
+ current_band: snapshot.band,
1611
+ latest_epoch_seq: snapshot.latestEpochSeq,
1612
+ max_lag_epoch_count: snapshot.maxLagEpochCount,
1613
+ lag_count_capped: snapshot.lagCountCapped,
1614
+ plugin_progress: snapshot.pluginProgress.filter((progress) => (progress.lag_epoch_count >= DEGRADED_LAG_EPOCHS)),
1615
+ };
1616
+ if (snapshot.band === 'critical') {
1617
+ this.onDiagnostic('runtime.view.lag_critical', common, scope, 'warn');
1618
+ }
1619
+ else if (snapshot.band === 'degraded') {
1620
+ this.onDiagnostic('runtime.view.lag_degraded', common, scope, 'warn');
1621
+ }
1622
+ else {
1623
+ this.onDiagnostic('runtime.view.lag_recovered', common, scope, 'info');
1624
+ }
1625
+ }
1626
+ failRuntime(error, pluginId, scope = this.activeScope ?? undefined) {
1627
+ if (this.fatalError)
1628
+ return;
1629
+ this.fatalError = error;
1630
+ for (const active of this.activeInvocations.values()) {
1631
+ if (!active.controller.signal.aborted)
1632
+ active.controller.abort(error);
1633
+ }
1634
+ for (const controller of this.activeCommits.values()) {
1635
+ if (!controller.signal.aborted)
1636
+ controller.abort(error);
1637
+ }
1638
+ for (const pending of this.pending.values())
1639
+ pending.reject(error);
1640
+ this.pending.clear();
1641
+ this.bufferedInvocations.clear();
1642
+ if (scope)
1643
+ this.onFatalError?.(error, pluginId, scope);
1644
+ this.resolveIdle();
1645
+ }
1646
+ isIdle() {
1647
+ return this.pending.size === 0
1648
+ && this.activeInvocations.size === 0
1649
+ && this.activeCommits.size === 0
1650
+ && this.bufferedInvocationCount() === 0
1651
+ && !this.pumping;
1652
+ }
1653
+ resolveIdle() {
1654
+ if (!this.isIdle())
1655
+ return;
1656
+ const waiters = this.idleWaiters.splice(0);
1657
+ for (const resolve of waiters)
1658
+ resolve();
1659
+ }
1660
+ }