@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,85 @@
1
+ import type { RuntimeEpochPluginInput, RuntimeEventProposal } from '../framework/plugins/contracts.js';
2
+ import type { EventNotificationContent } from '../framework/events/types.js';
3
+ import type { StrategyMemory } from '../memory/contracts.js';
4
+ export interface PerceptionBinding {
5
+ readonly name: string;
6
+ readonly resourceId?: string;
7
+ readonly input?: Readonly<Record<string, unknown>>;
8
+ readonly reflexPriority?: number;
9
+ readonly cooldownMs?: number;
10
+ readonly maxRuntimeMs?: number;
11
+ readonly rearm?: 'after_clear' | 'after_cooldown';
12
+ }
13
+ export interface PerceptionManifest {
14
+ readonly config?: Readonly<Record<string, unknown>>;
15
+ readonly consumes?: readonly string[];
16
+ readonly produces?: readonly string[];
17
+ readonly strategies?: Readonly<Record<string, PerceptionBinding>>;
18
+ readonly behaviors?: Readonly<Record<string, PerceptionBinding>>;
19
+ }
20
+ export interface PerceptionSource {
21
+ readonly id: string;
22
+ readonly name: string;
23
+ readonly module: PerceptionManifest;
24
+ readonly value: unknown;
25
+ }
26
+ export interface PerceptionActivation {
27
+ readonly behavior: string;
28
+ readonly input?: Readonly<Record<string, unknown>>;
29
+ readonly reason?: string;
30
+ }
31
+ export interface PerceptionResult {
32
+ readonly state?: unknown;
33
+ readonly events?: readonly {
34
+ readonly type: string;
35
+ readonly key: string;
36
+ readonly wakeAgent?: boolean;
37
+ readonly payload: Readonly<Record<string, unknown>>;
38
+ }[];
39
+ readonly activations?: readonly (PerceptionActivation | {
40
+ readonly strategy: string;
41
+ readonly input?: Readonly<Record<string, unknown>>;
42
+ readonly reason?: string;
43
+ })[];
44
+ }
45
+ export interface PerceptionInvocation {
46
+ readonly scope: {
47
+ readonly sessionId: string;
48
+ readonly segmentId: string;
49
+ };
50
+ readonly value: unknown;
51
+ }
52
+ export interface PerceptionRunner {
53
+ start(): Promise<void>;
54
+ evaluate(input: PerceptionInvocation): Promise<PerceptionResult>;
55
+ stop(): Promise<void>;
56
+ }
57
+ export interface PerceptionBoundary {
58
+ readonly state: unknown;
59
+ readonly identity?: string;
60
+ readonly resetModules: boolean;
61
+ readonly resetScope: boolean;
62
+ readonly notificationOnly: boolean;
63
+ readonly nowMs: number;
64
+ readonly reflexAllowed: boolean;
65
+ readonly value: unknown;
66
+ }
67
+ export interface PerceptionBindingInput {
68
+ readonly availableBehaviors: readonly string[];
69
+ readonly availableBindings: readonly string[];
70
+ readonly enabledBindings: readonly string[];
71
+ }
72
+ export interface PerceptionAdapter {
73
+ reset(): void;
74
+ recover(checkpoint: unknown): unknown;
75
+ prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown): PerceptionBoundary;
76
+ input(source: PerceptionSource, boundary: PerceptionBoundary, inputState: unknown, state: unknown, config: Readonly<Record<string, unknown>>, bindings: PerceptionBindingInput): {
77
+ invocation: PerceptionInvocation;
78
+ inputState: unknown;
79
+ evaluate: boolean;
80
+ };
81
+ createRunner(source: PerceptionSource, bindMemory: (input: PerceptionInvocation, active: () => boolean) => StrategyMemory): PerceptionRunner;
82
+ configure(source: PerceptionSource, value: Readonly<Record<string, unknown>>): Readonly<Record<string, unknown>>;
83
+ describe(source: PerceptionSource, locale: string): unknown;
84
+ notification(event: RuntimeEventProposal, boundary: PerceptionBoundary): EventNotificationContent;
85
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ /** Bounded independent evaluations; results retain source order, never completion order. */
2
+ export declare function mapConcurrent<T, R>(items: readonly T[], limit: number, evaluate: (item: T) => Promise<R>): Promise<R[]>;
@@ -0,0 +1,12 @@
1
+ /** Bounded independent evaluations; results retain source order, never completion order. */
2
+ export async function mapConcurrent(items, limit, evaluate) {
3
+ const results = new Array(items.length);
4
+ let next = 0;
5
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
6
+ while (next < items.length) {
7
+ const index = next++;
8
+ results[index] = await evaluate(items[index]);
9
+ }
10
+ }));
11
+ return results;
12
+ }
@@ -0,0 +1,114 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../framework/plugins/contracts.js';
2
+ import type { StrategyMemoryStore } from '../memory/strategy-memory.js';
3
+ import type { ReflexDriver } from '../strategy/contracts.js';
4
+ import { type ReactionBehaviorCandidate } from './binding-resolution.js';
5
+ import type { PerceptionSource, PerceptionAdapter } from './contracts.js';
6
+ export declare const REACTION_HOST_EVENT_TYPES: readonly ["perception.behavior_unavailable", "perception.module_failed"];
7
+ export interface PerceptionHostOptions {
8
+ id: string;
9
+ sources: readonly PerceptionSource[];
10
+ after: readonly string[];
11
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
12
+ adapter: PerceptionAdapter;
13
+ }
14
+ /** Observing and notifications remain active independently of fixed Reflex admission. */
15
+ export declare class PerceptionHost implements RuntimeEpochPlugin<Record<string, any>> {
16
+ private readonly options;
17
+ readonly agentNotificationProducer = true;
18
+ readonly kind: "epoch";
19
+ readonly id: string;
20
+ readonly version = "1";
21
+ readonly catchUp: "strict_ordered";
22
+ readonly timeoutMs = 10000;
23
+ readonly after: readonly string[];
24
+ readonly consumes: {
25
+ events: readonly string[];
26
+ };
27
+ readonly produces: {
28
+ events: readonly string[];
29
+ };
30
+ private readonly sources;
31
+ private readonly runners;
32
+ private readonly failed;
33
+ private checkpoint;
34
+ constructor(options: PerceptionHostOptions);
35
+ private driver?;
36
+ private memory?;
37
+ private scope?;
38
+ private stopped;
39
+ private generation;
40
+ private watches;
41
+ private configs;
42
+ attachDriver(driver: ReflexDriver): void;
43
+ attachMemory(memory: StrategyMemoryStore): void;
44
+ private sameScope;
45
+ bindings(id?: string): {
46
+ id: string;
47
+ perception_id: string;
48
+ binding: string;
49
+ trigger_id: string;
50
+ available: boolean;
51
+ reason: string | undefined;
52
+ enabled: boolean;
53
+ priority: number;
54
+ armed: boolean;
55
+ cooldown_ms: number;
56
+ cooldown_remaining_ms: number;
57
+ }[];
58
+ private lastNow?;
59
+ private busy;
60
+ diagnosticSnapshot(): {
61
+ worker_pool: {
62
+ busy_worker_count: number;
63
+ };
64
+ modules: {
65
+ id: string;
66
+ observing: boolean;
67
+ input: Readonly<Record<string, unknown>>;
68
+ bindings: {
69
+ id: string;
70
+ perception_id: string;
71
+ binding: string;
72
+ trigger_id: string;
73
+ available: boolean;
74
+ reason: string | undefined;
75
+ enabled: boolean;
76
+ priority: number;
77
+ armed: boolean;
78
+ cooldown_ms: number;
79
+ cooldown_remaining_ms: number;
80
+ }[];
81
+ }[];
82
+ };
83
+ setWatch(id: string, enabled: boolean, guard: () => boolean): string[];
84
+ configure(id: string, patch: Readonly<Record<string, unknown>>, guard: () => boolean): {
85
+ applied: boolean;
86
+ id: string;
87
+ input: Readonly<Record<string, unknown>>;
88
+ };
89
+ behaviorInputChanged(id: string): void;
90
+ status(id?: string): {
91
+ id: string;
92
+ observing: boolean;
93
+ input: Readonly<Record<string, unknown>>;
94
+ bindings: {
95
+ id: string;
96
+ perception_id: string;
97
+ binding: string;
98
+ trigger_id: string;
99
+ available: boolean;
100
+ reason: string | undefined;
101
+ enabled: boolean;
102
+ priority: number;
103
+ armed: boolean;
104
+ cooldown_ms: number;
105
+ cooldown_remaining_ms: number;
106
+ }[];
107
+ }[];
108
+ start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void>;
109
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void;
110
+ stop(): Promise<void>;
111
+ localizedModuleDescriptors(locale: string): unknown[];
112
+ update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult>;
113
+ private validate;
114
+ }
@@ -0,0 +1,336 @@
1
+ import { unavailableStrategyMemory } from '../memory/strategy-memory-rpc.js';
2
+ import { resolveReactionBehavior } from './binding-resolution.js';
3
+ import { mapConcurrent } from './map-concurrent.js';
4
+ import { normalizePerceptionManifestNames, normalizePerceptionResultNames } from './strategy-names.js';
5
+ export const REACTION_HOST_EVENT_TYPES = ['perception.behavior_unavailable', 'perception.module_failed'];
6
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
7
+ /** Observing and notifications remain active independently of fixed Reflex admission. */
8
+ export class PerceptionHost {
9
+ options;
10
+ agentNotificationProducer = true;
11
+ kind = 'epoch';
12
+ id;
13
+ version = '1';
14
+ catchUp = 'strict_ordered';
15
+ timeoutMs = 10_000;
16
+ after;
17
+ consumes;
18
+ produces;
19
+ sources;
20
+ runners = new Map();
21
+ failed = new Set();
22
+ checkpoint = { modules: {}, failures: [] };
23
+ constructor(options) {
24
+ this.options = options;
25
+ this.id = options.id;
26
+ this.sources = options.sources.filter(s => s.module).map(source => ({ ...source, module: normalizePerceptionManifestNames(source.module) })).sort((a, b) => a.id.localeCompare(b.id));
27
+ this.after = options.after;
28
+ this.consumes = { events: [...new Set(this.sources.flatMap(source => [...(source.module.consumes ?? [])]))] };
29
+ this.produces = { events: [...new Set([...REACTION_HOST_EVENT_TYPES,
30
+ ...this.sources.flatMap(source => [...(source.module.produces ?? [])])])] };
31
+ }
32
+ driver;
33
+ memory;
34
+ scope;
35
+ stopped = true;
36
+ generation = 0;
37
+ watches = new Set();
38
+ configs = new Map();
39
+ attachDriver(driver) { this.driver = driver; }
40
+ attachMemory(memory) { this.memory = memory; }
41
+ sameScope(scope) {
42
+ return this.scope?.sessionId === scope.sessionId && this.scope.segmentId === scope.segmentId;
43
+ }
44
+ bindings(id) {
45
+ const candidates = this.options.behaviors?.() ?? [];
46
+ return this.sources.flatMap(source => Object.entries(source.module.behaviors ?? {}).map(([key, binding]) => {
47
+ const target = resolveReactionBehavior(binding, candidates), state = this.checkpoint.modules[source.id]?.bindings[key];
48
+ return { id: target ?? binding.name, perception_id: source.id, binding: key,
49
+ trigger_id: `perception:${source.id}:${key}`, available: !!target && !this.failed.has(source.id),
50
+ reason: this.failed.has(source.id) ? 'perception_module_failed' : !target ? 'behavior_not_loaded' : undefined,
51
+ enabled: !!target && this.watches.has(target), priority: binding.reflexPriority ?? 0,
52
+ armed: state?.armed ?? true, cooldown_ms: binding.cooldownMs ?? 1000,
53
+ cooldown_remaining_ms: Math.max(0, (binding.cooldownMs ?? 1000) - ((this.lastNow ?? 0) - (state?.lastAcceptedAt ?? -Infinity))) };
54
+ })).filter(binding => id === undefined || binding.id === id);
55
+ }
56
+ lastNow;
57
+ busy = 0;
58
+ diagnosticSnapshot() { return { worker_pool: { busy_worker_count: this.busy }, modules: this.status() }; }
59
+ setWatch(id, enabled, guard) {
60
+ if (this.stopped || !guard())
61
+ throw Error('stale_runtime_scope');
62
+ const bindings = this.bindings(id);
63
+ if (!bindings.length || enabled && !bindings.some(binding => binding.available))
64
+ throw Error('perception_binding_unavailable');
65
+ if (enabled) {
66
+ this.watches.add(id);
67
+ for (const binding of bindings) {
68
+ const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
69
+ if (state) {
70
+ state.armed = true;
71
+ state.failedAttempt = undefined;
72
+ }
73
+ }
74
+ }
75
+ else
76
+ this.watches.delete(id);
77
+ this.generation++;
78
+ return bindings.map(binding => binding.trigger_id);
79
+ }
80
+ configure(id, patch, guard) {
81
+ if (this.stopped || !guard())
82
+ throw Error('stale_runtime_scope');
83
+ const source = this.sources.find(s => s.id === id);
84
+ if (!source)
85
+ throw Error('perception_not_found');
86
+ if (this.failed.has(id))
87
+ throw Error('perception_module_failed');
88
+ const input = this.options.adapter.configure(source, { ...(this.configs.get(id) ?? source.module.config), ...patch });
89
+ this.configs.set(id, input);
90
+ this.generation++;
91
+ for (const state of Object.values(this.checkpoint.modules[id]?.bindings ?? {})) {
92
+ state.failedAttempt = undefined;
93
+ state.warning = undefined;
94
+ }
95
+ return { applied: true, id, input };
96
+ }
97
+ behaviorInputChanged(id) {
98
+ this.generation++;
99
+ for (const binding of this.bindings(id)) {
100
+ const state = this.checkpoint.modules[binding.perception_id]?.bindings[binding.binding];
101
+ if (state) {
102
+ state.failedAttempt = undefined;
103
+ state.warning = undefined;
104
+ }
105
+ }
106
+ }
107
+ status(id) {
108
+ return this.sources.filter(s => id === undefined || id === s.id).map(s => ({ id: s.id,
109
+ observing: !this.stopped && !this.failed.has(s.id), input: this.configs.get(s.id) ?? s.module.config ?? {},
110
+ bindings: this.bindings().filter(b => b.perception_id === s.id) }));
111
+ }
112
+ async start(context) {
113
+ this.stopped = false;
114
+ this.scope = { ...context.scope };
115
+ this.generation++;
116
+ this.watches.clear();
117
+ this.configs.clear();
118
+ this.checkpoint = { modules: {}, failures: [] };
119
+ this.failed.clear();
120
+ this.options.adapter.reset();
121
+ await Promise.all(this.sources.map(async (source, index) => {
122
+ try {
123
+ if (index >= 32)
124
+ throw new Error('REACTION_MODULE_LIMIT');
125
+ const runner = this.options.adapter.createRunner(source, (input, active) => {
126
+ const resolved = Object.values(source.module.behaviors ?? {}).map(binding => resolveReactionBehavior(binding, this.options.behaviors?.() ?? []));
127
+ const targets = [...new Set(resolved)];
128
+ return this.memory?.bind(input.scope, targets.length === 1 && targets[0] ? `behavior:${targets[0]}` : `perception:${source.id}`, () => active() && !this.stopped && !!this.scope && this.sameScope(input.scope)) ?? unavailableStrategyMemory;
129
+ });
130
+ this.runners.set(source.id, runner);
131
+ await runner.start();
132
+ }
133
+ catch {
134
+ this.failed.add(source.id);
135
+ await this.runners.get(source.id)?.stop();
136
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
137
+ }
138
+ }));
139
+ // Assembled, available bindings participate automatically. A watch command
140
+ // restores a binding disabled during this scope; it is not an arming step.
141
+ for (const binding of this.bindings())
142
+ if (binding.available)
143
+ this.watches.add(binding.id);
144
+ }
145
+ recover(context) {
146
+ const saved = context.checkpoint();
147
+ if (saved?.modules && Array.isArray(saved.failures)) {
148
+ this.checkpoint = structuredClone(saved);
149
+ this.checkpoint.adapterState = this.options.adapter.recover(this.checkpoint);
150
+ // Existing notification-only module checkpoints have no binding state.
151
+ for (const state of Object.values(this.checkpoint.modules))
152
+ state.bindings ??= {};
153
+ }
154
+ this.options.adapter.reset();
155
+ }
156
+ async stop() { this.stopped = true; this.generation++; await Promise.all([...this.runners.values()].map(runner => runner.stop())); this.runners.clear(); }
157
+ localizedModuleDescriptors(locale) {
158
+ return this.sources.filter(source => !this.failed.has(source.id)).map(source => this.options.adapter.describe(source, locale));
159
+ }
160
+ async update(input, context) {
161
+ const prepared = this.options.adapter.prepare(input, this.checkpoint.adapterState);
162
+ if (prepared.notificationOnly)
163
+ return { outcome: 'noop', reason: 'notification_only' };
164
+ this.scope = { ...input.epoch.scope };
165
+ if (prepared.resetScope)
166
+ this.checkpoint = { modules: {}, failures: [] };
167
+ if (prepared.resetModules)
168
+ for (const state of Object.values(this.checkpoint.modules)) {
169
+ state.value = undefined;
170
+ for (const binding of Object.values(state.bindings)) {
171
+ binding.armed = true;
172
+ binding.lastAcceptedAt = undefined;
173
+ binding.failedAttempt = undefined;
174
+ }
175
+ }
176
+ this.checkpoint.adapterState = prepared.state;
177
+ const nowMs = prepared.nowMs;
178
+ this.lastNow = nowMs;
179
+ const candidates = this.options.behaviors?.() ?? [];
180
+ const events = [];
181
+ const requests = [];
182
+ const results = await mapConcurrent(this.sources, 4, async (source) => {
183
+ const events = [];
184
+ const requests = [];
185
+ if (!this.failed.has(source.id)) {
186
+ try {
187
+ const state = Object.hasOwn(this.checkpoint.modules, source.id)
188
+ ? this.checkpoint.modules[source.id] : (this.checkpoint.modules[source.id] = { bindings: {} });
189
+ const bindings = {
190
+ availableBehaviors: [...new Set([...candidates.filter(c => c.loadable).map(c => c.id),
191
+ ...Object.values(source.module.behaviors ?? {}).filter(binding => resolveReactionBehavior(binding, candidates)).map(binding => binding.name)])],
192
+ availableBindings: Object.entries(source.module.behaviors ?? {}).filter(([, binding]) => !!resolveReactionBehavior(binding, candidates)).map(([key]) => key),
193
+ enabledBindings: Object.entries(source.module.behaviors ?? {}).filter(([, binding]) => {
194
+ const id = resolveReactionBehavior(binding, candidates);
195
+ return !!id && this.watches.has(id);
196
+ }).map(([key]) => key)
197
+ };
198
+ const module = this.options.adapter.input(source, prepared, state.inputState, state.value, this.configs.get(source.id) ?? source.module.config ?? {}, bindings);
199
+ if (!module.evaluate)
200
+ return { events, requests };
201
+ const generation = this.generation;
202
+ this.busy++;
203
+ let result;
204
+ try {
205
+ result = normalizePerceptionResultNames(await this.runners.get(source.id).evaluate(module.invocation));
206
+ }
207
+ finally {
208
+ this.busy--;
209
+ }
210
+ this.validate(result, source);
211
+ state.value = structuredClone(result.state);
212
+ state.inputState = module.inputState;
213
+ for (const event of result.events ?? [])
214
+ events.push({ type: event.type,
215
+ dedupeKey: JSON.stringify([source.id, event.key]), dedupeScope: 'segment', wakeAgent: event.wakeAgent ?? true,
216
+ payload: { ...event.payload }, occurredAt: new Date(nowMs).toISOString() });
217
+ const matched = new Map((result.activations ?? []).map(activation => [activation.behavior, activation]));
218
+ for (const [key, binding] of Object.entries(source.module.behaviors ?? {})) {
219
+ const current = state.bindings[key] ??= { armed: true, warningSequence: 0 };
220
+ if (current.warning === 'behavior_not_loaded' && resolveReactionBehavior(binding, candidates)) {
221
+ current.warning = undefined;
222
+ current.failedAttempt = undefined;
223
+ }
224
+ if (!matched.has(key)) {
225
+ current.armed = true;
226
+ current.failedAttempt = undefined;
227
+ continue;
228
+ }
229
+ const target = resolveReactionBehavior(binding, candidates);
230
+ if (generation !== this.generation || !target || !this.watches.has(target))
231
+ continue;
232
+ if (!prepared.reflexAllowed)
233
+ continue;
234
+ // Ignore only the missing binding; the module's other outputs continue above.
235
+ if (current.warning === 'behavior_not_loaded')
236
+ continue;
237
+ if ((binding.rearm ?? 'after_clear') === 'after_clear' && !current.armed)
238
+ continue;
239
+ if (current.lastAcceptedAt !== undefined && nowMs - current.lastAcceptedAt < (binding.cooldownMs ?? 1_000))
240
+ continue;
241
+ requests.push({ source, activation: matched.get(key), state: current, generation });
242
+ }
243
+ }
244
+ catch {
245
+ this.failed.add(source.id);
246
+ await this.runners.get(source.id)?.stop();
247
+ context.diagnostic('perception.module_failed', { module_id: source.id }, 'warn');
248
+ }
249
+ }
250
+ if (this.failed.has(source.id) && !this.checkpoint.failures.includes(source.id)) {
251
+ this.checkpoint.failures.push(source.id);
252
+ events.push({ type: 'perception.module_failed', wakeAgent: true, dedupeKey: `module:${source.id}`,
253
+ payload: { module_id: source.id, text: `感知“${source.name}”的反应脚本不可用,已停止该模块;其他感知和策略继续运行。` } });
254
+ }
255
+ return { events, requests };
256
+ });
257
+ for (const result of results) {
258
+ events.push(...result.events);
259
+ requests.push(...result.requests);
260
+ }
261
+ requests.sort((a, b) => (b.source.module.behaviors[b.activation.behavior].reflexPriority ?? 0)
262
+ - (a.source.module.behaviors[a.activation.behavior].reflexPriority ?? 0));
263
+ for (const { source, activation, state, generation } of requests) {
264
+ if (context.signal.aborted || generation !== this.generation)
265
+ break;
266
+ const binding = source.module.behaviors[activation.behavior];
267
+ const behavior = resolveReactionBehavior(binding, (this.options.behaviors?.() ?? []));
268
+ const attempt = JSON.stringify([behavior, binding.input ?? {}, activation.input ?? {}]);
269
+ if (state.failedAttempt === attempt)
270
+ continue;
271
+ let result = { accepted: false, reason: 'behavior_not_loaded' };
272
+ if (behavior && this.watches.has(behavior)) {
273
+ try {
274
+ result = await this.driver?.requestReflex({ source: 'perception',
275
+ triggerId: `perception:${source.id}:${activation.behavior}`, scope: input.epoch.scope,
276
+ epochId: input.epoch.epochSeq, configGeneration: generation, behavior,
277
+ behaviorInput: { ...binding.input, ...activation.input }, reflexPriority: binding.reflexPriority ?? 0,
278
+ maxRuntimeMs: binding.maxRuntimeMs ?? 10_000,
279
+ reason: activation.reason ?? `perception:${source.id}:${activation.behavior}` }, { isCurrent: () => !this.stopped && !context.signal.aborted && generation === this.generation
280
+ && this.watches.has(behavior) && this.sameScope(input.epoch.scope) })
281
+ ?? { accepted: false, reason: 'activation_unavailable' };
282
+ }
283
+ catch {
284
+ result = { accepted: false, reason: 'activation_unavailable' };
285
+ }
286
+ }
287
+ if (result.accepted) {
288
+ state.armed = false;
289
+ state.lastAcceptedAt = nowMs;
290
+ state.warning = undefined;
291
+ state.failedAttempt = undefined;
292
+ }
293
+ else if (!['same_trigger_active', 'reflex_priority_not_higher', 'stale_request', 'activation_ineligible'].includes(result.reason ?? '')) {
294
+ const reason = result.reason ?? 'activation_unavailable';
295
+ state.failedAttempt = attempt;
296
+ if (state.warning !== reason) {
297
+ state.warning = reason;
298
+ state.warningSequence++;
299
+ events.push({ type: 'perception.behavior_unavailable', wakeAgent: true,
300
+ dedupeKey: JSON.stringify([prepared.identity, source.id, activation.behavior, state.warningSequence]),
301
+ payload: { module_id: source.id, binding: activation.behavior, behavior_name: binding.name,
302
+ ...(binding.resourceId ? { preferred_resource_id: binding.resourceId } : {}),
303
+ ...(behavior ? { behavior_id: behavior } : {}), reason,
304
+ text: `感知“${source.name}”未能触发策略“${binding.name}”(${reason})。已跳过本次触发,请 Agent 判断处理;其他感知和策略继续运行。` } });
305
+ }
306
+ }
307
+ }
308
+ return { outcome: 'processed', events: events.map(event => ({ ...event,
309
+ notificationContent: this.options.adapter.notification(event, prepared) })), checkpoint: structuredClone(this.checkpoint),
310
+ ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1).commitSeq } : {}) };
311
+ }
312
+ validate(result, source) {
313
+ if (!record(result) || Object.keys(result).some(key => !['state', 'events', 'activations'].includes(key))
314
+ || result.events !== undefined && !Array.isArray(result.events)
315
+ || result.activations !== undefined && !Array.isArray(result.activations)
316
+ || (result.events?.length ?? 0) > 32 || (result.activations?.length ?? 0) > 16
317
+ || Buffer.byteLength(JSON.stringify(result)) > 128_000)
318
+ throw new Error('REACTION_OUTPUT_INVALID');
319
+ for (const event of result.events ?? []) {
320
+ if (!record(event) || !source.module.produces?.includes(event.type)
321
+ || typeof event.key !== 'string' || !event.key.trim() || event.key.length > 512
322
+ || event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean'
323
+ || !record(event.payload))
324
+ throw new Error('REACTION_EVENT_INVALID');
325
+ }
326
+ const bindings = new Set();
327
+ for (const activation of result.activations ?? []) {
328
+ if (!record(activation) || typeof activation.behavior !== 'string' || !Object.hasOwn(source.module.behaviors ?? {}, activation.behavior)
329
+ || bindings.has(activation.behavior) || activation.input !== undefined && !record(activation.input)
330
+ || activation.reason !== undefined && (typeof activation.reason !== 'string' || activation.reason.length > 512)
331
+ || Object.keys(activation).some(key => !['behavior', 'input', 'reason'].includes(key)))
332
+ throw new Error('REACTION_ACTIVATION_INVALID');
333
+ bindings.add(activation.behavior);
334
+ }
335
+ }
336
+ }
@@ -0,0 +1,11 @@
1
+ import type { StrategyMemory } from '../memory/contracts.js';
2
+ export interface PerceptionWorkerModule<Input> {
3
+ create(): {
4
+ evaluate(input: Readonly<Input>, api: Readonly<{
5
+ memory: StrategyMemory;
6
+ }>): unknown | Promise<unknown>;
7
+ };
8
+ prepareInput?(input: Input): Input;
9
+ }
10
+ /** Shared lifecycle and memory RPC; SDK validation/input shaping remain with the adapter. */
11
+ export declare function runPerceptionWorker<Input>(load: (data: Record<string, any>) => Promise<PerceptionWorkerModule<Input>>): Promise<void>;
@@ -0,0 +1,44 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { StrategyMemoryRpcClient } from '../memory/strategy-memory-rpc.js';
3
+ function freeze(value, seen = new WeakSet()) {
4
+ if (!value || typeof value !== 'object' || seen.has(value))
5
+ return value;
6
+ seen.add(value);
7
+ for (const child of Object.values(value))
8
+ freeze(child, seen);
9
+ return Object.freeze(value);
10
+ }
11
+ /** Shared lifecycle and memory RPC; SDK validation/input shaping remain with the adapter. */
12
+ export async function runPerceptionWorker(load) {
13
+ const port = parentPort;
14
+ if (!port)
15
+ throw Error('PERCEPTION_MODULE_PARENT_MISSING');
16
+ try {
17
+ const loaded = await load(workerData);
18
+ const memory = new StrategyMemoryRpcClient(message => port.postMessage(message));
19
+ let active;
20
+ port.on('message', async (message) => {
21
+ if (memory.receive(message))
22
+ return;
23
+ const { id, input } = message;
24
+ active = id;
25
+ try {
26
+ const result = await loaded.create().evaluate(freeze(loaded.prepareInput?.(input) ?? input), Object.freeze({ memory: memory.bind(String(id), () => active === id) })) ?? {};
27
+ if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000)
28
+ throw Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
29
+ port.postMessage({ type: 'result', id, result });
30
+ }
31
+ catch {
32
+ port.postMessage({ type: 'error', id });
33
+ }
34
+ finally {
35
+ if (active === id)
36
+ active = undefined;
37
+ }
38
+ });
39
+ port.postMessage({ type: 'ready' });
40
+ }
41
+ catch {
42
+ port.postMessage({ type: 'error' });
43
+ }
44
+ }
@@ -0,0 +1,21 @@
1
+ import type { StrategyMemory } from '../memory/contracts.js';
2
+ export interface PerceptionWorkerOptions {
3
+ readonly compatibilityError?: string;
4
+ readonly workerData: Record<string, unknown>;
5
+ }
6
+ /** Memory-bounded independent perception execution with scoped memory RPC. */
7
+ export declare class PerceptionWorker<TInput, TResult> {
8
+ private readonly options;
9
+ private readonly bindMemory?;
10
+ private worker?;
11
+ private sequence;
12
+ private failure?;
13
+ private pending?;
14
+ private memory?;
15
+ constructor(options: PerceptionWorkerOptions, bindMemory?: ((input: TInput, active: () => boolean) => StrategyMemory) | undefined);
16
+ start(): Promise<void>;
17
+ evaluate(input: TInput): Promise<TResult>;
18
+ stop(): Promise<void>;
19
+ private wait;
20
+ private fail;
21
+ }