@gamekits/ai-core 0.1.0-alpha.10

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 (156) hide show
  1. package/dist/composition/create-ai-module.d.ts +5 -0
  2. package/dist/composition/create-ai-module.d.ts.map +1 -0
  3. package/dist/composition/create-ai-runtime.d.ts +4 -0
  4. package/dist/composition/create-ai-runtime.d.ts.map +1 -0
  5. package/dist/composition/index.d.ts +4 -0
  6. package/dist/composition/index.d.ts.map +1 -0
  7. package/dist/composition/options.d.ts +48 -0
  8. package/dist/composition/options.d.ts.map +1 -0
  9. package/dist/composition/registry.d.ts +4 -0
  10. package/dist/composition/registry.d.ts.map +1 -0
  11. package/dist/composition/runtime-config.d.ts +26 -0
  12. package/dist/composition/runtime-config.d.ts.map +1 -0
  13. package/dist/contracts/agent-binding.d.ts +9 -0
  14. package/dist/contracts/agent-binding.d.ts.map +1 -0
  15. package/dist/contracts/agent-context.d.ts +21 -0
  16. package/dist/contracts/agent-context.d.ts.map +1 -0
  17. package/dist/contracts/blackboard-value.d.ts +5 -0
  18. package/dist/contracts/blackboard-value.d.ts.map +1 -0
  19. package/dist/contracts/clone-binding.d.ts +3 -0
  20. package/dist/contracts/clone-binding.d.ts.map +1 -0
  21. package/dist/contracts/clone-runtime-value.d.ts +3 -0
  22. package/dist/contracts/clone-runtime-value.d.ts.map +1 -0
  23. package/dist/contracts/errors.d.ts +8 -0
  24. package/dist/contracts/errors.d.ts.map +1 -0
  25. package/dist/contracts/index.d.ts +10 -0
  26. package/dist/contracts/index.d.ts.map +1 -0
  27. package/dist/contracts/intent.d.ts +42 -0
  28. package/dist/contracts/intent.d.ts.map +1 -0
  29. package/dist/contracts/navigation-access.d.ts +16 -0
  30. package/dist/contracts/navigation-access.d.ts.map +1 -0
  31. package/dist/contracts/navigation-queries.d.ts +3 -0
  32. package/dist/contracts/navigation-queries.d.ts.map +1 -0
  33. package/dist/contracts/physics-queries.d.ts +3 -0
  34. package/dist/contracts/physics-queries.d.ts.map +1 -0
  35. package/dist/contracts/shared-fact-queries.d.ts +7 -0
  36. package/dist/contracts/shared-fact-queries.d.ts.map +1 -0
  37. package/dist/contracts/world-read-model.d.ts +9 -0
  38. package/dist/contracts/world-read-model.d.ts.map +1 -0
  39. package/dist/controller/agent-context-factory.d.ts +23 -0
  40. package/dist/controller/agent-context-factory.d.ts.map +1 -0
  41. package/dist/controller/agent-state.d.ts +29 -0
  42. package/dist/controller/agent-state.d.ts.map +1 -0
  43. package/dist/controller/create-agent-state.d.ts +12 -0
  44. package/dist/controller/create-agent-state.d.ts.map +1 -0
  45. package/dist/controller/create-ai-handle.d.ts +8 -0
  46. package/dist/controller/create-ai-handle.d.ts.map +1 -0
  47. package/dist/controller/goal-controller.d.ts +21 -0
  48. package/dist/controller/goal-controller.d.ts.map +1 -0
  49. package/dist/controller/index.d.ts +3 -0
  50. package/dist/controller/index.d.ts.map +1 -0
  51. package/dist/controller/runtime.d.ts +29 -0
  52. package/dist/controller/runtime.d.ts.map +1 -0
  53. package/dist/create-ai-runtime-Cd-h8AF9.js +1867 -0
  54. package/dist/decision/cooldowns.d.ts +2 -0
  55. package/dist/decision/cooldowns.d.ts.map +1 -0
  56. package/dist/decision/goal-scoring.d.ts +12 -0
  57. package/dist/decision/goal-scoring.d.ts.map +1 -0
  58. package/dist/decision/goal-selection.d.ts +17 -0
  59. package/dist/decision/goal-selection.d.ts.map +1 -0
  60. package/dist/decision/index.d.ts +3 -0
  61. package/dist/decision/index.d.ts.map +1 -0
  62. package/dist/decision/utility-curve.d.ts +4 -0
  63. package/dist/decision/utility-curve.d.ts.map +1 -0
  64. package/dist/decision/utility.d.ts +47 -0
  65. package/dist/decision/utility.d.ts.map +1 -0
  66. package/dist/definition/agent-definition-compiler.d.ts +12 -0
  67. package/dist/definition/agent-definition-compiler.d.ts.map +1 -0
  68. package/dist/definition/agent-definition.d.ts +12 -0
  69. package/dist/definition/agent-definition.d.ts.map +1 -0
  70. package/dist/definition/ai-data-types.d.ts +16 -0
  71. package/dist/definition/ai-data-types.d.ts.map +1 -0
  72. package/dist/definition/clone-definitions.d.ts +9 -0
  73. package/dist/definition/clone-definitions.d.ts.map +1 -0
  74. package/dist/definition/compiled-agent-definition.d.ts +23 -0
  75. package/dist/definition/compiled-agent-definition.d.ts.map +1 -0
  76. package/dist/definition/goal-definition.d.ts +14 -0
  77. package/dist/definition/goal-definition.d.ts.map +1 -0
  78. package/dist/definition/index.d.ts +6 -0
  79. package/dist/definition/index.d.ts.map +1 -0
  80. package/dist/definition/sensor-definition.d.ts +8 -0
  81. package/dist/definition/sensor-definition.d.ts.map +1 -0
  82. package/dist/definition/task-definition.d.ts +10 -0
  83. package/dist/definition/task-definition.d.ts.map +1 -0
  84. package/dist/index.d.ts +11 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +205 -0
  87. package/dist/memory/blackboard.d.ts +24 -0
  88. package/dist/memory/blackboard.d.ts.map +1 -0
  89. package/dist/memory/index.d.ts +3 -0
  90. package/dist/memory/index.d.ts.map +1 -0
  91. package/dist/observability/index.d.ts +3 -0
  92. package/dist/observability/index.d.ts.map +1 -0
  93. package/dist/observability/snapshot-projection.d.ts +17 -0
  94. package/dist/observability/snapshot-projection.d.ts.map +1 -0
  95. package/dist/observability/snapshot.d.ts +32 -0
  96. package/dist/observability/snapshot.d.ts.map +1 -0
  97. package/dist/observability/trace-recorder.d.ts +17 -0
  98. package/dist/observability/trace-recorder.d.ts.map +1 -0
  99. package/dist/observability/trace-store.d.ts +15 -0
  100. package/dist/observability/trace-store.d.ts.map +1 -0
  101. package/dist/observability/trace.d.ts +29 -0
  102. package/dist/observability/trace.d.ts.map +1 -0
  103. package/dist/perception/index.d.ts +3 -0
  104. package/dist/perception/index.d.ts.map +1 -0
  105. package/dist/perception/perception-controller.d.ts +27 -0
  106. package/dist/perception/perception-controller.d.ts.map +1 -0
  107. package/dist/perception/perception-fact.d.ts +12 -0
  108. package/dist/perception/perception-fact.d.ts.map +1 -0
  109. package/dist/perception/perception-memory.d.ts +8 -0
  110. package/dist/perception/perception-memory.d.ts.map +1 -0
  111. package/dist/perception/sensor-sampler.d.ts +8 -0
  112. package/dist/perception/sensor-sampler.d.ts.map +1 -0
  113. package/dist/persistence/checkpoint-compatibility.d.ts +4 -0
  114. package/dist/persistence/checkpoint-compatibility.d.ts.map +1 -0
  115. package/dist/persistence/checkpoint-projection.d.ts +5 -0
  116. package/dist/persistence/checkpoint-projection.d.ts.map +1 -0
  117. package/dist/persistence/checkpoint-validation.d.ts +3 -0
  118. package/dist/persistence/checkpoint-validation.d.ts.map +1 -0
  119. package/dist/persistence/checkpoint.d.ts +30 -0
  120. package/dist/persistence/checkpoint.d.ts.map +1 -0
  121. package/dist/persistence/index.d.ts +3 -0
  122. package/dist/persistence/index.d.ts.map +1 -0
  123. package/dist/persistence/restore-binding.d.ts +4 -0
  124. package/dist/persistence/restore-binding.d.ts.map +1 -0
  125. package/dist/persistence/restore-task-state.d.ts +4 -0
  126. package/dist/persistence/restore-task-state.d.ts.map +1 -0
  127. package/dist/persistence/save-contributor.d.ts +15 -0
  128. package/dist/persistence/save-contributor.d.ts.map +1 -0
  129. package/dist/scheduler/decision-scheduler.d.ts +20 -0
  130. package/dist/scheduler/decision-scheduler.d.ts.map +1 -0
  131. package/dist/scheduler/due-work.d.ts +8 -0
  132. package/dist/scheduler/due-work.d.ts.map +1 -0
  133. package/dist/scheduler/index.d.ts +2 -0
  134. package/dist/scheduler/index.d.ts.map +1 -0
  135. package/dist/scheduler/reclassify-agent.d.ts +13 -0
  136. package/dist/scheduler/reclassify-agent.d.ts.map +1 -0
  137. package/dist/scheduler/scheduler-class.d.ts +7 -0
  138. package/dist/scheduler/scheduler-class.d.ts.map +1 -0
  139. package/dist/scheduler/timing.d.ts +3 -0
  140. package/dist/scheduler/timing.d.ts.map +1 -0
  141. package/dist/task/clone-task-state.d.ts +3 -0
  142. package/dist/task/clone-task-state.d.ts.map +1 -0
  143. package/dist/task/index.d.ts +2 -0
  144. package/dist/task/index.d.ts.map +1 -0
  145. package/dist/task/task-controller.d.ts +41 -0
  146. package/dist/task/task-controller.d.ts.map +1 -0
  147. package/dist/task/task-executor.d.ts +37 -0
  148. package/dist/task/task-executor.d.ts.map +1 -0
  149. package/dist/testing/index.d.ts +3 -0
  150. package/dist/testing/index.d.ts.map +1 -0
  151. package/dist/testing/index.js +126 -0
  152. package/dist/testing/memory-runtime-fixture.d.ts +17 -0
  153. package/dist/testing/memory-runtime-fixture.d.ts.map +1 -0
  154. package/dist/testing/runtime-conformance.d.ts +14 -0
  155. package/dist/testing/runtime-conformance.d.ts.map +1 -0
  156. package/package.json +39 -0
