@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,64 @@
1
+ import { registerHooks } from 'node:module';
2
+ import { resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { addEsmModuleRoot, addRuntimeModuleAliases, initialize as initializeRuntimeModuleHooks, load as loadRuntimeModule, resolve as resolveRuntimeModule, } from './runtime-module-loader-hooks.mjs';
5
+ let loaderRegistered = false;
6
+ let registeredAliases = {};
7
+ const defaultAliases = Object.freeze({
8
+ // src/ and dist/ have the same depth. Pin the public build in either case,
9
+ // rather than allowing checkout imports to create a second set of SDK bases.
10
+ '@myclaw163/game-agent-runtime': new URL('../../../dist/index.js', import.meta.url).href,
11
+ '@myclaw163/game-agent-runtime/sdk/strategy.js': new URL('../../../dist/sdk/strategy.js', import.meta.url).href,
12
+ '@myclaw163/game-agent-runtime/sdk/perception.js': new URL('../../../dist/sdk/perception.js', import.meta.url).href,
13
+ });
14
+ /** Game aliases extend the host's own SDK; they cannot replace its base-class identities. */
15
+ function mergedSdkAliases(additional) {
16
+ for (const [specifier, target] of Object.entries(additional)) {
17
+ if (Object.hasOwn(defaultAliases, specifier) && defaultAliases[specifier] !== target) {
18
+ throw Error('runtime_sdk_alias_conflict:' + specifier);
19
+ }
20
+ }
21
+ return Object.freeze({ ...defaultAliases, ...additional });
22
+ }
23
+ function moduleUrl(source) {
24
+ if (source instanceof URL)
25
+ return source;
26
+ return source.startsWith('file:') ? new URL(source) : pathToFileURL(resolve(source));
27
+ }
28
+ /**
29
+ * Import a trusted local module without bundling it. Runtime author SDKs always
30
+ * resolve to this installed package; games may add their own SDK aliases for
31
+ * scripts living outside the package's node_modules search path.
32
+ */
33
+ export async function importRuntimeModule(source, sdkAliases = {}) {
34
+ const target = moduleUrl(source);
35
+ registerRuntimeModuleLoader(sdkAliases);
36
+ addEsmModuleRoot(new URL('.', target).href);
37
+ return import(target.href);
38
+ }
39
+ /** Register the direct-import hooks once in the current JavaScript isolate. */
40
+ export function registerRuntimeModuleLoader(sdkAliases = {}) {
41
+ const aliases = mergedSdkAliases(sdkAliases);
42
+ if (loaderRegistered) {
43
+ for (const [key, value] of Object.entries(aliases)) {
44
+ if (registeredAliases[key] && registeredAliases[key] !== value)
45
+ throw Error('runtime_sdk_alias_conflict:' + key);
46
+ }
47
+ registeredAliases = Object.freeze({ ...registeredAliases, ...aliases });
48
+ addRuntimeModuleAliases(aliases);
49
+ return;
50
+ }
51
+ registeredAliases = aliases;
52
+ // One synchronous in-process hook transforms TypeScript and maps public SDK
53
+ // names to this exact installed package. No module gets its own compiler.
54
+ initializeRuntimeModuleHooks({ sdkAliases: registeredAliases, nativeTypeScript: true });
55
+ registerHooks({ resolve: resolveRuntimeModule, load: loadRuntimeModule });
56
+ loaderRegistered = true;
57
+ }
58
+ /** Loader data for Worker Threads, which use the same in-process TS transform. */
59
+ export function runtimeModuleThreadLoaderConfig(sdkAliases = {}) {
60
+ return {
61
+ hooksUrl: new URL('./runtime-module-loader-hooks.mjs', import.meta.url).href,
62
+ sdkAliases: mergedSdkAliases(sdkAliases),
63
+ };
64
+ }
@@ -0,0 +1,7 @@
1
+ export declare const MAX_RUNTIME_MODULE_OUTPUT_BYTES: number;
2
+ export interface RuntimeModuleOutputSize {
3
+ readonly bytes: number;
4
+ readonly limitBytes: number;
5
+ }
6
+ /** Bounds cloneable external-module output before it is copied into the Owner. */
7
+ export declare function assertRuntimeModuleOutputSize(value: unknown, code: string, limitBytes?: number): RuntimeModuleOutputSize;
@@ -0,0 +1,15 @@
1
+ import { serialize } from 'node:v8';
2
+ export const MAX_RUNTIME_MODULE_OUTPUT_BYTES = 1024 * 1024;
3
+ /** Bounds cloneable external-module output before it is copied into the Owner. */
4
+ export function assertRuntimeModuleOutputSize(value, code, limitBytes = MAX_RUNTIME_MODULE_OUTPUT_BYTES) {
5
+ let bytes;
6
+ try {
7
+ bytes = serialize(value).byteLength;
8
+ }
9
+ catch {
10
+ throw new Error(`${code}_not_serializable`);
11
+ }
12
+ if (bytes > limitBytes)
13
+ throw new Error(`${code}_too_large:${bytes}:${limitBytes}`);
14
+ return { bytes, limitBytes };
15
+ }
@@ -0,0 +1,23 @@
1
+ import { workerData } from 'node:worker_threads';
2
+ import { registerHooks } from 'node:module';
3
+
4
+ const bootstrap = workerData?.runtimeModuleBootstrap;
5
+ if (
6
+ !bootstrap
7
+ || typeof bootstrap.hostUrl !== 'string'
8
+ || typeof bootstrap.hooksUrl !== 'string'
9
+ || !bootstrap.sdkAliases
10
+ || typeof bootstrap.sdkAliases !== 'object'
11
+ || (bootstrap.esmModuleRoots !== undefined && !Array.isArray(bootstrap.esmModuleRoots))
12
+ ) {
13
+ throw new Error('runtime_module_worker_bootstrap_invalid');
14
+ }
15
+
16
+ const hooks = await import(bootstrap.hooksUrl);
17
+ hooks.initialize({
18
+ sdkAliases: bootstrap.sdkAliases,
19
+ nativeTypeScript: true,
20
+ esmModuleRoots: bootstrap.esmModuleRoots ?? [],
21
+ });
22
+ registerHooks({ resolve: hooks.resolve, load: hooks.load });
23
+ await import(bootstrap.hostUrl);
@@ -0,0 +1,94 @@
1
+ import type { ScopeRef } from './contracts.js';
2
+ export interface ParticipationSession {
3
+ id: string;
4
+ adapterId: string;
5
+ accountId: string;
6
+ resumeKey?: string;
7
+ mode?: string;
8
+ startedAt: string;
9
+ endedAt?: string;
10
+ }
11
+ export interface ParticipationSegment {
12
+ id: string;
13
+ sessionId: string;
14
+ kind: string;
15
+ identity?: string;
16
+ ordinal: number;
17
+ startedAt: string;
18
+ endedAt?: string;
19
+ }
20
+ export declare function canReuseParticipationSegment(current: Pick<ParticipationSegment, 'kind' | 'identity' | 'endedAt'>, kind: string, identity?: string): boolean;
21
+ export interface ParticipationSnapshot {
22
+ session: ParticipationSession;
23
+ segment: ParticipationSegment;
24
+ connections: Record<string, string>;
25
+ }
26
+ export type ParticipationTransition = {
27
+ type: 'session_opened';
28
+ snapshot: ParticipationSnapshot;
29
+ } | {
30
+ type: 'session_updated';
31
+ snapshot: ParticipationSnapshot;
32
+ } | {
33
+ type: 'segment_changed';
34
+ previous?: ParticipationSegment;
35
+ snapshot: ParticipationSnapshot;
36
+ } | {
37
+ type: 'segment_updated';
38
+ snapshot: ParticipationSnapshot;
39
+ } | {
40
+ type: 'connection_changed';
41
+ sourceId: string;
42
+ previous?: string;
43
+ snapshot: ParticipationSnapshot;
44
+ } | {
45
+ type: 'session_closed';
46
+ snapshot: ParticipationSnapshot;
47
+ };
48
+ export interface ParticipationManagerOptions {
49
+ now?: () => Date;
50
+ createId?: (prefix: 'session' | 'segment') => string;
51
+ initial?: ParticipationSnapshot;
52
+ onTransition?: (transition: ParticipationTransition) => void;
53
+ }
54
+ export interface OpenSessionInput {
55
+ adapterId: string;
56
+ accountId: string;
57
+ resumeKey?: string;
58
+ mode?: string;
59
+ initialSegment?: {
60
+ kind: string;
61
+ identity?: string;
62
+ };
63
+ }
64
+ /**
65
+ * Owns logical participation scope. A network reconnect only changes a
66
+ * connection id; queue/lobby/game transitions change the segment; explicitly
67
+ * leaving and joining again changes the session.
68
+ */
69
+ export declare class ParticipationManager {
70
+ private readonly now;
71
+ private readonly createId;
72
+ private readonly onTransition?;
73
+ private currentValue;
74
+ constructor(options?: ParticipationManagerOptions);
75
+ get active(): boolean;
76
+ snapshot(): ParticipationSnapshot | null;
77
+ requireSnapshot(): ParticipationSnapshot;
78
+ scope(): ScopeRef;
79
+ openSession(input: OpenSessionInput): ParticipationSnapshot;
80
+ activateSegment(kind: string, identity?: string): ParticipationSnapshot;
81
+ /**
82
+ * Adopt the first authoritative backend participation identity.
83
+ *
84
+ * A queue session starts before a game id or room code necessarily exists.
85
+ * Once learned, that identity may be persisted exactly once. Replacing it
86
+ * with a different identity would make a later owner restart resume the
87
+ * wrong participation, so conflicts are rejected.
88
+ */
89
+ adoptResumeKey(resumeKey: string): ParticipationSnapshot;
90
+ updateMode(mode: string): ParticipationSnapshot;
91
+ bindConnection(sourceId: string, connectionId: string): ParticipationSnapshot;
92
+ connectionId(sourceId: string): string | undefined;
93
+ closeSession(_reason?: string): ParticipationSnapshot | null;
94
+ }
@@ -0,0 +1,185 @@
1
+ import { randomUUID } from 'crypto';
2
+ export function canReuseParticipationSegment(current, kind, identity) {
3
+ return !current.endedAt && current.kind === kind
4
+ && (identity === undefined || current.identity === undefined || current.identity === identity);
5
+ }
6
+ function clone(value) {
7
+ return structuredClone(value);
8
+ }
9
+ /**
10
+ * Owns logical participation scope. A network reconnect only changes a
11
+ * connection id; queue/lobby/game transitions change the segment; explicitly
12
+ * leaving and joining again changes the session.
13
+ */
14
+ export class ParticipationManager {
15
+ now;
16
+ createId;
17
+ onTransition;
18
+ currentValue;
19
+ constructor(options = {}) {
20
+ this.now = options.now ?? (() => new Date());
21
+ this.createId = options.createId ?? ((prefix) => `${prefix}_${randomUUID()}`);
22
+ this.onTransition = options.onTransition;
23
+ this.currentValue = options.initial ? clone(options.initial) : null;
24
+ }
25
+ get active() {
26
+ return !!this.currentValue && !this.currentValue.session.endedAt;
27
+ }
28
+ snapshot() {
29
+ return this.currentValue ? clone(this.currentValue) : null;
30
+ }
31
+ requireSnapshot() {
32
+ const snapshot = this.snapshot();
33
+ if (!snapshot)
34
+ throw new Error('No active participation session.');
35
+ return snapshot;
36
+ }
37
+ scope() {
38
+ const snapshot = this.requireSnapshot();
39
+ return {
40
+ adapterId: snapshot.session.adapterId,
41
+ accountId: snapshot.session.accountId,
42
+ sessionId: snapshot.session.id,
43
+ segmentId: snapshot.segment.id,
44
+ };
45
+ }
46
+ openSession(input) {
47
+ const current = this.currentValue;
48
+ if (current
49
+ && !current.session.endedAt
50
+ && current.session.adapterId === input.adapterId
51
+ && current.session.accountId === input.accountId
52
+ && current.session.resumeKey === input.resumeKey) {
53
+ if (input.mode)
54
+ this.updateMode(input.mode);
55
+ if (input.initialSegment) {
56
+ return this.activateSegment(input.initialSegment.kind, input.initialSegment.identity);
57
+ }
58
+ return this.requireSnapshot();
59
+ }
60
+ if (current && !current.session.endedAt)
61
+ this.closeSession('replaced');
62
+ const startedAt = this.now().toISOString();
63
+ const session = {
64
+ id: this.createId('session'),
65
+ adapterId: input.adapterId,
66
+ accountId: input.accountId,
67
+ resumeKey: input.resumeKey,
68
+ mode: input.mode,
69
+ startedAt,
70
+ };
71
+ const initial = input.initialSegment ?? { kind: 'unknown' };
72
+ const segment = {
73
+ id: this.createId('segment'),
74
+ sessionId: session.id,
75
+ kind: initial.kind,
76
+ identity: initial.identity,
77
+ ordinal: 1,
78
+ startedAt,
79
+ };
80
+ this.currentValue = { session, segment, connections: {} };
81
+ const snapshot = this.requireSnapshot();
82
+ this.onTransition?.({ type: 'session_opened', snapshot });
83
+ return snapshot;
84
+ }
85
+ activateSegment(kind, identity) {
86
+ if (!this.currentValue || this.currentValue.session.endedAt) {
87
+ throw new Error('Cannot activate a segment without an active session.');
88
+ }
89
+ const current = this.currentValue.segment;
90
+ if (canReuseParticipationSegment(current, kind, identity)) {
91
+ // An omitted identity means "keep the currently known identity". This
92
+ // matters for room reconnect loops, where a caller may only know that it
93
+ // is returning to the lobby while the durable room code is already set.
94
+ if (identity === undefined || current.identity === identity) {
95
+ return this.requireSnapshot();
96
+ }
97
+ // Learning an authoritative identity does not create a new logical
98
+ // segment. Persist it in place so early queue/lobby events remain in the
99
+ // same segment and no artificial backlog boundary is introduced.
100
+ if (current.identity === undefined) {
101
+ current.identity = identity;
102
+ const snapshot = this.requireSnapshot();
103
+ this.onTransition?.({ type: 'segment_updated', snapshot });
104
+ return snapshot;
105
+ }
106
+ }
107
+ const changedAt = this.now().toISOString();
108
+ const previous = { ...current, endedAt: current.endedAt ?? changedAt };
109
+ const segment = {
110
+ id: this.createId('segment'),
111
+ sessionId: this.currentValue.session.id,
112
+ kind,
113
+ identity,
114
+ ordinal: current.ordinal + 1,
115
+ startedAt: changedAt,
116
+ };
117
+ this.currentValue.segment = segment;
118
+ const snapshot = this.requireSnapshot();
119
+ this.onTransition?.({ type: 'segment_changed', previous, snapshot });
120
+ return snapshot;
121
+ }
122
+ /**
123
+ * Adopt the first authoritative backend participation identity.
124
+ *
125
+ * A queue session starts before a game id or room code necessarily exists.
126
+ * Once learned, that identity may be persisted exactly once. Replacing it
127
+ * with a different identity would make a later owner restart resume the
128
+ * wrong participation, so conflicts are rejected.
129
+ */
130
+ adoptResumeKey(resumeKey) {
131
+ if (!this.currentValue || this.currentValue.session.endedAt) {
132
+ throw new Error('Cannot adopt a resume key without an active session.');
133
+ }
134
+ if (!resumeKey)
135
+ throw new Error('resumeKey is required.');
136
+ const current = this.currentValue.session.resumeKey;
137
+ if (current === resumeKey)
138
+ return this.requireSnapshot();
139
+ if (current !== undefined) {
140
+ throw new Error(`Cannot replace participation resume key ${current} with ${resumeKey}.`);
141
+ }
142
+ this.currentValue.session.resumeKey = resumeKey;
143
+ const snapshot = this.requireSnapshot();
144
+ this.onTransition?.({ type: 'session_updated', snapshot });
145
+ return snapshot;
146
+ }
147
+ updateMode(mode) {
148
+ if (!this.currentValue || this.currentValue.session.endedAt) {
149
+ throw new Error('Cannot update mode without an active session.');
150
+ }
151
+ if (!mode)
152
+ throw new Error('mode is required.');
153
+ if (this.currentValue.session.mode === mode)
154
+ return this.requireSnapshot();
155
+ this.currentValue.session.mode = mode;
156
+ const snapshot = this.requireSnapshot();
157
+ this.onTransition?.({ type: 'session_updated', snapshot });
158
+ return snapshot;
159
+ }
160
+ bindConnection(sourceId, connectionId) {
161
+ if (!this.currentValue || this.currentValue.session.endedAt) {
162
+ throw new Error('Cannot bind a connection without an active session.');
163
+ }
164
+ const previous = this.currentValue.connections[sourceId];
165
+ if (previous === connectionId)
166
+ return this.requireSnapshot();
167
+ this.currentValue.connections[sourceId] = connectionId;
168
+ const snapshot = this.requireSnapshot();
169
+ this.onTransition?.({ type: 'connection_changed', sourceId, previous, snapshot });
170
+ return snapshot;
171
+ }
172
+ connectionId(sourceId) {
173
+ return this.currentValue?.connections[sourceId];
174
+ }
175
+ closeSession(_reason) {
176
+ if (!this.currentValue || this.currentValue.session.endedAt)
177
+ return this.snapshot();
178
+ const endedAt = this.now().toISOString();
179
+ this.currentValue.segment.endedAt ??= endedAt;
180
+ this.currentValue.session.endedAt = endedAt;
181
+ const snapshot = this.requireSnapshot();
182
+ this.onTransition?.({ type: 'session_closed', snapshot });
183
+ return snapshot;
184
+ }
185
+ }
@@ -0,0 +1,62 @@
1
+ import { parentPort, workerData, threadId } from 'worker_threads';
2
+ import { getHeapStatistics } from 'v8';
3
+ import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
4
+ import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
5
+ import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
6
+ const paths = workerData;
7
+ const opened = SqliteEventRepository.open(paths.eventLedgerPath, paths.eventStoreCompatibility);
8
+ if (!opened.ok)
9
+ throw new Error(`${opened.unavailable.code}: ${opened.unavailable.message}`);
10
+ const stores = {
11
+ events: opened.repository,
12
+ history: new SqliteStateHistoryRepository(paths.stateHistoryPath),
13
+ input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
14
+ };
15
+ function reportMemory() {
16
+ if (!paths.diagnostics)
17
+ return;
18
+ const memory = process.memoryUsage();
19
+ parentPort?.postMessage({ type: 'diagnostics', memory: {
20
+ sampled_at_ms: Date.now(), thread_id: threadId,
21
+ heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
22
+ external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
23
+ heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
24
+ // RSS is process-wide; never present it as this Worker's private memory.
25
+ } });
26
+ }
27
+ reportMemory();
28
+ const memoryTimer = paths.diagnostics ? setInterval(reportMemory, 5_000) : undefined;
29
+ memoryTimer?.unref();
30
+ parentPort?.on('message', (message) => {
31
+ try {
32
+ if (message.type === 'batch') {
33
+ for (const operation of message.operations ?? []) {
34
+ const store = stores[operation.store];
35
+ const method = store[operation.method];
36
+ if (typeof method !== 'function')
37
+ throw new Error(`Unknown persistence operation: ${operation.store}.${operation.method}`);
38
+ method.apply(store, operation.args);
39
+ }
40
+ parentPort?.postMessage({ type: 'ack', id: message.id });
41
+ return;
42
+ }
43
+ if (message.type === 'barrier') {
44
+ parentPort?.postMessage({ type: 'barrier', id: message.id });
45
+ return;
46
+ }
47
+ if (memoryTimer)
48
+ clearInterval(memoryTimer);
49
+ reportMemory();
50
+ stores.history.close();
51
+ stores.input.close();
52
+ stores.events.close();
53
+ parentPort?.postMessage({ type: 'closed', id: message.id });
54
+ }
55
+ catch (error) {
56
+ parentPort?.postMessage({
57
+ type: 'error',
58
+ id: message.id,
59
+ error: error instanceof Error ? error.message : String(error),
60
+ });
61
+ }
62
+ });
@@ -0,0 +1,36 @@
1
+ import type { EventStoreCompatibility } from '../events/store-compatibility.js';
2
+ import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
3
+ import { type RuntimeResumeSelection } from '../events/runtime-resume.js';
4
+ import type { EventRepository } from '../events/event-repository.js';
5
+ import type { EventAccountScope } from '../events/types.js';
6
+ import type { RuntimePersistenceStore } from '../plugins/contracts.js';
7
+ import type { StateHistoryRepository } from '../state/history/contracts.js';
8
+ export interface MemoryFirstPersistenceOptions {
9
+ eventLedgerPath: string;
10
+ eventStoreCompatibility?: EventStoreCompatibility;
11
+ stateHistoryPath: string;
12
+ inputJournalPath: string;
13
+ maxPendingOperations?: number;
14
+ batchSize?: number;
15
+ flushIntervalMs?: number;
16
+ recovery?: RuntimeResumeSelection & {
17
+ account: EventAccountScope;
18
+ };
19
+ onDiagnostic?: (name: string, attributes: Readonly<Record<string, unknown>>) => void;
20
+ onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
21
+ }
22
+ export interface AsyncPersistenceHealth {
23
+ mode: 'memory-first-sqlite-mirror';
24
+ pendingOperations: number;
25
+ droppedOperations: number;
26
+ degraded: boolean;
27
+ error?: string;
28
+ workerMemory?: Readonly<Record<string, number>>;
29
+ }
30
+ export interface MemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>> {
31
+ eventRepository: EventRepository & MailboxRepository;
32
+ stateHistoryRepository: StateHistoryRepository<TPosition, TState>;
33
+ inputJournal: RuntimePersistenceStore<TState, TEvent>;
34
+ health(): AsyncPersistenceHealth;
35
+ }
36
+ export declare function createMemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>>(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent>;