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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +67 -2
  2. package/dist/framework/action-diagnostics.d.ts +11 -0
  3. package/dist/framework/action-diagnostics.js +67 -0
  4. package/dist/framework/capability-registry.d.ts +58 -0
  5. package/dist/framework/capability-registry.js +325 -0
  6. package/dist/framework/contracts.d.ts +121 -0
  7. package/dist/framework/contracts.js +2 -0
  8. package/dist/framework/control/control-scheduler.d.ts +69 -0
  9. package/dist/framework/control/control-scheduler.js +1016 -0
  10. package/dist/framework/control/domain-set.d.ts +18 -0
  11. package/dist/framework/control/domain-set.js +70 -0
  12. package/dist/framework/control/index.d.ts +3 -0
  13. package/dist/framework/control/index.js +3 -0
  14. package/dist/framework/control/types.d.ts +142 -0
  15. package/dist/framework/control/types.js +13 -0
  16. package/dist/framework/control-coordinator.d.ts +7 -0
  17. package/dist/framework/control-coordinator.js +7 -0
  18. package/dist/framework/events/event-catalog.d.ts +23 -0
  19. package/dist/framework/events/event-catalog.js +52 -0
  20. package/dist/framework/events/event-delivery-service.d.ts +33 -0
  21. package/dist/framework/events/event-delivery-service.js +165 -0
  22. package/dist/framework/events/event-ingress.d.ts +28 -0
  23. package/dist/framework/events/event-ingress.js +76 -0
  24. package/dist/framework/events/event-repository.d.ts +38 -0
  25. package/dist/framework/events/event-repository.js +20 -0
  26. package/dist/framework/events/index.d.ts +7 -0
  27. package/dist/framework/events/index.js +7 -0
  28. package/dist/framework/events/memory-event-repository.d.ts +77 -0
  29. package/dist/framework/events/memory-event-repository.js +909 -0
  30. package/dist/framework/events/runtime-resume.d.ts +11 -0
  31. package/dist/framework/events/runtime-resume.js +7 -0
  32. package/dist/framework/events/sqlite-event-repository.d.ts +94 -0
  33. package/dist/framework/events/sqlite-event-repository.js +2044 -0
  34. package/dist/framework/events/store-compatibility.d.ts +17 -0
  35. package/dist/framework/events/store-compatibility.js +17 -0
  36. package/dist/framework/events/types.d.ts +244 -0
  37. package/dist/framework/events/types.js +39 -0
  38. package/dist/framework/index.d.ts +7 -0
  39. package/dist/framework/index.js +7 -0
  40. package/dist/framework/load-node-sqlite.d.ts +5 -0
  41. package/dist/framework/load-node-sqlite.js +19 -0
  42. package/dist/framework/mailbox/coalescer.d.ts +30 -0
  43. package/dist/framework/mailbox/coalescer.js +45 -0
  44. package/dist/framework/mailbox/host-notification-sink.d.ts +31 -0
  45. package/dist/framework/mailbox/host-notification-sink.js +13 -0
  46. package/dist/framework/mailbox/identity.d.ts +15 -0
  47. package/dist/framework/mailbox/identity.js +28 -0
  48. package/dist/framework/mailbox/index.d.ts +7 -0
  49. package/dist/framework/mailbox/index.js +7 -0
  50. package/dist/framework/mailbox/mailbox-dispatcher.d.ts +65 -0
  51. package/dist/framework/mailbox/mailbox-dispatcher.js +242 -0
  52. package/dist/framework/mailbox/mailbox-repository.d.ts +17 -0
  53. package/dist/framework/mailbox/mailbox-repository.js +9 -0
  54. package/dist/framework/mailbox/notification-projector.d.ts +25 -0
  55. package/dist/framework/mailbox/notification-projector.js +50 -0
  56. package/dist/framework/mailbox/types.d.ts +128 -0
  57. package/dist/framework/mailbox/types.js +1 -0
  58. package/dist/framework/modules/runtime-module-loader-hooks.mjs +156 -0
  59. package/dist/framework/modules/runtime-module-loader.d.ts +14 -0
  60. package/dist/framework/modules/runtime-module-loader.js +64 -0
  61. package/dist/framework/modules/runtime-module-output.d.ts +7 -0
  62. package/dist/framework/modules/runtime-module-output.js +15 -0
  63. package/dist/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
  64. package/dist/framework/participation-manager.d.ts +94 -0
  65. package/dist/framework/participation-manager.js +185 -0
  66. package/dist/framework/persistence/async-sqlite-persistence-worker.d.ts +1 -0
  67. package/dist/framework/persistence/async-sqlite-persistence-worker.js +62 -0
  68. package/dist/framework/persistence/memory-first-persistence.d.ts +36 -0
  69. package/dist/framework/persistence/memory-first-persistence.js +459 -0
  70. package/dist/framework/plugins/contracts.d.ts +345 -0
  71. package/dist/framework/plugins/contracts.js +1 -0
  72. package/dist/framework/plugins/index.d.ts +4 -0
  73. package/dist/framework/plugins/index.js +4 -0
  74. package/dist/framework/plugins/runtime-event-identity.d.ts +3 -0
  75. package/dist/framework/plugins/runtime-event-identity.js +11 -0
  76. package/dist/framework/plugins/runtime-input-journal.d.ts +85 -0
  77. package/dist/framework/plugins/runtime-input-journal.js +716 -0
  78. package/dist/framework/plugins/runtime-plugin-scheduler.d.ts +188 -0
  79. package/dist/framework/plugins/runtime-plugin-scheduler.js +1660 -0
  80. package/dist/framework/runtime.d.ts +264 -0
  81. package/dist/framework/runtime.js +1811 -0
  82. package/dist/framework/serial-task-queue.d.ts +6 -0
  83. package/dist/framework/serial-task-queue.js +12 -0
  84. package/dist/framework/state/contracts.d.ts +30 -0
  85. package/dist/framework/state/contracts.js +1 -0
  86. package/dist/framework/state/current-state-store.d.ts +17 -0
  87. package/dist/framework/state/current-state-store.js +153 -0
  88. package/dist/framework/state/durable-agent-state-snapshot.d.ts +61 -0
  89. package/dist/framework/state/durable-agent-state-snapshot.js +162 -0
  90. package/dist/framework/state/freshness.d.ts +7 -0
  91. package/dist/framework/state/freshness.js +52 -0
  92. package/dist/framework/state/history/contracts.d.ts +133 -0
  93. package/dist/framework/state/history/contracts.js +1 -0
  94. package/dist/framework/state/history/history-writer.d.ts +55 -0
  95. package/dist/framework/state/history/history-writer.js +157 -0
  96. package/dist/framework/state/history/memory-state-history-repository.d.ts +25 -0
  97. package/dist/framework/state/history/memory-state-history-repository.js +199 -0
  98. package/dist/framework/state/history/sqlite-state-history-repository.d.ts +28 -0
  99. package/dist/framework/state/history/sqlite-state-history-repository.js +565 -0
  100. package/dist/framework/state/history/trajectory-projector.d.ts +53 -0
  101. package/dist/framework/state/history/trajectory-projector.js +130 -0
  102. package/dist/framework/state/index.d.ts +12 -0
  103. package/dist/framework/state/index.js +12 -0
  104. package/dist/framework/state/state-ingress.d.ts +18 -0
  105. package/dist/framework/state/state-ingress.js +68 -0
  106. package/dist/framework/state/state-provider.d.ts +11 -0
  107. package/dist/framework/state/state-provider.js +56 -0
  108. package/dist/framework/state/types.d.ts +107 -0
  109. package/dist/framework/state/types.js +19 -0
  110. package/dist/index.d.ts +1 -0
  111. package/dist/index.js +1 -0
  112. package/dist/mailbox/adapters/claude-channel-adapter.d.ts +34 -0
  113. package/dist/mailbox/adapters/claude-channel-adapter.js +71 -0
  114. package/dist/mailbox/adapters/claude-channel-socket.d.ts +56 -0
  115. package/dist/mailbox/adapters/claude-channel-socket.js +279 -0
  116. package/dist/mailbox/adapters/desktop-event-socket.d.ts +81 -0
  117. package/dist/mailbox/adapters/desktop-event-socket.js +339 -0
  118. package/dist/mailbox/agent-mailbox-coordinator.d.ts +104 -0
  119. package/dist/mailbox/agent-mailbox-coordinator.js +412 -0
  120. package/dist/mailbox/host-monitor-rate-gate.d.ts +60 -0
  121. package/dist/mailbox/host-monitor-rate-gate.js +93 -0
  122. package/dist/mailbox/mailbox-event-batch-delivery.d.ts +73 -0
  123. package/dist/mailbox/mailbox-event-batch-delivery.js +251 -0
  124. package/dist/mailbox/mailbox-host-relay.d.ts +52 -0
  125. package/dist/mailbox/mailbox-host-relay.js +299 -0
  126. package/dist/mailbox/mailbox-plugin.d.ts +58 -0
  127. package/dist/mailbox/mailbox-plugin.js +128 -0
  128. package/dist/mailbox/mailbox-service.d.ts +128 -0
  129. package/dist/mailbox/mailbox-service.js +582 -0
  130. package/dist/memory/contracts.d.ts +12 -0
  131. package/dist/memory/contracts.js +1 -0
  132. package/dist/memory/strategy-memory-rpc.d.ts +21 -0
  133. package/dist/memory/strategy-memory-rpc.js +86 -0
  134. package/dist/memory/strategy-memory.d.ts +15 -0
  135. package/dist/memory/strategy-memory.js +95 -0
  136. package/dist/observability/detail-capture.d.ts +25 -0
  137. package/dist/observability/detail-capture.js +136 -0
  138. package/dist/observability/index.d.ts +5 -0
  139. package/dist/observability/index.js +5 -0
  140. package/dist/observability/process-timing.d.ts +14 -0
  141. package/dist/observability/process-timing.js +56 -0
  142. package/dist/observability/recorder.d.ts +56 -0
  143. package/dist/observability/recorder.js +202 -0
  144. package/dist/observability/redaction.d.ts +30 -0
  145. package/dist/observability/redaction.js +166 -0
  146. package/dist/observability/reporter.d.ts +32 -0
  147. package/dist/observability/reporter.js +140 -0
  148. package/dist/observability/sinks.d.ts +36 -0
  149. package/dist/observability/sinks.js +121 -0
  150. package/dist/observability/types.d.ts +81 -0
  151. package/dist/observability/types.js +1 -0
  152. package/dist/owner/control-channel.d.ts +42 -0
  153. package/dist/owner/control-channel.js +188 -0
  154. package/dist/owner/parent-process-watch.d.ts +15 -0
  155. package/dist/owner/parent-process-watch.js +40 -0
  156. package/dist/owner/process-identity.d.ts +10 -0
  157. package/dist/owner/process-identity.js +65 -0
  158. package/dist/owner/runtime-lock.d.ts +5 -0
  159. package/dist/owner/runtime-lock.js +47 -0
  160. package/dist/perception/binding-resolution.d.ts +9 -0
  161. package/dist/perception/binding-resolution.js +14 -0
  162. package/dist/perception/contracts.d.ts +85 -0
  163. package/dist/perception/contracts.js +1 -0
  164. package/dist/perception/map-concurrent.d.ts +2 -0
  165. package/dist/perception/map-concurrent.js +12 -0
  166. package/dist/perception/perception-host.d.ts +114 -0
  167. package/dist/perception/perception-host.js +338 -0
  168. package/dist/perception/perception-worker-host.d.ts +11 -0
  169. package/dist/perception/perception-worker-host.js +44 -0
  170. package/dist/perception/perception-worker.d.ts +21 -0
  171. package/dist/perception/perception-worker.js +77 -0
  172. package/dist/perception/strategy-names.d.ts +7 -0
  173. package/dist/perception/strategy-names.js +22 -0
  174. package/dist/sdk/perception.d.ts +5 -0
  175. package/dist/sdk/perception.js +6 -0
  176. package/dist/sdk/strategy.d.ts +6 -0
  177. package/dist/sdk/strategy.js +3 -0
  178. package/dist/strategy/activation-manager.d.ts +105 -0
  179. package/dist/strategy/activation-manager.js +367 -0
  180. package/dist/strategy/behavior-decision-history.d.ts +20 -0
  181. package/dist/strategy/behavior-decision-history.js +59 -0
  182. package/dist/strategy/behavior-instance-snapshot.d.ts +31 -0
  183. package/dist/strategy/behavior-instance-snapshot.js +145 -0
  184. package/dist/strategy/contracts.d.ts +189 -0
  185. package/dist/strategy/contracts.js +1 -0
  186. package/dist/strategy/control-driver.d.ts +25 -0
  187. package/dist/strategy/control-driver.js +131 -0
  188. package/dist/strategy/in-process-runner.d.ts +25 -0
  189. package/dist/strategy/in-process-runner.js +40 -0
  190. package/dist/strategy/strategy-host.d.ts +165 -0
  191. package/dist/strategy/strategy-host.js +1456 -0
  192. package/dist/strategy/strategy-script-runner.d.ts +81 -0
  193. package/dist/strategy/strategy-script-runner.js +235 -0
  194. package/dist/strategy/strategy-worker-host.d.ts +27 -0
  195. package/dist/strategy/strategy-worker-host.js +96 -0
  196. package/dist/strategy/thread-strategy-executor.d.ts +120 -0
  197. package/dist/strategy/thread-strategy-executor.js +778 -0
  198. package/examples/grid-game.mjs +129 -0
  199. package/examples/grid-perception-worker.mjs +6 -0
  200. package/examples/grid-perception.mjs +12 -0
  201. package/examples/grid-strategy-worker.mjs +11 -0
  202. package/examples/grid-strategy.mjs +13 -0
  203. package/examples/run-grid-game.mjs +24 -0
  204. package/package.json +53 -4
