@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,81 @@
1
+ import type { StrategyDecision } from './contracts.js';
2
+ import type { StrategyMemory } from '../memory/contracts.js';
3
+ import type { RuntimeDiagnosticSeverity } from '../framework/plugins/contracts.js';
4
+ import { type StrategyThreadSource, type StrategyThreadBridge } from './thread-strategy-executor.js';
5
+ import { type DetailCaptureConfig } from '../observability/detail-capture.js';
6
+ import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
7
+ export interface ScriptFrame {
8
+ readonly epochId: number;
9
+ readonly scope: Readonly<{
10
+ sessionId: string;
11
+ segmentId: string;
12
+ }>;
13
+ }
14
+ export interface StrategyScript<Frame, Decision, Api> {
15
+ decide(input: Readonly<Frame>, api: Api): Decision | void | Promise<Decision | void>;
16
+ }
17
+ export interface PreparedStrategyScript<Frame, Decision, Api, Source extends StrategyThreadSource> {
18
+ readonly module?: StrategyScript<Frame, Decision, Api>;
19
+ readonly manifest: {
20
+ readonly execution?: 'serial' | 'parallel';
21
+ readonly everyTicks?: number;
22
+ };
23
+ readonly source?: Source;
24
+ }
25
+ export interface ScriptApiContext<Observation> {
26
+ readonly memory?: StrategyMemory;
27
+ readonly isActive: () => boolean;
28
+ readonly onQuery: () => void;
29
+ readonly observationSnapshot?: Readonly<Observation>;
30
+ }
31
+ export interface StrategyScriptRunnerOptions<Frame extends ScriptFrame, Decision extends StrategyDecision, Api, Source extends StrategyThreadSource, Observation> {
32
+ readonly bridge: StrategyThreadBridge<Source>;
33
+ readonly createApi: (input: Readonly<Frame>, context: ScriptApiContext<Observation>) => Api;
34
+ readonly normalize: (value: unknown) => Decision;
35
+ readonly inputMetadata?: (input: Readonly<Frame>) => Readonly<Record<string, unknown>>;
36
+ readonly captureConfig?: DetailCaptureConfig;
37
+ readonly memory?: (input: Readonly<Frame>, isActive: () => boolean) => StrategyMemory;
38
+ readonly snapshotStore?: BehaviorSnapshotStore;
39
+ readonly behaviorId: string;
40
+ readonly activationId: string;
41
+ readonly instanceGeneration: number;
42
+ readonly prepared: PreparedStrategyScript<Frame, Decision, Api, Source>;
43
+ readonly diagnostic?: (name: string, attributes?: Readonly<Record<string, unknown>>, severity?: RuntimeDiagnosticSeverity) => void;
44
+ readonly isActive: () => boolean;
45
+ readonly diagnosticsEnabled?: boolean;
46
+ }
47
+ /**
48
+ * One Activation-generation runner. Serial retains one instance; parallel
49
+ * creates an isolated instance per computation. Source modules run in Workers.
50
+ */
51
+ export declare class StrategyScriptRunner<Frame extends ScriptFrame, Decision extends StrategyDecision, Api, Source extends StrategyThreadSource, Observation = unknown> {
52
+ private readonly options;
53
+ readonly behaviorId: string;
54
+ readonly activationId: string;
55
+ readonly instanceGeneration: number;
56
+ readonly prepared: PreparedStrategyScript<Frame, Decision, Api, Source>;
57
+ private serialModule?;
58
+ private serialTail;
59
+ private readonly parallelLifecycle;
60
+ private parallelExecutor?;
61
+ private parallelReady?;
62
+ private parallelStop?;
63
+ private stopped;
64
+ private readonly capture;
65
+ constructor(options: StrategyScriptRunnerOptions<Frame, Decision, Api, Source, Observation>);
66
+ get execution(): 'parallel' | 'serial';
67
+ /** Start/import Workers at activation, outside per-decision computation deadlines. */
68
+ prepare(): Promise<void>;
69
+ get everyTicks(): number;
70
+ diagnosticSnapshot(): Readonly<Record<string, unknown>>;
71
+ decideSerial(input: Readonly<Frame>, signal: AbortSignal, observationSnapshot?: Readonly<Observation>): Promise<Decision>;
72
+ private decideSerialInternal;
73
+ decideParallel(input: Readonly<Frame>, signal: AbortSignal, observationSnapshot?: Readonly<Observation>): Promise<Decision>;
74
+ private traceDecision;
75
+ stop(reason?: 'switched' | 'scope_ended' | 'shutdown'): Promise<void>;
76
+ private invokeThread;
77
+ private ensureThreadExecutor;
78
+ private invoke;
79
+ private diagnostic;
80
+ private enqueue;
81
+ }
@@ -0,0 +1,235 @@
1
+ import { ThreadStrategyExecutor } from './thread-strategy-executor.js';
2
+ import { DetailCapture } from '../observability/detail-capture.js';
3
+ function errorCode(error) {
4
+ const message = error instanceof Error ? error.message : String(error);
5
+ return /^[A-Za-z][A-Za-z0-9_.:-]{0,159}$/.test(message)
6
+ ? message
7
+ : 'BEHAVIOR_DECIDE_FAILED';
8
+ }
9
+ function abortError(signal) {
10
+ return signal.reason instanceof Error
11
+ ? signal.reason
12
+ : new Error('behavior_decide_aborted');
13
+ }
14
+ /**
15
+ * One Activation-generation runner. Serial retains one instance; parallel
16
+ * creates an isolated instance per computation. Source modules run in Workers.
17
+ */
18
+ export class StrategyScriptRunner {
19
+ options;
20
+ behaviorId;
21
+ activationId;
22
+ instanceGeneration;
23
+ prepared;
24
+ serialModule;
25
+ serialTail = Promise.resolve();
26
+ parallelLifecycle = new AbortController();
27
+ parallelExecutor;
28
+ parallelReady;
29
+ parallelStop;
30
+ stopped = false;
31
+ capture;
32
+ constructor(options) {
33
+ this.options = options;
34
+ this.behaviorId = options.behaviorId;
35
+ this.activationId = options.activationId;
36
+ this.instanceGeneration = options.instanceGeneration;
37
+ this.prepared = options.prepared;
38
+ this.serialModule = options.prepared.module;
39
+ this.capture = new DetailCapture('behavior_io', options.diagnostic, options.captureConfig);
40
+ }
41
+ get execution() {
42
+ return this.prepared.manifest.execution ?? 'parallel';
43
+ }
44
+ /** Start/import Workers at activation, outside per-decision computation deadlines. */
45
+ async prepare() {
46
+ if (!this.prepared.source)
47
+ return;
48
+ this.ensureThreadExecutor();
49
+ await this.parallelReady;
50
+ }
51
+ get everyTicks() {
52
+ return this.prepared.manifest.everyTicks ?? 1;
53
+ }
54
+ diagnosticSnapshot() {
55
+ const pool = this.parallelExecutor?.snapshot();
56
+ return Object.freeze({
57
+ execution: this.execution,
58
+ every_ticks: this.everyTicks,
59
+ stopped: this.stopped,
60
+ worker_pool: pool
61
+ ? {
62
+ state: pool.state,
63
+ worker_count: pool.workerCount,
64
+ idle_worker_count: pool.idleWorkerCount,
65
+ busy_worker_count: pool.busyWorkerCount,
66
+ queued_request_count: pool.queuedRequestCount,
67
+ in_flight_request_count: pool.inFlightRequestCount,
68
+ started_worker_count: pool.startedWorkerCount,
69
+ retired_worker_count: pool.retiredWorkerCount,
70
+ worker_heap_used_bytes: pool.workerHeapUsedBytes,
71
+ peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes,
72
+ }
73
+ : null,
74
+ });
75
+ }
76
+ decideSerial(input, signal, observationSnapshot) {
77
+ return this.traceDecision(input, observationSnapshot, signal, () => this.decideSerialInternal(input, signal, observationSnapshot));
78
+ }
79
+ decideSerialInternal(input, signal, observationSnapshot) {
80
+ if (this.prepared.source) {
81
+ return this.enqueue(() => this.invokeThread(input, signal, observationSnapshot));
82
+ }
83
+ const module = this.serialModule;
84
+ if (!module)
85
+ return Promise.reject(new Error('behavior_serial_module_missing'));
86
+ return this.enqueue(() => this.invoke(module, input, signal, observationSnapshot));
87
+ }
88
+ decideParallel(input, signal, observationSnapshot) {
89
+ return this.traceDecision(input, observationSnapshot, signal, () => this.invokeThread(input, signal, observationSnapshot));
90
+ }
91
+ traceDecision(input, observationSnapshot, signal, invoke) {
92
+ if (!this.capture.enabled)
93
+ return invoke();
94
+ return this.capture.run('decide', {
95
+ behavior_id: this.behaviorId, activation_id: this.activationId, instance_generation: this.instanceGeneration,
96
+ epoch_id: input.epochId, ...(this.options.inputMetadata?.(input) ?? {}),
97
+ session_id: input.scope.sessionId, segment_id: input.scope.segmentId, execution: this.execution,
98
+ }, { frame: input, observation: observationSnapshot }, invoke, signal);
99
+ }
100
+ stop(reason = 'switched') {
101
+ if (this.parallelStop)
102
+ return this.parallelStop;
103
+ this.stopped = true;
104
+ this.parallelLifecycle.abort(new Error(`behavior_runner_stopped:${reason}`));
105
+ const executor = this.parallelExecutor;
106
+ this.parallelExecutor = undefined;
107
+ this.parallelReady = undefined;
108
+ this.parallelStop = executor?.stop(reason) ?? Promise.resolve();
109
+ return this.parallelStop;
110
+ }
111
+ async invokeThread(input, signal, observationSnapshot) {
112
+ if (this.stopped)
113
+ throw new Error('behavior_runner_stopped');
114
+ if (signal.aborted)
115
+ throw abortError(signal);
116
+ if (!this.options.isActive())
117
+ throw new Error('behavior_activation_superseded');
118
+ const executor = this.ensureThreadExecutor();
119
+ await this.parallelReady;
120
+ if (this.stopped)
121
+ throw new Error('behavior_runner_stopped');
122
+ if (signal.aborted)
123
+ throw abortError(signal);
124
+ if (!this.options.isActive())
125
+ throw new Error('behavior_activation_superseded');
126
+ const decision = await executor.update(input, signal, observationSnapshot);
127
+ if (signal.aborted)
128
+ throw abortError(signal);
129
+ if (!this.options.isActive())
130
+ throw new Error('behavior_activation_superseded');
131
+ return decision;
132
+ }
133
+ ensureThreadExecutor() {
134
+ if (this.parallelExecutor)
135
+ return this.parallelExecutor;
136
+ const source = this.prepared.source;
137
+ if (!source)
138
+ throw new Error('behavior_thread_source_missing');
139
+ if (source.id !== this.behaviorId || source.execution !== this.execution) {
140
+ throw new Error('behavior_thread_source_invalid');
141
+ }
142
+ const executor = new ThreadStrategyExecutor({
143
+ bridge: this.options.bridge, inputMetadata: this.options.inputMetadata,
144
+ memory: this.options.memory && ((frame, active) => this.options.memory(frame, () => active() && !this.stopped && this.options.isActive())),
145
+ fixedWorkers: true,
146
+ snapshotStore: this.options.snapshotStore,
147
+ source,
148
+ diagnostic: this.options.diagnostic,
149
+ diagnosticsEnabled: this.options.diagnosticsEnabled,
150
+ });
151
+ this.parallelExecutor = executor;
152
+ this.parallelReady = executor.start(this.parallelLifecycle.signal);
153
+ return executor;
154
+ }
155
+ async invoke(module, input, signal, observationSnapshot) {
156
+ if (this.stopped)
157
+ throw new Error('behavior_runner_stopped');
158
+ if (signal.aborted)
159
+ throw abortError(signal);
160
+ if (!this.options.isActive())
161
+ throw new Error('behavior_activation_superseded');
162
+ const startedAt = performance.now();
163
+ let invocationActive = true;
164
+ let queryCount = 0;
165
+ const api = this.options.createApi(input, {
166
+ memory: this.options.memory?.(input, () => invocationActive && !signal.aborted && !this.stopped && this.options.isActive()),
167
+ isActive: () => invocationActive
168
+ && !signal.aborted
169
+ && !this.stopped
170
+ && this.options.isActive(),
171
+ onQuery: () => { queryCount += 1; },
172
+ ...(observationSnapshot === undefined ? {} : { observationSnapshot }),
173
+ });
174
+ this.diagnostic('behavior.decide.started', {
175
+ behavior_id: this.behaviorId,
176
+ activation_id: this.activationId,
177
+ instance_generation: this.instanceGeneration,
178
+ epoch_id: input.epochId,
179
+ execution: this.execution,
180
+ }, 'debug');
181
+ try {
182
+ const decision = this.options.normalize(await module.decide(input, api));
183
+ if (signal.aborted)
184
+ throw abortError(signal);
185
+ if (!this.options.isActive())
186
+ throw new Error('behavior_activation_superseded');
187
+ this.diagnostic('behavior.decide.completed', {
188
+ behavior_id: this.behaviorId,
189
+ activation_id: this.activationId,
190
+ instance_generation: this.instanceGeneration,
191
+ epoch_id: input.epochId,
192
+ ...(this.options.inputMetadata?.(input) ?? {}),
193
+ duration_ms: Math.round(performance.now() - startedAt),
194
+ read_query_count: queryCount,
195
+ action_count: decision.actions?.length ?? 0,
196
+ action_kinds: (decision.actions ?? []).map((action) => action.action),
197
+ empty_decision: (decision.actions?.length ?? 0) === 0,
198
+ event_count: decision.events?.length ?? 0,
199
+ finished: decision.finish !== undefined,
200
+ execution: this.execution,
201
+ }, 'debug');
202
+ return decision;
203
+ }
204
+ catch (error) {
205
+ this.diagnostic('behavior.decide.failed', {
206
+ behavior_id: this.behaviorId,
207
+ activation_id: this.activationId,
208
+ instance_generation: this.instanceGeneration,
209
+ epoch_id: input.epochId,
210
+ ...(this.options.inputMetadata?.(input) ?? {}),
211
+ duration_ms: Math.round(performance.now() - startedAt),
212
+ read_query_count: queryCount,
213
+ error_code: errorCode(error),
214
+ execution: this.execution,
215
+ }, signal.aborted ? 'debug' : 'error');
216
+ throw error;
217
+ }
218
+ finally {
219
+ invocationActive = false;
220
+ }
221
+ }
222
+ diagnostic(name, attributes, severity) {
223
+ try {
224
+ this.options.diagnostic?.(name, attributes, severity);
225
+ }
226
+ catch {
227
+ // Diagnostics are observational and never alter module execution.
228
+ }
229
+ }
230
+ enqueue(operation) {
231
+ const pending = this.serialTail.then(operation, operation);
232
+ this.serialTail = pending.then(() => undefined, () => undefined);
233
+ return pending;
234
+ }
235
+ }
@@ -0,0 +1,27 @@
1
+ import type { StrategyThreadSource, BehaviorTiming } from './thread-strategy-executor.js';
2
+ import type { ScriptApiContext, StrategyScript } from './strategy-script-runner.js';
3
+ export interface StrategyWorkerData<Source extends StrategyThreadSource> {
4
+ readonly poolId: string;
5
+ readonly slotId: number;
6
+ readonly source: Source;
7
+ readonly sourceUrl: string;
8
+ readonly diagnosticsEnabled?: boolean;
9
+ readonly prepareInput?: Readonly<Record<string, unknown>>;
10
+ }
11
+ export interface StrategyWorkerModule<Frame, Decision, Api> {
12
+ readonly execution: 'serial' | 'parallel';
13
+ readonly stateMode?: 'isolated' | 'snapshot';
14
+ create(): StrategyScript<Frame, Decision, Api>;
15
+ prepare(input: Readonly<Record<string, unknown>>): {
16
+ manifest: unknown;
17
+ input: Readonly<Record<string, unknown>>;
18
+ timing?: BehaviorTiming;
19
+ };
20
+ }
21
+ export interface StrategyWorkerAdapter<Source extends StrategyThreadSource, Frame, Decision, Api, Observation> {
22
+ load(data: StrategyWorkerData<Source>): Promise<StrategyWorkerModule<Frame, Decision, Api>>;
23
+ createApi(input: Readonly<Frame>, context: ScriptApiContext<Observation>): Api;
24
+ normalize(value: unknown): Decision;
25
+ }
26
+ /** Worker-side lifecycle/RPC/snapshots. The adapter supplies only SDK and domain semantics. */
27
+ export declare function runStrategyWorker<Source extends StrategyThreadSource, Frame, Decision, Api, Observation>(adapter: StrategyWorkerAdapter<Source, Frame, Decision, Api, Observation>): Promise<void>;
@@ -0,0 +1,96 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { parentPort, workerData } from 'node:worker_threads';
3
+ import { StrategyMemoryRpcClient } from '../memory/strategy-memory-rpc.js';
4
+ import { assertRuntimeModuleOutputSize } from '../framework/modules/runtime-module-output.js';
5
+ import { captureBehaviorInstance, restoreBehaviorInstance } from './behavior-instance-snapshot.js';
6
+ function freeze(value, seen = new WeakSet()) {
7
+ if (!value || typeof value !== 'object' || seen.has(value))
8
+ return value;
9
+ seen.add(value);
10
+ for (const child of Object.values(value))
11
+ freeze(child, seen);
12
+ return Object.freeze(value);
13
+ }
14
+ function errorMessage(error) { return error instanceof Error ? error.message : String(error); }
15
+ function errorCode(error, fallback) {
16
+ const explicit = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' ? error.code.trim() : '';
17
+ if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(explicit))
18
+ return explicit;
19
+ return /^([A-Za-z][A-Za-z0-9_.-]{0,119})(?::|$)/.exec(errorMessage(error).trim())?.[1] ?? fallback;
20
+ }
21
+ /** Worker-side lifecycle/RPC/snapshots. The adapter supplies only SDK and domain semantics. */
22
+ export async function runStrategyWorker(adapter) {
23
+ const port = parentPort;
24
+ if (!port)
25
+ throw new Error('behavior_thread_parent_missing');
26
+ const data = workerData;
27
+ if (!data || typeof data.poolId !== 'string' || typeof data.slotId !== 'number' || !data.source || typeof data.sourceUrl !== 'string') {
28
+ throw new Error('behavior_thread_worker_data_invalid');
29
+ }
30
+ const send = (value) => port.postMessage({ ...value, poolId: data.poolId, slotId: data.slotId });
31
+ const diagnosticMemory = () => data.diagnosticsEnabled === true ? { heapUsedBytes: process.memoryUsage().heapUsed } : {};
32
+ const memory = new StrategyMemoryRpcClient(send);
33
+ let loaded;
34
+ let preparation;
35
+ let serialInstance;
36
+ try {
37
+ loaded = await adapter.load(data);
38
+ if (data.prepareInput !== undefined) {
39
+ preparation = loaded.prepare(data.prepareInput);
40
+ assertRuntimeModuleOutputSize(preparation.input, 'behavior_normalize_output');
41
+ }
42
+ if (loaded.execution === 'serial' && data.prepareInput === undefined)
43
+ serialInstance = loaded.create();
44
+ }
45
+ catch (error) {
46
+ send({ type: 'error', code: errorCode(error, 'BEHAVIOR_THREAD_START_FAILED'), message: errorMessage(error) });
47
+ throw error;
48
+ }
49
+ const run = async (request) => {
50
+ if (!request || typeof request !== 'object' || request.poolId !== data.poolId || typeof request.requestId !== 'string') {
51
+ throw new Error('behavior_thread_request_invalid');
52
+ }
53
+ if (request.type === 'stop') {
54
+ send({ type: 'stopped', requestId: request.requestId });
55
+ return;
56
+ }
57
+ if (request.type !== 'run' || request.operation !== 'decide')
58
+ throw new Error('behavior_thread_request_invalid');
59
+ if (!request.frame || typeof request.frame !== 'object')
60
+ throw new Error('behavior_thread_frame_invalid');
61
+ const started = performance.now();
62
+ let queryCount = 0, invocationActive = true;
63
+ const input = freeze(structuredClone(request.frame));
64
+ const instance = loaded.execution === 'serial' ? serialInstance ??= loaded.create() : loaded.create();
65
+ if (!instance || typeof instance.decide !== 'function')
66
+ throw new Error('behavior_thread_instance_invalid');
67
+ if (loaded.stateMode === 'snapshot' && request.instanceSnapshot)
68
+ restoreBehaviorInstance(instance, request.instanceSnapshot);
69
+ const api = adapter.createApi(input, {
70
+ memory: memory.bind(request.requestId, () => invocationActive), onQuery: () => { queryCount++; }, isActive: () => invocationActive,
71
+ ...(request.observationSnapshot === undefined ? {} : { observationSnapshot: request.observationSnapshot }),
72
+ });
73
+ try {
74
+ const result = adapter.normalize(await instance.decide(input, api));
75
+ const instanceSnapshot = loaded.stateMode === 'snapshot' ? captureBehaviorInstance(instance) : undefined;
76
+ if (instanceSnapshot)
77
+ assertRuntimeModuleOutputSize({ result, instanceSnapshot }, 'behavior_snapshot_output');
78
+ send({ type: 'result', requestId: request.requestId, result, ...(instanceSnapshot === undefined ? {} : { instanceSnapshot }),
79
+ queryCount, durationMs: Math.round((performance.now() - started) * 1000) / 1000, ...diagnosticMemory() });
80
+ }
81
+ finally {
82
+ invocationActive = false;
83
+ }
84
+ };
85
+ let tail = Promise.resolve();
86
+ port.on('message', (request) => {
87
+ if (memory.receive(request))
88
+ return;
89
+ tail = tail.then(() => run(request)).catch(error => send({ type: 'error',
90
+ ...(typeof request?.requestId === 'string' ? { requestId: request.requestId } : {}),
91
+ code: errorCode(error, 'BEHAVIOR_THREAD_OPERATION_FAILED'), message: errorMessage(error), ...diagnosticMemory() }));
92
+ });
93
+ send({ type: 'ready', behaviorId: data.source.id, execution: loaded.execution,
94
+ ...(preparation === undefined ? {} : { manifest: preparation.manifest, input: preparation.input, timing: preparation.timing }),
95
+ ...diagnosticMemory() });
96
+ }
@@ -0,0 +1,120 @@
1
+ import type { RuntimeDiagnosticSeverity } from '../framework/plugins/index.js';
2
+ import type { RuntimeModuleThreadLoaderConfig } from '../framework/modules/runtime-module-loader.js';
3
+ import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
4
+ import type { StrategyMemory } from '../memory/contracts.js';
5
+ export interface StrategyThreadSource {
6
+ readonly id: string;
7
+ readonly execution: 'serial' | 'parallel';
8
+ readonly stateMode?: 'isolated' | 'snapshot';
9
+ }
10
+ export interface StrategyThreadFrame {
11
+ readonly epochId: number;
12
+ }
13
+ export interface StrategyThreadBridge<Source extends StrategyThreadSource> {
14
+ readonly hostUrl: string;
15
+ pin(source: Source): Source;
16
+ resolve(source: Source): Source;
17
+ sourceUrl(source: Source): string;
18
+ loader(): RuntimeModuleThreadLoaderConfig;
19
+ }
20
+ export interface BehaviorTiming {
21
+ readonly timeout_ms?: number;
22
+ readonly duration_ms?: number;
23
+ }
24
+ export declare const PARALLEL_STRATEGY_THREAD_POOL_SIZE = 10;
25
+ export interface ThreadStrategyExecutorOptions<Source extends StrategyThreadSource, Frame extends StrategyThreadFrame, Observation> {
26
+ readonly bridge: StrategyThreadBridge<Source>;
27
+ readonly inputMetadata?: (frame: Frame) => Readonly<Record<string, unknown>>;
28
+ readonly memory?: (frame: Readonly<Frame>, isActive: () => boolean) => StrategyMemory;
29
+ readonly fixedWorkers?: boolean;
30
+ readonly snapshotStore?: BehaviorSnapshotStore;
31
+ readonly source: Source;
32
+ /** Maximum Worker count and in-flight request window. Tests may reduce it. */
33
+ readonly poolSize?: number;
34
+ /** How long an expanded, idle pool is retained before returning to two Workers. */
35
+ readonly idleWorkerTimeoutMs?: number;
36
+ readonly maxOldGenerationSizeMb?: number;
37
+ /** Samples Worker heaps only for explicit full diagnostics. */
38
+ readonly diagnosticsEnabled?: boolean;
39
+ readonly diagnostic?: (name: string, attributes?: Readonly<Record<string, unknown>>, severity?: RuntimeDiagnosticSeverity) => void;
40
+ }
41
+ export interface ThreadStrategyExecutorSnapshot {
42
+ readonly state: 'new' | 'starting' | 'running' | 'stopping' | 'stopped';
43
+ readonly workerCount: number;
44
+ readonly idleWorkerCount: number;
45
+ readonly busyWorkerCount: number;
46
+ readonly queuedRequestCount: number;
47
+ readonly inFlightRequestCount: number;
48
+ readonly startedWorkerCount: number;
49
+ readonly retiredWorkerCount: number;
50
+ readonly workerHeapUsedBytes: number;
51
+ readonly peakWorkerHeapUsedBytes: number;
52
+ }
53
+ export interface StrategyThreadPreparation<Source extends StrategyThreadSource, Manifest> {
54
+ readonly manifest: Readonly<Manifest>;
55
+ readonly input: Readonly<Record<string, unknown>>;
56
+ readonly timing?: Readonly<BehaviorTiming>;
57
+ readonly source: Source;
58
+ }
59
+ /** Imports and normalizes a Behavior without evaluating player code in the Owner. */
60
+ export declare function prepareStrategyInWorker<Source extends StrategyThreadSource, Manifest = unknown>(source: Source, input: Readonly<Record<string, unknown>>, options: Readonly<{
61
+ bridge: StrategyThreadBridge<Source>;
62
+ maxOldGenerationSizeMb?: number;
63
+ diagnosticsEnabled?: boolean;
64
+ }>): Promise<StrategyThreadPreparation<Source, Manifest>>;
65
+ /** Adaptive Worker Thread pool for cross-tick computations. */
66
+ export declare class ThreadStrategyExecutor<Source extends StrategyThreadSource, Frame extends StrategyThreadFrame, Decision, Observation = unknown> {
67
+ private readonly snapshotStore;
68
+ readonly runtimeInstanceId: `${string}-${string}-${string}-${string}-${string}`;
69
+ private readonly maxWorkerCount;
70
+ private readonly maxPendingRequestCount;
71
+ private readonly minWorkerCount;
72
+ private readonly idleWorkerTimeoutMs;
73
+ private readonly maxOldGenerationSizeMb;
74
+ private state;
75
+ private readonly slots;
76
+ private readonly queue;
77
+ private readonly inFlight;
78
+ private readonly spawnTasks;
79
+ private startTask?;
80
+ private stopTask?;
81
+ private replacementTask?;
82
+ private replacementRetryTimer?;
83
+ private idleScaleDownTimer?;
84
+ private replacementFailureCount;
85
+ private nextSlotId;
86
+ private startedWorkerCount;
87
+ private retiredWorkerCount;
88
+ private peakWorkerHeapUsedBytes;
89
+ private desiredWorkerCount;
90
+ private readonly options;
91
+ constructor(options: ThreadStrategyExecutorOptions<Source, Frame, Observation>);
92
+ get isAlive(): boolean;
93
+ start(signal: AbortSignal): Promise<void>;
94
+ update(frame: Frame, signal: AbortSignal, observationSnapshot?: Readonly<Observation>): Promise<Decision>;
95
+ reset(_signal: AbortSignal): Promise<void>;
96
+ stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void>;
97
+ private performStop;
98
+ snapshot(): ThreadStrategyExecutorSnapshot;
99
+ private awaitStart;
100
+ private submit;
101
+ private spawnSlot;
102
+ private pump;
103
+ private handleMessage;
104
+ private resolveRequest;
105
+ private rejectRequest;
106
+ private abortRequest;
107
+ private failSlot;
108
+ private retireSlot;
109
+ private ensureReplacement;
110
+ private growForPressure;
111
+ private scheduleIdleScaleDown;
112
+ private nextIdleScaleDownDelayMs;
113
+ private cancelIdleScaleDown;
114
+ private trimIdleWorkers;
115
+ private currentWorkerDemand;
116
+ private activeWorkerCount;
117
+ private currentWorkerHeapUsedBytes;
118
+ private updateWorkerHeap;
119
+ private diagnostic;
120
+ }