@myclaw163/game-agent-runtime 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +242 -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 +56 -0
  127. package/dist/mailbox/mailbox-plugin.js +111 -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 +336 -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,242 @@
1
+ import { IdentityMailboxCoalescer } from './coalescer.js';
2
+ import { HostNotificationDeliveryError, } from './host-notification-sink.js';
3
+ const DEFAULT_LEASE_TTL_MS = 30_000;
4
+ const DEFAULT_RETRY_BASE_MS = 250;
5
+ const DEFAULT_RETRY_MAX_MS = 30_000;
6
+ function defaultRetryAt(context) {
7
+ const exponent = Math.max(0, Math.min(16, context.attemptCount - 1));
8
+ const delay = Math.min(DEFAULT_RETRY_MAX_MS, DEFAULT_RETRY_BASE_MS * (2 ** exponent));
9
+ return context.nowMs + delay;
10
+ }
11
+ function errorCode(error) {
12
+ if (error instanceof HostNotificationDeliveryError)
13
+ return error.code.slice(0, 100);
14
+ if (error instanceof Error && error.name.trim().length > 0) {
15
+ return error.name.trim().slice(0, 100);
16
+ }
17
+ return 'HostNotificationDeliveryError';
18
+ }
19
+ /**
20
+ * Pumps one durable Mailbox scope into one Host Adapter.
21
+ *
22
+ * It intentionally knows nothing about Agent active/idle state or game Event
23
+ * types. notifyAvailable always attempts immediately; retry timing is persisted
24
+ * by Repository.nackMailboxClaim through retryAtMs.
25
+ */
26
+ export class MailboxDispatcher {
27
+ repository;
28
+ resolveScope;
29
+ ownerId;
30
+ sink;
31
+ coalescer;
32
+ leaseTtlMs;
33
+ retryAt;
34
+ now;
35
+ onAttempt;
36
+ onError;
37
+ stopped = false;
38
+ pumpRequested = false;
39
+ pumpPromise = null;
40
+ retryTimer = null;
41
+ constructor(options) {
42
+ this.repository = options.repository;
43
+ const configuredScope = options.scope;
44
+ this.resolveScope = typeof configuredScope === 'function' ? configuredScope : () => configuredScope;
45
+ this.ownerId = options.ownerId;
46
+ this.sink = options.sink;
47
+ this.coalescer = options.coalescer ?? new IdentityMailboxCoalescer();
48
+ this.leaseTtlMs = options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
49
+ this.retryAt = options.retryAt ?? defaultRetryAt;
50
+ this.now = options.now ?? Date.now;
51
+ this.onAttempt = options.onAttempt;
52
+ this.onError = options.onError;
53
+ if (!this.ownerId)
54
+ throw new Error('MailboxDispatcher ownerId is required.');
55
+ if (!Number.isFinite(this.leaseTtlMs) || this.leaseTtlMs <= 0) {
56
+ throw new Error('MailboxDispatcher leaseTtlMs must be positive.');
57
+ }
58
+ if (!Number.isInteger(this.coalescer.maxItems) || this.coalescer.maxItems <= 0) {
59
+ throw new Error('MailboxCoalescer maxItems must be a positive integer.');
60
+ }
61
+ }
62
+ /** Signals new work without waiting for Host delivery. */
63
+ notifyAvailable() {
64
+ if (this.stopped)
65
+ return;
66
+ this.pumpRequested = true;
67
+ this.clearRetryTimer();
68
+ this.ensurePump();
69
+ }
70
+ /** Drains work available now, but never waits for a future retry timer. */
71
+ async flush() {
72
+ if (this.stopped) {
73
+ await this.pumpPromise;
74
+ return;
75
+ }
76
+ this.notifyAvailable();
77
+ while (this.pumpPromise)
78
+ await this.pumpPromise;
79
+ }
80
+ /** Stops future retries, while allowing an in-flight Host acceptance to settle. */
81
+ async stop() {
82
+ if (this.stopped) {
83
+ await this.pumpPromise;
84
+ return;
85
+ }
86
+ this.stopped = true;
87
+ this.pumpRequested = false;
88
+ this.clearRetryTimer();
89
+ await this.pumpPromise;
90
+ }
91
+ ensurePump() {
92
+ if (this.stopped || this.pumpPromise)
93
+ return;
94
+ this.pumpPromise = this.pump()
95
+ .catch((error) => {
96
+ try {
97
+ this.onError?.(error);
98
+ }
99
+ catch { }
100
+ // A transient scope/repository failure happens before any item can be
101
+ // claimed and therefore has no persisted item retryAt. Still retry the
102
+ // pump itself so one SQLite busy/read error cannot strand durable work
103
+ // until an unrelated future Event happens to arrive.
104
+ this.scheduleAt(this.now() + DEFAULT_RETRY_BASE_MS);
105
+ })
106
+ .finally(() => {
107
+ this.pumpPromise = null;
108
+ if (this.pumpRequested && !this.stopped)
109
+ this.ensurePump();
110
+ });
111
+ }
112
+ async pump() {
113
+ while (!this.stopped) {
114
+ this.pumpRequested = false;
115
+ const nowMs = this.now();
116
+ const scope = this.resolveScope();
117
+ if (!scope)
118
+ return;
119
+ const claim = this.repository.claimMailbox({
120
+ ...scope,
121
+ ownerId: this.ownerId,
122
+ leaseTtlMs: this.leaseTtlMs,
123
+ nowMs,
124
+ maxItems: this.coalescer.maxItems,
125
+ });
126
+ if (!claim) {
127
+ this.scheduleHead();
128
+ if (this.pumpRequested)
129
+ continue;
130
+ return;
131
+ }
132
+ const controller = new AbortController();
133
+ try {
134
+ try {
135
+ this.onAttempt?.(claim.items);
136
+ }
137
+ catch (error) {
138
+ this.onError?.(error, claim.items);
139
+ }
140
+ const notification = this.coalescer.coalesce(claim.items);
141
+ const acceptance = await this.sink.deliver(notification, controller.signal);
142
+ const acknowledged = this.repository.ackMailboxClaim({
143
+ ownerId: this.ownerId,
144
+ claimToken: claim.claimToken,
145
+ acceptedAt: acceptance.acceptedAt,
146
+ acceptanceLevel: acceptance.acceptanceLevel ?? 'sink_emitted',
147
+ receiptId: acceptance.receiptId,
148
+ nowMs: this.now(),
149
+ });
150
+ if (acknowledged.status === 'claim_lost') {
151
+ this.onError?.(new Error(`Mailbox claim ${claim.claimToken} was lost before acknowledgement.`), claim.items);
152
+ this.scheduleHead();
153
+ return;
154
+ }
155
+ }
156
+ catch (error) {
157
+ const failedAtMs = this.now();
158
+ const terminal = error instanceof HostNotificationDeliveryError && !error.retryable;
159
+ const attemptCount = Math.max(1, ...claim.items.map((item) => item.attemptCount));
160
+ const retryAtMs = terminal || this.stopped
161
+ ? failedAtMs
162
+ : Math.max(failedAtMs, this.retryAt({
163
+ attemptCount,
164
+ error,
165
+ items: claim.items,
166
+ nowMs: failedAtMs,
167
+ }));
168
+ const released = this.repository.nackMailboxClaim({
169
+ ownerId: this.ownerId,
170
+ claimToken: claim.claimToken,
171
+ retryAtMs,
172
+ errorCode: errorCode(error),
173
+ nowMs: failedAtMs,
174
+ });
175
+ this.onError?.(error, claim.items);
176
+ if (terminal && released.status === 'released') {
177
+ // A malformed envelope, stale credential, or identity conflict will
178
+ // not heal through backoff. Remove it from the active-notification
179
+ // FIFO while leaving the underlying Event detail pullable via
180
+ // the explicit event query, and surface the typed error through onError/logging.
181
+ this.repository.suppressMailboxItems({
182
+ consumerId: scope.consumerId,
183
+ sessionId: scope.sessionId,
184
+ segmentId: scope.segmentId,
185
+ eventIds: claim.items.map((item) => item.eventId),
186
+ modes: [scope.mode],
187
+ nowMs: failedAtMs,
188
+ });
189
+ this.pumpRequested = true;
190
+ continue;
191
+ }
192
+ if (!this.stopped) {
193
+ if (released.status === 'released')
194
+ this.scheduleAt(retryAtMs);
195
+ else if (released.status === 'claim_lost')
196
+ this.scheduleHead();
197
+ }
198
+ return;
199
+ }
200
+ }
201
+ }
202
+ scheduleHead() {
203
+ const scope = this.resolveScope();
204
+ if (!scope)
205
+ return;
206
+ const [head] = this.repository.peekMailbox({
207
+ consumerId: scope.consumerId,
208
+ sessionId: scope.sessionId,
209
+ segmentId: scope.segmentId,
210
+ modes: [scope.mode],
211
+ states: ['pending', 'claimed'],
212
+ order: 'asc',
213
+ limit: 1,
214
+ });
215
+ if (!head)
216
+ return;
217
+ const wakeAt = head.state === 'claimed'
218
+ ? head.claimExpiresAtMs ?? this.now()
219
+ : head.availableAtMs;
220
+ this.scheduleAt(wakeAt);
221
+ }
222
+ scheduleAt(wakeAtMs) {
223
+ if (this.stopped)
224
+ return;
225
+ const delay = Math.max(0, wakeAtMs - this.now());
226
+ if (this.retryTimer)
227
+ return;
228
+ const timer = setTimeout(() => {
229
+ this.retryTimer = null;
230
+ this.notifyAvailable();
231
+ }, delay);
232
+ if (typeof timer === 'object' && 'unref' in timer)
233
+ timer.unref();
234
+ this.retryTimer = timer;
235
+ }
236
+ clearRetryTimer() {
237
+ if (!this.retryTimer)
238
+ return;
239
+ clearTimeout(this.retryTimer);
240
+ this.retryTimer = null;
241
+ }
242
+ }
@@ -0,0 +1,17 @@
1
+ import type { AckMailboxClaimRequest, AckMailboxClaimResult, ClaimMailboxItemsRequest, EnqueueMailboxItem, EnqueueMailboxResult, MailboxClaim, MailboxDeliveryMode, MailboxItem, MailboxPeekFilter, NackMailboxClaimRequest, NackMailboxClaimResult, SuppressMailboxItemsFilter } from './types.js';
2
+ /**
3
+ * Mutable notification delivery storage. It is deliberately separate from
4
+ * EventRepository even when both interfaces share one SQLite connection.
5
+ */
6
+ export interface MailboxRepository {
7
+ enqueueMailboxItem<T = unknown>(request: EnqueueMailboxItem<T>): EnqueueMailboxResult<T>;
8
+ mailboxItem<T = unknown>(itemId: string): MailboxItem<T> | null;
9
+ mailboxItemForEvent<T = unknown>(consumerId: string, eventId: string, mode: MailboxDeliveryMode): MailboxItem<T> | null;
10
+ peekMailbox<T = unknown>(filter: MailboxPeekFilter): MailboxItem<T>[];
11
+ claimMailbox<T = unknown>(request: ClaimMailboxItemsRequest): MailboxClaim<T> | null;
12
+ ackMailboxClaim(request: AckMailboxClaimRequest): AckMailboxClaimResult;
13
+ nackMailboxClaim(request: NackMailboxClaimRequest): NackMailboxClaimResult;
14
+ suppressMailboxItems(filter: SuppressMailboxItemsFilter): number;
15
+ }
16
+ export type RuntimeEventRepository<TEventRepository> = TEventRepository & MailboxRepository;
17
+ export declare function isMailboxRepository(value: unknown): value is MailboxRepository;
@@ -0,0 +1,9 @@
1
+ export function isMailboxRepository(value) {
2
+ if (!value || typeof value !== 'object')
3
+ return false;
4
+ const candidate = value;
5
+ return typeof candidate.enqueueMailboxItem === 'function'
6
+ && typeof candidate.claimMailbox === 'function'
7
+ && typeof candidate.ackMailboxClaim === 'function'
8
+ && typeof candidate.nackMailboxClaim === 'function';
9
+ }
@@ -0,0 +1,25 @@
1
+ import type { CanonicalEvent } from '../events/index.js';
2
+ import type { MailboxRepository } from './mailbox-repository.js';
3
+ import type { MailboxDeliveryMode, MailboxItem } from './types.js';
4
+ export interface NotificationProjectorOptions<TPayload> {
5
+ repository: MailboxRepository;
6
+ consumerId: string;
7
+ mode: MailboxDeliveryMode;
8
+ formatterVersion: string;
9
+ present(event: CanonicalEvent): TPayload;
10
+ /** A batching hint only. It never decides whether the Event is eligible. */
11
+ coalesceKey?: (event: CanonicalEvent) => string;
12
+ now?: () => number;
13
+ }
14
+ /**
15
+ * Materializes an immutable notification envelope from a committed Event.
16
+ * Re-running projection after a crash is idempotent and never mutates an
17
+ * existing payload, even if the installed formatter version has changed.
18
+ */
19
+ export declare class NotificationProjector<TPayload = unknown> {
20
+ private readonly options;
21
+ private readonly now;
22
+ constructor(options: NotificationProjectorOptions<TPayload>);
23
+ project(event: CanonicalEvent): MailboxItem<TPayload>;
24
+ projectAll(events: readonly CanonicalEvent[]): MailboxItem<TPayload>[];
25
+ }
@@ -0,0 +1,50 @@
1
+ import { stableMailboxItemId } from './identity.js';
2
+ /**
3
+ * Materializes an immutable notification envelope from a committed Event.
4
+ * Re-running projection after a crash is idempotent and never mutates an
5
+ * existing payload, even if the installed formatter version has changed.
6
+ */
7
+ export class NotificationProjector {
8
+ options;
9
+ now;
10
+ constructor(options) {
11
+ this.options = options;
12
+ this.now = options.now ?? Date.now;
13
+ if (!options.consumerId)
14
+ throw new Error('NotificationProjector consumerId is required.');
15
+ if (!options.formatterVersion) {
16
+ throw new Error('NotificationProjector formatterVersion is required.');
17
+ }
18
+ }
19
+ project(event) {
20
+ const itemId = stableMailboxItemId({
21
+ consumerId: this.options.consumerId,
22
+ sessionId: event.sessionId,
23
+ eventId: event.eventId,
24
+ mode: this.options.mode,
25
+ });
26
+ const existing = this.options.repository.mailboxItem(itemId);
27
+ if (existing)
28
+ return existing;
29
+ const nowMs = this.now();
30
+ const createdAt = new Date(nowMs).toISOString();
31
+ return this.options.repository.enqueueMailboxItem({
32
+ itemId,
33
+ schemaVersion: 1,
34
+ formatterVersion: this.options.formatterVersion,
35
+ consumerId: this.options.consumerId,
36
+ sessionId: event.sessionId,
37
+ segmentId: event.segmentId,
38
+ eventId: event.eventId,
39
+ eventCommitSeq: event.commitSeq,
40
+ mode: this.options.mode,
41
+ coalesceKey: this.options.coalesceKey?.(event) ?? event.type,
42
+ payload: this.options.present(event),
43
+ availableAtMs: nowMs,
44
+ createdAt,
45
+ }).item;
46
+ }
47
+ projectAll(events) {
48
+ return events.map((event) => this.project(event));
49
+ }
50
+ }
@@ -0,0 +1,128 @@
1
+ export type MailboxDeliveryMode = 'short';
2
+ export type MailboxItemState = 'pending' | 'claimed' | 'accepted' | 'suppressed';
3
+ /** CCL cannot generally observe whether a model actually saw a notification. */
4
+ export type MailboxAcceptanceLevel = 'sink_emitted' | 'host_accepted';
5
+ /**
6
+ * A durable, already-presented notification envelope.
7
+ *
8
+ * The canonical Event remains the game fact. A Mailbox item is only a mutable
9
+ * delivery record for one logical Agent consumer.
10
+ */
11
+ export interface MailboxItem<T = unknown> {
12
+ itemId: string;
13
+ schemaVersion: number;
14
+ formatterVersion: string;
15
+ consumerId: string;
16
+ sessionId: string;
17
+ segmentId: string;
18
+ eventId: string;
19
+ eventCommitSeq: number;
20
+ /** Optional stable delivery position; canonical event sequence remains unchanged. */
21
+ deliveryOrder?: number;
22
+ mode: MailboxDeliveryMode;
23
+ coalesceKey: string;
24
+ payload: T;
25
+ state: MailboxItemState;
26
+ attemptCount: number;
27
+ availableAtMs: number;
28
+ createdAt: string;
29
+ updatedAt: string;
30
+ lastAttemptAt?: string;
31
+ claimOwner?: string;
32
+ claimToken?: string;
33
+ claimExpiresAtMs?: number;
34
+ acceptedAt?: string;
35
+ acceptanceLevel?: MailboxAcceptanceLevel;
36
+ receiptId?: string;
37
+ lastErrorCode?: string;
38
+ }
39
+ export interface EnqueueMailboxItem<T = unknown> {
40
+ itemId: string;
41
+ schemaVersion?: number;
42
+ formatterVersion: string;
43
+ consumerId: string;
44
+ sessionId: string;
45
+ segmentId: string;
46
+ eventId: string;
47
+ eventCommitSeq: number;
48
+ /** Optional stable delivery position; canonical event sequence remains unchanged. */
49
+ deliveryOrder?: number;
50
+ mode: MailboxDeliveryMode;
51
+ coalesceKey: string;
52
+ payload: T;
53
+ availableAtMs?: number;
54
+ createdAt?: string;
55
+ }
56
+ export interface EnqueueMailboxResult<T = unknown> {
57
+ inserted: boolean;
58
+ item: MailboxItem<T>;
59
+ }
60
+ export interface MailboxPeekFilter {
61
+ consumerId: string;
62
+ sessionId?: string;
63
+ segmentId?: string;
64
+ eventIds?: string[];
65
+ modes?: MailboxDeliveryMode[];
66
+ states?: MailboxItemState[];
67
+ /** Pure read bound; it never changes attempts, leases, or delivery state. */
68
+ limit?: number;
69
+ order?: 'asc' | 'desc';
70
+ }
71
+ export interface ClaimMailboxItemsRequest {
72
+ consumerId: string;
73
+ sessionId: string;
74
+ segmentId: string;
75
+ mode: MailboxDeliveryMode;
76
+ ownerId: string;
77
+ leaseTtlMs: number;
78
+ nowMs?: number;
79
+ /**
80
+ * Claims a FIFO prefix. Items after the first are included only while their
81
+ * coalesceKey matches, so batching never lets a later topic overtake one.
82
+ */
83
+ maxItems?: number;
84
+ /** Internal deterministic token used by mirrored persistence stores. */
85
+ claimToken?: string;
86
+ }
87
+ export interface MailboxClaim<T = unknown> {
88
+ ownerId: string;
89
+ claimToken: string;
90
+ claimExpiresAtMs: number;
91
+ items: MailboxItem<T>[];
92
+ }
93
+ export interface AckMailboxClaimRequest {
94
+ ownerId: string;
95
+ claimToken: string;
96
+ acceptedAt?: string;
97
+ /** Defaults to sink_emitted for legacy stdout transports. */
98
+ acceptanceLevel?: MailboxAcceptanceLevel;
99
+ receiptId?: string;
100
+ nowMs?: number;
101
+ }
102
+ export interface AckMailboxClaimResult {
103
+ status: 'accepted' | 'already_accepted' | 'claim_lost';
104
+ itemIds: string[];
105
+ eventIds: string[];
106
+ }
107
+ export interface NackMailboxClaimRequest {
108
+ ownerId: string;
109
+ claimToken: string;
110
+ retryAtMs: number;
111
+ errorCode?: string;
112
+ nowMs?: number;
113
+ }
114
+ export interface NackMailboxClaimResult {
115
+ status: 'released' | 'suppressed' | 'claim_lost';
116
+ itemIds: string[];
117
+ }
118
+ export interface SuppressMailboxItemsFilter {
119
+ consumerId: string;
120
+ sessionId?: string;
121
+ segmentId?: string;
122
+ excludeSegmentId?: string;
123
+ eventIds?: string[];
124
+ modes?: MailboxDeliveryMode[];
125
+ /** Claimed items are in flight and are not suppressed by default. */
126
+ includeExpiredClaims?: boolean;
127
+ nowMs?: number;
128
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,156 @@
1
+ import { accessSync, readFileSync } from 'node:fs';
2
+ import { transformSync } from 'amaro';
3
+
4
+ let sdkAliases = Object.create(null);
5
+ let nativeTypeScript = false;
6
+ const esmModuleRoots = new Set();
7
+
8
+ function addEsmRoot(root) {
9
+ if (typeof root !== 'string') return;
10
+ try {
11
+ const url = new URL(root);
12
+ if (url.protocol !== 'file:') return;
13
+ url.search = '';
14
+ url.hash = '';
15
+ esmModuleRoots.add(url.href.endsWith('/') ? url.href : `${url.href}/`);
16
+ } catch {
17
+ // Invalid roots never broaden the loader scope.
18
+ }
19
+ }
20
+
21
+ export function initialize(data) {
22
+ sdkAliases = data?.sdkAliases ?? Object.create(null);
23
+ nativeTypeScript = data?.nativeTypeScript === true;
24
+ esmModuleRoots.clear();
25
+ for (const root of data?.esmModuleRoots ?? []) addEsmRoot(root);
26
+ }
27
+
28
+ export function addEsmModuleRoot(root) {
29
+ addEsmRoot(root);
30
+ }
31
+
32
+ function isTypeScriptUrl(url) {
33
+ return /\.(?:ts|tsx)(?:\?|$)/i.test(url);
34
+ }
35
+
36
+ function withNativeTypeScriptFormat(result) {
37
+ if (!nativeTypeScript || !isTypeScriptUrl(result.url)) return result;
38
+ return { ...result, format: 'module' };
39
+ }
40
+
41
+ function userTypeScriptUrl(specifier, parentURL) {
42
+ if (!nativeTypeScript || typeof specifier !== 'string') return undefined;
43
+ let url;
44
+ try {
45
+ url = new URL(specifier, parentURL);
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ if (url.protocol !== 'file:' || !isTypeScriptUrl(url.href)) return undefined;
50
+
51
+ // Compare only the physical file location. Query strings are deliberately
52
+ // retained on the returned URL because Runtime uses them to isolate module
53
+ // state between lifecycles.
54
+ const physicalUrl = new URL(url.href);
55
+ physicalUrl.search = '';
56
+ physicalUrl.hash = '';
57
+ if (![...esmModuleRoots].some((root) => physicalUrl.href.startsWith(root))) {
58
+ return undefined;
59
+ }
60
+ return url.href;
61
+ }
62
+
63
+ function isUserEsmJavaScript(url) {
64
+ if (!/\.js(?:\?|$)/i.test(url)) return false;
65
+ return [...esmModuleRoots].some((root) => {
66
+ if (!url.startsWith(root)) return false;
67
+ const relative = url.slice(root.length).split(/[?#]/, 1)[0].toLowerCase();
68
+ return relative !== 'node_modules' && !relative.startsWith('node_modules/')
69
+ && !relative.includes('/node_modules/');
70
+ });
71
+ }
72
+
73
+ function sourceFallbackUrl(specifier, parentURL) {
74
+ if (typeof specifier !== 'string' || !parentURL) return undefined;
75
+ if (!specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('file:')) {
76
+ return undefined;
77
+ }
78
+ let url;
79
+ try {
80
+ url = new URL(specifier, parentURL);
81
+ } catch {
82
+ return undefined;
83
+ }
84
+ if (url.protocol !== 'file:') return undefined;
85
+ const match = /\.(js|jsx)(\?.*)?$/i.exec(url.href);
86
+ if (!match) return undefined;
87
+ const extension = match[1].toLowerCase() === 'jsx' ? 'tsx' : 'ts';
88
+ return new URL(url.href.slice(0, match.index) + `.${extension}${match[2] ?? ''}`);
89
+ }
90
+
91
+ export function resolve(specifier, context, nextResolve) {
92
+ const target = sdkAliases[specifier];
93
+ if (typeof target === 'string') {
94
+ return withNativeTypeScriptFormat({
95
+ shortCircuit: true,
96
+ url: target,
97
+ });
98
+ }
99
+ // The CLI registers tsx before this hook. Letting tsx resolve a queried
100
+ // user .ts/.tsx entry can percent-encode the query into a CommonJS virtual
101
+ // URL, which then turns public SDK imports into unresolved require() calls.
102
+ // Claim only registered user-module roots here so package resolution and
103
+ // node_modules continue through the normal loader chain.
104
+ const directUserTypeScriptUrl = userTypeScriptUrl(specifier, context.parentURL);
105
+ if (directUserTypeScriptUrl) {
106
+ return {
107
+ format: 'module',
108
+ shortCircuit: true,
109
+ url: directUserTypeScriptUrl,
110
+ };
111
+ }
112
+ try {
113
+ return withNativeTypeScriptFormat(nextResolve(specifier, context));
114
+ } catch (error) {
115
+ const fallback = sourceFallbackUrl(specifier, context.parentURL);
116
+ if (!fallback) throw error;
117
+ try {
118
+ accessSync(fallback);
119
+ } catch {
120
+ throw error;
121
+ }
122
+ return withNativeTypeScriptFormat({
123
+ shortCircuit: true,
124
+ url: fallback.href,
125
+ });
126
+ }
127
+ }
128
+
129
+ export function load(url, context, nextLoad) {
130
+ // User data directories do not need their own package.json merely to make a
131
+ // Strategy/Perception/Intent .ts file ESM. Owner and Worker Threads share the same
132
+ // in-process transform semantics without starting a compiler service.
133
+ if (/\.(?:ts|tsx)(?:\?|$)/i.test(url)) {
134
+ if (nativeTypeScript) {
135
+ const source = readFileSync(new URL(url), 'utf8');
136
+ return {
137
+ format: 'module',
138
+ shortCircuit: true,
139
+ source: transformSync(source, {
140
+ filename: new URL(url).pathname,
141
+ mode: 'transform',
142
+ }).code,
143
+ };
144
+ }
145
+ return nextLoad(url, {
146
+ ...context,
147
+ format: 'module',
148
+ });
149
+ }
150
+ if (isUserEsmJavaScript(url)) {
151
+ return nextLoad(url, { ...context, format: 'module' });
152
+ }
153
+ return nextLoad(url, context);
154
+ }
155
+
156
+ export function addRuntimeModuleAliases(aliases) { sdkAliases = { ...sdkAliases, ...aliases }; }
@@ -0,0 +1,14 @@
1
+ export interface RuntimeModuleThreadLoaderConfig {
2
+ readonly hooksUrl: string;
3
+ readonly sdkAliases: Readonly<Record<string, string>>;
4
+ }
5
+ /**
6
+ * Import a trusted local module without bundling it. Runtime author SDKs always
7
+ * resolve to this installed package; games may add their own SDK aliases for
8
+ * scripts living outside the package's node_modules search path.
9
+ */
10
+ export declare function importRuntimeModule(source: string | URL, sdkAliases?: Readonly<Record<string, string>>): Promise<Record<string, unknown>>;
11
+ /** Register the direct-import hooks once in the current JavaScript isolate. */
12
+ export declare function registerRuntimeModuleLoader(sdkAliases?: Readonly<Record<string, string>>): void;
13
+ /** Loader data for Worker Threads, which use the same in-process TS transform. */
14
+ export declare function runtimeModuleThreadLoaderConfig(sdkAliases?: Readonly<Record<string, string>>): RuntimeModuleThreadLoaderConfig;