@@ -0,0 +1,1867 @@
1
+ //#region src/contracts/world-read-model.ts
2
+ function createAiWorldReadModel(world) {
3
+ return Object.freeze({
4
+ has(entity) {
5
+ return world.has(entity);
6
+ },
7
+ get(entity, component) {
8
+ return world.get(entity, component);
9
+ },
10
+ query(components) {
11
+ return world.query(components === void 0 ? void 0 : [...components]);
12
+ },
13
+ count() {
14
+ return world.count();
15
+ }
16
+ });
17
+ }
18
+ //#endregion
19
+ //#region src/contracts/errors.ts
20
+ var AiError = class extends Error {
21
+ code;
22
+ details;
23
+ constructor(code, message, details) {
24
+ super(message);
25
+ this.name = "AiError";
26
+ this.code = code;
27
+ this.details = details;
28
+ }
29
+ };
30
+ function createAiError(code, message, details) {
31
+ return new AiError(code, message, details);
32
+ }
33
+ //#endregion
34
+ //#region src/contracts/navigation-queries.ts
35
+ function createAiNavigationQueries(queries) {
36
+ return Object.freeze({
37
+ projectPoint: queries.projectPoint.bind(queries),
38
+ requestPath: queries.requestPath.bind(queries),
39
+ poll: queries.poll.bind(queries),
40
+ cancel: queries.cancel.bind(queries),
41
+ sampleRoute: queries.sampleRoute.bind(queries),
42
+ releaseRoute: queries.releaseRoute.bind(queries),
43
+ revision: queries.revision.bind(queries),
44
+ snapshot: queries.snapshot.bind(queries)
45
+ });
46
+ }
47
+ //#endregion
48
+ //#region src/contracts/navigation-access.ts
49
+ function createAiNavigationAccess(options) {
50
+ const queries = createAiNavigationQueries(options.queries);
51
+ const facades = /* @__PURE__ */ new Map();
52
+ const rejectionPrefix = `ai-budget/${encodeURIComponent(options.id)}/`;
53
+ let updating = false;
54
+ let requestsThisUpdate = 0;
55
+ let rejectedTotal = 0;
56
+ let rejectionSequence = 0;
57
+ return {
58
+ beginUpdate() {
59
+ updating = true;
60
+ requestsThisUpdate = 0;
61
+ },
62
+ endUpdate() {
63
+ updating = false;
64
+ },
65
+ forAgent(agentId) {
66
+ const existing = facades.get(agentId);
67
+ if (existing !== void 0) return existing;
68
+ const facade = Object.freeze({
69
+ projectPoint: queries.projectPoint,
70
+ requestPath(request) {
71
+ if (!updating || requestsThisUpdate < options.maxRequestsPerUpdate) {
72
+ if (updating) requestsThisUpdate += 1;
73
+ return queries.requestPath(request);
74
+ }
75
+ rejectedTotal += 1;
76
+ rejectionSequence += 1;
77
+ options.onRejected(agentId, request);
78
+ return `${rejectionPrefix}${rejectionSequence}/${encodeURIComponent(request.requesterId)}`;
79
+ },
80
+ poll(requestId) {
81
+ const rejection = parseRejectedRequest(requestId);
82
+ if (rejection !== void 0) return {
83
+ status: "rejected",
84
+ requestId,
85
+ requesterId: rejection.requesterId,
86
+ reason: "queue-full",
87
+ revision: queries.revision(),
88
+ message: "AI path request budget exceeded"
89
+ };
90
+ return queries.poll(requestId);
91
+ },
92
+ cancel(requestId) {
93
+ if (parseRejectedRequest(requestId) === void 0) queries.cancel(requestId);
94
+ },
95
+ sampleRoute: queries.sampleRoute,
96
+ releaseRoute: queries.releaseRoute,
97
+ revision: queries.revision,
98
+ snapshot: queries.snapshot
99
+ });
100
+ facades.set(agentId, facade);
101
+ return facade;
102
+ },
103
+ release(agentId) {
104
+ facades.delete(agentId);
105
+ },
106
+ rejectedRequests() {
107
+ return rejectedTotal;
108
+ },
109
+ clear() {
110
+ facades.clear();
111
+ updating = false;
112
+ requestsThisUpdate = 0;
113
+ }
114
+ };
115
+ function parseRejectedRequest(requestId) {
116
+ if (!requestId.startsWith(rejectionPrefix)) return;
117
+ const separator = requestId.indexOf("/", rejectionPrefix.length);
118
+ if (separator < 0) return;
119
+ try {
120
+ return { requesterId: decodeURIComponent(requestId.slice(separator + 1)) };
121
+ } catch {
122
+ return { requesterId: "unknown" };
123
+ }
124
+ }
125
+ }
126
+ //#endregion
127
+ //#region src/contracts/physics-queries.ts
128
+ function createAiPhysicsQueries(queries) {
129
+ return Object.freeze({
130
+ query: queries.query.bind(queries),
131
+ queryPoint: queries.queryPoint.bind(queries),
132
+ raycast: queries.raycast.bind(queries),
133
+ shapeCast: queries.shapeCast.bind(queries),
134
+ overlapShape: queries.overlapShape.bind(queries),
135
+ checkOverlap: queries.checkOverlap.bind(queries),
136
+ checkCollision: queries.checkCollision.bind(queries),
137
+ queryBounds: queries.queryBounds.bind(queries),
138
+ snapshot: queries.snapshot.bind(queries)
139
+ });
140
+ }
141
+ //#endregion
142
+ //#region src/contracts/clone-runtime-value.ts
143
+ function cloneAiRecord(value) {
144
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneAiRuntimeValue(item)]));
145
+ }
146
+ function cloneAiRuntimeValue(value) {
147
+ if (Array.isArray(value)) return value.map((item) => cloneAiRuntimeValue(item));
148
+ if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneAiRuntimeValue(item)]));
149
+ return value;
150
+ }
151
+ //#endregion
152
+ //#region src/contracts/shared-fact-queries.ts
153
+ function createAiSharedFactQueries(queries) {
154
+ return Object.freeze({
155
+ facts() {
156
+ return queries.facts().map(cloneSharedFact);
157
+ },
158
+ fact(key, subjectId) {
159
+ const value = queries.fact(key, subjectId);
160
+ return value === void 0 ? void 0 : cloneSharedFact(value);
161
+ }
162
+ });
163
+ }
164
+ function cloneSharedFact(fact) {
165
+ return {
166
+ ...fact,
167
+ ...fact.position === void 0 ? {} : { position: { ...fact.position } },
168
+ ...fact.metadata === void 0 ? {} : { metadata: cloneAiRecord(fact.metadata) }
169
+ };
170
+ }
171
+ //#endregion
172
+ //#region src/contracts/clone-binding.ts
173
+ function cloneAiAgentBinding(binding) {
174
+ return { ...binding };
175
+ }
176
+ //#endregion
177
+ //#region src/definition/clone-definitions.ts
178
+ function cloneAiAgentDefinition(definition) {
179
+ return {
180
+ ...definition,
181
+ sensors: definition.sensors.map((reference) => ({ ...reference })),
182
+ goals: definition.goals.map((reference) => ({ ...reference })),
183
+ ...definition.tags === void 0 ? {} : { tags: [...definition.tags] }
184
+ };
185
+ }
186
+ function cloneAiSensorDefinition(sensor) {
187
+ return {
188
+ ...sensor,
189
+ ...sensor.args === void 0 ? {} : { args: cloneAiRecord(sensor.args) },
190
+ ...sensor.tags === void 0 ? {} : { tags: [...sensor.tags] }
191
+ };
192
+ }
193
+ function cloneAiGoalDefinition(goal) {
194
+ return {
195
+ ...goal,
196
+ task: { ...goal.task },
197
+ considerations: goal.considerations.map((consideration) => ({
198
+ ...consideration,
199
+ curve: consideration.curve.type === "points" ? {
200
+ type: "points",
201
+ points: consideration.curve.points.map((point) => ({ ...point }))
202
+ } : { ...consideration.curve }
203
+ })),
204
+ ...goal.tags === void 0 ? {} : { tags: [...goal.tags] }
205
+ };
206
+ }
207
+ function cloneAiTaskDefinition(task) {
208
+ return {
209
+ ...task,
210
+ ...task.args === void 0 ? {} : { args: cloneAiRecord(task.args) },
211
+ ...task.tags === void 0 ? {} : { tags: [...task.tags] }
212
+ };
213
+ }
214
+ //#endregion
215
+ //#region src/perception/perception-memory.ts
216
+ function retainAiPerceptionFacts(memory, facts, limit) {
217
+ for (const input of facts) {
218
+ if (!input.key || !Number.isFinite(input.observedAt)) continue;
219
+ const fact = cloneAiPerceptionFact(input);
220
+ const key = aiPerceptionFactKey(fact.key, fact.subjectId);
221
+ memory.delete(key);
222
+ memory.set(key, fact);
223
+ }
224
+ while (memory.size > limit) {
225
+ let oldestKey;
226
+ let oldestAt = Number.POSITIVE_INFINITY;
227
+ for (const [key, fact] of memory) if (fact.observedAt < oldestAt || fact.observedAt === oldestAt && (oldestKey === void 0 || key < oldestKey)) {
228
+ oldestKey = key;
229
+ oldestAt = fact.observedAt;
230
+ }
231
+ if (oldestKey === void 0) break;
232
+ memory.delete(oldestKey);
233
+ }
234
+ }
235
+ function pruneAiPerceptionMemory(memory, elapsed) {
236
+ for (const [key, fact] of memory) if (fact.expiresAt !== void 0 && fact.expiresAt <= elapsed) memory.delete(key);
237
+ }
238
+ function listAiPerceptionFacts(memory) {
239
+ return [...memory.values()].sort((left, right) => left.key === right.key ? (left.subjectId ?? "").localeCompare(right.subjectId ?? "") : left.key.localeCompare(right.key)).map(cloneAiPerceptionFact);
240
+ }
241
+ function readAiPerceptionFact(memory, key, subjectId) {
242
+ const fact = memory.get(aiPerceptionFactKey(key, subjectId));
243
+ return fact === void 0 ? void 0 : cloneAiPerceptionFact(fact);
244
+ }
245
+ function cloneAiPerceptionFact(fact) {
246
+ return {
247
+ ...fact,
248
+ ...fact.position === void 0 ? {} : { position: { ...fact.position } },
249
+ ...fact.metadata === void 0 ? {} : { metadata: cloneAiRecord(fact.metadata) }
250
+ };
251
+ }
252
+ function aiPerceptionFactKey(key, subjectId) {
253
+ return `${key}\u0000${subjectId ?? ""}`;
254
+ }
255
+ //#endregion
256
+ //#region src/controller/agent-context-factory.ts
257
+ function createAiAgentContextFactory(options) {
258
+ function read(state) {
259
+ const navigation = options.navigationFor(state);
260
+ return {
261
+ elapsed: options.elapsed(),
262
+ agent: cloneAiAgentBinding(state.binding),
263
+ definition: cloneAiAgentDefinition(state.definition),
264
+ world: options.world,
265
+ ...navigation === void 0 ? {} : { navigation },
266
+ ...options.physics === void 0 ? {} : { physics: options.physics },
267
+ ...options.sharedFacts === void 0 ? {} : { sharedFacts: options.sharedFacts },
268
+ facts: () => listAiPerceptionFacts(state.memory),
269
+ fact: (key, subjectId) => readAiPerceptionFact(state.memory, key, subjectId),
270
+ blackboard: (key) => state.blackboard.read(key)
271
+ };
272
+ }
273
+ return {
274
+ read,
275
+ task(state, goal, task, taskState) {
276
+ return {
277
+ ...read(state),
278
+ goal: cloneAiGoalDefinition(goal),
279
+ task: cloneAiTaskDefinition(task),
280
+ state: cloneAiRecord(taskState.state),
281
+ emit(intent) {
282
+ options.onIntent(state, task, intent);
283
+ },
284
+ setBlackboard(key, value) {
285
+ state.blackboard.set(key, value);
286
+ },
287
+ deleteBlackboard(key) {
288
+ state.blackboard.delete(key);
289
+ }
290
+ };
291
+ }
292
+ };
293
+ }
294
+ //#endregion
295
+ //#region src/memory/blackboard.ts
296
+ function createAiBlackboard(options) {
297
+ const values = /* @__PURE__ */ new Map();
298
+ return {
299
+ limit: options.limit,
300
+ get size() {
301
+ return values.size;
302
+ },
303
+ set(key, value) {
304
+ validateKey(key, options.valueLimits.maxStringLength);
305
+ if (!values.has(key) && values.size >= options.limit) throw createAiError("ai.blackboard_capacity", "AI blackboard capacity is exhausted", {
306
+ key,
307
+ limit: options.limit
308
+ });
309
+ values.set(key, cloneAiBlackboardValue(value, options.valueLimits));
310
+ },
311
+ delete(key) {
312
+ values.delete(key);
313
+ },
314
+ read(key) {
315
+ const value = values.get(key);
316
+ return value === void 0 ? void 0 : cloneAiBlackboardValue(value, options.valueLimits);
317
+ },
318
+ keys() {
319
+ return [...values.keys()].sort();
320
+ },
321
+ capture() {
322
+ return captureValues(values, options.valueLimits);
323
+ },
324
+ replace(nextValues) {
325
+ const entries = Object.entries(nextValues).sort(([left], [right]) => left.localeCompare(right));
326
+ if (entries.length > options.limit) throw createAiError("ai.blackboard_capacity", "AI checkpoint blackboard exceeds capacity", {
327
+ entries: entries.length,
328
+ limit: options.limit
329
+ });
330
+ const replacement = /* @__PURE__ */ new Map();
331
+ for (const [key, value] of entries) {
332
+ validateKey(key, options.valueLimits.maxStringLength);
333
+ replacement.set(key, cloneAiBlackboardValue(value, options.valueLimits));
334
+ }
335
+ values.clear();
336
+ for (const [key, value] of replacement) values.set(key, value);
337
+ },
338
+ clear() {
339
+ values.clear();
340
+ }
341
+ };
342
+ }
343
+ function cloneAiBlackboardValue(value, limits) {
344
+ let nodes = 0;
345
+ const ancestors = /* @__PURE__ */ new Set();
346
+ return visit(value, 0);
347
+ function visit(current, depth) {
348
+ nodes += 1;
349
+ if (nodes > limits.maxNodes) throw invalidValue("AI blackboard value exceeds the node limit", { maxNodes: limits.maxNodes });
350
+ if (depth > limits.maxDepth) throw invalidValue("AI blackboard value exceeds the depth limit", { maxDepth: limits.maxDepth });
351
+ if (current === null || typeof current === "boolean") return current;
352
+ if (typeof current === "number") {
353
+ if (!Number.isFinite(current)) throw invalidValue("AI blackboard numbers must be finite");
354
+ return current;
355
+ }
356
+ if (typeof current === "string") {
357
+ if (current.length > limits.maxStringLength) throw invalidValue("AI blackboard string exceeds the length limit", { maxStringLength: limits.maxStringLength });
358
+ return current;
359
+ }
360
+ if (typeof current !== "object") throw invalidValue("AI blackboard values must be JSON-like data");
361
+ if (ancestors.has(current)) throw invalidValue("AI blackboard values cannot contain cycles");
362
+ ancestors.add(current);
363
+ try {
364
+ if (Array.isArray(current)) {
365
+ const result = [];
366
+ for (let index = 0; index < current.length; index += 1) {
367
+ if (!(index in current)) throw invalidValue("AI blackboard arrays cannot contain sparse entries");
368
+ result.push(visit(current[index], depth + 1));
369
+ }
370
+ return result;
371
+ }
372
+ const prototype = Object.getPrototypeOf(current);
373
+ if (prototype !== Object.prototype && prototype !== null) throw invalidValue("AI blackboard values cannot contain class or native objects");
374
+ const result = {};
375
+ const descriptors = Object.getOwnPropertyDescriptors(current);
376
+ for (const key of Object.keys(descriptors).sort()) {
377
+ validateKey(key, limits.maxStringLength);
378
+ const descriptor = descriptors[key];
379
+ if (descriptor === void 0 || !("value" in descriptor)) throw invalidValue("AI blackboard values cannot contain accessors", { key });
380
+ if (descriptor.enumerable) Object.defineProperty(result, key, {
381
+ value: visit(descriptor.value, depth + 1),
382
+ enumerable: true,
383
+ configurable: true,
384
+ writable: true
385
+ });
386
+ }
387
+ return result;
388
+ } finally {
389
+ ancestors.delete(current);
390
+ }
391
+ }
392
+ }
393
+ function captureValues(values, limits) {
394
+ return Object.fromEntries([...values.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => [key, cloneAiBlackboardValue(value, limits)]));
395
+ }
396
+ function validateKey(key, maxLength) {
397
+ if (typeof key !== "string" || key.trim().length === 0 || key.length > maxLength) throw createAiError("ai.blackboard_invalid_key", "AI blackboard keys must be non-empty and within the configured length limit", {
398
+ key,
399
+ maxLength
400
+ });
401
+ }
402
+ function invalidValue(message, details) {
403
+ return createAiError("ai.blackboard_invalid_value", message, details);
404
+ }
405
+ //#endregion
406
+ //#region src/scheduler/timing.ts
407
+ function effectiveAiInterval(base, multiplier) {
408
+ return Math.max(1, base * (multiplier ?? 1));
409
+ }
410
+ function stableAiScheduleOffset(key, interval) {
411
+ let hash = 2166136261;
412
+ for (let index = 0; index < key.length; index += 1) {
413
+ hash ^= key.charCodeAt(index);
414
+ hash = Math.imul(hash, 16777619);
415
+ }
416
+ return (hash >>> 0) % Math.max(1, Math.floor(interval));
417
+ }
418
+ //#endregion
419
+ //#region src/controller/create-agent-state.ts
420
+ function createAiAgentState(options) {
421
+ const { binding, compiled } = options;
422
+ const decisionInterval = effectiveAiInterval(compiled.definition.decisionIntervalMs, compiled.schedulerClass.decisionIntervalMultiplier);
423
+ const state = {
424
+ binding: cloneAiAgentBinding(binding),
425
+ definition: compiled.definition,
426
+ sensors: compiled.sensors,
427
+ goals: compiled.goals,
428
+ goalsById: compiled.goalsById,
429
+ tasksById: compiled.tasksById,
430
+ schedulerClass: compiled.schedulerClass,
431
+ memory: /* @__PURE__ */ new Map(),
432
+ blackboard: createAiBlackboard({
433
+ limit: options.blackboardLimit,
434
+ valueLimits: options.blackboardValueLimits
435
+ }),
436
+ currentGoalId: void 0,
437
+ currentGoalScore: void 0,
438
+ committedUntil: void 0,
439
+ task: void 0,
440
+ cooldowns: /* @__PURE__ */ new Map(),
441
+ nextDecisionAt: options.elapsed + stableAiScheduleOffset(binding.agentId, decisionInterval),
442
+ nextSensorAt: /* @__PURE__ */ new Map(),
443
+ delayedDecisions: 0
444
+ };
445
+ for (const sensor of compiled.sensors) {
446
+ const interval = effectiveAiInterval(sensor.intervalMs, compiled.schedulerClass.sensorIntervalMultiplier);
447
+ state.nextSensorAt.set(sensor.id, options.elapsed + stableAiScheduleOffset(`${binding.agentId}:${sensor.id}`, interval));
448
+ }
449
+ return state;
450
+ }
451
+ //#endregion
452
+ //#region src/decision/goal-selection.ts
453
+ function selectAiGoal(options) {
454
+ const candidate = options.scores.find((score) => score.eligible);
455
+ const current = options.currentGoalId === void 0 ? void 0 : options.scores.find((score) => score.goalId === options.currentGoalId);
456
+ if (options.currentGoalId === void 0) return {
457
+ action: candidate === void 0 ? "clear" : "select",
458
+ reason: candidate === void 0 ? "no-eligible-goal" : "initial",
459
+ candidate,
460
+ current
461
+ };
462
+ if (candidate?.goalId === options.currentGoalId) return {
463
+ action: "keep",
464
+ reason: "unchanged",
465
+ candidate,
466
+ current
467
+ };
468
+ if (current?.eligible && (options.committedUntil ?? 0) > options.elapsed) return {
469
+ action: "keep",
470
+ reason: "commitment-active",
471
+ candidate,
472
+ current
473
+ };
474
+ if (candidate === void 0) return {
475
+ action: options.canInterrupt ? "clear" : "keep",
476
+ reason: options.canInterrupt ? "no-eligible-goal" : "interrupt-policy",
477
+ candidate,
478
+ current
479
+ };
480
+ if (current?.eligible && candidate.score < current.score + options.switchThreshold) return {
481
+ action: "keep",
482
+ reason: "switch-threshold",
483
+ candidate,
484
+ current
485
+ };
486
+ if (!options.canInterrupt) return {
487
+ action: "keep",
488
+ reason: "interrupt-policy",
489
+ candidate,
490
+ current
491
+ };
492
+ return {
493
+ action: "select",
494
+ reason: current?.eligible ? "higher-score" : "current-ineligible",
495
+ candidate,
496
+ current
497
+ };
498
+ }
499
+ //#endregion
500
+ //#region src/decision/utility-curve.ts
501
+ function evaluateAiUtilityCurve(curve, raw) {
502
+ if (!Number.isFinite(raw)) return 0;
503
+ switch (curve.type) {
504
+ case "linear": return normalize(raw, curve.min ?? 0, curve.max ?? 1);
505
+ case "inverse": return 1 - normalize(raw, curve.min ?? 0, curve.max ?? 1);
506
+ case "step": return clampAiUtilityValue(raw >= curve.threshold ? curve.above ?? 1 : curve.below ?? 0);
507
+ case "power": return Math.pow(normalize(raw, curve.min ?? 0, curve.max ?? 1), curve.exponent);
508
+ case "points": return evaluatePointsCurve(curve.points, raw);
509
+ }
510
+ }
511
+ function evaluatePointsCurve(points, raw) {
512
+ const first = points[0];
513
+ const last = points.at(-1);
514
+ if (first === void 0 || last === void 0) return 0;
515
+ if (raw <= first.x) return clampAiUtilityValue(first.y);
516
+ if (raw >= last.x) return clampAiUtilityValue(last.y);
517
+ for (let index = 0; index < points.length - 1; index += 1) {
518
+ const left = points[index];
519
+ const right = points[index + 1];
520
+ if (left !== void 0 && right !== void 0 && raw >= left.x && raw <= right.x) {
521
+ const amount = (raw - left.x) / (right.x - left.x);
522
+ return clampAiUtilityValue(left.y + (right.y - left.y) * amount);
523
+ }
524
+ }
525
+ return 0;
526
+ }
527
+ function normalize(value, min, max) {
528
+ return max === min ? value >= max ? 1 : 0 : clampAiUtilityValue((value - min) / (max - min));
529
+ }
530
+ function clampAiUtilityValue(value) {
531
+ return Math.max(0, Math.min(1, value));
532
+ }
533
+ //#endregion
534
+ //#region src/decision/goal-scoring.ts
535
+ function scoreAiGoals(options) {
536
+ const scores = options.goals.map((goal) => {
537
+ const considerations = goal.considerations.map((consideration) => {
538
+ const raw = options.resolveInput(consideration.input)?.read(options.context, consideration) ?? 0;
539
+ return {
540
+ input: consideration.input,
541
+ raw,
542
+ curved: evaluateAiUtilityCurve(consideration.curve, raw),
543
+ weight: consideration.weight ?? 1
544
+ };
545
+ });
546
+ const totalWeight = considerations.reduce((total, item) => total + item.weight, 0);
547
+ const score = clampAiUtilityValue((considerations.some((item) => item.curved <= 0) ? 0 : Math.exp(considerations.reduce((total, item) => total + Math.log(clampAiUtilityValue(item.curved)) * item.weight, 0) / Math.max(totalWeight, 1))) * (goal.weight ?? 1));
548
+ const cooldownUntil = options.cooldowns.get(goal.id) ?? 0;
549
+ return {
550
+ goalId: goal.id,
551
+ score,
552
+ eligible: score >= (goal.minScore ?? 0) && cooldownUntil <= options.elapsed,
553
+ considerations
554
+ };
555
+ });
556
+ scores.sort((left, right) => left.score === right.score ? left.goalId.localeCompare(right.goalId) : right.score - left.score);
557
+ return scores;
558
+ }
559
+ //#endregion
560
+ //#region src/controller/goal-controller.ts
561
+ function createAiGoalController(options) {
562
+ const controller = {
563
+ score(state) {
564
+ const scores = scoreAiGoals({
565
+ goals: state.goals,
566
+ context: options.readContext(state),
567
+ cooldowns: state.cooldowns,
568
+ elapsed: options.elapsed(),
569
+ resolveInput: options.resolveInput
570
+ });
571
+ options.onScores(state, scores);
572
+ return scores;
573
+ },
574
+ decide(state) {
575
+ const scores = controller.score(state);
576
+ const currentGoal = state.currentGoalId === void 0 ? void 0 : options.goalFor(state, state.currentGoalId);
577
+ const elapsed = options.elapsed();
578
+ const decision = selectAiGoal({
579
+ scores,
580
+ currentGoalId: state.currentGoalId,
581
+ committedUntil: state.committedUntil,
582
+ elapsed,
583
+ switchThreshold: currentGoal?.switchThreshold ?? 0,
584
+ canInterrupt: options.tasks.canInterrupt(state)
585
+ });
586
+ options.onDecision(state, decision);
587
+ if (decision.action === "keep") {
588
+ if (decision.current !== void 0) state.currentGoalScore = decision.current.score;
589
+ return;
590
+ }
591
+ if (decision.action === "clear") {
592
+ if (state.currentGoalId !== void 0) {
593
+ options.tasks.cancel(state, "no-eligible-goal");
594
+ state.currentGoalId = void 0;
595
+ state.currentGoalScore = void 0;
596
+ state.committedUntil = void 0;
597
+ }
598
+ return;
599
+ }
600
+ const candidate = decision.candidate;
601
+ if (candidate === void 0) return;
602
+ if (state.currentGoalId !== void 0 && currentGoal !== void 0) {
603
+ options.tasks.cancel(state, "goal-switched");
604
+ if ((currentGoal.cooldownMs ?? 0) > 0) state.cooldowns.set(currentGoal.id, elapsed + (currentGoal.cooldownMs ?? 0));
605
+ }
606
+ const goal = options.goalFor(state, candidate.goalId);
607
+ state.currentGoalId = goal.id;
608
+ state.currentGoalScore = candidate.score;
609
+ state.committedUntil = elapsed + (goal.commitmentMs ?? 0);
610
+ options.onSelected(state, goal, candidate.score);
611
+ options.tasks.start(state, goal);
612
+ }
613
+ };
614
+ return controller;
615
+ }
616
+ //#endregion
617
+ //#region src/decision/cooldowns.ts
618
+ function pruneAiGoalCooldowns(cooldowns, elapsed) {
619
+ for (const [goalId, cooldownUntil] of cooldowns) if (cooldownUntil <= elapsed) cooldowns.delete(goalId);
620
+ }
621
+ //#endregion
622
+ //#region src/definition/ai-data-types.ts
623
+ const AI_AGENT_TYPE = "ai.agent";
624
+ const AI_SENSOR_TYPE = "ai.sensor";
625
+ const AI_GOAL_TYPE = "ai.goal";
626
+ const AI_TASK_TYPE = "ai.task";
627
+ function createAiDataTypes() {
628
+ return [
629
+ createAiAgentDataType(),
630
+ createAiSensorDataType(),
631
+ createAiGoalDataType(),
632
+ createAiTaskDataType()
633
+ ];
634
+ }
635
+ function createAiAgentDataType() {
636
+ return {
637
+ type: AI_AGENT_TYPE,
638
+ getTags: (definition) => definition.tags ?? [],
639
+ validate(document) {
640
+ const diagnostics = validateId(document, "ai.agent_missing_id");
641
+ if (!positiveFinite(document.data.decisionIntervalMs)) diagnostics.push(diagnostic("ai.agent_invalid_decision_interval", "AI agent decisionIntervalMs must be positive and finite", document, "decisionIntervalMs"));
642
+ if (!Number.isSafeInteger(document.data.memoryLimit) || document.data.memoryLimit <= 0) diagnostics.push(diagnostic("ai.agent_invalid_memory_limit", "AI agent memoryLimit must be a positive integer", document, "memoryLimit"));
643
+ if (document.data.blackboardLimit !== void 0 && (!Number.isSafeInteger(document.data.blackboardLimit) || document.data.blackboardLimit <= 0)) diagnostics.push(diagnostic("ai.agent_invalid_blackboard_limit", "AI agent blackboardLimit must be a positive integer", document, "blackboardLimit"));
644
+ diagnostics.push(...validateRefs(document.data.sensors, AI_SENSOR_TYPE, document, "sensors"));
645
+ diagnostics.push(...validateRefs(document.data.goals, AI_GOAL_TYPE, document, "goals"));
646
+ return diagnostics;
647
+ },
648
+ references(document) {
649
+ return [...references(document.data.sensors, "sensors"), ...references(document.data.goals, "goals")];
650
+ }
651
+ };
652
+ }
653
+ function createAiSensorDataType() {
654
+ return {
655
+ type: AI_SENSOR_TYPE,
656
+ getTags: (definition) => definition.tags ?? [],
657
+ validate(document) {
658
+ const diagnostics = validateId(document, "ai.sensor_missing_id");
659
+ if (!nonEmptyString(document.data.sampler)) diagnostics.push(diagnostic("ai.sensor_missing_sampler", "AI sensor requires a sampler id", document, "sampler"));
660
+ if (!positiveFinite(document.data.intervalMs)) diagnostics.push(diagnostic("ai.sensor_invalid_interval", "AI sensor intervalMs must be positive and finite", document, "intervalMs"));
661
+ return diagnostics;
662
+ }
663
+ };
664
+ }
665
+ function createAiGoalDataType() {
666
+ return {
667
+ type: AI_GOAL_TYPE,
668
+ getTags: (definition) => definition.tags ?? [],
669
+ validate(document) {
670
+ const diagnostics = validateId(document, "ai.goal_missing_id");
671
+ diagnostics.push(...validateRefs([document.data.task], AI_TASK_TYPE, document, "task"));
672
+ if (!Array.isArray(document.data.considerations) || document.data.considerations.length === 0) diagnostics.push(diagnostic("ai.goal_missing_considerations", "AI goal requires at least one consideration", document, "considerations"));
673
+ for (const [index, consideration] of (document.data.considerations ?? []).entries()) {
674
+ if (!nonEmptyString(consideration.input)) diagnostics.push(diagnostic("ai.goal_missing_input", "AI consideration requires an input id", document, `considerations[${index}].input`));
675
+ if (consideration.weight !== void 0 && !positiveFinite(consideration.weight)) diagnostics.push(diagnostic("ai.goal_invalid_consideration_weight", "AI consideration weight must be positive and finite", document, `considerations[${index}].weight`));
676
+ diagnostics.push(...validateCurve(consideration.curve, document, `considerations[${index}].curve`));
677
+ }
678
+ for (const [field, value] of [
679
+ ["weight", document.data.weight],
680
+ ["commitmentMs", document.data.commitmentMs],
681
+ ["switchThreshold", document.data.switchThreshold],
682
+ ["cooldownMs", document.data.cooldownMs]
683
+ ]) if (value !== void 0 && !nonNegativeFinite(value)) diagnostics.push(diagnostic("ai.goal_invalid_number", `AI goal ${field} must be non-negative and finite`, document, field));
684
+ if (document.data.minScore !== void 0 && (!Number.isFinite(document.data.minScore) || document.data.minScore < 0 || document.data.minScore > 1)) diagnostics.push(diagnostic("ai.goal_invalid_min_score", "AI goal minScore must be between zero and one", document, "minScore"));
685
+ return diagnostics;
686
+ },
687
+ references(document) {
688
+ return references([document.data.task], "task");
689
+ }
690
+ };
691
+ }
692
+ function createAiTaskDataType() {
693
+ return {
694
+ type: AI_TASK_TYPE,
695
+ getTags: (definition) => definition.tags ?? [],
696
+ validate(document) {
697
+ const diagnostics = validateId(document, "ai.task_missing_id");
698
+ if (!nonEmptyString(document.data.executor)) diagnostics.push(diagnostic("ai.task_missing_executor", "AI task requires an executor id", document, "executor"));
699
+ if (document.data.interruptPolicy !== void 0 && ![
700
+ "always",
701
+ "safe-point",
702
+ "never"
703
+ ].includes(document.data.interruptPolicy)) diagnostics.push(diagnostic("ai.task_invalid_interrupt_policy", "AI task interrupt policy is invalid", document, "interruptPolicy"));
704
+ if (document.data.timeoutMs !== void 0 && !positiveFinite(document.data.timeoutMs)) diagnostics.push(diagnostic("ai.task_invalid_timeout", "AI task timeoutMs must be positive and finite", document, "timeoutMs"));
705
+ return diagnostics;
706
+ }
707
+ };
708
+ }
709
+ function validateCurve(curve, document, path) {
710
+ if (!curve || ![
711
+ "linear",
712
+ "inverse",
713
+ "step",
714
+ "power",
715
+ "points"
716
+ ].includes(curve.type)) return [diagnostic("ai.goal_invalid_curve", "AI utility curve type is invalid", document, path)];
717
+ if (curve.type === "power" && !positiveFinite(curve.exponent)) return [diagnostic("ai.goal_invalid_curve_exponent", "AI power curve exponent must be positive and finite", document, `${path}.exponent`)];
718
+ if (curve.type === "step" && !Number.isFinite(curve.threshold)) return [diagnostic("ai.goal_invalid_curve_threshold", "AI step curve threshold must be finite", document, `${path}.threshold`)];
719
+ if (curve.type === "points") {
720
+ if (curve.points.length < 2) return [diagnostic("ai.goal_invalid_curve_points", "AI points curve requires at least two points", document, `${path}.points`)];
721
+ for (let index = 0; index < curve.points.length; index += 1) {
722
+ const point = curve.points[index];
723
+ const previous = curve.points[index - 1];
724
+ if (point === void 0 || !Number.isFinite(point.x) || !Number.isFinite(point.y) || previous !== void 0 && point.x <= previous.x) return [diagnostic("ai.goal_invalid_curve_points", "AI points curve coordinates must be finite and sorted by ascending x", document, `${path}.points[${index}]`)];
725
+ }
726
+ }
727
+ return [];
728
+ }
729
+ function validateRefs(values, expectedType, document, path) {
730
+ if (!Array.isArray(values)) return [diagnostic("ai.invalid_references", `AI ${path} must be an array`, document, path)];
731
+ const diagnostics = [];
732
+ const ids = /* @__PURE__ */ new Set();
733
+ for (const [index, reference] of values.entries()) {
734
+ if (reference?.type !== expectedType || !nonEmptyString(reference.id) || ids.has(reference.id)) diagnostics.push(diagnostic(ids.has(reference?.id) ? "ai.duplicate_reference" : "ai.invalid_reference", `AI ${path} entries must be unique ${expectedType} references`, document, `${path}[${index}]`));
735
+ if (reference?.id) ids.add(reference.id);
736
+ }
737
+ return diagnostics;
738
+ }
739
+ function references(values, path) {
740
+ return (values ?? []).filter((reference) => reference?.type && reference.id).map((reference, index) => ({
741
+ type: reference.type,
742
+ id: reference.id,
743
+ path: `${path}[${index}]`
744
+ }));
745
+ }
746
+ function validateId(document, code) {
747
+ return nonEmptyString(document.data.id) ? [] : [diagnostic(code, "AI definition requires an id", document, "id")];
748
+ }
749
+ function diagnostic(code, message, document, path) {
750
+ return {
751
+ code,
752
+ message,
753
+ severity: "error",
754
+ key: {
755
+ type: document.type,
756
+ id: document.id
757
+ },
758
+ path,
759
+ ...document.sourcePackId === void 0 ? {} : { sourcePackId: document.sourcePackId }
760
+ };
761
+ }
762
+ function nonEmptyString(value) {
763
+ return typeof value === "string" && value.trim().length > 0;
764
+ }
765
+ function positiveFinite(value) {
766
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
767
+ }
768
+ function nonNegativeFinite(value) {
769
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
770
+ }
771
+ //#endregion
772
+ //#region src/definition/agent-definition-compiler.ts
773
+ function createAiAgentDefinitionCompiler(options) {
774
+ const compiledDefinitions = /* @__PURE__ */ new Map();
775
+ return {
776
+ compile(definitionId) {
777
+ const existing = compiledDefinitions.get(definitionId);
778
+ if (existing !== void 0) return existing;
779
+ const definition = cloneAiAgentDefinition(definitionFor(AI_AGENT_TYPE, definitionId));
780
+ const sensors = definition.sensors.map((sensorRef) => cloneAiSensorDefinition(definitionFor(AI_SENSOR_TYPE, sensorRef.id)));
781
+ for (const sensor of sensors) if (!options.registries.sensors.has(sensor.sampler)) throw createAiError("ai.definition_missing", `AI sensor sampler is not registered: ${sensor.sampler}`);
782
+ const goals = definition.goals.map((goalRef) => cloneAiGoalDefinition(definitionFor(AI_GOAL_TYPE, goalRef.id)));
783
+ const goalsById = new Map(goals.map((goal) => [goal.id, goal]));
784
+ if (goalsById.size !== goals.length) throw createAiError("ai.duplicate_registry_entry", `AI agent contains duplicate goals: ${definition.id}`);
785
+ const tasksById = /* @__PURE__ */ new Map();
786
+ for (const goal of goals) {
787
+ for (const consideration of goal.considerations) if (!options.registries.inputs.has(consideration.input)) throw createAiError("ai.definition_missing", `AI utility input is not registered: ${consideration.input}`);
788
+ let task = tasksById.get(goal.task.id);
789
+ if (task === void 0) {
790
+ task = cloneAiTaskDefinition(definitionFor(AI_TASK_TYPE, goal.task.id));
791
+ tasksById.set(task.id, task);
792
+ }
793
+ if (!options.registries.tasks.has(task.executor)) throw createAiError("ai.definition_missing", `AI task executor is not registered: ${task.executor}`);
794
+ }
795
+ const schedulerClassId = definition.schedulerClass ?? "default";
796
+ const schedulerClass = options.registries.schedulerClasses.get(schedulerClassId);
797
+ if (schedulerClass === void 0) throw createAiError("ai.definition_missing", `AI scheduler class is not registered: ${schedulerClassId}`);
798
+ const compiled = {
799
+ definition,
800
+ sensors,
801
+ goals,
802
+ goalsById,
803
+ tasksById,
804
+ schedulerClass
805
+ };
806
+ compiledDefinitions.set(definitionId, compiled);
807
+ return compiled;
808
+ },
809
+ size() {
810
+ return compiledDefinitions.size;
811
+ },
812
+ clear() {
813
+ compiledDefinitions.clear();
814
+ }
815
+ };
816
+ function definitionFor(type, definitionId) {
817
+ if (!options.dataRegistry.has(type, definitionId)) throw createAiError("ai.definition_missing", `AI definition is missing: ${type}/${definitionId}`);
818
+ return options.dataRegistry.getValue(type, definitionId);
819
+ }
820
+ }
821
+ //#endregion
822
+ //#region src/task/clone-task-state.ts
823
+ function cloneAiTaskState(task) {
824
+ return {
825
+ ...task,
826
+ state: cloneAiRecord(task.state)
827
+ };
828
+ }
829
+ //#endregion
830
+ //#region src/observability/snapshot-projection.ts
831
+ function projectAiAgentSnapshot(state) {
832
+ return {
833
+ binding: cloneAiAgentBinding(state.binding),
834
+ schedulerClassId: state.schedulerClass.id,
835
+ ...state.currentGoalId === void 0 ? {} : { goalId: state.currentGoalId },
836
+ ...state.currentGoalScore === void 0 ? {} : { goalScore: state.currentGoalScore },
837
+ ...state.committedUntil === void 0 ? {} : { committedUntil: state.committedUntil },
838
+ ...state.task === void 0 ? {} : { task: cloneAiTaskState(state.task) },
839
+ memorySize: state.memory.size,
840
+ blackboardSize: state.blackboard.size,
841
+ blackboardLimit: state.blackboard.limit,
842
+ blackboardKeys: state.blackboard.keys(),
843
+ nextDecisionAt: state.nextDecisionAt,
844
+ delayedDecisions: state.delayedDecisions
845
+ };
846
+ }
847
+ function projectAiRuntimeSnapshot(options) {
848
+ const agents = options.agents.map(projectAiAgentSnapshot);
849
+ return {
850
+ id: options.id,
851
+ elapsed: options.elapsed,
852
+ disposed: options.disposed,
853
+ compiledDefinitions: options.compiledDefinitions,
854
+ agents,
855
+ activeTasks: agents.filter((agent) => agent.task?.status === "running").length,
856
+ memoryFacts: agents.reduce((total, agent) => total + agent.memorySize, 0),
857
+ intentsEmitted: options.intentsEmitted,
858
+ delayedSensorSamples: options.delayedSensorSamples,
859
+ delayedDecisions: options.delayedDecisions,
860
+ rejectedPathRequests: options.rejectedPathRequests,
861
+ droppedTraceEntries: options.droppedTraceEntries,
862
+ traceEntries: options.traceEntries
863
+ };
864
+ }
865
+ //#endregion
866
+ //#region src/observability/trace-recorder.ts
867
+ function createAiTraceRecorder(options) {
868
+ let updating = false;
869
+ let producedThisUpdate = 0;
870
+ let droppedThisUpdate = 0;
871
+ let droppedTotal = 0;
872
+ const droppedKinds = /* @__PURE__ */ new Map();
873
+ return {
874
+ beginUpdate() {
875
+ updating = true;
876
+ producedThisUpdate = 0;
877
+ droppedThisUpdate = 0;
878
+ droppedKinds.clear();
879
+ },
880
+ push(entry) {
881
+ if (!options.enabled) return;
882
+ if (updating && producedThisUpdate >= options.maxEntriesPerUpdate) {
883
+ droppedThisUpdate += 1;
884
+ droppedTotal += 1;
885
+ droppedKinds.set(entry.kind, (droppedKinds.get(entry.kind) ?? 0) + 1);
886
+ return;
887
+ }
888
+ if (updating) producedThisUpdate += 1;
889
+ options.store.push(entry);
890
+ },
891
+ endUpdate(timestamp) {
892
+ updating = false;
893
+ if (!options.enabled || !options.emitDropSummary || droppedThisUpdate === 0) return;
894
+ options.store.push({
895
+ kind: "budget",
896
+ label: "ai.trace_dropped",
897
+ timestamp,
898
+ payload: {
899
+ dropped: droppedThisUpdate,
900
+ kinds: Object.fromEntries([...droppedKinds.entries()].sort(([left], [right]) => left.localeCompare(right)))
901
+ }
902
+ });
903
+ },
904
+ dropped() {
905
+ return droppedTotal;
906
+ }
907
+ };
908
+ }
909
+ //#endregion
910
+ //#region src/observability/trace-store.ts
911
+ function createAiTraceStore(options = {}) {
912
+ const limit = readLimit(options.limit, 512);
913
+ const retainedKinds = options.kinds === void 0 ? void 0 : new Set(options.kinds);
914
+ const kindLimits = /* @__PURE__ */ new Map();
915
+ for (const [kind, kindLimit] of Object.entries(options.kindLimits ?? {})) if (kindLimit !== void 0) kindLimits.set(kind, readLimit(kindLimit, limit));
916
+ const retainedKindCounts = /* @__PURE__ */ new Map();
917
+ const entries = [];
918
+ let sequence = 0;
919
+ return {
920
+ push(entry) {
921
+ const value = cloneTrace({
922
+ ...entry,
923
+ sequence
924
+ });
925
+ sequence += 1;
926
+ const kindLimit = kindLimits.get(entry.kind) ?? limit;
927
+ if (limit > 0 && kindLimit > 0 && retainedKinds?.has(entry.kind) !== false) {
928
+ entries.push(value);
929
+ if (kindLimits.has(entry.kind)) {
930
+ retainedKindCounts.set(entry.kind, (retainedKindCounts.get(entry.kind) ?? 0) + 1);
931
+ if ((retainedKindCounts.get(entry.kind) ?? 0) > kindLimit) {
932
+ const oldestKindIndex = entries.findIndex((candidate) => candidate.kind === entry.kind);
933
+ if (oldestKindIndex >= 0) {
934
+ const [removed] = entries.splice(oldestKindIndex, 1);
935
+ decrementRetainedKindCount(retainedKindCounts, removed?.kind);
936
+ }
937
+ }
938
+ }
939
+ if (entries.length > limit) {
940
+ const removed = entries.splice(0, entries.length - limit);
941
+ for (const removedEntry of removed) decrementRetainedKindCount(retainedKindCounts, removedEntry.kind);
942
+ }
943
+ }
944
+ notifyEntry(options, value);
945
+ },
946
+ snapshot() {
947
+ return entries.map(cloneTrace);
948
+ },
949
+ clear() {
950
+ entries.length = 0;
951
+ retainedKindCounts.clear();
952
+ },
953
+ size() {
954
+ return entries.length;
955
+ }
956
+ };
957
+ }
958
+ function decrementRetainedKindCount(counts, kind) {
959
+ if (kind === void 0 || !counts.has(kind)) return;
960
+ const next = (counts.get(kind) ?? 0) - 1;
961
+ if (next <= 0) {
962
+ counts.delete(kind);
963
+ return;
964
+ }
965
+ counts.set(kind, next);
966
+ }
967
+ function notifyEntry(options, entry) {
968
+ if (options.onEntry === void 0) return;
969
+ try {
970
+ options.onEntry(cloneTrace(entry));
971
+ } catch (error) {
972
+ try {
973
+ options.onEntryError?.(error, cloneTrace(entry));
974
+ } catch {}
975
+ }
976
+ }
977
+ function cloneTrace(entry) {
978
+ return {
979
+ ...entry,
980
+ ...entry.payload === void 0 ? {} : { payload: cloneAiRecord(entry.payload) }
981
+ };
982
+ }
983
+ function readLimit(value, fallback) {
984
+ const resolved = value ?? fallback;
985
+ if (!Number.isSafeInteger(resolved) || resolved < 0) throw new RangeError("AI trace limit must be a non-negative integer");
986
+ return resolved;
987
+ }
988
+ //#endregion
989
+ //#region src/scheduler/due-work.ts
990
+ function compareAiDueWork(left, right) {
991
+ if (left.dueAt !== right.dueAt) return left.dueAt - right.dueAt;
992
+ if (left.priority !== right.priority) return right.priority - left.priority;
993
+ const agentOrder = left.agentId.localeCompare(right.agentId);
994
+ if (agentOrder !== 0) return agentOrder;
995
+ return (left.itemId ?? "").localeCompare(right.itemId ?? "");
996
+ }
997
+ //#endregion
998
+ //#region src/perception/perception-controller.ts
999
+ function createAiPerceptionController(options) {
1000
+ return { sample(agents) {
1001
+ const elapsed = options.elapsed();
1002
+ const due = agents.flatMap((agent) => agent.sensors.flatMap((sensor) => {
1003
+ const dueAt = agent.nextSensorAt.get(sensor.id) ?? elapsed;
1004
+ return dueAt <= elapsed ? [{
1005
+ agent,
1006
+ sensor,
1007
+ dueAt
1008
+ }] : [];
1009
+ }));
1010
+ due.sort((left, right) => compareAiDueWork({
1011
+ dueAt: left.dueAt,
1012
+ priority: left.agent.schedulerClass.priority ?? 0,
1013
+ agentId: left.agent.binding.agentId,
1014
+ itemId: left.sensor.id
1015
+ }, {
1016
+ dueAt: right.dueAt,
1017
+ priority: right.agent.schedulerClass.priority ?? 0,
1018
+ agentId: right.agent.binding.agentId,
1019
+ itemId: right.sensor.id
1020
+ }));
1021
+ let samples = 0;
1022
+ let delayed = 0;
1023
+ for (const { agent, sensor } of due) {
1024
+ if (samples >= options.maxSamplesPerTick) {
1025
+ delayed += 1;
1026
+ options.onDelayed(agent, sensor);
1027
+ continue;
1028
+ }
1029
+ const sampler = options.samplerFor(sensor.sampler);
1030
+ if (sampler === void 0) continue;
1031
+ const facts = sampler.sample(options.contextFor(agent), sensor);
1032
+ retainAiPerceptionFacts(agent.memory, facts, agent.definition.memoryLimit);
1033
+ agent.nextSensorAt.set(sensor.id, elapsed + effectiveAiInterval(sensor.intervalMs, agent.schedulerClass.sensorIntervalMultiplier));
1034
+ samples += 1;
1035
+ options.onSample(agent, sensor, facts);
1036
+ }
1037
+ return delayed;
1038
+ } };
1039
+ }
1040
+ //#endregion
1041
+ //#region src/persistence/checkpoint-projection.ts
1042
+ function projectAiAgentCheckpoint(state) {
1043
+ return {
1044
+ binding: cloneAiAgentBinding(state.binding),
1045
+ schedulerClassId: state.schedulerClass.id,
1046
+ memory: listAiPerceptionFacts(state.memory),
1047
+ blackboard: state.blackboard.capture(),
1048
+ ...state.currentGoalId === void 0 ? {} : { currentGoalId: state.currentGoalId },
1049
+ ...state.currentGoalScore === void 0 ? {} : { currentGoalScore: state.currentGoalScore },
1050
+ ...state.committedUntil === void 0 ? {} : { committedUntil: state.committedUntil },
1051
+ ...state.task === void 0 ? {} : { task: cloneAiTaskState(state.task) },
1052
+ cooldowns: [...state.cooldowns.entries()].sort(([left], [right]) => left.localeCompare(right)),
1053
+ nextDecisionAt: state.nextDecisionAt,
1054
+ nextSensorAt: [...state.nextSensorAt.entries()].sort(([left], [right]) => left.localeCompare(right)),
1055
+ delayedDecisions: state.delayedDecisions
1056
+ };
1057
+ }
1058
+ function restoreAiAgentCheckpoint(state, checkpoint) {
1059
+ state.memory.clear();
1060
+ retainAiPerceptionFacts(state.memory, checkpoint.memory, state.definition.memoryLimit);
1061
+ state.blackboard.replace(checkpoint.blackboard);
1062
+ state.currentGoalId = checkpoint.currentGoalId;
1063
+ state.currentGoalScore = checkpoint.currentGoalScore;
1064
+ state.committedUntil = checkpoint.committedUntil;
1065
+ state.task = checkpoint.task === void 0 ? void 0 : cloneAiTaskState(checkpoint.task);
1066
+ state.cooldowns = new Map(checkpoint.cooldowns);
1067
+ state.nextDecisionAt = checkpoint.nextDecisionAt;
1068
+ state.nextSensorAt = new Map(checkpoint.nextSensorAt);
1069
+ state.delayedDecisions = checkpoint.delayedDecisions;
1070
+ }
1071
+ //#endregion
1072
+ //#region src/persistence/checkpoint-compatibility.ts
1073
+ function validateAiCheckpointCompatibility(state, checkpoint) {
1074
+ if (checkpoint.currentGoalId !== void 0 && !state.goalsById.has(checkpoint.currentGoalId)) throw incompatible(checkpoint, `goal ${checkpoint.currentGoalId} is not defined`);
1075
+ if (checkpoint.task !== void 0) {
1076
+ const task = state.tasksById.get(checkpoint.task.taskId);
1077
+ if (checkpoint.currentGoalId === void 0 || task === void 0 || task.executor !== checkpoint.task.executorId) throw incompatible(checkpoint, `task ${checkpoint.task.taskId} is not compatible`);
1078
+ }
1079
+ for (const [goalId] of checkpoint.cooldowns) if (!state.goalsById.has(goalId)) throw incompatible(checkpoint, `cooldown goal ${goalId} is not defined`);
1080
+ const sensorIds = new Set(state.sensors.map((sensor) => sensor.id));
1081
+ for (const [sensorId] of checkpoint.nextSensorAt) if (!sensorIds.has(sensorId)) throw incompatible(checkpoint, `sensor ${sensorId} is not defined`);
1082
+ }
1083
+ function incompatible(checkpoint, reason) {
1084
+ return createAiError("ai.invalid_config", "AI checkpoint does not match its definition", {
1085
+ agentId: checkpoint.binding.agentId,
1086
+ definitionId: checkpoint.binding.definitionId,
1087
+ reason
1088
+ });
1089
+ }
1090
+ //#endregion
1091
+ //#region src/persistence/checkpoint-validation.ts
1092
+ function validateAiRuntimeCheckpoint(checkpoint) {
1093
+ if (checkpoint.version !== 1 || !Number.isFinite(checkpoint.elapsed) || checkpoint.elapsed < 0 || !Array.isArray(checkpoint.agents)) throw createAiError("ai.invalid_config", "AI checkpoint is invalid");
1094
+ const agentIds = /* @__PURE__ */ new Set();
1095
+ for (const rawAgent of checkpoint.agents) {
1096
+ if (!isRecord(rawAgent)) throw createAiError("ai.invalid_config", "AI checkpoint agent state is invalid");
1097
+ const agent = rawAgent;
1098
+ if (typeof agent.binding?.agentId !== "string" || agent.binding.agentId.length === 0 || agentIds.has(agent.binding.agentId) || typeof agent.binding.definitionId !== "string" || agent.binding.definitionId.length === 0 || agent.schedulerClassId !== void 0 && (typeof agent.schedulerClassId !== "string" || agent.schedulerClassId.length === 0) || !Array.isArray(agent.memory) || typeof agent.blackboard !== "object" || agent.blackboard === null || Array.isArray(agent.blackboard) || !Array.isArray(agent.cooldowns) || !agent.cooldowns.every(validScheduleEntry) || !Array.isArray(agent.nextSensorAt) || !agent.nextSensorAt.every(validScheduleEntry) || !Number.isFinite(agent.nextDecisionAt) || agent.nextDecisionAt < 0 || !Number.isSafeInteger(agent.delayedDecisions) || agent.delayedDecisions < 0 || !validOptionalFinite(agent.currentGoalScore, 0, 1) || !validOptionalFinite(agent.committedUntil, 0) || agent.currentGoalId !== void 0 && (typeof agent.currentGoalId !== "string" || agent.currentGoalId.length === 0) || !validTask(agent.task)) throw createAiError("ai.invalid_config", "AI checkpoint agent state is invalid", { agentId: agent.binding?.agentId });
1099
+ agentIds.add(agent.binding.agentId);
1100
+ }
1101
+ }
1102
+ function validScheduleEntry(entry) {
1103
+ return Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string" && entry[0].length > 0 && Number.isFinite(entry[1]) && entry[1] >= 0;
1104
+ }
1105
+ function validTask(task) {
1106
+ return task === void 0 || typeof task.taskId === "string" && task.taskId.length > 0 && typeof task.executorId === "string" && task.executorId.length > 0 && ["starting", "running"].includes(task.status) && Number.isFinite(task.startedAt) && task.startedAt >= 0 && Number.isFinite(task.updatedAt) && task.updatedAt >= task.startedAt && typeof task.safeToInterrupt === "boolean" && isRecord(task.state);
1107
+ }
1108
+ function validOptionalFinite(value, minimum, maximum) {
1109
+ return value === void 0 || Number.isFinite(value) && value >= minimum && (maximum === void 0 || value <= maximum);
1110
+ }
1111
+ function isRecord(value) {
1112
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1113
+ }
1114
+ //#endregion
1115
+ //#region src/persistence/restore-binding.ts
1116
+ function restoreAiAgentBinding(binding, options) {
1117
+ const restored = cloneAiAgentBinding(binding);
1118
+ if (binding.entityId !== void 0 && options?.resolveEntityId !== void 0) {
1119
+ const entityId = options.resolveEntityId(binding.entityId);
1120
+ if (entityId === void 0) return;
1121
+ restored.entityId = entityId;
1122
+ }
1123
+ if (binding.actorId !== void 0 && options?.resolveActorId !== void 0) {
1124
+ const actorId = options.resolveActorId(binding.actorId);
1125
+ if (actorId === void 0) return;
1126
+ restored.actorId = actorId;
1127
+ }
1128
+ return restored;
1129
+ }
1130
+ //#endregion
1131
+ //#region src/persistence/restore-task-state.ts
1132
+ function restoreAiTaskState(checkpoint, binding, elapsed, options) {
1133
+ if (checkpoint.task === void 0 || options?.resolveTaskState === void 0) return checkpoint;
1134
+ const state = options.resolveTaskState(cloneAiRecord(checkpoint.task.state), { ...binding });
1135
+ if (state === void 0) return {
1136
+ ...checkpoint,
1137
+ binding,
1138
+ currentGoalId: void 0,
1139
+ currentGoalScore: void 0,
1140
+ committedUntil: void 0,
1141
+ task: void 0,
1142
+ nextDecisionAt: elapsed
1143
+ };
1144
+ return {
1145
+ ...checkpoint,
1146
+ binding,
1147
+ task: {
1148
+ ...checkpoint.task,
1149
+ state: cloneAiRecord(state)
1150
+ }
1151
+ };
1152
+ }
1153
+ //#endregion
1154
+ //#region src/scheduler/decision-scheduler.ts
1155
+ function createAiDecisionScheduler(options) {
1156
+ return { run(agents) {
1157
+ const elapsed = options.elapsed();
1158
+ const due = agents.filter((agent) => agent.nextDecisionAt <= elapsed).sort((left, right) => compareAiDueWork({
1159
+ dueAt: left.nextDecisionAt,
1160
+ priority: left.schedulerClass.priority ?? 0,
1161
+ agentId: left.binding.agentId
1162
+ }, {
1163
+ dueAt: right.nextDecisionAt,
1164
+ priority: right.schedulerClass.priority ?? 0,
1165
+ agentId: right.binding.agentId
1166
+ }));
1167
+ let decisions = 0;
1168
+ let delayed = 0;
1169
+ for (const agent of due) {
1170
+ if (decisions >= options.maxDecisionsPerTick) {
1171
+ agent.delayedDecisions += 1;
1172
+ delayed += 1;
1173
+ options.onDelayed(agent);
1174
+ continue;
1175
+ }
1176
+ agent.nextDecisionAt = elapsed + effectiveAiInterval(agent.definition.decisionIntervalMs, agent.schedulerClass.decisionIntervalMultiplier);
1177
+ options.onDecision(agent);
1178
+ decisions += 1;
1179
+ }
1180
+ return delayed;
1181
+ } };
1182
+ }
1183
+ //#endregion
1184
+ //#region src/scheduler/reclassify-agent.ts
1185
+ function reclassifyAiAgent(agent, schedulerClass, elapsed) {
1186
+ const previous = agent.schedulerClass;
1187
+ if (previous.id === schedulerClass.id) return;
1188
+ agent.nextDecisionAt = rescaleDueAt(agent.nextDecisionAt, elapsed, effectiveAiInterval(agent.definition.decisionIntervalMs, previous.decisionIntervalMultiplier), effectiveAiInterval(agent.definition.decisionIntervalMs, schedulerClass.decisionIntervalMultiplier));
1189
+ for (const sensor of agent.sensors) {
1190
+ const dueAt = agent.nextSensorAt.get(sensor.id);
1191
+ if (dueAt === void 0) continue;
1192
+ agent.nextSensorAt.set(sensor.id, rescaleDueAt(dueAt, elapsed, effectiveAiInterval(sensor.intervalMs, previous.sensorIntervalMultiplier), effectiveAiInterval(sensor.intervalMs, schedulerClass.sensorIntervalMultiplier)));
1193
+ }
1194
+ agent.schedulerClass = schedulerClass;
1195
+ }
1196
+ function rescaleDueAt(dueAt, elapsed, previousInterval, nextInterval) {
1197
+ if (dueAt <= elapsed) return dueAt;
1198
+ return elapsed + Math.max(1, (dueAt - elapsed) / previousInterval * nextInterval);
1199
+ }
1200
+ //#endregion
1201
+ //#region src/task/task-controller.ts
1202
+ function createAiTaskController(options) {
1203
+ return {
1204
+ update(agent, deltaMs) {
1205
+ const taskState = agent.task;
1206
+ const elapsed = options.elapsed();
1207
+ if (taskState === void 0 || taskState.status !== "running" || taskState.updatedAt === elapsed) return;
1208
+ const task = options.taskFor(agent, taskState.taskId);
1209
+ if (task.timeoutMs !== void 0 && elapsed - taskState.startedAt >= task.timeoutMs) {
1210
+ finish(agent, {
1211
+ status: "failed",
1212
+ reason: "timeout",
1213
+ state: taskState.state
1214
+ });
1215
+ return;
1216
+ }
1217
+ const executor = options.executorFor(task.executor);
1218
+ if (executor === void 0 || agent.currentGoalId === void 0) {
1219
+ finish(agent, {
1220
+ status: "failed",
1221
+ reason: "executor-missing",
1222
+ state: taskState.state
1223
+ });
1224
+ return;
1225
+ }
1226
+ const goal = options.goalFor(agent, agent.currentGoalId);
1227
+ applyStep(agent, executor.update(options.contextFor(agent, goal, task, taskState), deltaMs));
1228
+ },
1229
+ start(agent, goal) {
1230
+ const task = options.taskFor(agent, goal.task.id);
1231
+ const executor = options.executorFor(task.executor);
1232
+ const elapsed = options.elapsed();
1233
+ const taskState = {
1234
+ taskId: task.id,
1235
+ executorId: task.executor,
1236
+ status: "starting",
1237
+ startedAt: elapsed,
1238
+ updatedAt: elapsed,
1239
+ safeToInterrupt: task.interruptPolicy === "always",
1240
+ state: {}
1241
+ };
1242
+ agent.task = taskState;
1243
+ if (executor === void 0) {
1244
+ finish(agent, {
1245
+ status: "failed",
1246
+ reason: "executor-missing"
1247
+ });
1248
+ return;
1249
+ }
1250
+ taskState.executorId = executor.id;
1251
+ options.onTransition(agent, {
1252
+ status: "started",
1253
+ taskId: task.id,
1254
+ executorId: executor.id,
1255
+ goalId: goal.id
1256
+ });
1257
+ applyStep(agent, executor.start(options.contextFor(agent, goal, task, taskState)));
1258
+ },
1259
+ cancel(agent, reason) {
1260
+ const taskState = agent.task;
1261
+ if (taskState === void 0) return;
1262
+ const task = options.taskFor(agent, taskState.taskId);
1263
+ const goal = agent.currentGoalId === void 0 ? void 0 : options.goalFor(agent, agent.currentGoalId);
1264
+ const executor = options.executorFor(task.executor);
1265
+ if (goal !== void 0) executor?.cancel?.(options.contextFor(agent, goal, task, taskState), reason);
1266
+ taskState.status = "cancelled";
1267
+ taskState.failureReason = reason;
1268
+ options.onTransition(agent, {
1269
+ status: "cancelled",
1270
+ taskId: task.id,
1271
+ goalId: agent.currentGoalId,
1272
+ reason
1273
+ });
1274
+ agent.task = void 0;
1275
+ },
1276
+ canInterrupt(agent) {
1277
+ const taskState = agent.task;
1278
+ if (taskState === void 0) return true;
1279
+ switch (options.taskFor(agent, taskState.taskId).interruptPolicy ?? "always") {
1280
+ case "always": return true;
1281
+ case "safe-point": return taskState.safeToInterrupt;
1282
+ case "never": return false;
1283
+ }
1284
+ }
1285
+ };
1286
+ function applyStep(agent, step) {
1287
+ const taskState = agent.task;
1288
+ if (taskState === void 0) return;
1289
+ taskState.updatedAt = options.elapsed();
1290
+ taskState.state = cloneAiRecord(step.state ?? taskState.state);
1291
+ taskState.safeToInterrupt = step.safeToInterrupt ?? taskState.safeToInterrupt;
1292
+ if (step.status === "running") {
1293
+ taskState.status = "running";
1294
+ return;
1295
+ }
1296
+ finish(agent, {
1297
+ ...step,
1298
+ status: step.status
1299
+ });
1300
+ }
1301
+ function finish(agent, step) {
1302
+ const taskState = agent.task;
1303
+ const elapsed = options.elapsed();
1304
+ if (taskState !== void 0) {
1305
+ taskState.status = step.status;
1306
+ taskState.updatedAt = elapsed;
1307
+ taskState.state = cloneAiRecord(step.state ?? taskState.state);
1308
+ if (step.reason === void 0) delete taskState.failureReason;
1309
+ else taskState.failureReason = step.reason;
1310
+ }
1311
+ const goalId = agent.currentGoalId;
1312
+ options.onTransition(agent, {
1313
+ status: step.status,
1314
+ taskId: taskState?.taskId ?? "unknown",
1315
+ goalId,
1316
+ reason: step.reason
1317
+ });
1318
+ if (goalId !== void 0) {
1319
+ const goal = options.goalFor(agent, goalId);
1320
+ if ((goal.cooldownMs ?? 0) > 0) agent.cooldowns.set(goalId, elapsed + (goal.cooldownMs ?? 0));
1321
+ }
1322
+ agent.task = void 0;
1323
+ agent.currentGoalId = void 0;
1324
+ agent.currentGoalScore = void 0;
1325
+ agent.committedUntil = void 0;
1326
+ agent.nextDecisionAt = elapsed + (step.status === "failed" ? options.failureBackoffMs : options.decisionInterval(agent));
1327
+ }
1328
+ }
1329
+ //#endregion
1330
+ //#region src/composition/registry.ts
1331
+ function createAiRegistry(values, category) {
1332
+ const result = /* @__PURE__ */ new Map();
1333
+ for (const value of values) {
1334
+ if (!value.id || result.has(value.id)) throw createAiError("ai.duplicate_registry_entry", `Duplicate AI ${category} registry entry: ${value.id}`);
1335
+ result.set(value.id, value);
1336
+ }
1337
+ return result;
1338
+ }
1339
+ //#endregion
1340
+ //#region src/observability/trace.ts
1341
+ const AI_TRACE_KINDS = [
1342
+ "lifecycle",
1343
+ "perception",
1344
+ "decision",
1345
+ "goal",
1346
+ "task",
1347
+ "intent",
1348
+ "budget"
1349
+ ];
1350
+ //#endregion
1351
+ //#region src/composition/runtime-config.ts
1352
+ function resolveAiRuntimeLimits(options) {
1353
+ return {
1354
+ maxSensorSamplesPerTick: resolvePositiveAiInteger(options.maxSensorSamplesPerTick, 256),
1355
+ maxDecisionsPerTick: resolvePositiveAiInteger(options.maxDecisionsPerTick, 128),
1356
+ maxPathRequestsPerTick: resolveNonNegativeAiInteger(options.maxPathRequestsPerTick, 64),
1357
+ failureBackoffMs: resolveNonNegativeAiNumber(options.failureBackoffMs, 100),
1358
+ defaultBlackboardLimit: resolvePositiveAiInteger(options.defaultBlackboardLimit, 32),
1359
+ blackboardValueLimits: {
1360
+ maxDepth: resolvePositiveAiInteger(options.maxBlackboardValueDepth, 8),
1361
+ maxNodes: resolvePositiveAiInteger(options.maxBlackboardValueNodes, 256),
1362
+ maxStringLength: resolvePositiveAiInteger(options.maxBlackboardStringLength, 4096)
1363
+ },
1364
+ traceRetention: resolveAiTraceRetention(options),
1365
+ traceProduction: resolveAiTraceProduction(options)
1366
+ };
1367
+ }
1368
+ function resolveAiTraceProduction(options) {
1369
+ const configured = options.traceProduction;
1370
+ const enabled = (options.traceRetention?.limit ?? options.traceLimit ?? 512) > 0 || options.onTrace !== void 0;
1371
+ const goalScoreDetail = configured?.goalScoreDetail ?? "summary";
1372
+ if (!(goalScoreDetail === "summary" || goalScoreDetail === "winner" || goalScoreDetail === "all")) throw createAiError("ai.invalid_config", "AI goal score trace detail is not supported", { goalScoreDetail });
1373
+ return {
1374
+ enabled,
1375
+ maxEntriesPerUpdate: resolveNonNegativeAiInteger(configured?.maxEntriesPerUpdate, enabled ? 512 : 0),
1376
+ goalScoreDetail,
1377
+ emitDropSummary: configured?.emitDropSummary ?? true
1378
+ };
1379
+ }
1380
+ function resolveAiTraceRetention(options) {
1381
+ const configured = options.traceRetention;
1382
+ const limit = resolveNonNegativeAiInteger(configured?.limit ?? options.traceLimit, 512);
1383
+ const kinds = configured?.kinds === void 0 ? void 0 : [...new Set(configured.kinds)];
1384
+ for (const kind of kinds ?? []) if (!AI_TRACE_KINDS.includes(kind)) throw createAiError("ai.invalid_config", "AI trace kind is not supported", { kind });
1385
+ const kindLimits = {};
1386
+ for (const kind of AI_TRACE_KINDS) {
1387
+ const kindLimit = configured?.kindLimits?.[kind];
1388
+ if (kindLimit !== void 0) kindLimits[kind] = resolveNonNegativeAiInteger(kindLimit, limit);
1389
+ }
1390
+ return {
1391
+ limit,
1392
+ ...kinds === void 0 ? {} : { kinds },
1393
+ ...Object.keys(kindLimits).length === 0 ? {} : { kindLimits }
1394
+ };
1395
+ }
1396
+ function resolvePositiveAiInteger(value, fallback) {
1397
+ const resolved = value ?? fallback;
1398
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) throw createAiError("ai.invalid_config", "AI limit must be a positive integer", { value: resolved });
1399
+ return resolved;
1400
+ }
1401
+ function resolveNonNegativeAiInteger(value, fallback) {
1402
+ const resolved = value ?? fallback;
1403
+ if (!Number.isSafeInteger(resolved) || resolved < 0) throw createAiError("ai.invalid_config", "AI limit must be a non-negative integer", { value: resolved });
1404
+ return resolved;
1405
+ }
1406
+ function resolveNonNegativeAiNumber(value, fallback) {
1407
+ const resolved = value ?? fallback;
1408
+ if (!Number.isFinite(resolved) || resolved < 0) throw createAiError("ai.invalid_config", "AI duration must be non-negative", { value: resolved });
1409
+ return resolved;
1410
+ }
1411
+ //#endregion
1412
+ //#region src/composition/create-ai-runtime.ts
1413
+ function createAiRuntime(options) {
1414
+ const id = options.id ?? "ai";
1415
+ const limits = resolveAiRuntimeLimits(options);
1416
+ const world = createAiWorldReadModel(options.world);
1417
+ const physics = options.physics === void 0 ? void 0 : createAiPhysicsQueries(options.physics);
1418
+ const sharedFacts = options.sharedFacts === void 0 ? void 0 : createAiSharedFactQueries(options.sharedFacts);
1419
+ const sensorRegistry = createAiRegistry(options.sensors ?? [], "sensor");
1420
+ const inputRegistry = createAiRegistry(options.inputs ?? [], "input");
1421
+ const taskRegistry = createAiRegistry(options.tasks ?? [], "task");
1422
+ const schedulerClasses = new Map([["default", {
1423
+ id: "default",
1424
+ decisionIntervalMultiplier: 1,
1425
+ sensorIntervalMultiplier: 1
1426
+ }]]);
1427
+ for (const schedulerClass of options.schedulerClasses ?? []) {
1428
+ if (schedulerClasses.has(schedulerClass.id)) throw createAiError("ai.duplicate_registry_entry", `Duplicate AI scheduler class: ${schedulerClass.id}`);
1429
+ schedulerClasses.set(schedulerClass.id, { ...schedulerClass });
1430
+ }
1431
+ const definitionCompiler = createAiAgentDefinitionCompiler({
1432
+ dataRegistry: options.dataRegistry,
1433
+ registries: {
1434
+ sensors: sensorRegistry,
1435
+ inputs: inputRegistry,
1436
+ tasks: taskRegistry,
1437
+ schedulerClasses
1438
+ }
1439
+ });
1440
+ const traceStore = createAiTraceStore({
1441
+ ...limits.traceRetention,
1442
+ onEntry: options.onTrace,
1443
+ onEntryError: options.onTraceError
1444
+ });
1445
+ const agents = /* @__PURE__ */ new Map();
1446
+ let elapsed = 0;
1447
+ let disposed = false;
1448
+ let intentsEmitted = 0;
1449
+ let delayedSensorSamples = 0;
1450
+ let delayedDecisions = 0;
1451
+ const trace = createAiTraceRecorder({
1452
+ store: traceStore,
1453
+ enabled: limits.traceProduction.enabled,
1454
+ maxEntriesPerUpdate: limits.traceProduction.maxEntriesPerUpdate,
1455
+ emitDropSummary: limits.traceProduction.emitDropSummary
1456
+ });
1457
+ const navigation = options.navigation === void 0 ? void 0 : createAiNavigationAccess({
1458
+ id,
1459
+ queries: options.navigation,
1460
+ maxRequestsPerUpdate: limits.maxPathRequestsPerTick,
1461
+ onRejected(agentId, request) {
1462
+ trace.push({
1463
+ kind: "budget",
1464
+ label: "ai.path_request_rejected",
1465
+ timestamp: elapsed,
1466
+ agentId,
1467
+ payload: {
1468
+ requesterId: request.requesterId,
1469
+ profileId: request.profileId
1470
+ }
1471
+ });
1472
+ }
1473
+ });
1474
+ const contextFactory = createAiAgentContextFactory({
1475
+ elapsed: () => elapsed,
1476
+ world,
1477
+ navigationFor: (state) => navigation?.forAgent(state.binding.agentId),
1478
+ physics,
1479
+ sharedFacts,
1480
+ onIntent(state, task, intent) {
1481
+ const value = {
1482
+ ...intent,
1483
+ agentId: state.binding.agentId,
1484
+ source: `ai:${task.id}`
1485
+ };
1486
+ options.intentSink.emit(value);
1487
+ intentsEmitted += 1;
1488
+ trace.push({
1489
+ kind: "intent",
1490
+ label: "ai.intent_emitted",
1491
+ timestamp: elapsed,
1492
+ agentId: state.binding.agentId,
1493
+ payload: {
1494
+ type: value.type,
1495
+ taskId: task.id
1496
+ }
1497
+ });
1498
+ options.eventBus?.emit("ai.intent", value, id);
1499
+ }
1500
+ });
1501
+ const taskController = createAiTaskController({
1502
+ elapsed: () => elapsed,
1503
+ failureBackoffMs: limits.failureBackoffMs,
1504
+ decisionInterval: (state) => effectiveAiInterval(state.definition.decisionIntervalMs, state.schedulerClass.decisionIntervalMultiplier),
1505
+ taskFor,
1506
+ goalFor,
1507
+ executorFor: (executorId) => taskRegistry.get(executorId),
1508
+ contextFor: contextFactory.task,
1509
+ onTransition: recordTaskTransition
1510
+ });
1511
+ const perceptionController = createAiPerceptionController({
1512
+ elapsed: () => elapsed,
1513
+ maxSamplesPerTick: limits.maxSensorSamplesPerTick,
1514
+ samplerFor: (samplerId) => sensorRegistry.get(samplerId),
1515
+ contextFor: contextFactory.read,
1516
+ onSample(state, sensor, facts) {
1517
+ trace.push({
1518
+ kind: "perception",
1519
+ label: "ai.sensor_sampled",
1520
+ timestamp: elapsed,
1521
+ agentId: state.binding.agentId,
1522
+ payload: {
1523
+ sensorId: sensor.id,
1524
+ facts: facts.length
1525
+ }
1526
+ });
1527
+ },
1528
+ onDelayed(state, sensor) {
1529
+ trace.push({
1530
+ kind: "budget",
1531
+ label: "ai.sensor_delayed",
1532
+ timestamp: elapsed,
1533
+ agentId: state.binding.agentId,
1534
+ payload: { sensorId: sensor.id }
1535
+ });
1536
+ }
1537
+ });
1538
+ const goalController = createAiGoalController({
1539
+ elapsed: () => elapsed,
1540
+ resolveInput: (inputId) => inputRegistry.get(inputId),
1541
+ readContext: contextFactory.read,
1542
+ goalFor,
1543
+ tasks: taskController,
1544
+ onScores(state, scores) {
1545
+ trace.push({
1546
+ kind: "decision",
1547
+ label: "ai.goals_scored",
1548
+ timestamp: elapsed,
1549
+ agentId: state.binding.agentId,
1550
+ payload: projectGoalScores(scores)
1551
+ });
1552
+ },
1553
+ onDecision(state, decision) {
1554
+ trace.push({
1555
+ kind: "decision",
1556
+ label: "ai.goal_decided",
1557
+ timestamp: elapsed,
1558
+ agentId: state.binding.agentId,
1559
+ payload: {
1560
+ action: decision.action,
1561
+ reason: decision.reason,
1562
+ currentGoalId: state.currentGoalId ?? null,
1563
+ candidateGoalId: decision.candidate?.goalId ?? null
1564
+ }
1565
+ });
1566
+ },
1567
+ onSelected(state, goal, score) {
1568
+ trace.push({
1569
+ kind: "goal",
1570
+ label: "ai.goal_selected",
1571
+ timestamp: elapsed,
1572
+ agentId: state.binding.agentId,
1573
+ payload: {
1574
+ goalId: goal.id,
1575
+ score
1576
+ }
1577
+ });
1578
+ options.eventBus?.emit("ai.goal_selected", {
1579
+ agentId: state.binding.agentId,
1580
+ goalId: goal.id,
1581
+ score
1582
+ }, id);
1583
+ }
1584
+ });
1585
+ const decisionScheduler = createAiDecisionScheduler({
1586
+ elapsed: () => elapsed,
1587
+ maxDecisionsPerTick: limits.maxDecisionsPerTick,
1588
+ onDecision: (state) => goalController.decide(state),
1589
+ onDelayed(state) {
1590
+ trace.push({
1591
+ kind: "budget",
1592
+ label: "ai.decision_delayed",
1593
+ timestamp: elapsed,
1594
+ agentId: state.binding.agentId
1595
+ });
1596
+ }
1597
+ });
1598
+ trace.push({
1599
+ kind: "lifecycle",
1600
+ label: "ai.created",
1601
+ timestamp: elapsed
1602
+ });
1603
+ return {
1604
+ bind(binding) {
1605
+ requireActive();
1606
+ if (!binding.agentId || agents.has(binding.agentId)) throw createAiError("ai.agent_bound", `AI agent is already bound: ${binding.agentId}`, { agentId: binding.agentId });
1607
+ const compiled = definitionCompiler.compile(binding.definitionId);
1608
+ const definition = compiled.definition;
1609
+ const state = createAiAgentState({
1610
+ binding,
1611
+ compiled,
1612
+ elapsed,
1613
+ blackboardLimit: resolvePositiveAiInteger(definition.blackboardLimit, limits.defaultBlackboardLimit),
1614
+ blackboardValueLimits: limits.blackboardValueLimits
1615
+ });
1616
+ agents.set(binding.agentId, state);
1617
+ trace.push({
1618
+ kind: "lifecycle",
1619
+ label: "ai.agent_bound",
1620
+ timestamp: elapsed,
1621
+ agentId: binding.agentId,
1622
+ payload: { definitionId: binding.definitionId }
1623
+ });
1624
+ },
1625
+ unbind(agentId, reason = "owner-removed") {
1626
+ const state = agents.get(agentId);
1627
+ if (state === void 0) return;
1628
+ taskController.cancel(state, reason);
1629
+ agents.delete(agentId);
1630
+ navigation?.release(agentId);
1631
+ trace.push({
1632
+ kind: "lifecycle",
1633
+ label: "ai.agent_unbound",
1634
+ timestamp: elapsed,
1635
+ agentId,
1636
+ payload: { reason }
1637
+ });
1638
+ },
1639
+ hasAgent(agentId) {
1640
+ return agents.has(agentId);
1641
+ },
1642
+ observe(agentId, facts) {
1643
+ const state = requireAgent(agentId);
1644
+ retainAiPerceptionFacts(state.memory, facts, state.definition.memoryLimit);
1645
+ },
1646
+ setBlackboard(agentId, key, value) {
1647
+ requireAgent(agentId).blackboard.set(key, value);
1648
+ },
1649
+ deleteBlackboard(agentId, key) {
1650
+ requireAgent(agentId).blackboard.delete(key);
1651
+ },
1652
+ setSchedulerClass(agentId, schedulerClassId) {
1653
+ const state = requireAgent(agentId);
1654
+ const schedulerClass = schedulerClasses.get(schedulerClassId);
1655
+ if (schedulerClass === void 0) throw createAiError("ai.definition_missing", `AI scheduler class is not registered: ${schedulerClassId}`, {
1656
+ agentId,
1657
+ schedulerClassId
1658
+ });
1659
+ const previousSchedulerClassId = state.schedulerClass.id;
1660
+ if (previousSchedulerClassId === schedulerClass.id) return;
1661
+ reclassifyAiAgent(state, schedulerClass, elapsed);
1662
+ trace.push({
1663
+ kind: "lifecycle",
1664
+ label: "ai.scheduler_class_changed",
1665
+ timestamp: elapsed,
1666
+ agentId,
1667
+ payload: {
1668
+ previousSchedulerClassId,
1669
+ schedulerClassId: schedulerClass.id,
1670
+ nextDecisionAt: state.nextDecisionAt
1671
+ }
1672
+ });
1673
+ },
1674
+ getAgent(agentId) {
1675
+ const state = agents.get(agentId);
1676
+ return state === void 0 ? void 0 : projectAiAgentSnapshot(state);
1677
+ },
1678
+ listAgents() {
1679
+ return sortedAgents().map(projectAiAgentSnapshot);
1680
+ },
1681
+ scoreGoals(agentId) {
1682
+ return goalController.score(requireAgent(agentId));
1683
+ },
1684
+ update(deltaMs, elapsedMs) {
1685
+ if (disposed) return;
1686
+ const delta = Number.isFinite(deltaMs) ? Math.max(0, deltaMs) : 0;
1687
+ elapsed = Number.isFinite(elapsedMs) ? Math.max(elapsed, elapsedMs) : elapsed + delta;
1688
+ trace.beginUpdate();
1689
+ navigation?.beginUpdate();
1690
+ try {
1691
+ const ordered = sortedAgents();
1692
+ for (const state of ordered) {
1693
+ pruneAiPerceptionMemory(state.memory, elapsed);
1694
+ pruneAiGoalCooldowns(state.cooldowns, elapsed);
1695
+ }
1696
+ delayedSensorSamples += perceptionController.sample(ordered);
1697
+ delayedDecisions += decisionScheduler.run(ordered);
1698
+ updateTasks(ordered, delta);
1699
+ } finally {
1700
+ navigation?.endUpdate();
1701
+ trace.endUpdate(elapsed);
1702
+ }
1703
+ },
1704
+ captureCheckpoint() {
1705
+ return {
1706
+ version: 1,
1707
+ elapsed,
1708
+ agents: sortedAgents().map(projectAiAgentCheckpoint)
1709
+ };
1710
+ },
1711
+ restoreCheckpoint(checkpoint, restoreOptions) {
1712
+ requireActive();
1713
+ validateAiRuntimeCheckpoint(checkpoint);
1714
+ const restoredStates = [];
1715
+ for (const saved of [...checkpoint.agents].sort((left, right) => left.binding.agentId.localeCompare(right.binding.agentId))) {
1716
+ const binding = restoreAiAgentBinding(saved.binding, restoreOptions);
1717
+ if (binding === void 0) continue;
1718
+ const compiled = definitionCompiler.compile(binding.definitionId);
1719
+ const restored = restoreAiTaskState(saved, binding, checkpoint.elapsed, restoreOptions);
1720
+ const schedulerClassId = restored.schedulerClassId ?? compiled.schedulerClass.id;
1721
+ const schedulerClass = schedulerClasses.get(schedulerClassId);
1722
+ if (schedulerClass === void 0) throw createAiError("ai.definition_missing", `AI scheduler class is not registered: ${schedulerClassId}`, {
1723
+ agentId: binding.agentId,
1724
+ schedulerClassId
1725
+ });
1726
+ const state = createAiAgentState({
1727
+ binding,
1728
+ compiled,
1729
+ elapsed: checkpoint.elapsed,
1730
+ blackboardLimit: resolvePositiveAiInteger(compiled.definition.blackboardLimit, limits.defaultBlackboardLimit),
1731
+ blackboardValueLimits: limits.blackboardValueLimits
1732
+ });
1733
+ state.schedulerClass = schedulerClass;
1734
+ validateAiCheckpointCompatibility(state, restored);
1735
+ restoreAiAgentCheckpoint(state, restored);
1736
+ restoredStates.push(state);
1737
+ }
1738
+ for (const state of agents.values()) taskController.cancel(state, "checkpoint-restore");
1739
+ agents.clear();
1740
+ navigation?.clear();
1741
+ elapsed = checkpoint.elapsed;
1742
+ for (const state of restoredStates) {
1743
+ agents.set(state.binding.agentId, state);
1744
+ trace.push({
1745
+ kind: "lifecycle",
1746
+ label: "ai.agent_bound",
1747
+ timestamp: elapsed,
1748
+ agentId: state.binding.agentId,
1749
+ payload: {
1750
+ definitionId: state.binding.definitionId,
1751
+ restored: true
1752
+ }
1753
+ });
1754
+ }
1755
+ trace.push({
1756
+ kind: "lifecycle",
1757
+ label: "ai.checkpoint_restored",
1758
+ timestamp: elapsed,
1759
+ payload: { agents: agents.size }
1760
+ });
1761
+ },
1762
+ snapshot() {
1763
+ return projectAiRuntimeSnapshot({
1764
+ id,
1765
+ elapsed,
1766
+ disposed,
1767
+ compiledDefinitions: definitionCompiler.size(),
1768
+ agents: sortedAgents(),
1769
+ intentsEmitted,
1770
+ delayedSensorSamples,
1771
+ delayedDecisions,
1772
+ rejectedPathRequests: navigation?.rejectedRequests() ?? 0,
1773
+ droppedTraceEntries: trace.dropped(),
1774
+ traceEntries: traceStore.size()
1775
+ });
1776
+ },
1777
+ traces() {
1778
+ return traceStore.snapshot();
1779
+ },
1780
+ dispose() {
1781
+ if (disposed) return;
1782
+ for (const state of agents.values()) taskController.cancel(state, "runtime-disposed");
1783
+ agents.clear();
1784
+ navigation?.clear();
1785
+ definitionCompiler.clear();
1786
+ disposed = true;
1787
+ traceStore.clear();
1788
+ }
1789
+ };
1790
+ function updateTasks(ordered, deltaMs) {
1791
+ for (const state of ordered) taskController.update(state, deltaMs);
1792
+ }
1793
+ function recordTaskTransition(state, transition) {
1794
+ if (transition.status === "started") {
1795
+ trace.push({
1796
+ kind: "task",
1797
+ label: "ai.task_started",
1798
+ timestamp: elapsed,
1799
+ agentId: state.binding.agentId,
1800
+ payload: {
1801
+ taskId: transition.taskId,
1802
+ executorId: transition.executorId
1803
+ }
1804
+ });
1805
+ return;
1806
+ }
1807
+ trace.push({
1808
+ kind: "task",
1809
+ label: `ai.task_${transition.status}`,
1810
+ timestamp: elapsed,
1811
+ agentId: state.binding.agentId,
1812
+ payload: {
1813
+ taskId: transition.taskId,
1814
+ goalId: transition.goalId ?? null,
1815
+ reason: transition.reason ?? null
1816
+ }
1817
+ });
1818
+ options.eventBus?.emit("ai.task_transition", {
1819
+ agentId: state.binding.agentId,
1820
+ taskId: transition.taskId,
1821
+ status: transition.status,
1822
+ reason: transition.reason
1823
+ }, id);
1824
+ }
1825
+ function requireAgent(agentId) {
1826
+ const state = agents.get(agentId);
1827
+ if (state === void 0) throw createAiError("ai.agent_missing", `AI agent is not bound: ${agentId}`, { agentId });
1828
+ return state;
1829
+ }
1830
+ function goalFor(state, goalId) {
1831
+ const goal = state.goalsById.get(goalId);
1832
+ if (goal === void 0) throw createAiError("ai.definition_missing", `AI goal is missing: ${goalId}`);
1833
+ return goal;
1834
+ }
1835
+ function taskFor(state, taskId) {
1836
+ const task = state.tasksById.get(taskId);
1837
+ if (task === void 0) throw createAiError("ai.definition_missing", `AI task is missing: ${taskId}`);
1838
+ return task;
1839
+ }
1840
+ function sortedAgents() {
1841
+ return [...agents.values()].sort((left, right) => {
1842
+ const leftPriority = left.schedulerClass.priority ?? 0;
1843
+ const rightPriority = right.schedulerClass.priority ?? 0;
1844
+ return leftPriority === rightPriority ? left.binding.agentId.localeCompare(right.binding.agentId) : rightPriority - leftPriority;
1845
+ });
1846
+ }
1847
+ function projectGoalScores(scores) {
1848
+ const winner = scores.find((score) => score.eligible);
1849
+ const detail = limits.traceProduction.goalScoreDetail;
1850
+ const detailedScores = detail === "all" ? scores : detail === "winner" && winner !== void 0 ? [winner] : [];
1851
+ return {
1852
+ candidates: scores.length,
1853
+ winner: winner?.goalId ?? null,
1854
+ ...detailedScores.length === 0 ? {} : { scores: detailedScores.map((score) => ({
1855
+ goalId: score.goalId,
1856
+ score: score.score,
1857
+ eligible: score.eligible,
1858
+ considerations: score.considerations.map((consideration) => ({ ...consideration }))
1859
+ })) }
1860
+ };
1861
+ }
1862
+ function requireActive() {
1863
+ if (disposed) throw createAiError("ai.invalid_config", "AI runtime is disposed");
1864
+ }
1865
+ }
1866
+ //#endregion
1867
+ export { createAiError as _, AI_SENSOR_TYPE as a, createAiDataTypes as c, createAiTaskDataType as d, evaluateAiUtilityCurve as f, AiError as g, createAiNavigationQueries as h, AI_GOAL_TYPE as i, createAiGoalDataType as l, createAiPhysicsQueries as m, AI_TRACE_KINDS as n, AI_TASK_TYPE as o, createAiSharedFactQueries as p, AI_AGENT_TYPE as r, createAiAgentDataType as s, createAiRuntime as t, createAiSensorDataType as u, createAiWorldReadModel as v };