@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,17 @@
1
+ export interface EventStoreCompatibility {
2
+ legacyConsumer: string;
3
+ monitorConsumer: string;
4
+ detailsConsumer: string;
5
+ desktopConsumer: string;
6
+ channelConsumer: string;
7
+ detailEvidence: readonly string[];
8
+ desktopEvidence: readonly string[];
9
+ channelEvidence: readonly string[];
10
+ desktopVia: string;
11
+ channelVia: string;
12
+ legacyDeliveryVias: readonly string[];
13
+ initialDeliveryVias: readonly string[];
14
+ }
15
+ export declare const DEFAULT_EVENT_STORE_COMPATIBILITY: EventStoreCompatibility;
16
+ export declare function eventStoreCompatibility(value?: EventStoreCompatibility): EventStoreCompatibility;
17
+ export declare const sqlValueList: (values: readonly string[]) => string;
@@ -0,0 +1,17 @@
1
+ export const DEFAULT_EVENT_STORE_COMPATIBILITY = {
2
+ legacyConsumer: 'local-agent', monitorConsumer: 'local-agent:monitor', detailsConsumer: 'local-agent:events',
3
+ desktopConsumer: 'local-agent:desktop', channelConsumer: 'local-agent:channel',
4
+ detailEvidence: ['events', 'events_backlog', 'stdout_full'], desktopEvidence: ['mailbox_full', 'desktop_ipc'], channelEvidence: ['channel'],
5
+ desktopVia: 'desktop_ipc', channelVia: 'channel', legacyDeliveryVias: ['stdout_full', 'mailbox_full', 'desktop_ipc', 'channel', 'events', 'events_backlog'],
6
+ initialDeliveryVias: ['stdout_full', 'mailbox_full', 'events', 'events_backlog'],
7
+ };
8
+ export function eventStoreCompatibility(value = DEFAULT_EVENT_STORE_COMPATIBILITY) {
9
+ for (const item of Object.values(value).flat())
10
+ if (typeof item !== 'string' || !/^[a-z0-9][a-z0-9._:-]{0,119}$/.test(item))
11
+ throw Error('event_store_compatibility_invalid');
12
+ for (const item of Object.values(value))
13
+ if (Array.isArray(item) && item.length === 0)
14
+ throw Error('event_store_compatibility_empty');
15
+ return structuredClone(value);
16
+ }
17
+ export const sqlValueList = (values) => values.map(value => `'${value}'`).join(', ');
@@ -0,0 +1,242 @@
1
+ import type { MailboxAcceptanceLevel } from '../mailbox/types.js';
2
+ export declare const DEFAULT_EVENT_CONSUMER_ID = "local-agent";
3
+ export type EventProducer = 'backend_push' | 'local_synth';
4
+ export type AgentNotificationSource = 'perception' | 'system';
5
+ /** Producer-owned, frozen notification content. Delivery never enriches it from live State. */
6
+ export interface EventNotificationContent {
7
+ event: Record<string, unknown>;
8
+ monitorText: string;
9
+ desktopEvent?: Record<string, unknown>;
10
+ }
11
+ export type EventDeliveryClass = 'monitor_and_events' | 'internal_only';
12
+ /** Delivery metadata may be resolved before Ready; factual identity/payload never change. */
13
+ export interface EventDeliveryDecision {
14
+ eventId: string;
15
+ deliveryClass: EventDeliveryClass;
16
+ }
17
+ export type MonitorDeliveryState = 'not_applicable' | 'pending' | 'notified' | 'suppressed';
18
+ export type DetailDeliveryState = 'not_applicable' | 'pending' | 'deferred' | 'delivered';
19
+ /** Stable output-adapter identifier persisted with a durable detail ACK. */
20
+ export type DetailDeliveryVia = string;
21
+ export declare function validateDetailDeliveryVia(value: string): DetailDeliveryVia;
22
+ export type LeaseChannel = 'monitor' | 'details';
23
+ export interface PlaySessionRecord {
24
+ sessionId: string;
25
+ adapterId: string;
26
+ accountId: string;
27
+ /** Stable remote participation identity used to reattach after owner restart. */
28
+ resumeKey?: string;
29
+ mode?: string;
30
+ status: 'open' | 'sealed';
31
+ isCurrent: boolean;
32
+ openedAt: string;
33
+ sealedAt?: string;
34
+ }
35
+ export interface EventSegmentRecord {
36
+ segmentId: string;
37
+ sessionId: string;
38
+ sequence: number;
39
+ kind: string;
40
+ scopeRef?: string;
41
+ status: 'open' | 'closed';
42
+ isCurrent: boolean;
43
+ openedAt: string;
44
+ closedAt?: string;
45
+ }
46
+ export interface CurrentEventScope {
47
+ session: PlaySessionRecord;
48
+ segment: EventSegmentRecord;
49
+ }
50
+ export interface EventAccountScope {
51
+ adapterId: string;
52
+ accountId: string;
53
+ }
54
+ export interface EventSourceRef {
55
+ /** Stable logical source. It must not change for an ordinary reconnect. */
56
+ sourceId: string;
57
+ /** Stable backend identity, when the protocol supplies one. */
58
+ eventId?: string;
59
+ /** Per-source ordering identity, scoped to the target session and segment. */
60
+ sequence?: string | number;
61
+ /** Physical connection identity. It is diagnostic and never defines a segment. */
62
+ connectionId?: string;
63
+ replayed?: boolean;
64
+ /** Opaque resume token committed atomically with the event. */
65
+ checkpoint?: string;
66
+ }
67
+ export interface PublishEventInput {
68
+ notificationContent?: EventNotificationContent;
69
+ /** Original committed fact referenced by a separately admitted notification. */
70
+ notificationOf?: string;
71
+ /** Whether this Event may initiate Agent delivery; omitted means true. */
72
+ readonly wakeAgent?: boolean;
73
+ /** Runtime epoch that admitted or derived this Event. */
74
+ epochSeq?: number;
75
+ type: string;
76
+ producer: EventProducer;
77
+ /** Set by Runtime for Epoch Plugin output; absent for Source/backend input. */
78
+ producerPluginId?: string;
79
+ /** Stable position in that plugin's output list for this epoch. */
80
+ producerOutputIndex?: number;
81
+ sessionId: string;
82
+ segmentId: string;
83
+ payload?: Record<string, unknown>;
84
+ occurredAt?: string;
85
+ receivedAt?: string;
86
+ eventId?: string;
87
+ source: EventSourceRef;
88
+ }
89
+ export interface CanonicalEvent {
90
+ notificationContent?: EventNotificationContent;
91
+ /** Notification authority is assigned by the host, never by module payloads. */
92
+ notificationSource?: AgentNotificationSource;
93
+ notificationOf?: string;
94
+ /** Whether this Event may initiate Agent delivery; omitted means true. */
95
+ readonly wakeAgent?: boolean;
96
+ commitSeq: number;
97
+ /** Absent only for records written before the epoch runtime migration. */
98
+ epochSeq?: number;
99
+ eventId: string;
100
+ sessionId: string;
101
+ segmentId: string;
102
+ type: string;
103
+ producer: EventProducer;
104
+ producerPluginId?: string;
105
+ producerOutputIndex?: number;
106
+ deliveryClass: EventDeliveryClass;
107
+ occurredAt: string;
108
+ receivedAt: string;
109
+ payload: Record<string, unknown>;
110
+ sourceId: string;
111
+ sourceEventId?: string;
112
+ sourceSequence?: string;
113
+ connectionId?: string;
114
+ replayed: boolean;
115
+ }
116
+ export interface CanonicalEventDraft extends Omit<CanonicalEvent, 'commitSeq'> {
117
+ }
118
+ export interface EventDeliveryRecord {
119
+ eventId: string;
120
+ consumerId: string;
121
+ monitorState: MonitorDeliveryState;
122
+ /** Persisted before the Monitor sink is invoked, enabling owner recovery. */
123
+ monitorAttemptCount: number;
124
+ monitorLastAttemptAt?: string;
125
+ monitorDeliveredAt?: string;
126
+ detailState: DetailDeliveryState;
127
+ detailDeliveredAt?: string;
128
+ detailDeliveryVia?: DetailDeliveryVia;
129
+ /** Historical rows may be unknown. Neither level means that a model read or acted. */
130
+ detailAcceptanceLevel?: MailboxAcceptanceLevel;
131
+ }
132
+ export interface EventWithDelivery {
133
+ event: CanonicalEvent;
134
+ delivery: EventDeliveryRecord;
135
+ }
136
+ export interface SourceCheckpointRecord {
137
+ sourceId: string;
138
+ checkpoint: string;
139
+ sourceSequence?: string;
140
+ eventId: string;
141
+ committedAt: string;
142
+ }
143
+ export interface CommitEventRequest {
144
+ event: CanonicalEventDraft;
145
+ consumerIds: string[];
146
+ checkpoint?: SourceCheckpointRecord;
147
+ }
148
+ export interface CommitEventResult {
149
+ inserted: boolean;
150
+ event: CanonicalEvent;
151
+ }
152
+ export interface EventListFilter {
153
+ sessionId: string;
154
+ segmentId?: string;
155
+ excludeSegmentId?: string;
156
+ types?: string[];
157
+ deliveryClasses?: EventDeliveryClass[];
158
+ detailStates?: DetailDeliveryState[];
159
+ monitorStates?: MonitorDeliveryState[];
160
+ maxCommitSeq?: number;
161
+ /** Excludes Events produced by epochs newer than an immutable Ready View. */
162
+ maxEpochSeq?: number;
163
+ order?: 'asc' | 'desc';
164
+ }
165
+ /** Read-only journal query. It deliberately has no consumer or delivery fields. */
166
+ export interface CommittedEventListFilter {
167
+ sessionId: string;
168
+ segmentId?: string;
169
+ types?: string[];
170
+ /** Return only Events produced by this exact Runtime epoch. */
171
+ epochSeq?: number;
172
+ /** Newly ready epoch range; unlike a commit cursor, this also covers interleaved source intake. */
173
+ afterEpochSeq?: number;
174
+ /** Return only events committed strictly after this cursor. */
175
+ afterCommitSeq?: number;
176
+ maxCommitSeq?: number;
177
+ /** Legacy Events without an epoch remain visible; current Runtime Events are bounded. */
178
+ maxEpochSeq?: number;
179
+ order?: 'asc' | 'desc';
180
+ /** Apply the bound in the repository, before payloads are materialized. */
181
+ limit?: number;
182
+ }
183
+ export interface LatestEventScopeOptions {
184
+ /** When supplied, select the newest matching segment in the chosen session. */
185
+ segmentKinds?: string[];
186
+ }
187
+ export interface BacklogSummary {
188
+ unreadCount: number;
189
+ segmentCount: number;
190
+ oldestAt?: string;
191
+ newestAt?: string;
192
+ available: boolean;
193
+ }
194
+ export interface ConsumerLease {
195
+ consumerId: string;
196
+ channel: LeaseChannel;
197
+ ownerId: string;
198
+ expiresAt: number;
199
+ }
200
+ export interface AcquireLeaseRequest {
201
+ consumerId: string;
202
+ channel: LeaseChannel;
203
+ ownerId: string;
204
+ ttlMs: number;
205
+ nowMs?: number;
206
+ }
207
+ export interface DetailStateTransition {
208
+ eventIds: string[];
209
+ consumerId: string;
210
+ from: DetailDeliveryState[];
211
+ to: DetailDeliveryState;
212
+ deliveredAt?: string;
213
+ deliveryVia?: DetailDeliveryVia;
214
+ acceptanceLevel?: MailboxAcceptanceLevel;
215
+ lease?: ConsumerLease;
216
+ nowMs?: number;
217
+ }
218
+ export interface MonitorStateTransition {
219
+ eventIds: string[];
220
+ consumerId: string;
221
+ from: MonitorDeliveryState[];
222
+ to: MonitorDeliveryState;
223
+ deliveredAt?: string;
224
+ lease?: ConsumerLease;
225
+ nowMs?: number;
226
+ }
227
+ export interface MonitorDeliveryAttempt {
228
+ eventId: string;
229
+ consumerId: string;
230
+ attemptedAt: string;
231
+ lease: ConsumerLease;
232
+ nowMs?: number;
233
+ }
234
+ export interface EventCatalogEntry {
235
+ type: string;
236
+ producer: EventProducer;
237
+ deliveryClass: EventDeliveryClass;
238
+ /** Explicit notification policy override; absent preserves the producer's wake choice. */
239
+ wakeAgent?: boolean;
240
+ }
241
+ export declare function initialDeliveryFor(event: Pick<CanonicalEvent, 'eventId' | 'deliveryClass'>, consumerId: string, channels?: readonly LeaseChannel[]): EventDeliveryRecord;
242
+ export declare function cloneRecord<T>(value: T): T;
@@ -0,0 +1,39 @@
1
+ export const DEFAULT_EVENT_CONSUMER_ID = 'local-agent';
2
+ const DETAIL_DELIVERY_VIA_PATTERN = /^[a-z0-9][a-z0-9._-]{0,119}$/;
3
+ export function validateDetailDeliveryVia(value) {
4
+ if (!DETAIL_DELIVERY_VIA_PATTERN.test(value)) {
5
+ throw new Error('Detail delivery adapter id must be 1-120 lowercase ASCII characters using a-z, 0-9, dot, underscore, or hyphen.');
6
+ }
7
+ return value;
8
+ }
9
+ export function initialDeliveryFor(event, consumerId, channels = ['monitor', 'details']) {
10
+ let delivery;
11
+ switch (event.deliveryClass) {
12
+ case 'monitor_and_events':
13
+ delivery = {
14
+ eventId: event.eventId,
15
+ consumerId,
16
+ monitorState: 'pending',
17
+ monitorAttemptCount: 0,
18
+ detailState: 'pending',
19
+ };
20
+ break;
21
+ case 'internal_only':
22
+ delivery = {
23
+ eventId: event.eventId,
24
+ consumerId,
25
+ monitorState: 'not_applicable',
26
+ monitorAttemptCount: 0,
27
+ detailState: 'not_applicable',
28
+ };
29
+ break;
30
+ }
31
+ if (!channels.includes('monitor'))
32
+ delivery.monitorState = 'not_applicable';
33
+ if (!channels.includes('details'))
34
+ delivery.detailState = 'not_applicable';
35
+ return delivery;
36
+ }
37
+ export function cloneRecord(value) {
38
+ return structuredClone(value);
39
+ }
@@ -0,0 +1,7 @@
1
+ /** Public, game-neutral CCL Runtime framework. */
2
+ export * from './runtime.js';
3
+ export * from './plugins/index.js';
4
+ export * from './events/index.js';
5
+ export * from './mailbox/index.js';
6
+ export * from './state/index.js';
7
+ export * from './capability-registry.js';
@@ -0,0 +1,7 @@
1
+ /** Public, game-neutral CCL Runtime framework. */
2
+ export * from './runtime.js';
3
+ export * from './plugins/index.js';
4
+ export * from './events/index.js';
5
+ export * from './mailbox/index.js';
6
+ export * from './state/index.js';
7
+ export * from './capability-registry.js';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Load node:sqlite without leaking Node's version-dependent ExperimentalWarning
3
+ * into Agent-facing stderr. Other warnings keep their normal behavior.
4
+ */
5
+ export declare function loadNodeSqliteModule<T>(requireModule: (id: string) => unknown): T;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Load node:sqlite without leaking Node's version-dependent ExperimentalWarning
3
+ * into Agent-facing stderr. Other warnings keep their normal behavior.
4
+ */
5
+ export function loadNodeSqliteModule(requireModule) {
6
+ const original = process.emitWarning;
7
+ process.emitWarning = ((warning, ...args) => {
8
+ const message = warning instanceof Error ? warning.message : String(warning);
9
+ if (message.includes('SQLite is an experimental feature'))
10
+ return;
11
+ return original.call(process, warning, ...args);
12
+ });
13
+ try {
14
+ return requireModule('node:sqlite');
15
+ }
16
+ finally {
17
+ process.emitWarning = original;
18
+ }
19
+ }
@@ -0,0 +1,30 @@
1
+ import type { MailboxDeliveryMode, MailboxItem } from './types.js';
2
+ export interface MailboxNotification<TPayload = unknown> {
3
+ notificationId: string;
4
+ consumerId: string;
5
+ sessionId: string;
6
+ segmentId: string;
7
+ mode: MailboxDeliveryMode;
8
+ formatterVersion: string;
9
+ coalesceKey: string;
10
+ itemIds: string[];
11
+ eventIds: string[];
12
+ firstEventCommitSeq: number;
13
+ lastEventCommitSeq: number;
14
+ payload: TPayload;
15
+ }
16
+ /**
17
+ * A coalescer only shapes already-presented Mailbox payloads. It never reads
18
+ * game Event types, decides when to wake an Agent, or changes delivery state.
19
+ */
20
+ export interface MailboxCoalescer<TItemPayload = unknown, TNotificationPayload = TItemPayload> {
21
+ /** Passed to Repository.claimMailbox; the repository still enforces FIFO. */
22
+ readonly maxItems: number;
23
+ coalesce(items: readonly MailboxItem<TItemPayload>[]): MailboxNotification<TNotificationPayload>;
24
+ }
25
+ export declare function mailboxNotification<TItemPayload, TNotificationPayload>(items: readonly MailboxItem<TItemPayload>[], payload: TNotificationPayload): MailboxNotification<TNotificationPayload>;
26
+ /** Default policy: claim and deliver exactly one durable item at a time. */
27
+ export declare class IdentityMailboxCoalescer<TPayload = unknown> implements MailboxCoalescer<TPayload, TPayload> {
28
+ readonly maxItems = 1;
29
+ coalesce(items: readonly MailboxItem<TPayload>[]): MailboxNotification<TPayload>;
30
+ }
@@ -0,0 +1,45 @@
1
+ import { stableMailboxNotificationId } from './identity.js';
2
+ function assertOneClaimGroup(items) {
3
+ const first = items[0];
4
+ if (!first)
5
+ throw new Error('Cannot coalesce an empty Mailbox claim.');
6
+ for (const item of items.slice(1)) {
7
+ if (item.consumerId !== first.consumerId
8
+ || item.sessionId !== first.sessionId
9
+ || item.segmentId !== first.segmentId
10
+ || item.mode !== first.mode
11
+ || item.formatterVersion !== first.formatterVersion
12
+ || item.coalesceKey !== first.coalesceKey) {
13
+ throw new Error('A Mailbox claim may only contain one consumer, segment, mode, formatter version, and coalesce key.');
14
+ }
15
+ }
16
+ return first;
17
+ }
18
+ export function mailboxNotification(items, payload) {
19
+ const first = assertOneClaimGroup(items);
20
+ const last = items[items.length - 1] ?? first;
21
+ return {
22
+ notificationId: stableMailboxNotificationId(items.map((item) => item.itemId)),
23
+ consumerId: first.consumerId,
24
+ sessionId: first.sessionId,
25
+ segmentId: first.segmentId,
26
+ mode: first.mode,
27
+ formatterVersion: first.formatterVersion,
28
+ coalesceKey: first.coalesceKey,
29
+ itemIds: items.map((item) => item.itemId),
30
+ eventIds: items.map((item) => item.eventId),
31
+ firstEventCommitSeq: first.eventCommitSeq,
32
+ lastEventCommitSeq: last.eventCommitSeq,
33
+ payload,
34
+ };
35
+ }
36
+ /** Default policy: claim and deliver exactly one durable item at a time. */
37
+ export class IdentityMailboxCoalescer {
38
+ maxItems = 1;
39
+ coalesce(items) {
40
+ if (items.length !== 1) {
41
+ throw new Error(`IdentityMailboxCoalescer expected one item, received ${items.length}.`);
42
+ }
43
+ return mailboxNotification(items, items[0].payload);
44
+ }
45
+ }
@@ -0,0 +1,31 @@
1
+ import type { MailboxNotification } from './coalescer.js';
2
+ import type { MailboxAcceptanceLevel } from './types.js';
3
+ /**
4
+ * Returning means this adapter completed the handoff level named by
5
+ * acceptanceLevel. Implementations must not wait for the Agent's resulting
6
+ * turn to finish, and stdout-like sinks must not claim Host acceptance.
7
+ */
8
+ export interface HostNotificationAcceptance {
9
+ acceptedAt: string;
10
+ receiptId?: string;
11
+ /**
12
+ * `sink_emitted` is the conservative default for stdout-like transports.
13
+ * `host_accepted` means the Host durably acknowledged its own input queue.
14
+ */
15
+ acceptanceLevel?: MailboxAcceptanceLevel;
16
+ }
17
+ /** A Host rejected this notification with an explicit retry policy. */
18
+ export declare class HostNotificationDeliveryError extends Error {
19
+ readonly retryable: boolean;
20
+ readonly code: string;
21
+ readonly httpStatus?: number;
22
+ constructor(options: {
23
+ message: string;
24
+ retryable: boolean;
25
+ code: string;
26
+ httpStatus?: number;
27
+ });
28
+ }
29
+ export interface HostNotificationSink<TPayload = unknown> {
30
+ deliver(notification: MailboxNotification<TPayload>, signal: AbortSignal): Promise<HostNotificationAcceptance>;
31
+ }
@@ -0,0 +1,13 @@
1
+ /** A Host rejected this notification with an explicit retry policy. */
2
+ export class HostNotificationDeliveryError extends Error {
3
+ retryable;
4
+ code;
5
+ httpStatus;
6
+ constructor(options) {
7
+ super(options.message);
8
+ this.name = 'HostNotificationDeliveryError';
9
+ this.retryable = options.retryable;
10
+ this.code = options.code;
11
+ this.httpStatus = options.httpStatus;
12
+ }
13
+ }
@@ -0,0 +1,15 @@
1
+ import type { MailboxDeliveryMode } from './types.js';
2
+ export interface StableMailboxItemIdentity {
3
+ consumerId: string;
4
+ sessionId: string;
5
+ eventId: string;
6
+ mode: MailboxDeliveryMode;
7
+ }
8
+ /**
9
+ * Builds the durable identity of one Event delivery without including mutable
10
+ * presentation or retry fields. Re-projecting the same Event is therefore an
11
+ * idempotent enqueue even after a process restart or formatter upgrade.
12
+ */
13
+ export declare function stableMailboxItemId(identity: StableMailboxItemIdentity): string;
14
+ /** Stable for one ordered item set; reliable Hosts should also dedupe itemIds. */
15
+ export declare function stableMailboxNotificationId(itemIds: readonly string[]): string;
@@ -0,0 +1,28 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * Builds the durable identity of one Event delivery without including mutable
4
+ * presentation or retry fields. Re-projecting the same Event is therefore an
5
+ * idempotent enqueue even after a process restart or formatter upgrade.
6
+ */
7
+ export function stableMailboxItemId(identity) {
8
+ const digest = createHash('sha256')
9
+ .update(JSON.stringify([
10
+ 'ccl.mailbox.item.v1',
11
+ identity.consumerId,
12
+ identity.sessionId,
13
+ identity.eventId,
14
+ identity.mode,
15
+ ]))
16
+ .digest('hex');
17
+ return `mbx_${digest}`;
18
+ }
19
+ /** Stable for one ordered item set; reliable Hosts should also dedupe itemIds. */
20
+ export function stableMailboxNotificationId(itemIds) {
21
+ if (itemIds.length === 0) {
22
+ throw new Error('A mailbox notification must contain at least one item.');
23
+ }
24
+ const digest = createHash('sha256')
25
+ .update(JSON.stringify(['ccl.mailbox.notification.v1', ...itemIds]))
26
+ .digest('hex');
27
+ return `mbn_${digest}`;
28
+ }
@@ -0,0 +1,7 @@
1
+ export * from './types.js';
2
+ export * from './mailbox-repository.js';
3
+ export * from './identity.js';
4
+ export * from './notification-projector.js';
5
+ export * from './coalescer.js';
6
+ export * from './host-notification-sink.js';
7
+ export * from './mailbox-dispatcher.js';
@@ -0,0 +1,7 @@
1
+ export * from './types.js';
2
+ export * from './mailbox-repository.js';
3
+ export * from './identity.js';
4
+ export * from './notification-projector.js';
5
+ export * from './coalescer.js';
6
+ export * from './host-notification-sink.js';
7
+ export * from './mailbox-dispatcher.js';
@@ -0,0 +1,65 @@
1
+ import type { MailboxCoalescer } from './coalescer.js';
2
+ import { type HostNotificationSink } from './host-notification-sink.js';
3
+ import type { MailboxRepository } from './mailbox-repository.js';
4
+ import type { MailboxDeliveryMode, MailboxItem } from './types.js';
5
+ export interface MailboxDispatcherScope {
6
+ consumerId: string;
7
+ sessionId: string;
8
+ segmentId: string;
9
+ mode: MailboxDeliveryMode;
10
+ }
11
+ export interface MailboxRetryContext<TPayload = unknown> {
12
+ attemptCount: number;
13
+ error: unknown;
14
+ items: readonly MailboxItem<TPayload>[];
15
+ nowMs: number;
16
+ }
17
+ export type MailboxRetryAt<TPayload = unknown> = (context: MailboxRetryContext<TPayload>) => number;
18
+ export interface MailboxDispatcherOptions<TItemPayload = unknown, TNotificationPayload = TItemPayload> {
19
+ repository: MailboxRepository;
20
+ /** null means there is currently no foreground game scope; park until notified. */
21
+ scope: MailboxDispatcherScope | (() => MailboxDispatcherScope | null);
22
+ ownerId: string;
23
+ sink: HostNotificationSink<TNotificationPayload>;
24
+ coalescer?: MailboxCoalescer<TItemPayload, TNotificationPayload>;
25
+ leaseTtlMs?: number;
26
+ retryAt?: MailboxRetryAt<TItemPayload>;
27
+ now?: () => number;
28
+ onAttempt?: (items: readonly MailboxItem<TItemPayload>[]) => void;
29
+ onError?: (error: unknown, items?: readonly MailboxItem<TItemPayload>[]) => void;
30
+ }
31
+ /**
32
+ * Pumps one durable Mailbox scope into one Host Adapter.
33
+ *
34
+ * It intentionally knows nothing about Agent active/idle state or game Event
35
+ * types. notifyAvailable always attempts immediately; retry timing is persisted
36
+ * by Repository.nackMailboxClaim through retryAtMs.
37
+ */
38
+ export declare class MailboxDispatcher<TItemPayload = unknown, TNotificationPayload = TItemPayload> {
39
+ private readonly repository;
40
+ private readonly resolveScope;
41
+ private readonly ownerId;
42
+ private readonly sink;
43
+ private readonly coalescer;
44
+ private readonly leaseTtlMs;
45
+ private readonly retryAt;
46
+ private readonly now;
47
+ private readonly onAttempt?;
48
+ private readonly onError?;
49
+ private stopped;
50
+ private pumpRequested;
51
+ private pumpPromise;
52
+ private retryTimer;
53
+ constructor(options: MailboxDispatcherOptions<TItemPayload, TNotificationPayload>);
54
+ /** Signals new work without waiting for Host delivery. */
55
+ notifyAvailable(): void;
56
+ /** Drains work available now, but never waits for a future retry timer. */
57
+ flush(): Promise<void>;
58
+ /** Stops future retries, while allowing an in-flight Host acceptance to settle. */
59
+ stop(): Promise<void>;
60
+ private ensurePump;
61
+ private pump;
62
+ private scheduleHead;
63
+ private scheduleAt;
64
+ private clearRetryTimer;
65
+ }