@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,77 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import { serveStrategyMemoryRequest, unavailableStrategyMemory } from '../memory/strategy-memory-rpc.js';
3
+ /** Memory-bounded independent perception execution with scoped memory RPC. */
4
+ export class PerceptionWorker {
5
+ options;
6
+ bindMemory;
7
+ worker;
8
+ sequence = 0;
9
+ failure;
10
+ pending;
11
+ memory;
12
+ constructor(options, bindMemory) {
13
+ this.options = options;
14
+ this.bindMemory = bindMemory;
15
+ }
16
+ async start() {
17
+ if (this.options.compatibilityError)
18
+ throw new Error(this.options.compatibilityError);
19
+ const ready = this.wait(8_000);
20
+ this.worker = new Worker(new URL('../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
21
+ execArgv: [], stdout: true, stderr: true, resourceLimits: { maxOldGenerationSizeMb: 64 }, workerData: this.options.workerData,
22
+ });
23
+ this.worker.stdout?.on('data', () => { });
24
+ this.worker.stderr?.on('data', () => { });
25
+ this.worker.on('error', error => this.fail(error));
26
+ this.worker.on('exit', () => this.fail(new Error('PERCEPTION_MODULE_WORKER_EXITED')));
27
+ this.worker.on('message', message => {
28
+ if (message.type === 'strategy_memory') {
29
+ void serveStrategyMemoryRequest(message, () => {
30
+ if (message.requestId !== String(this.pending?.id))
31
+ throw Error('strategy_memory_inactive');
32
+ return this.memory ?? unavailableStrategyMemory;
33
+ }, reply => this.worker?.postMessage(reply));
34
+ return;
35
+ }
36
+ if (!this.pending || (message.id !== undefined && message.id !== this.pending.id))
37
+ return;
38
+ if (message.type === 'error') {
39
+ this.fail(new Error('PERCEPTION_MODULE_MODULE_FAILED'));
40
+ return;
41
+ }
42
+ const pending = this.pending;
43
+ this.pending = undefined;
44
+ clearTimeout(pending.timer);
45
+ pending.resolve(message.result);
46
+ });
47
+ await ready;
48
+ }
49
+ async evaluate(input) {
50
+ if (this.failure)
51
+ throw this.failure;
52
+ if (!this.worker)
53
+ throw new Error('PERCEPTION_MODULE_WORKER_NOT_STARTED');
54
+ const id = ++this.sequence;
55
+ const result = this.wait(500, id);
56
+ this.memory = this.bindMemory?.(input, () => this.pending?.id === id && !this.failure);
57
+ this.worker.postMessage({ id, input });
58
+ return result;
59
+ }
60
+ async stop() { this.fail(new Error('PERCEPTION_MODULE_STOPPED')); await this.worker?.terminate(); this.worker = undefined; }
61
+ wait(ms, id) {
62
+ if (this.pending)
63
+ throw new Error('PERCEPTION_MODULE_CONCURRENT_CALL');
64
+ return new Promise((resolve, reject) => {
65
+ this.pending = { id, resolve, reject, timer: setTimeout(() => { this.fail(new Error('PERCEPTION_MODULE_TIMEOUT')); void this.stop(); }, ms) };
66
+ });
67
+ }
68
+ fail(error) {
69
+ this.failure = error;
70
+ if (this.pending) {
71
+ const pending = this.pending;
72
+ this.pending = undefined;
73
+ clearTimeout(pending.timer);
74
+ pending.reject(error);
75
+ }
76
+ }
77
+ }
@@ -0,0 +1,7 @@
1
+ import type { PerceptionActivation, PerceptionManifest, PerceptionResult } from './contracts.js';
2
+ export type NormalizedPerceptionResult = Omit<PerceptionResult, 'activations'> & {
3
+ readonly activations?: readonly PerceptionActivation[];
4
+ };
5
+ /** Keep one internal binding identity; accepting aliases never creates two requests. */
6
+ export declare function normalizePerceptionManifestNames(manifest: PerceptionManifest): PerceptionManifest;
7
+ export declare function normalizePerceptionResultNames(result: PerceptionResult): NormalizedPerceptionResult;
@@ -0,0 +1,22 @@
1
+ /** Keep one internal binding identity; accepting aliases never creates two requests. */
2
+ export function normalizePerceptionManifestNames(manifest) {
3
+ if (manifest.strategies !== undefined && manifest.behaviors !== undefined)
4
+ throw Error('perception_strategy_bindings_conflict');
5
+ const { strategies, ...rest } = manifest;
6
+ return strategies === undefined ? manifest : { ...rest, behaviors: strategies };
7
+ }
8
+ export function normalizePerceptionResultNames(result) {
9
+ if (!result || typeof result !== 'object' || !Array.isArray(result.activations))
10
+ return result;
11
+ return { ...result, activations: result.activations.map(activation => {
12
+ if (!activation || typeof activation !== 'object')
13
+ return activation;
14
+ if ('strategy' in activation) {
15
+ if ('behavior' in activation)
16
+ throw Error('perception_strategy_activation_conflict');
17
+ const { strategy, ...rest } = activation;
18
+ return { ...rest, behavior: strategy };
19
+ }
20
+ return activation;
21
+ }) };
22
+ }
@@ -0,0 +1,5 @@
1
+ /** Authoring base for independent perception scripts with game-defined input. */
2
+ export declare abstract class Perception<TInput, TApi, TResult> {
3
+ evaluate(_input: Readonly<TInput>, _api?: TApi): TResult | Promise<TResult>;
4
+ }
5
+ export type { PerceptionResult, PerceptionAdapter, PerceptionBinding } from '../perception/contracts.js';
@@ -0,0 +1,6 @@
1
+ /** Authoring base for independent perception scripts with game-defined input. */
2
+ export class Perception {
3
+ evaluate(_input, _api) {
4
+ throw new Error('PERCEPTION_EVALUATE_NOT_IMPLEMENTED');
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ /** A game supplies its input, read API and decision types; the base has no game fields. */
2
+ export declare abstract class Strategy<TInput, TApi, TDecision> {
3
+ abstract decide(input: Readonly<TInput>, api: TApi): TDecision | void | Promise<TDecision | void>;
4
+ }
5
+ export type { StrategyMemory, StrategyMemoryValue } from '../memory/contracts.js';
6
+ export type { StrategyDecision, StrategyFrame, StrategyAction, StrategyAdapter } from '../strategy/contracts.js';
@@ -0,0 +1,3 @@
1
+ /** A game supplies its input, read API and decision types; the base has no game fields. */
2
+ export class Strategy {
3
+ }
@@ -0,0 +1,105 @@
1
+ type BehaviorActivationLayer = 'long' | 'short' | 'reflex';
2
+ export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'perception' | 'behavior' | 'system';
3
+ export type BehaviorActivationState = 'running' | 'suspended';
4
+ export interface BehaviorActivationSpec {
5
+ readonly activationId: string;
6
+ readonly behaviorId: string;
7
+ readonly layer: BehaviorActivationLayer;
8
+ readonly source: BehaviorActivationSource;
9
+ readonly input: Readonly<Record<string, unknown>>;
10
+ readonly requestedAt: number;
11
+ readonly maxRuntimeMs?: number;
12
+ readonly deadlineOutcome?: 'completed' | 'failed';
13
+ readonly triggerId?: string;
14
+ readonly reflexPriority?: number;
15
+ }
16
+ export interface BehaviorFallbackBinding {
17
+ readonly behaviorId: string;
18
+ readonly input: Readonly<Record<string, unknown>>;
19
+ }
20
+ export interface BehaviorActivationSnapshot extends BehaviorActivationSpec {
21
+ readonly state: BehaviorActivationState;
22
+ readonly instanceGeneration: number;
23
+ readonly startedAt?: number;
24
+ readonly deadlineAt?: number;
25
+ }
26
+ export type BehaviorActivationTransitionType = 'started' | 'suspended' | 'restarted' | 'completed' | 'failed' | 'cancelled' | 'replaced' | 'ignored';
27
+ export interface BehaviorActivationTransition {
28
+ readonly type: BehaviorActivationTransitionType;
29
+ readonly activationId: string;
30
+ readonly behaviorId: string;
31
+ readonly layer: BehaviorActivationLayer;
32
+ readonly at: number;
33
+ readonly reason: string;
34
+ readonly instanceGeneration: number;
35
+ readonly replacedByActivationId?: string;
36
+ }
37
+ export interface BehaviorActivationManagerOptions {
38
+ readonly idleMs?: number;
39
+ readonly createActivationId?: () => string;
40
+ }
41
+ /**
42
+ * Owns the bounded physical-control stack: one long, one short, one reflex.
43
+ * It never imports modules or submits Actions; Behavior Host applies transitions.
44
+ */
45
+ export declare class BehaviorActivationManager {
46
+ private idleMs;
47
+ private readonly createActivationId;
48
+ private fallback?;
49
+ private long?;
50
+ private short?;
51
+ private reflex?;
52
+ private longEligibleAt?;
53
+ private boundaryActive;
54
+ private idleGeneration;
55
+ private fallbackStartedGeneration;
56
+ private sequence;
57
+ constructor(options?: BehaviorActivationManagerOptions);
58
+ setIdleMs(idleMs: number, now: number): readonly BehaviorActivationTransition[];
59
+ idleDelayMs(): number;
60
+ bindFallback(binding: BehaviorFallbackBinding | undefined, now: number, startImmediately?: boolean): readonly BehaviorActivationTransition[];
61
+ noteAgentActivity(now: number): readonly BehaviorActivationTransition[];
62
+ /**
63
+ * Enter a game boundary where background executions cannot keep authority.
64
+ * Finite foreground work is cancelled; an explicit/fallback long Activation
65
+ * is retained as configuration but must later restart from a fresh runner.
66
+ */
67
+ enterBoundary(reason: string, now: number): readonly BehaviorActivationTransition[];
68
+ /** Starts the one shared hand-back delay after a suspended boundary. */
69
+ leaveBoundary(now: number): readonly BehaviorActivationTransition[];
70
+ /** Ends every Activation in the current game scope while retaining policy bindings. */
71
+ clearScope(reason: string, now: number): readonly BehaviorActivationTransition[];
72
+ startLong(spec: Omit<BehaviorActivationSpec, 'layer'> & {
73
+ readonly layer?: 'long';
74
+ }, now: number): readonly BehaviorActivationTransition[];
75
+ startShort(spec: Omit<BehaviorActivationSpec, 'layer'> & {
76
+ readonly layer?: 'short';
77
+ }, now: number): readonly BehaviorActivationTransition[];
78
+ requestReflex(spec: Omit<BehaviorActivationSpec, 'layer' | 'source'> & {
79
+ readonly layer?: 'reflex';
80
+ readonly source?: 'trigger' | 'perception';
81
+ }, now: number): readonly BehaviorActivationTransition[];
82
+ finish(activationId: string, outcome: 'completed' | 'failed', reason: string, now: number): readonly BehaviorActivationTransition[];
83
+ cancel(activationId: string, reason: string, now: number): readonly BehaviorActivationTransition[];
84
+ advance(now: number): readonly BehaviorActivationTransition[];
85
+ current(): BehaviorActivationSnapshot | undefined;
86
+ /** New immutable input, same activation and deadline; old decision generations expire. */
87
+ updateInput(activationId: string, input: Readonly<Record<string, unknown>>, now: number): readonly BehaviorActivationTransition[];
88
+ updateFallbackInput(behaviorId: string, input: Readonly<Record<string, unknown>>): void;
89
+ snapshot(): Readonly<{
90
+ long?: BehaviorActivationSnapshot;
91
+ short?: BehaviorActivationSnapshot;
92
+ reflex?: BehaviorActivationSnapshot;
93
+ fallback?: BehaviorFallbackBinding;
94
+ idleMs: number;
95
+ longEligibleAt?: number;
96
+ }>;
97
+ isCurrent(activationId: string, instanceGeneration: number): boolean;
98
+ private remove;
99
+ private findLayer;
100
+ private activation;
101
+ private restart;
102
+ private transition;
103
+ private snapshotActivation;
104
+ }
105
+ export {};
@@ -0,0 +1,367 @@
1
+ const DEFAULT_IDLE_MS = 500;
2
+ function cloneInput(input) {
3
+ return Object.freeze(structuredClone(input));
4
+ }
5
+ function validateIdleMs(value) {
6
+ if (!Number.isSafeInteger(value) || value < 0 || value > 60_000) {
7
+ throw new Error('behavior_idle_ms_invalid');
8
+ }
9
+ return value;
10
+ }
11
+ function validateSpec(spec) {
12
+ if (!spec.activationId.trim())
13
+ throw new Error('behavior_activation_id_invalid');
14
+ if (!spec.behaviorId.trim())
15
+ throw new Error('behavior_id_invalid');
16
+ if (!['long', 'short', 'reflex'].includes(spec.layer)) {
17
+ throw new Error('behavior_activation_layer_invalid');
18
+ }
19
+ if (!Number.isFinite(spec.requestedAt))
20
+ throw new Error('behavior_activation_time_invalid');
21
+ if (spec.maxRuntimeMs !== undefined
22
+ && (!Number.isSafeInteger(spec.maxRuntimeMs) || spec.maxRuntimeMs <= 0))
23
+ throw new Error('behavior_activation_runtime_invalid');
24
+ if (spec.deadlineOutcome !== undefined
25
+ && spec.deadlineOutcome !== 'completed'
26
+ && spec.deadlineOutcome !== 'failed')
27
+ throw new Error('behavior_activation_deadline_outcome_invalid');
28
+ if (spec.deadlineOutcome !== undefined && spec.maxRuntimeMs === undefined) {
29
+ throw new Error('behavior_activation_deadline_outcome_without_runtime');
30
+ }
31
+ if (spec.layer === 'reflex') {
32
+ if (!spec.triggerId?.trim())
33
+ throw new Error('behavior_reflex_trigger_id_invalid');
34
+ if (!Number.isSafeInteger(spec.reflexPriority)) {
35
+ throw new Error('behavior_reflex_priority_invalid');
36
+ }
37
+ }
38
+ else if (spec.triggerId !== undefined || spec.reflexPriority !== undefined) {
39
+ throw new Error('behavior_reflex_fields_not_allowed');
40
+ }
41
+ return Object.freeze({
42
+ ...spec,
43
+ input: cloneInput(spec.input),
44
+ });
45
+ }
46
+ /**
47
+ * Owns the bounded physical-control stack: one long, one short, one reflex.
48
+ * It never imports modules or submits Actions; Behavior Host applies transitions.
49
+ */
50
+ export class BehaviorActivationManager {
51
+ idleMs;
52
+ createActivationId;
53
+ fallback;
54
+ long;
55
+ short;
56
+ reflex;
57
+ longEligibleAt;
58
+ boundaryActive = false;
59
+ idleGeneration = 0;
60
+ fallbackStartedGeneration = -1;
61
+ sequence = 0;
62
+ constructor(options = {}) {
63
+ this.idleMs = validateIdleMs(options.idleMs ?? DEFAULT_IDLE_MS);
64
+ this.createActivationId = options.createActivationId
65
+ ?? (() => `behavior-${++this.sequence}`);
66
+ }
67
+ setIdleMs(idleMs, now) {
68
+ this.idleMs = validateIdleMs(idleMs);
69
+ if (!this.short && !this.reflex && (!this.long || this.long.state === 'suspended')) {
70
+ this.longEligibleAt = now + this.idleMs;
71
+ }
72
+ return this.advance(now);
73
+ }
74
+ idleDelayMs() {
75
+ return this.idleMs;
76
+ }
77
+ bindFallback(binding, now, startImmediately = false) {
78
+ this.fallback = binding
79
+ ? Object.freeze({ behaviorId: binding.behaviorId, input: cloneInput(binding.input) })
80
+ : undefined;
81
+ this.idleGeneration += 1;
82
+ this.fallbackStartedGeneration = -1;
83
+ if (!this.short && !this.reflex && !this.long) {
84
+ this.longEligibleAt = startImmediately ? now : now + this.idleMs;
85
+ }
86
+ return this.advance(now);
87
+ }
88
+ noteAgentActivity(now) {
89
+ this.idleGeneration += 1;
90
+ this.fallbackStartedGeneration = -1;
91
+ this.longEligibleAt = now + this.idleMs;
92
+ if (this.long?.spec.source !== 'idle')
93
+ return [];
94
+ const transitions = [this.transition(this.long, 'cancelled', now, 'agent_activity')];
95
+ this.long = undefined;
96
+ return transitions;
97
+ }
98
+ /**
99
+ * Enter a game boundary where background executions cannot keep authority.
100
+ * Finite foreground work is cancelled; an explicit/fallback long Activation
101
+ * is retained as configuration but must later restart from a fresh runner.
102
+ */
103
+ enterBoundary(reason, now) {
104
+ this.boundaryActive = true;
105
+ const transitions = [];
106
+ if (this.reflex) {
107
+ transitions.push(this.transition(this.reflex, 'cancelled', now, reason));
108
+ this.reflex = undefined;
109
+ }
110
+ if (this.short) {
111
+ transitions.push(this.transition(this.short, 'cancelled', now, reason));
112
+ this.short = undefined;
113
+ }
114
+ if (this.long?.state === 'running') {
115
+ this.long.state = 'suspended';
116
+ transitions.push(this.transition(this.long, 'suspended', now, reason));
117
+ }
118
+ this.longEligibleAt = undefined;
119
+ return transitions;
120
+ }
121
+ /** Starts the one shared hand-back delay after a suspended boundary. */
122
+ leaveBoundary(now) {
123
+ this.boundaryActive = false;
124
+ if (this.reflex || this.short)
125
+ return [];
126
+ if (this.long?.state === 'suspended' || (!this.long && this.fallback)) {
127
+ this.longEligibleAt = now + this.idleMs;
128
+ }
129
+ return this.advance(now);
130
+ }
131
+ /** Ends every Activation in the current game scope while retaining policy bindings. */
132
+ clearScope(reason, now) {
133
+ this.boundaryActive = true;
134
+ const transitions = [];
135
+ for (const layer of ['reflex', 'short', 'long']) {
136
+ const activation = this[layer];
137
+ if (!activation)
138
+ continue;
139
+ transitions.push(this.transition(activation, 'cancelled', now, reason));
140
+ this[layer] = undefined;
141
+ }
142
+ this.idleGeneration += 1;
143
+ this.fallbackStartedGeneration = -1;
144
+ this.longEligibleAt = undefined;
145
+ return transitions;
146
+ }
147
+ startLong(spec, now) {
148
+ const next = this.activation({ ...spec, layer: 'long' }, now);
149
+ const transitions = [];
150
+ if (this.long) {
151
+ transitions.push(this.transition(this.long, 'replaced', now, 'long_replaced', next.spec.activationId));
152
+ }
153
+ this.long = next;
154
+ this.longEligibleAt = undefined;
155
+ if (this.boundaryActive || this.short || this.reflex) {
156
+ next.state = 'suspended';
157
+ transitions.push(this.transition(next, 'suspended', now, this.boundaryActive ? 'phase_boundary' : 'higher_layer_active'));
158
+ }
159
+ else {
160
+ transitions.push(this.transition(next, 'started', now, 'explicit_long_started'));
161
+ }
162
+ return transitions;
163
+ }
164
+ startShort(spec, now) {
165
+ const next = this.activation({ ...spec, layer: 'short' }, now);
166
+ const transitions = [];
167
+ if (this.short) {
168
+ transitions.push(this.transition(this.short, 'replaced', now, 'short_replaced', next.spec.activationId));
169
+ }
170
+ this.short = next;
171
+ if (this.long?.state === 'running') {
172
+ this.long.state = 'suspended';
173
+ transitions.push(this.transition(this.long, 'suspended', now, 'short_started'));
174
+ }
175
+ if (this.reflex) {
176
+ next.state = 'suspended';
177
+ transitions.push(this.transition(next, 'suspended', now, 'reflex_active'));
178
+ }
179
+ else {
180
+ transitions.push(this.transition(next, 'started', now, 'short_started'));
181
+ }
182
+ return transitions;
183
+ }
184
+ requestReflex(spec, now) {
185
+ const candidate = this.activation({ ...spec, layer: 'reflex', source: spec.source ?? 'trigger' }, now);
186
+ const active = this.reflex;
187
+ if (active) {
188
+ const sameTrigger = active.spec.triggerId === candidate.spec.triggerId;
189
+ const higher = candidate.spec.reflexPriority > active.spec.reflexPriority;
190
+ if (sameTrigger || !higher) {
191
+ return [this.transition(candidate, 'ignored', now, sameTrigger ? 'reflex_trigger_already_active' : 'reflex_priority_not_higher')];
192
+ }
193
+ }
194
+ const transitions = [];
195
+ if (active) {
196
+ transitions.push(this.transition(active, 'replaced', now, 'higher_priority_reflex', candidate.spec.activationId));
197
+ }
198
+ this.reflex = candidate;
199
+ if (this.short?.state === 'running') {
200
+ this.short.state = 'suspended';
201
+ transitions.push(this.transition(this.short, 'suspended', now, 'reflex_started'));
202
+ }
203
+ if (this.long?.state === 'running') {
204
+ this.long.state = 'suspended';
205
+ transitions.push(this.transition(this.long, 'suspended', now, 'reflex_started'));
206
+ }
207
+ transitions.push(this.transition(candidate, 'started', now, 'reflex_started'));
208
+ return transitions;
209
+ }
210
+ finish(activationId, outcome, reason, now) {
211
+ return this.remove(activationId, outcome, reason, now);
212
+ }
213
+ cancel(activationId, reason, now) {
214
+ return this.remove(activationId, 'cancelled', reason, now);
215
+ }
216
+ advance(now) {
217
+ const transitions = [];
218
+ for (const activation of [this.reflex, this.short, this.long]) {
219
+ if (activation?.deadlineAt !== undefined && now >= activation.deadlineAt) {
220
+ const outcome = activation.spec.deadlineOutcome ?? 'failed';
221
+ transitions.push(...this.remove(activation.spec.activationId, outcome, outcome === 'completed' ? 'duration_elapsed' : 'deadline_elapsed', now));
222
+ }
223
+ }
224
+ if (this.reflex || this.short)
225
+ return transitions;
226
+ // Direct Agent Actions may rearm the idle delay during a boundary. Keep the
227
+ // deadline checks above, but never hand long control back inside a boundary.
228
+ if (this.boundaryActive)
229
+ return transitions;
230
+ if (this.long?.state === 'suspended') {
231
+ if (this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
232
+ this.longEligibleAt = undefined;
233
+ transitions.push(this.restart(this.long, now, 'idle_delay_elapsed'));
234
+ }
235
+ return transitions;
236
+ }
237
+ if (!this.long && this.fallback && this.longEligibleAt !== undefined && now >= this.longEligibleAt) {
238
+ if (this.fallbackStartedGeneration === this.idleGeneration)
239
+ return transitions;
240
+ this.fallbackStartedGeneration = this.idleGeneration;
241
+ this.longEligibleAt = undefined;
242
+ const activation = this.activation({
243
+ activationId: this.createActivationId(),
244
+ behaviorId: this.fallback.behaviorId,
245
+ input: this.fallback.input,
246
+ layer: 'long',
247
+ source: 'idle',
248
+ requestedAt: now,
249
+ }, now);
250
+ this.long = activation;
251
+ transitions.push(this.transition(activation, 'started', now, 'idle_fallback_started'));
252
+ }
253
+ return transitions;
254
+ }
255
+ current() {
256
+ return this.snapshotActivation(this.reflex ?? this.short ?? (this.long?.state === 'running' ? this.long : undefined));
257
+ }
258
+ /** New immutable input, same activation and deadline; old decision generations expire. */
259
+ updateInput(activationId, input, now) {
260
+ const active = [this.long, this.short, this.reflex].find(entry => entry?.spec.activationId === activationId);
261
+ if (!active)
262
+ throw new Error('behavior_activation_not_found');
263
+ active.spec = { ...active.spec, input: cloneInput(input) };
264
+ active.instanceGeneration += 1;
265
+ return [this.transition(active, active.state === 'running' ? 'restarted' : 'suspended', now, 'behavior_input_updated')];
266
+ }
267
+ updateFallbackInput(behaviorId, input) {
268
+ if (this.fallback?.behaviorId === behaviorId)
269
+ this.fallback = { behaviorId, input: cloneInput(input) };
270
+ }
271
+ snapshot() {
272
+ return Object.freeze({
273
+ ...(this.long ? { long: this.snapshotActivation(this.long) } : {}),
274
+ ...(this.short ? { short: this.snapshotActivation(this.short) } : {}),
275
+ ...(this.reflex ? { reflex: this.snapshotActivation(this.reflex) } : {}),
276
+ ...(this.fallback ? { fallback: structuredClone(this.fallback) } : {}),
277
+ idleMs: this.idleMs,
278
+ ...(this.longEligibleAt !== undefined ? { longEligibleAt: this.longEligibleAt } : {}),
279
+ });
280
+ }
281
+ isCurrent(activationId, instanceGeneration) {
282
+ const current = this.current();
283
+ return current?.activationId === activationId
284
+ && current.instanceGeneration === instanceGeneration
285
+ && current.state === 'running';
286
+ }
287
+ remove(activationId, outcome, reason, now) {
288
+ const layer = this.findLayer(activationId);
289
+ if (!layer)
290
+ return [];
291
+ const activation = this[layer];
292
+ const transitions = [
293
+ this.transition(activation, outcome, now, reason),
294
+ ];
295
+ this[layer] = undefined;
296
+ if (layer === 'reflex') {
297
+ if (this.short)
298
+ transitions.push(this.restart(this.short, now, 'reflex_ended'));
299
+ else
300
+ this.longEligibleAt = now + this.idleMs;
301
+ }
302
+ else if (layer === 'short') {
303
+ if (!this.reflex)
304
+ this.longEligibleAt = now + this.idleMs;
305
+ }
306
+ else if (!this.short && !this.reflex) {
307
+ this.longEligibleAt = now + this.idleMs;
308
+ }
309
+ return transitions;
310
+ }
311
+ findLayer(activationId) {
312
+ if (this.reflex?.spec.activationId === activationId)
313
+ return 'reflex';
314
+ if (this.short?.spec.activationId === activationId)
315
+ return 'short';
316
+ if (this.long?.spec.activationId === activationId)
317
+ return 'long';
318
+ return undefined;
319
+ }
320
+ activation(spec, now) {
321
+ const validated = validateSpec(spec);
322
+ return {
323
+ spec: validated,
324
+ state: 'running',
325
+ instanceGeneration: 1,
326
+ startedAt: now,
327
+ ...(validated.maxRuntimeMs !== undefined
328
+ ? { deadlineAt: now + validated.maxRuntimeMs }
329
+ : {}),
330
+ };
331
+ }
332
+ restart(activation, now, reason) {
333
+ activation.state = 'running';
334
+ activation.instanceGeneration += 1;
335
+ activation.startedAt = now;
336
+ if (activation.spec.maxRuntimeMs !== undefined) {
337
+ // A suspended activation keeps its original deadline. Fresh restart is
338
+ // about module state and input, not extending its authority lease.
339
+ activation.deadlineAt ??= activation.spec.requestedAt + activation.spec.maxRuntimeMs;
340
+ }
341
+ return this.transition(activation, 'restarted', now, reason);
342
+ }
343
+ transition(activation, type, at, reason, replacedByActivationId) {
344
+ return Object.freeze({
345
+ type,
346
+ activationId: activation.spec.activationId,
347
+ behaviorId: activation.spec.behaviorId,
348
+ layer: activation.spec.layer,
349
+ at,
350
+ reason,
351
+ instanceGeneration: activation.instanceGeneration,
352
+ ...(replacedByActivationId ? { replacedByActivationId } : {}),
353
+ });
354
+ }
355
+ snapshotActivation(activation) {
356
+ if (!activation)
357
+ return undefined;
358
+ return Object.freeze({
359
+ ...activation.spec,
360
+ input: cloneInput(activation.spec.input),
361
+ state: activation.state,
362
+ instanceGeneration: activation.instanceGeneration,
363
+ ...(activation.startedAt !== undefined ? { startedAt: activation.startedAt } : {}),
364
+ ...(activation.deadlineAt !== undefined ? { deadlineAt: activation.deadlineAt } : {}),
365
+ });
366
+ }
367
+ }
@@ -0,0 +1,20 @@
1
+ import type { StrategyAction as BehaviorDecisionAction, DecisionFrame as BehaviorDecisionFrame } from './contracts.js';
2
+ export declare const BEHAVIOR_DECISION_HISTORY_LIMIT = 100;
3
+ interface DecisionFrameStart {
4
+ readonly epochId: number;
5
+ readonly tick: number;
6
+ readonly instanceGeneration: number;
7
+ }
8
+ /** One Owner-owned, activation-local ring shared by concurrent Decision computations. */
9
+ export declare class BehaviorDecisionHistory {
10
+ private readonly frames;
11
+ private cachedSnapshot?;
12
+ begin(start: DecisionFrameStart): Readonly<BehaviorDecisionFrame>;
13
+ complete(epochId: number, actions: readonly Readonly<BehaviorDecisionAction>[] | undefined): Readonly<BehaviorDecisionFrame> | undefined;
14
+ notComputed(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined;
15
+ fail(epochId: number, reason: string): Readonly<BehaviorDecisionFrame> | undefined;
16
+ snapshot(): readonly Readonly<BehaviorDecisionFrame>[];
17
+ clear(): void;
18
+ private resolve;
19
+ }
20
+ export {};