@@ -0,0 +1,6 @@
1
+ /** Serializes compatibility ingress tasks without participating in epoch scheduling. */
2
+ export declare class SerialTaskQueue {
3
+ private tail;
4
+ run<T>(task: () => T | Promise<T>): Promise<T>;
5
+ flush(): Promise<void>;
6
+ }
@@ -0,0 +1,12 @@
1
+ /** Serializes compatibility ingress tasks without participating in epoch scheduling. */
2
+ export class SerialTaskQueue {
3
+ tail = Promise.resolve();
4
+ run(task) {
5
+ const result = this.tail.then(task, task);
6
+ this.tail = result.then(() => undefined, () => undefined);
7
+ return result;
8
+ }
9
+ async flush() {
10
+ await this.tail;
11
+ }
12
+ }
@@ -0,0 +1,30 @@
1
+ import type { ApplyStateResult, CurrentStateSnapshot, RuntimeConnectionState, RuntimeScope, StateFactPatch, StateFrameEnvelope } from './types.js';
2
+ export interface CurrentStateReader<TState = unknown> {
3
+ snapshot(): CurrentStateSnapshot<TState>;
4
+ }
5
+ export interface CurrentStateWriter<TState = unknown> extends CurrentStateReader<TState> {
6
+ openScope(scope: RuntimeScope, atMs?: number): CurrentStateSnapshot<TState>;
7
+ openConnection(connectionId: string, atMs?: number): CurrentStateSnapshot<TState>;
8
+ markConnectionState(connectionId: string, state: RuntimeConnectionState, atMs?: number): CurrentStateSnapshot<TState>;
9
+ markLiveness(connectionId: string, atMs?: number): boolean;
10
+ applyFacts(patches: StateFactPatch[], atMs?: number): CurrentStateSnapshot<TState>;
11
+ applyBackendState(frame: StateFrameEnvelope<TState>): ApplyStateResult<TState>;
12
+ clear(): void;
13
+ }
14
+ export interface StateIngressObserver<TState = unknown> {
15
+ onFrameAccepted?(frame: StateFrameEnvelope<TState>, result: Extract<ApplyStateResult<TState>, {
16
+ accepted: true;
17
+ }>): void | Promise<void>;
18
+ onConnectionChanged?(scope: RuntimeScope | null, connectionId: string, state: RuntimeConnectionState, atMs: number): void | Promise<void>;
19
+ onObserverError?(error: unknown): void;
20
+ }
21
+ /**
22
+ * Optional lifecycle hooks for observers that buffer durable side effects.
23
+ * State ingestion never waits for disk I/O, while the owner can still flush
24
+ * the last accepted frame before it exits.
25
+ */
26
+ export interface FlushableStateIngressObserver<TState = unknown> extends StateIngressObserver<TState> {
27
+ flush?(): Promise<void>;
28
+ close?(): Promise<void>;
29
+ }
30
+ export type StateViewProjector<TState, TView> = (snapshot: CurrentStateSnapshot<TState>) => TView;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { CurrentStateWriter } from './contracts.js';
2
+ import { type ApplyStateResult, type CurrentStateSnapshot, type RuntimeConnectionState, type RuntimeScope, type StateFactPatch, type StateFrameEnvelope } from './types.js';
3
+ export declare class CurrentStateStore<TState = unknown> implements CurrentStateWriter<TState> {
4
+ private currentScope;
5
+ private backendState;
6
+ private readonly sessionFacts;
7
+ private readonly segmentFacts;
8
+ private meta;
9
+ openScope(scope: RuntimeScope, _atMs?: number): CurrentStateSnapshot<TState>;
10
+ openConnection(connectionId: string, atMs?: number): CurrentStateSnapshot<TState>;
11
+ markConnectionState(connectionId: string, state: RuntimeConnectionState, atMs?: number): CurrentStateSnapshot<TState>;
12
+ markLiveness(connectionId: string, atMs?: number): boolean;
13
+ applyFacts(patches: StateFactPatch[], atMs?: number): CurrentStateSnapshot<TState>;
14
+ applyBackendState(frame: StateFrameEnvelope<TState>): ApplyStateResult<TState>;
15
+ snapshot(): CurrentStateSnapshot<TState>;
16
+ clear(): void;
17
+ }
@@ -0,0 +1,153 @@
1
+ import { cloneCanonical, sameRuntimeScope, sameRuntimeSession, } from './types.js';
2
+ function emptyMeta() {
3
+ return {
4
+ sourceId: null,
5
+ connectionId: null,
6
+ connectionState: 'disconnected',
7
+ awaitingFirstFrame: true,
8
+ receiveSeq: 0,
9
+ lastSourceSeq: null,
10
+ backendTick: null,
11
+ lastStateSourceKey: null,
12
+ lastStateReceivedAtMs: null,
13
+ lastStateReceivedMonotonicMs: null,
14
+ lastLivenessAtMs: null,
15
+ gapSinceMs: null,
16
+ };
17
+ }
18
+ function copyFactMap(source) {
19
+ return Object.fromEntries(Array.from(source.entries(), ([key, value]) => [key, cloneCanonical(value)]));
20
+ }
21
+ export class CurrentStateStore {
22
+ currentScope = null;
23
+ backendState = null;
24
+ sessionFacts = new Map();
25
+ segmentFacts = new Map();
26
+ meta = emptyMeta();
27
+ openScope(scope, _atMs = Date.now()) {
28
+ if (sameRuntimeScope(this.currentScope, scope))
29
+ return this.snapshot();
30
+ const sameSession = sameRuntimeSession(this.currentScope, scope);
31
+ if (!sameSession)
32
+ this.sessionFacts.clear();
33
+ this.segmentFacts.clear();
34
+ this.currentScope = cloneCanonical(scope);
35
+ this.backendState = null;
36
+ this.meta = emptyMeta();
37
+ return this.snapshot();
38
+ }
39
+ openConnection(connectionId, atMs = Date.now()) {
40
+ if (!this.currentScope)
41
+ throw new Error('Cannot open a connection before opening a scope');
42
+ if (!connectionId)
43
+ throw new Error('connectionId is required');
44
+ const isNewConnection = this.meta.connectionId !== connectionId;
45
+ if (isNewConnection) {
46
+ this.meta.connectionId = connectionId;
47
+ this.meta.receiveSeq = 0;
48
+ this.meta.lastSourceSeq = null;
49
+ this.meta.awaitingFirstFrame = true;
50
+ if (this.backendState !== null || this.meta.lastStateReceivedAtMs !== null) {
51
+ this.meta.gapSinceMs ??= atMs;
52
+ }
53
+ }
54
+ this.meta.connectionState = 'connected';
55
+ this.meta.lastLivenessAtMs = atMs;
56
+ return this.snapshot();
57
+ }
58
+ markConnectionState(connectionId, state, atMs = Date.now()) {
59
+ if (!this.meta.connectionId || this.meta.connectionId !== connectionId)
60
+ return this.snapshot();
61
+ this.meta.connectionState = state;
62
+ if (state !== 'connected') {
63
+ this.meta.gapSinceMs ??= atMs;
64
+ this.meta.awaitingFirstFrame = true;
65
+ }
66
+ return this.snapshot();
67
+ }
68
+ markLiveness(connectionId, atMs = Date.now()) {
69
+ if (!this.meta.connectionId || this.meta.connectionId !== connectionId)
70
+ return false;
71
+ this.meta.lastLivenessAtMs = atMs;
72
+ return true;
73
+ }
74
+ applyFacts(patches, atMs = Date.now()) {
75
+ if (!this.currentScope)
76
+ throw new Error('Cannot apply facts before opening a scope');
77
+ for (const patch of patches) {
78
+ if (!patch.key)
79
+ throw new Error('State fact key is required');
80
+ const target = patch.lifetime === 'session' ? this.sessionFacts : this.segmentFacts;
81
+ const other = patch.lifetime === 'session' ? this.segmentFacts : this.sessionFacts;
82
+ other.delete(patch.key);
83
+ target.set(patch.key, {
84
+ ...cloneCanonical(patch),
85
+ updatedAtMs: atMs,
86
+ });
87
+ }
88
+ return this.snapshot();
89
+ }
90
+ applyBackendState(frame) {
91
+ if (!this.currentScope) {
92
+ return { accepted: false, reason: 'scope_not_open', snapshot: this.snapshot() };
93
+ }
94
+ if (!sameRuntimeScope(this.currentScope, frame.scope)) {
95
+ return { accepted: false, reason: 'scope_mismatch', snapshot: this.snapshot() };
96
+ }
97
+ if (!this.meta.connectionId) {
98
+ return { accepted: false, reason: 'connection_not_open', snapshot: this.snapshot() };
99
+ }
100
+ if (this.meta.connectionId !== frame.connectionId) {
101
+ return { accepted: false, reason: 'stale_connection', snapshot: this.snapshot() };
102
+ }
103
+ if (frame.sourceSeq !== undefined
104
+ && this.meta.lastSourceSeq !== null
105
+ && (frame.sourceSeq === this.meta.lastSourceSeq
106
+ || (typeof frame.sourceSeq === 'number'
107
+ && typeof this.meta.lastSourceSeq === 'number'
108
+ && frame.sourceSeq < this.meta.lastSourceSeq))) {
109
+ return { accepted: false, reason: 'duplicate_or_out_of_order', snapshot: this.snapshot() };
110
+ }
111
+ const firstFrameAfterConnect = this.meta.awaitingFirstFrame;
112
+ this.backendState = cloneCanonical(frame.payload);
113
+ this.meta.sourceId = frame.sourceId ?? this.meta.sourceId;
114
+ this.meta.receiveSeq += 1;
115
+ this.meta.lastSourceSeq = frame.sourceSeq ?? this.meta.lastSourceSeq;
116
+ this.meta.backendTick = frame.backendTick ?? null;
117
+ this.meta.lastStateSourceKey = frame.sourceKey;
118
+ this.meta.lastStateReceivedAtMs = frame.receivedAtMs;
119
+ this.meta.lastStateReceivedMonotonicMs = frame.receivedMonotonicMs ?? null;
120
+ this.meta.lastLivenessAtMs = frame.receivedAtMs;
121
+ this.meta.connectionState = 'connected';
122
+ this.meta.awaitingFirstFrame = false;
123
+ this.meta.gapSinceMs = null;
124
+ return {
125
+ accepted: true,
126
+ receiveSeq: this.meta.receiveSeq,
127
+ firstFrameAfterConnect,
128
+ snapshot: this.snapshot(),
129
+ };
130
+ }
131
+ snapshot() {
132
+ const session = copyFactMap(this.sessionFacts);
133
+ const segment = copyFactMap(this.segmentFacts);
134
+ const globalFacts = {};
135
+ for (const [key, fact] of [...Object.entries(session), ...Object.entries(segment)]) {
136
+ globalFacts[key] = cloneCanonical(fact.value);
137
+ }
138
+ return {
139
+ scope: this.currentScope ? cloneCanonical(this.currentScope) : null,
140
+ backendState: this.backendState === null ? null : cloneCanonical(this.backendState),
141
+ globalFacts,
142
+ facts: { session, segment },
143
+ meta: cloneCanonical(this.meta),
144
+ };
145
+ }
146
+ clear() {
147
+ this.currentScope = null;
148
+ this.backendState = null;
149
+ this.sessionFacts.clear();
150
+ this.segmentFacts.clear();
151
+ this.meta = emptyMeta();
152
+ }
153
+ }
@@ -0,0 +1,61 @@
1
+ import type { FlushableStateIngressObserver } from './contracts.js';
2
+ import { type ApplyStateResult, type RuntimeScope, type StateFrameEnvelope, type StateFreshnessPolicy, type StateFreshnessPolicyResolver, type StateStatus } from './types.js';
3
+ export declare const DURABLE_AGENT_STATE_SNAPSHOT_FILE = "last-agent-state.json";
4
+ export declare const DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA = "ccl.last-agent-state.v1";
5
+ export interface DurableAgentStateSnapshot<TState = unknown> {
6
+ schema: typeof DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA;
7
+ scope: RuntimeScope;
8
+ state: TState;
9
+ stateStatus: StateStatus;
10
+ receivedAt: string;
11
+ }
12
+ export interface OfflineAgentStateSnapshot<TState = unknown> {
13
+ state: TState;
14
+ stateStatus: StateStatus;
15
+ scope: Omit<RuntimeScope, 'accountId'>;
16
+ }
17
+ export interface DurableAgentStateSnapshotObserverOptions<TState> {
18
+ freshnessPolicy?: StateFreshnessPolicy;
19
+ freshnessPolicyResolver?: StateFreshnessPolicyResolver;
20
+ isTerminal?: (state: TState) => boolean;
21
+ }
22
+ export declare function durableAgentStateSnapshotPath(stateDir: string): string;
23
+ /**
24
+ * A one-row durable cache. Writes are serialized and coalesced: transports do
25
+ * not block on disk, and flush() guarantees the newest accepted State reached
26
+ * an atomically replaced JSON file before owner shutdown completes.
27
+ */
28
+ export declare class AtomicJsonAgentStateSnapshotStore<TState = unknown> {
29
+ readonly path: string;
30
+ private pending;
31
+ private draining;
32
+ private lastErrorValue;
33
+ constructor(path: string);
34
+ enqueue(snapshot: DurableAgentStateSnapshot<TState>): void;
35
+ flush(): Promise<void>;
36
+ lastError(): unknown;
37
+ read(expectedScope?: RuntimeScope): Promise<DurableAgentStateSnapshot<TState> | null>;
38
+ private schedule;
39
+ private drain;
40
+ private writeAtomic;
41
+ }
42
+ /** Writes only accepted State frames; rejected/mismatched frames never replace the cache. */
43
+ export declare class DurableAgentStateSnapshotObserver<TState = unknown> implements FlushableStateIngressObserver<TState> {
44
+ private readonly store;
45
+ private readonly options;
46
+ private readonly freshness;
47
+ constructor(store: AtomicJsonAgentStateSnapshotStore<TState>, options?: DurableAgentStateSnapshotObserverOptions<TState>);
48
+ onFrameAccepted(frame: StateFrameEnvelope<TState>, result: Extract<ApplyStateResult<TState>, {
49
+ accepted: true;
50
+ }>): void;
51
+ flush(): Promise<void>;
52
+ }
53
+ /**
54
+ * Converts a same-scope durable row into an Agent-safe offline view. Internal
55
+ * account identity remains available for validation on disk and is removed at
56
+ * this single output boundary.
57
+ */
58
+ export declare function offlineAgentStateSnapshot<TState>(snapshot: DurableAgentStateSnapshot<TState>, options?: {
59
+ terminal?: boolean;
60
+ nowMs?: number;
61
+ }): OfflineAgentStateSnapshot<TState>;
@@ -0,0 +1,162 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { mkdir, readFile, rename, rm, writeFile } from 'fs/promises';
3
+ import { basename, dirname, join } from 'path';
4
+ import { StateFreshnessEvaluator } from './freshness.js';
5
+ import { cloneCanonical, sameRuntimeScope, } from './types.js';
6
+ export const DURABLE_AGENT_STATE_SNAPSHOT_FILE = 'last-agent-state.json';
7
+ export const DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA = 'ccl.last-agent-state.v1';
8
+ export function durableAgentStateSnapshotPath(stateDir) {
9
+ return join(stateDir, DURABLE_AGENT_STATE_SNAPSHOT_FILE);
10
+ }
11
+ function publicScope(scope) {
12
+ const { accountId: _accountId, ...safe } = scope;
13
+ return safe;
14
+ }
15
+ function isRuntimeScope(value) {
16
+ if (!value || typeof value !== 'object')
17
+ return false;
18
+ const scope = value;
19
+ return ['adapterId', 'accountId', 'sessionId', 'segmentId']
20
+ .every((key) => typeof scope[key] === 'string' && scope[key] !== '');
21
+ }
22
+ function isSnapshot(value) {
23
+ if (!value || typeof value !== 'object')
24
+ return false;
25
+ const row = value;
26
+ return row.schema === DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA
27
+ && isRuntimeScope(row.scope)
28
+ && Object.prototype.hasOwnProperty.call(row, 'state')
29
+ && !!row.stateStatus
30
+ && typeof row.stateStatus === 'object'
31
+ && typeof row.receivedAt === 'string'
32
+ && Number.isFinite(Date.parse(row.receivedAt));
33
+ }
34
+ /**
35
+ * A one-row durable cache. Writes are serialized and coalesced: transports do
36
+ * not block on disk, and flush() guarantees the newest accepted State reached
37
+ * an atomically replaced JSON file before owner shutdown completes.
38
+ */
39
+ export class AtomicJsonAgentStateSnapshotStore {
40
+ path;
41
+ pending = null;
42
+ draining = null;
43
+ lastErrorValue = null;
44
+ constructor(path) {
45
+ this.path = path;
46
+ }
47
+ enqueue(snapshot) {
48
+ this.pending = cloneCanonical(snapshot);
49
+ this.schedule();
50
+ }
51
+ async flush() {
52
+ while (this.pending || this.draining) {
53
+ this.schedule();
54
+ if (this.draining)
55
+ await this.draining;
56
+ }
57
+ }
58
+ lastError() {
59
+ return this.lastErrorValue;
60
+ }
61
+ async read(expectedScope) {
62
+ try {
63
+ const parsed = JSON.parse(await readFile(this.path, 'utf8'));
64
+ if (!isSnapshot(parsed))
65
+ return null;
66
+ if (expectedScope && !sameRuntimeScope(parsed.scope, expectedScope))
67
+ return null;
68
+ return cloneCanonical(parsed);
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ schedule() {
75
+ if (this.draining || !this.pending)
76
+ return;
77
+ this.draining = this.drain().finally(() => {
78
+ this.draining = null;
79
+ if (this.pending)
80
+ this.schedule();
81
+ });
82
+ }
83
+ async drain() {
84
+ while (this.pending) {
85
+ const snapshot = this.pending;
86
+ this.pending = null;
87
+ try {
88
+ await this.writeAtomic(snapshot);
89
+ this.lastErrorValue = null;
90
+ }
91
+ catch (error) {
92
+ // Current State remains available in owner memory. Persistence failure
93
+ // is observable but must never roll back or block State ingestion.
94
+ this.lastErrorValue = error;
95
+ }
96
+ }
97
+ }
98
+ async writeAtomic(snapshot) {
99
+ const directory = dirname(this.path);
100
+ const temporary = join(directory, `.${basename(this.path)}.${process.pid}.${randomUUID()}.tmp`);
101
+ await mkdir(directory, { recursive: true });
102
+ try {
103
+ await writeFile(temporary, `${JSON.stringify(snapshot)}\n`, 'utf8');
104
+ await rename(temporary, this.path);
105
+ }
106
+ finally {
107
+ await rm(temporary, { force: true }).catch(() => undefined);
108
+ }
109
+ }
110
+ }
111
+ /** Writes only accepted State frames; rejected/mismatched frames never replace the cache. */
112
+ export class DurableAgentStateSnapshotObserver {
113
+ store;
114
+ options;
115
+ freshness;
116
+ constructor(store, options = {}) {
117
+ this.store = store;
118
+ this.options = options;
119
+ this.freshness = new StateFreshnessEvaluator(options.freshnessPolicy, options.freshnessPolicyResolver);
120
+ }
121
+ onFrameAccepted(frame, result) {
122
+ const stateStatus = this.freshness.evaluate(result.snapshot, frame.scope, frame.receivedAtMs);
123
+ if (this.options.isTerminal?.(frame.payload))
124
+ stateStatus.terminal = true;
125
+ this.store.enqueue({
126
+ schema: DURABLE_AGENT_STATE_SNAPSHOT_SCHEMA,
127
+ scope: cloneCanonical(frame.scope),
128
+ state: cloneCanonical(frame.payload),
129
+ stateStatus,
130
+ receivedAt: new Date(frame.receivedAtMs).toISOString(),
131
+ });
132
+ }
133
+ flush() {
134
+ return this.store.flush();
135
+ }
136
+ }
137
+ /**
138
+ * Converts a same-scope durable row into an Agent-safe offline view. Internal
139
+ * account identity remains available for validation on disk and is removed at
140
+ * this single output boundary.
141
+ */
142
+ export function offlineAgentStateSnapshot(snapshot, options = {}) {
143
+ const terminal = options.terminal === true || snapshot.stateStatus.terminal === true;
144
+ const nowMs = options.nowMs ?? Date.now();
145
+ const receivedAtMs = Date.parse(snapshot.receivedAt);
146
+ const scope = publicScope(snapshot.scope);
147
+ return {
148
+ state: cloneCanonical(snapshot.state),
149
+ scope,
150
+ stateStatus: {
151
+ ...cloneCanonical(snapshot.stateStatus),
152
+ status: 'stale',
153
+ source: 'durable_snapshot',
154
+ scope: scope,
155
+ connectionState: 'owner_unavailable',
156
+ receivedAtMs: Number.isFinite(receivedAtMs) ? receivedAtMs : snapshot.stateStatus.receivedAtMs,
157
+ ageMs: Number.isFinite(receivedAtMs) ? Math.max(0, nowMs - receivedAtMs) : null,
158
+ reason: terminal ? 'terminal_snapshot' : 'owner_offline',
159
+ terminal,
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,7 @@
1
+ import { type CurrentStateSnapshot, type RuntimeScope, type StateFreshnessPolicy, type StateFreshnessPolicyResolver, type StateStatus } from './types.js';
2
+ export declare class StateFreshnessEvaluator {
3
+ private readonly policy;
4
+ private readonly resolvePolicy?;
5
+ constructor(policy?: StateFreshnessPolicy, resolvePolicy?: StateFreshnessPolicyResolver | undefined);
6
+ evaluate(snapshot: CurrentStateSnapshot, expectedScope?: RuntimeScope | null, nowMs?: number): StateStatus;
7
+ }
@@ -0,0 +1,52 @@
1
+ import { sameRuntimeScope, } from './types.js';
2
+ export class StateFreshnessEvaluator {
3
+ policy;
4
+ resolvePolicy;
5
+ constructor(policy = {}, resolvePolicy) {
6
+ this.policy = policy;
7
+ this.resolvePolicy = resolvePolicy;
8
+ }
9
+ evaluate(snapshot, expectedScope, nowMs = Date.now()) {
10
+ const base = {
11
+ semantics: 'latest_received',
12
+ scope: snapshot.scope,
13
+ connectionId: snapshot.meta.connectionId,
14
+ connectionState: snapshot.meta.connectionState,
15
+ receivedAtMs: snapshot.meta.lastStateReceivedAtMs,
16
+ ageMs: snapshot.meta.lastStateReceivedAtMs === null
17
+ ? null
18
+ : Math.max(0, nowMs - snapshot.meta.lastStateReceivedAtMs),
19
+ backendTick: snapshot.meta.backendTick,
20
+ };
21
+ if (!snapshot.scope) {
22
+ return { ...base, status: 'unavailable', source: null, reason: 'scope_not_open' };
23
+ }
24
+ if (expectedScope && !sameRuntimeScope(snapshot.scope, expectedScope)) {
25
+ return { ...base, status: 'unavailable', source: null, reason: 'scope_mismatch' };
26
+ }
27
+ if (snapshot.backendState === null || snapshot.meta.lastStateReceivedAtMs === null) {
28
+ return { ...base, status: 'unavailable', source: null, reason: 'state_not_received' };
29
+ }
30
+ if (snapshot.meta.connectionState !== 'connected') {
31
+ return { ...base, status: 'stale', source: 'owner_memory', reason: `connection_${snapshot.meta.connectionState}` };
32
+ }
33
+ if (snapshot.meta.awaitingFirstFrame) {
34
+ return { ...base, status: 'stale', source: 'owner_memory', reason: 'awaiting_first_frame' };
35
+ }
36
+ if (snapshot.meta.gapSinceMs !== null) {
37
+ return { ...base, status: 'stale', source: 'owner_memory', reason: 'stream_gap' };
38
+ }
39
+ const effectivePolicy = this.resolvePolicy?.(snapshot.meta.sourceId, snapshot) ?? this.policy;
40
+ const { maxLivenessSilenceMs, maxStateSilenceMs } = effectivePolicy;
41
+ if (maxLivenessSilenceMs !== undefined
42
+ && (snapshot.meta.lastLivenessAtMs === null
43
+ || nowMs - snapshot.meta.lastLivenessAtMs > maxLivenessSilenceMs)) {
44
+ return { ...base, status: 'stale', source: 'owner_memory', reason: 'liveness_timeout' };
45
+ }
46
+ if (maxStateSilenceMs !== undefined
47
+ && nowMs - snapshot.meta.lastStateReceivedAtMs > maxStateSilenceMs) {
48
+ return { ...base, status: 'stale', source: 'owner_memory', reason: 'state_silence_timeout' };
49
+ }
50
+ return { ...base, status: 'fresh', source: 'owner_memory', reason: null };
51
+ }
52
+ }
@@ -0,0 +1,133 @@
1
+ import type { RuntimeScope } from '../types.js';
2
+ export type TrajectorySubjectKind = 'self' | 'player' | 'system';
3
+ export type TrajectoryRecordKind = 'position' | 'visibility_gained' | 'visibility_lost' | 'stream_gap_started' | 'stream_gap_ended' | 'persistence_gap_started' | 'persistence_gap_ended' | 'retention_trimmed';
4
+ export interface TrajectoryRecord<TPosition = unknown> {
5
+ recordId: string;
6
+ recordSeq?: number;
7
+ scope: RuntimeScope;
8
+ connectionId?: string;
9
+ subjectId: string;
10
+ subjectKind: TrajectorySubjectKind;
11
+ kind: TrajectoryRecordKind;
12
+ sourceType: 'backend_state' | 'canonical_event' | 'local_lifecycle';
13
+ sourceKey: string;
14
+ sourceSeq?: number | string;
15
+ backendTick?: number;
16
+ observedAtMs?: number;
17
+ receivedAtMs: number;
18
+ spaceId?: string;
19
+ areaId?: string;
20
+ position?: TPosition;
21
+ attributes?: Record<string, unknown>;
22
+ }
23
+ export interface HistoryScopeRecord {
24
+ scope: RuntimeScope;
25
+ status: 'OPEN' | 'SEALED';
26
+ openedAtMs: number;
27
+ sealedAtMs: number | null;
28
+ historyComplete: boolean;
29
+ historyRevision: number;
30
+ }
31
+ export interface HistoryQuery {
32
+ scope: RuntimeScope;
33
+ subjectIds?: string[];
34
+ kinds?: TrajectoryRecordKind[];
35
+ afterRecordSeq?: number;
36
+ beforeRecordSeq?: number;
37
+ order?: 'asc' | 'desc';
38
+ limit?: number;
39
+ }
40
+ export interface HistoryQueryResult<TPosition = unknown> {
41
+ scope: HistoryScopeRecord | null;
42
+ records: Array<TrajectoryRecord<TPosition> & {
43
+ recordSeq: number;
44
+ }>;
45
+ page: {
46
+ order: 'asc' | 'desc';
47
+ limit: number;
48
+ hasMore: boolean;
49
+ firstRecordSeq: number | null;
50
+ lastRecordSeq: number | null;
51
+ };
52
+ }
53
+ export interface AppendHistoryResult {
54
+ inserted: number;
55
+ duplicates: number;
56
+ }
57
+ export interface StateFrameRecord<TState = Record<string, unknown>> {
58
+ frameSeq?: number;
59
+ /** Runtime epoch that admitted this complete State. */
60
+ epochSeq?: number;
61
+ scope: RuntimeScope;
62
+ sourceId?: string;
63
+ connectionId: string;
64
+ /** Stable accepted-frame identity within the scope. */
65
+ sourceKey: string;
66
+ sourceSeq?: number | string;
67
+ backendTick?: number;
68
+ observedAtMs?: number;
69
+ receivedAtMs: number;
70
+ state: TState;
71
+ }
72
+ export interface StoredStateFrame<TState = Record<string, unknown>> extends StateFrameRecord<TState> {
73
+ frameSeq: number;
74
+ }
75
+ export interface StateFrameQuery {
76
+ scope: RuntimeScope;
77
+ /** Runtime epoch bounds. A plugin invocation may read only its epoch and earlier epochs. */
78
+ fromEpochSeq?: number;
79
+ toEpochSeq?: number;
80
+ afterFrameSeq?: number;
81
+ beforeFrameSeq?: number;
82
+ fromBackendTick?: number;
83
+ toBackendTick?: number;
84
+ order?: 'asc' | 'desc';
85
+ limit?: number;
86
+ }
87
+ export interface StateFrameQueryResult<TState = Record<string, unknown>> {
88
+ frames: StoredStateFrame<TState>[];
89
+ page: {
90
+ order: 'asc' | 'desc';
91
+ limit: number;
92
+ hasMore: boolean;
93
+ firstFrameSeq: number | null;
94
+ lastFrameSeq: number | null;
95
+ };
96
+ }
97
+ export interface AppendStateFrameResult<TState = Record<string, unknown>> {
98
+ inserted: boolean;
99
+ frame: StoredStateFrame<TState>;
100
+ }
101
+ export interface StateHistorySnapshot<TPosition = unknown, TState = Record<string, unknown>> {
102
+ scopes: HistoryScopeRecord[];
103
+ stateFrames: StoredStateFrame<TState>[];
104
+ records: Array<TrajectoryRecord<TPosition> & {
105
+ recordSeq: number;
106
+ }>;
107
+ nextFrameSeq: number;
108
+ nextRecordSeq: number;
109
+ }
110
+ export interface StateFrameHistoryReader<TState = Record<string, unknown>> {
111
+ /** Reads the canonical accepted State journal. Implementations may use a hot cache. */
112
+ queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState>;
113
+ latestStateFrame(scope: RuntimeScope): StoredStateFrame<TState> | null;
114
+ }
115
+ /**
116
+ * Durable journal for complete accepted State frames. Game-specific projections
117
+ * are derived from this journal and must be rebuildable from it.
118
+ */
119
+ export interface StateJournal<TState = Record<string, unknown>> extends StateFrameHistoryReader<TState> {
120
+ openScope(scope: RuntimeScope, openedAtMs?: number, historyComplete?: boolean): HistoryScopeRecord;
121
+ sealScope(scope: RuntimeScope, sealedAtMs?: number): void;
122
+ markScopeIncomplete(scope: RuntimeScope): void;
123
+ getScope(scope: RuntimeScope): HistoryScopeRecord | null;
124
+ appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState>;
125
+ close?(): void | Promise<void>;
126
+ }
127
+ /** Sparse records used by transport-gap diagnostics and adapters that explicitly project them. */
128
+ export interface TrajectoryHistoryRepository<TPosition = unknown> {
129
+ append(records: TrajectoryRecord<TPosition>[]): AppendHistoryResult;
130
+ query(query: HistoryQuery): HistoryQueryResult<TPosition>;
131
+ }
132
+ export interface StateHistoryRepository<TPosition = unknown, TState = Record<string, unknown>> extends StateJournal<TState>, TrajectoryHistoryRepository<TPosition> {
133
+ }
@@ -0,0 +1 @@
1
+ export {};