@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,59 @@
1
+ export const BEHAVIOR_DECISION_HISTORY_LIMIT = 100;
2
+ function cloneActions(actions) {
3
+ return Object.freeze((actions ?? []).map((action) => Object.freeze(structuredClone(action))));
4
+ }
5
+ /** One Owner-owned, activation-local ring shared by concurrent Decision computations. */
6
+ export class BehaviorDecisionHistory {
7
+ frames = [];
8
+ cachedSnapshot;
9
+ begin(start) {
10
+ const existing = this.frames.find((frame) => frame.epochId === start.epochId);
11
+ if (existing)
12
+ return existing;
13
+ const frame = Object.freeze({
14
+ ...start,
15
+ status: 'pending',
16
+ actions: null,
17
+ });
18
+ this.frames.push(frame);
19
+ if (this.frames.length > BEHAVIOR_DECISION_HISTORY_LIMIT) {
20
+ this.frames.splice(0, this.frames.length - BEHAVIOR_DECISION_HISTORY_LIMIT);
21
+ }
22
+ this.cachedSnapshot = undefined;
23
+ return frame;
24
+ }
25
+ complete(epochId, actions) {
26
+ return this.resolve(epochId, 'completed', cloneActions(actions));
27
+ }
28
+ notComputed(epochId, reason) {
29
+ return this.resolve(epochId, 'not_computed', null, reason);
30
+ }
31
+ fail(epochId, reason) {
32
+ return this.resolve(epochId, 'failed', null, reason);
33
+ }
34
+ snapshot() {
35
+ this.cachedSnapshot ??= Object.freeze([...this.frames]);
36
+ return this.cachedSnapshot;
37
+ }
38
+ clear() {
39
+ this.frames.length = 0;
40
+ this.cachedSnapshot = undefined;
41
+ }
42
+ resolve(epochId, status, actions, reason) {
43
+ const index = this.frames.findIndex((frame) => frame.epochId === epochId);
44
+ if (index < 0)
45
+ return undefined;
46
+ const previous = this.frames[index];
47
+ const next = Object.freeze({
48
+ epochId: previous.epochId,
49
+ tick: previous.tick,
50
+ instanceGeneration: previous.instanceGeneration,
51
+ status,
52
+ actions,
53
+ ...(reason ? { reason } : {}),
54
+ });
55
+ this.frames[index] = next;
56
+ this.cachedSnapshot = undefined;
57
+ return next;
58
+ }
59
+ }
@@ -0,0 +1,31 @@
1
+ type Value = null | undefined | boolean | number | string | bigint | {
2
+ ref: number;
3
+ };
4
+ interface Node {
5
+ kind: 'object' | 'array' | 'map' | 'set' | 'date';
6
+ className?: string;
7
+ nullPrototype?: boolean;
8
+ entries?: Array<[string, Value]>;
9
+ items?: Value[];
10
+ pairs?: Array<[Value, Value]>;
11
+ time?: number;
12
+ }
13
+ export interface BehaviorInstanceSnapshot {
14
+ readonly nodes: readonly Node[];
15
+ }
16
+ export declare const MAX_BEHAVIOR_SNAPSHOT_BYTES: number;
17
+ /** One activation's completed computation state; never an Action receipt or commit checkpoint. */
18
+ export declare class BehaviorSnapshotStore {
19
+ generation: number;
20
+ latest?: {
21
+ epochId: number;
22
+ value: BehaviorInstanceSnapshot;
23
+ };
24
+ publish(epochId: number, value: BehaviorInstanceSnapshot, generation: number): boolean;
25
+ reset(): void;
26
+ }
27
+ /** Capture data only. Methods stay on fresh constructor-created instances in each Worker. */
28
+ export declare function captureBehaviorInstance(instance: object): BehaviorInstanceSnapshot;
29
+ /** Custom helper classes must be created by the constructor so their methods are retained. */
30
+ export declare function restoreBehaviorInstance(instance: object, snapshot: BehaviorInstanceSnapshot): void;
31
+ export {};
@@ -0,0 +1,145 @@
1
+ import { serialize } from 'node:v8';
2
+ export const MAX_BEHAVIOR_SNAPSHOT_BYTES = 1024 * 1024;
3
+ /** One activation's completed computation state; never an Action receipt or commit checkpoint. */
4
+ export class BehaviorSnapshotStore {
5
+ generation = 0;
6
+ latest;
7
+ publish(epochId, value, generation) {
8
+ if (generation !== this.generation || (this.latest && epochId <= this.latest.epochId))
9
+ return false;
10
+ this.latest = { epochId, value: structuredClone(value) };
11
+ return true;
12
+ }
13
+ reset() { this.generation++; this.latest = undefined; }
14
+ }
15
+ function unsupported(reason) { throw new Error(`behavior_snapshot_unsupported:${reason}`); }
16
+ function className(value) {
17
+ const proto = Object.getPrototypeOf(value);
18
+ if (proto === null || proto === Object.prototype)
19
+ return undefined;
20
+ const constructor = Object.getOwnPropertyDescriptor(proto, 'constructor')?.value;
21
+ return typeof constructor === 'function' ? constructor.name : unsupported('prototype');
22
+ }
23
+ /** Capture data only. Methods stay on fresh constructor-created instances in each Worker. */
24
+ export function captureBehaviorInstance(instance) {
25
+ const nodes = [];
26
+ const seen = new Map();
27
+ let stringBytes = 0;
28
+ function encode(value, depth) {
29
+ if (depth > 128)
30
+ unsupported('depth');
31
+ if (typeof value === 'string') {
32
+ stringBytes += Buffer.byteLength(value);
33
+ if (stringBytes > MAX_BEHAVIOR_SNAPSHOT_BYTES)
34
+ throw new Error('behavior_snapshot_too_large');
35
+ }
36
+ if (value === null || value === undefined || ['boolean', 'number', 'string', 'bigint'].includes(typeof value))
37
+ return value;
38
+ if (typeof value !== 'object')
39
+ unsupported(typeof value);
40
+ const object = value;
41
+ const prior = seen.get(object);
42
+ if (prior !== undefined)
43
+ return { ref: prior };
44
+ if (nodes.length >= 10_000)
45
+ throw new Error('behavior_snapshot_too_large');
46
+ const ref = nodes.length;
47
+ const node = { kind: 'object' };
48
+ seen.set(object, ref);
49
+ nodes.push(node);
50
+ if (Array.isArray(object)) {
51
+ node.kind = 'array';
52
+ node.items = object.map(v => encode(v, depth + 1));
53
+ }
54
+ else if (object instanceof Map) {
55
+ node.kind = 'map';
56
+ node.pairs = [...object].map(([k, v]) => [encode(k, depth + 1), encode(v, depth + 1)]);
57
+ }
58
+ else if (object instanceof Set) {
59
+ node.kind = 'set';
60
+ node.items = [...object].map(v => encode(v, depth + 1));
61
+ }
62
+ else if (object instanceof Date) {
63
+ node.kind = 'date';
64
+ node.time = object.getTime();
65
+ }
66
+ else {
67
+ node.className = className(object);
68
+ node.nullPrototype = Object.getPrototypeOf(object) === null;
69
+ node.entries = [];
70
+ for (const key of Reflect.ownKeys(object)) {
71
+ if (typeof key !== 'string')
72
+ unsupported('symbol_key');
73
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
74
+ if (!('value' in descriptor))
75
+ unsupported('accessor');
76
+ node.entries.push([key, encode(descriptor.value, depth + 1)]);
77
+ }
78
+ }
79
+ return { ref };
80
+ }
81
+ encode(instance, 0);
82
+ const snapshot = { nodes };
83
+ if (serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES)
84
+ throw new Error('behavior_snapshot_too_large');
85
+ return snapshot;
86
+ }
87
+ /** Custom helper classes must be created by the constructor so their methods are retained. */
88
+ export function restoreBehaviorInstance(instance, snapshot) {
89
+ if (!Array.isArray(snapshot.nodes) || snapshot.nodes.length === 0
90
+ || snapshot.nodes.length > 10_000 || serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES) {
91
+ throw new Error('behavior_snapshot_invalid');
92
+ }
93
+ const restored = new Map();
94
+ function decode(value, seed) {
95
+ if (value === null || typeof value !== 'object')
96
+ return value;
97
+ if (restored.has(value.ref))
98
+ return restored.get(value.ref);
99
+ const node = snapshot.nodes[value.ref];
100
+ if (!node)
101
+ throw new Error('behavior_snapshot_reference_invalid');
102
+ let result;
103
+ if (node.kind === 'array')
104
+ result = [];
105
+ else if (node.kind === 'map')
106
+ result = new Map();
107
+ else if (node.kind === 'set')
108
+ result = new Set();
109
+ else if (node.kind === 'date')
110
+ result = new Date(node.time);
111
+ else if (node.className) {
112
+ if (!seed || typeof seed !== 'object' || className(seed) !== node.className)
113
+ unsupported(`class_template:${node.className}`);
114
+ result = seed;
115
+ }
116
+ else
117
+ result = node.nullPrototype ? Object.create(null) : {};
118
+ restored.set(value.ref, result);
119
+ if (node.kind === 'object') {
120
+ const keys = new Set(node.entries.map(([key]) => key));
121
+ for (const key of Object.getOwnPropertyNames(result))
122
+ if (!keys.has(key)) {
123
+ if (!Reflect.deleteProperty(result, key))
124
+ unsupported('nonconfigurable_field');
125
+ }
126
+ for (const [key, entry] of node.entries) {
127
+ const initial = Object.getOwnPropertyDescriptor(result, key);
128
+ const decoded = decode(entry, initial && 'value' in initial ? initial.value : undefined);
129
+ Object.defineProperty(result, key, { value: decoded, enumerable: true, writable: true, configurable: true });
130
+ }
131
+ }
132
+ else if (node.kind === 'array')
133
+ node.items.forEach((v, i) => { result[i] = decode(v, seed?.[i]); });
134
+ else if (node.kind === 'set')
135
+ for (const v of node.items)
136
+ result.add(decode(v));
137
+ else if (node.kind === 'map')
138
+ for (const [k, v] of node.pairs) {
139
+ const key = decode(k);
140
+ result.set(key, decode(v, seed instanceof Map ? seed.get(key) : undefined));
141
+ }
142
+ return result;
143
+ }
144
+ decode({ ref: 0 }, instance);
145
+ }
@@ -0,0 +1,189 @@
1
+ import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext } from '../framework/plugins/contracts.js';
2
+ import type { StrategyMemory } from '../memory/contracts.js';
3
+ import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
4
+ export interface StrategyAction {
5
+ readonly action: string;
6
+ }
7
+ export interface StrategyStatus {
8
+ readonly summary: string;
9
+ readonly activity?: string;
10
+ readonly data?: Readonly<Record<string, unknown>>;
11
+ }
12
+ export interface StrategyFinish {
13
+ readonly outcome: 'completed' | 'failed';
14
+ readonly reason: string;
15
+ readonly summary?: string;
16
+ }
17
+ export type StrategyDelegation = {
18
+ readonly strategy: string;
19
+ readonly input?: Readonly<Record<string, unknown>>;
20
+ } | {
21
+ readonly behavior: string;
22
+ readonly input?: Readonly<Record<string, unknown>>;
23
+ };
24
+ export interface StrategyDecision {
25
+ readonly actions?: readonly Readonly<StrategyAction>[];
26
+ readonly status?: Readonly<StrategyStatus>;
27
+ readonly events?: readonly {
28
+ readonly type: string;
29
+ readonly payload: Readonly<Record<string, unknown>>;
30
+ readonly occurredAt?: string;
31
+ }[];
32
+ readonly finish?: Readonly<StrategyFinish>;
33
+ readonly delegate?: Readonly<StrategyDelegation>;
34
+ }
35
+ export interface StrategyContinuation {
36
+ readonly delegatedBehavior?: {
37
+ readonly activationId: string;
38
+ readonly behavior: string;
39
+ readonly outcome: 'completed' | 'failed' | 'cancelled' | 'replaced';
40
+ readonly reason: string;
41
+ readonly summary?: string;
42
+ };
43
+ }
44
+ export type DecisionFrameStatus = 'pending' | 'completed' | 'not_computed' | 'failed';
45
+ export interface DecisionFrame {
46
+ readonly epochId: number;
47
+ readonly tick: number;
48
+ readonly instanceGeneration: number;
49
+ readonly status: DecisionFrameStatus;
50
+ readonly actions: readonly Readonly<StrategyAction>[] | null;
51
+ readonly reason?: string;
52
+ }
53
+ export interface StrategyFrame {
54
+ readonly epochId: number;
55
+ readonly nowMs: number;
56
+ readonly tick: number;
57
+ readonly cycle?: unknown;
58
+ readonly scope: {
59
+ readonly sessionId: string;
60
+ readonly segmentId: string;
61
+ };
62
+ readonly events: readonly {
63
+ readonly eventId: string;
64
+ }[];
65
+ /** The typed game SDK input is carried opaquely and interpreted only by the game runner. */
66
+ readonly value: unknown;
67
+ }
68
+ export interface ModuleDisplay {
69
+ readonly id: string;
70
+ readonly name: string;
71
+ readonly description: string;
72
+ }
73
+ export interface PreparedStrategy {
74
+ readonly manifest: {
75
+ readonly id: string;
76
+ readonly name?: string;
77
+ readonly description: string;
78
+ readonly execution?: 'serial' | 'parallel';
79
+ readonly stateMode?: 'isolated' | 'snapshot';
80
+ readonly everyTicks?: number;
81
+ readonly produces?: readonly string[];
82
+ readonly runtime?: {
83
+ readonly defaultMs: number;
84
+ readonly controlGraceMs?: number;
85
+ readonly deadlineOutcome?: 'completed' | 'failed';
86
+ };
87
+ };
88
+ readonly input: Readonly<Record<string, unknown>>;
89
+ readonly rawInput?: Readonly<Record<string, unknown>>;
90
+ readonly timing?: {
91
+ readonly duration_ms?: number;
92
+ readonly timeout_ms?: number;
93
+ };
94
+ readonly display?: {
95
+ readonly name: string;
96
+ readonly description: string;
97
+ };
98
+ readonly module?: object;
99
+ readonly createModule?: () => object;
100
+ readonly source?: unknown;
101
+ readonly value: unknown;
102
+ }
103
+ export interface StrategyObservation {
104
+ readonly revision: number;
105
+ }
106
+ export interface StrategyRunner {
107
+ readonly execution: 'serial' | 'parallel';
108
+ readonly everyTicks: number;
109
+ prepare(): Promise<void>;
110
+ stop(reason?: 'switched' | 'scope_ended' | 'shutdown'): Promise<void>;
111
+ diagnosticSnapshot(): Readonly<Record<string, unknown>>;
112
+ decideSerial(input: StrategyFrame, signal: AbortSignal, observation?: StrategyObservation): Promise<StrategyDecision>;
113
+ decideParallel(input: StrategyFrame, signal: AbortSignal, observation?: StrategyObservation): Promise<StrategyDecision>;
114
+ }
115
+ export interface StrategyRunnerOptions {
116
+ readonly prepared: PreparedStrategy;
117
+ readonly behaviorId: string;
118
+ readonly activationId: string;
119
+ readonly instanceGeneration: number;
120
+ readonly isActive: () => boolean;
121
+ readonly diagnostic?: RuntimeEpochPluginContext['diagnostic'];
122
+ readonly diagnosticsEnabled?: boolean;
123
+ readonly snapshotStore?: BehaviorSnapshotStore;
124
+ readonly memory?: (input: StrategyFrame, active: () => boolean) => StrategyMemory;
125
+ }
126
+ export interface StrategyBoundary {
127
+ readonly notificationOnly: boolean;
128
+ readonly cycle: boolean;
129
+ readonly terminalReason?: string;
130
+ readonly hasObservation: boolean;
131
+ readonly observationTick?: number;
132
+ readonly pendingPauseReason?: string;
133
+ readonly actionGeneration?: number;
134
+ }
135
+ export interface StrategyPolicy {
136
+ readonly terminalReason?: string;
137
+ readonly inactiveReason?: string;
138
+ readonly pauseReason?: string;
139
+ readonly resume: boolean;
140
+ readonly pauseAfterDecision?: string;
141
+ readonly fallbackKey?: string;
142
+ }
143
+ export interface StrategyAdapter {
144
+ input(input: RuntimeEpochPluginInput<Record<string, any>>, parameters: Readonly<Record<string, unknown>>, continuation?: StrategyContinuation, history?: readonly Readonly<DecisionFrame>[]): StrategyFrame | null;
145
+ boundary(input: RuntimeEpochPluginInput<Record<string, any>>): StrategyBoundary;
146
+ policy(frame: StrategyFrame | null, layer?: 'long' | 'short' | 'reflex'): StrategyPolicy;
147
+ createRunner(options: StrategyRunnerOptions): StrategyRunner;
148
+ observations: {
149
+ capture(frame: StrategyFrame): StrategyObservation;
150
+ snapshot(epochId: number): StrategyObservation | undefined;
151
+ clear(): void;
152
+ };
153
+ action(action: Readonly<StrategyAction>, epochId: number, safetyGeneration: number | undefined, instanceGeneration: number, tick: number): Record<string, unknown>;
154
+ display(prepared?: PreparedStrategy): ModuleDisplay | undefined;
155
+ reportEligible(input: RuntimeEpochPluginInput<Record<string, any>>): boolean;
156
+ /** Display-only policy; selecting inactive metadata never grants action authority. */
157
+ reportSelection?(input: RuntimeEpochPluginInput<Record<string, any>>): 'active' | 'selected';
158
+ report(context: RuntimeEpochPluginContext<Record<string, any>>, display: ModuleDisplay): Promise<unknown>;
159
+ reportSucceeded(value: unknown): boolean;
160
+ }
161
+ export interface ReflexRequest {
162
+ readonly source: 'trigger' | 'perception';
163
+ readonly triggerId: string;
164
+ readonly scope: Readonly<{
165
+ sessionId: string;
166
+ segmentId: string;
167
+ }>;
168
+ readonly epochId: number;
169
+ readonly configGeneration: number;
170
+ readonly behavior: string;
171
+ readonly behaviorInput: Readonly<Record<string, unknown>>;
172
+ readonly reflexPriority: number;
173
+ readonly maxRuntimeMs: number;
174
+ readonly reason: string;
175
+ readonly evidence?: Readonly<Record<string, unknown>>;
176
+ }
177
+ export type ReflexResult = Readonly<{
178
+ accepted: true;
179
+ activationId: string;
180
+ replacedActivationId?: string;
181
+ }> | Readonly<{
182
+ accepted: false;
183
+ reason: string;
184
+ }>;
185
+ export interface ReflexDriver {
186
+ requestReflex(request: Readonly<ReflexRequest>, guard?: Readonly<{
187
+ isCurrent(): boolean;
188
+ }>): ReflexResult | Promise<ReflexResult>;
189
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ import { type BehaviorActionCaller } from '../framework/capability-registry.js';
2
+ import type { ScopeRef } from '../framework/contracts.js';
3
+ import type { Runtime } from '../framework/runtime.js';
4
+ import type { BehaviorActivationSnapshot } from './activation-manager.js';
5
+ export interface StrategyControlHandle {
6
+ readonly caller: BehaviorActionCaller;
7
+ readonly scope: ScopeRef;
8
+ readonly controllerId: string;
9
+ /** Reads current scheduler state, so a held activation can later become active. */
10
+ isAuthorized(): boolean;
11
+ release(reason: string): void;
12
+ }
13
+ export interface StrategyControlDriver {
14
+ acquire(activation: BehaviorActivationSnapshot, expectedScope: ScopeRef): StrategyControlHandle;
15
+ }
16
+ /**
17
+ * Narrow Behavior-Host facade over the Runtime control scheduler.
18
+ *
19
+ * The caller's fixed layer selects priority through behaviorControllerSpec;
20
+ * Trigger reflexPriority is deliberately never read here.
21
+ */
22
+ export declare function createStrategyControlDriver(runtime: Pick<Runtime<any>, 'actions' | 'scope'>, options: {
23
+ domains: readonly string[];
24
+ owner: string;
25
+ }): StrategyControlDriver;
@@ -0,0 +1,131 @@
1
+ import { actionControllerId, behaviorControllerSpec, } from '../framework/capability-registry.js';
2
+ function sameScope(left, right) {
3
+ return left.adapterId === right.adapterId
4
+ && left.accountId === right.accountId
5
+ && left.sessionId === right.sessionId
6
+ && left.segmentId === right.segmentId;
7
+ }
8
+ function isLiveController(runtime, controllerId) {
9
+ const controller = runtime.actions.controls.snapshot().controllers.find(candidate => candidate.controllerId === controllerId);
10
+ return controller !== undefined
11
+ && controller.state !== 'released'
12
+ && controller.state !== 'expired';
13
+ }
14
+ function directHandoffCaller(activation) {
15
+ if (activation.source === 'agent')
16
+ return { kind: 'agent' };
17
+ if (activation.source === 'user')
18
+ return { kind: 'user' };
19
+ return undefined;
20
+ }
21
+ function validateActivation(activation) {
22
+ if (activation.state !== 'running') {
23
+ throw new Error('behavior_control_activation_not_running');
24
+ }
25
+ if ((activation.layer === 'short' || activation.layer === 'reflex')
26
+ && activation.maxRuntimeMs === undefined) {
27
+ throw new Error('behavior_control_runtime_required');
28
+ }
29
+ }
30
+ /**
31
+ * Narrow Behavior-Host facade over the Runtime control scheduler.
32
+ *
33
+ * The caller's fixed layer selects priority through behaviorControllerSpec;
34
+ * Trigger reflexPriority is deliberately never read here.
35
+ */
36
+ export function createStrategyControlDriver(runtime, options) {
37
+ return {
38
+ acquire: (activation, expectedScope) => {
39
+ validateActivation(activation);
40
+ const scope = runtime.scope();
41
+ if (!sameScope(scope, expectedScope)) {
42
+ throw new Error('behavior_control_scope_changed');
43
+ }
44
+ const caller = Object.freeze({
45
+ kind: 'behavior',
46
+ activationId: activation.activationId,
47
+ layer: activation.layer,
48
+ activationGeneration: activation.instanceGeneration,
49
+ });
50
+ const controllerId = actionControllerId(caller);
51
+ const lifecycle = activation.layer === 'long'
52
+ && activation.maxRuntimeMs === undefined
53
+ ? 'persistent'
54
+ : 'finite';
55
+ let registered = false;
56
+ try {
57
+ runtime.actions.controls.registerController(behaviorControllerSpec(caller, {
58
+ scope,
59
+ domains: [...options.domains],
60
+ lifecycle,
61
+ ...(activation.maxRuntimeMs === undefined
62
+ ? {}
63
+ : { maxRuntimeMs: activation.maxRuntimeMs }),
64
+ ready: false,
65
+ holdMode: 'all_or_nothing',
66
+ metadata: {
67
+ owner: options.owner,
68
+ behaviorId: activation.behaviorId,
69
+ behaviorSource: activation.source,
70
+ },
71
+ }));
72
+ registered = true;
73
+ const handoffCaller = directHandoffCaller(activation);
74
+ const handoffControllerId = handoffCaller
75
+ ? actionControllerId(handoffCaller, scope)
76
+ : undefined;
77
+ let handedOff = false;
78
+ if (handoffControllerId && isLiveController(runtime, handoffControllerId)) {
79
+ try {
80
+ runtime.actions.controls.handoff({
81
+ fromControllerId: handoffControllerId,
82
+ toControllerId: controllerId,
83
+ domains: [...options.domains],
84
+ });
85
+ handedOff = true;
86
+ }
87
+ catch (error) {
88
+ // A source may disappear between the snapshot and handoff. A real
89
+ // higher blocker leaves the Behavior ready-but-held so it may
90
+ // become active later without recreating the runner.
91
+ if (isLiveController(runtime, handoffControllerId)
92
+ && (!(error instanceof Error) || error.message !== 'control_handoff_target_held'))
93
+ throw error;
94
+ }
95
+ }
96
+ if (!handedOff)
97
+ runtime.actions.controls.setReady(controllerId, true);
98
+ }
99
+ catch (error) {
100
+ if (registered) {
101
+ runtime.actions.controls.release(controllerId, {
102
+ reason: 'behavior_control_acquire_failed',
103
+ });
104
+ }
105
+ throw error;
106
+ }
107
+ let released = false;
108
+ return Object.freeze({
109
+ caller,
110
+ scope: Object.freeze({ ...scope }),
111
+ controllerId,
112
+ isAuthorized: () => {
113
+ if (released || !sameScope(runtime.scope(), scope))
114
+ return false;
115
+ const controller = runtime.actions.controls.snapshot().controllers.find(candidate => candidate.controllerId === controllerId);
116
+ return controller !== undefined
117
+ && controller.ready
118
+ && controller.state !== 'released'
119
+ && controller.state !== 'expired'
120
+ && options.domains.every(domain => controller.grantedDomains.includes(domain));
121
+ },
122
+ release: (reason) => {
123
+ if (released)
124
+ return;
125
+ released = true;
126
+ runtime.actions.controls.release(controllerId, { reason });
127
+ },
128
+ });
129
+ },
130
+ };
131
+ }
@@ -0,0 +1,25 @@
1
+ import type { Strategy } from '../sdk/strategy.js';
2
+ import type { PreparedStrategy, StrategyDecision, StrategyFrame, StrategyRunner } from './contracts.js';
3
+ export interface InProcessRunnerOptions<Input, Api> {
4
+ prepared: PreparedStrategy;
5
+ createModule(): Strategy<Input, Api, StrategyDecision>;
6
+ input(frame: StrategyFrame): Readonly<Input>;
7
+ api(frame: StrategyFrame, active: () => boolean): Api;
8
+ isActive(): boolean;
9
+ }
10
+ /** Trusted callbacks only. Untrusted or blocking scripts require a Worker-backed runner. */
11
+ export declare class InProcessStrategyRunner<Input, Api> implements StrategyRunner {
12
+ private readonly options;
13
+ private stopped;
14
+ private tail;
15
+ private serial?;
16
+ constructor(options: InProcessRunnerOptions<Input, Api>);
17
+ get execution(): 'serial' | 'parallel';
18
+ get everyTicks(): number;
19
+ prepare(): Promise<void>;
20
+ stop(): Promise<void>;
21
+ diagnosticSnapshot(): Readonly<Record<string, unknown>>;
22
+ decideSerial(frame: StrategyFrame, signal: AbortSignal): Promise<StrategyDecision>;
23
+ decideParallel(frame: StrategyFrame, signal: AbortSignal): Promise<StrategyDecision>;
24
+ private invoke;
25
+ }
@@ -0,0 +1,40 @@
1
+ /** Trusted callbacks only. Untrusted or blocking scripts require a Worker-backed runner. */
2
+ export class InProcessStrategyRunner {
3
+ options;
4
+ stopped = false;
5
+ tail = Promise.resolve();
6
+ serial;
7
+ constructor(options) {
8
+ this.options = options;
9
+ }
10
+ get execution() { return this.options.prepared.manifest.execution ?? 'parallel'; }
11
+ get everyTicks() { return this.options.prepared.manifest.everyTicks ?? 1; }
12
+ async prepare() { if (this.execution === 'serial')
13
+ this.serial = this.options.createModule(); }
14
+ async stop() { this.stopped = true; this.serial = undefined; }
15
+ diagnosticSnapshot() { return { execution: this.execution, stopped: this.stopped }; }
16
+ decideSerial(frame, signal) {
17
+ const run = this.tail.then(() => this.invoke(frame, signal, this.serial));
18
+ this.tail = run.then(() => undefined, () => undefined);
19
+ return run;
20
+ }
21
+ decideParallel(frame, signal) {
22
+ return this.invoke(frame, signal);
23
+ }
24
+ async invoke(frame, signal, instance) {
25
+ let running = true;
26
+ const active = () => running && !this.stopped && !signal.aborted && this.options.isActive();
27
+ if (!active())
28
+ throw new Error('strategy_execution_inactive');
29
+ try {
30
+ const module = instance ?? this.options.createModule();
31
+ const result = await module.decide(this.options.input(frame), this.options.api(frame, active));
32
+ if (!active())
33
+ throw new Error('strategy_execution_inactive');
34
+ return result ?? {};
35
+ }
36
+ finally {
37
+ running = false;
38
+ }
39
+ }
40
+ }