@myclaw163/clawclaw-cli 0.10.5 → 0.10.7

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 (57) hide show
  1. package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
  4. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
  5. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
  6. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
  7. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
  8. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1388 -0
  9. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
  10. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
  11. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
  12. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3034 -0
  13. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
  14. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
  15. package/docs/custom-modules/api-reference.md +10 -8
  16. package/docs/custom-modules/perception.md +26 -3
  17. package/docs/runtime/behavior-runtime.md +3 -1
  18. package/docs/runtime/official-perception-modules.md +2 -2
  19. package/docs/user-guide/behavior.md +3 -1
  20. package/package.json +5 -3
  21. package/scripts/build-strategy-worker.mjs +28 -0
  22. package/scripts/migrate-official-perceptions.mjs +157 -0
  23. package/skills/clawclaw/SKILL.md +17 -6
  24. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  25. package/skills/clawclaw/references/COMMANDS.md +3 -3
  26. package/skills/clawclaw/references/GAME-MECHANICS.md +12 -10
  27. package/skills/clawclaw/references/TACTICS.md +417 -29
  28. package/skills/clawclaw-creator/SKILL.md +3 -1
  29. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
  30. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
  31. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  32. package/src/commands/capability.ts +4 -2
  33. package/src/commands/load.ts +5 -2
  34. package/src/lib/agent-workspace-skills.ts +12 -7
  35. package/src/lib/capability-cloud-sync.ts +13 -7
  36. package/src/lib/capability-discovery.ts +10 -3
  37. package/src/lib/capability-selection.ts +7 -0
  38. package/src/lib/package-skills.ts +11 -1
  39. package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
  40. package/src/runtime/clawclaw/owner.ts +19 -4
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  45. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
  46. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
  47. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
  48. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
  49. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
  50. package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
  51. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
  52. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
  53. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
  54. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
  55. package/src/sdk/perception-plugin/index.ts +1 -0
  56. package/src/sdk/perception-plugin/lifecycle.ts +15 -0
  57. package/src/sdk/perception-plugin/module.ts +15 -0
@@ -0,0 +1,1388 @@
1
+ import {
2
+ BEHAVIOR_PLUGIN_API_VERSION
3
+ } from "./chunk-3VLVCU6P.js";
4
+ import {
5
+ __reExport,
6
+ hasValidClawclawResourceLocalizations
7
+ } from "./chunk-ATQQZA4X.js";
8
+
9
+ // src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts
10
+ import { runStrategyWorker } from "@myclaw163/game-agent-runtime/strategy/strategy-worker-host.js";
11
+
12
+ // src/runtime/clawclaw/navigation/walkable-grid.ts
13
+ import { readFileSync } from "fs";
14
+ var HEADER_SIZE = 20;
15
+ var Grid = class {
16
+ width;
17
+ height;
18
+ tileSize;
19
+ bits;
20
+ rowBytes;
21
+ constructor(buf) {
22
+ if (buf.toString("ascii", 0, 4) !== "CCWG") throw new Error("walkable grid: bad magic");
23
+ const version = buf.readUInt32LE(4);
24
+ if (version !== 1) throw new Error(`walkable grid: unsupported version ${version}`);
25
+ this.width = buf.readUInt32LE(8);
26
+ this.height = buf.readUInt32LE(12);
27
+ this.tileSize = buf.readUInt32LE(16);
28
+ this.rowBytes = Math.ceil(this.width / 8);
29
+ if (buf.length !== HEADER_SIZE + this.rowBytes * this.height) {
30
+ throw new Error("walkable grid: size mismatch");
31
+ }
32
+ this.bits = buf;
33
+ }
34
+ isWalkable(tx, ty) {
35
+ if (tx < 0 || ty < 0 || tx >= this.width || ty >= this.height) return false;
36
+ const byte = this.bits[HEADER_SIZE + ty * this.rowBytes + (tx >> 3)];
37
+ return (byte >> (tx & 7) & 1) === 1;
38
+ }
39
+ isWalkableCell(cell) {
40
+ return this.isWalkable(cell % this.width, Math.floor(cell / this.width));
41
+ }
42
+ worldToCell(wx, wy) {
43
+ const tx = Math.min(this.width - 1, Math.max(0, Math.floor(wx / this.tileSize)));
44
+ const ty = Math.min(this.height - 1, Math.max(0, Math.floor(wy / this.tileSize)));
45
+ return ty * this.width + tx;
46
+ }
47
+ cellToWorld(cell) {
48
+ const tx = cell % this.width;
49
+ const ty = Math.floor(cell / this.width);
50
+ return { x: tx * this.tileSize + this.tileSize / 2, y: ty * this.tileSize + this.tileSize / 2 };
51
+ }
52
+ snapToWalkable(cell, maxRadius = 8) {
53
+ const cx = cell % this.width;
54
+ const cy = Math.floor(cell / this.width);
55
+ for (let r = 0; r <= maxRadius; r++) {
56
+ let best = -1;
57
+ let bestSq = Infinity;
58
+ for (let dy = -r; dy <= r; dy++) {
59
+ for (let dx = -r; dx <= r; dx++) {
60
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
61
+ if (!this.isWalkable(cx + dx, cy + dy)) continue;
62
+ const sq = dx * dx + dy * dy;
63
+ if (sq < bestSq) {
64
+ bestSq = sq;
65
+ best = (cy + dy) * this.width + (cx + dx);
66
+ }
67
+ }
68
+ }
69
+ if (best >= 0) return best;
70
+ }
71
+ return -1;
72
+ }
73
+ };
74
+ var cached = null;
75
+ function loadWalkableGrid() {
76
+ if (!cached) {
77
+ cached = new Grid(readFileSync(new URL("./clawclaw-walkable.bin", import.meta.url)));
78
+ }
79
+ return cached;
80
+ }
81
+
82
+ // src/runtime/clawclaw/navigation/astar-path.ts
83
+ var MinHeap = class {
84
+ cells = [];
85
+ priorities = [];
86
+ clear() {
87
+ this.cells.length = 0;
88
+ this.priorities.length = 0;
89
+ }
90
+ push(cell, priority) {
91
+ let index = this.cells.length;
92
+ this.cells.push(cell);
93
+ this.priorities.push(priority);
94
+ while (index > 0) {
95
+ const parent = index - 1 >> 1;
96
+ if (this.priorities[parent] <= priority) break;
97
+ this.cells[index] = this.cells[parent];
98
+ this.priorities[index] = this.priorities[parent];
99
+ index = parent;
100
+ }
101
+ this.cells[index] = cell;
102
+ this.priorities[index] = priority;
103
+ }
104
+ pop() {
105
+ if (this.cells.length === 0) return null;
106
+ const cell = this.cells[0];
107
+ const priority = this.priorities[0];
108
+ const lastCell = this.cells.pop();
109
+ const lastPriority = this.priorities.pop();
110
+ if (this.cells.length > 0) {
111
+ let index = 0;
112
+ while (true) {
113
+ const left = index * 2 + 1;
114
+ if (left >= this.cells.length) break;
115
+ const right = left + 1;
116
+ const child = right < this.cells.length && this.priorities[right] < this.priorities[left] ? right : left;
117
+ if (this.priorities[child] >= lastPriority) break;
118
+ this.cells[index] = this.cells[child];
119
+ this.priorities[index] = this.priorities[child];
120
+ index = child;
121
+ }
122
+ this.cells[index] = lastCell;
123
+ this.priorities[index] = lastPriority;
124
+ }
125
+ return { cell, priority };
126
+ }
127
+ };
128
+ var NEIGHBORS = [
129
+ [1, 0],
130
+ [-1, 0],
131
+ [0, 1],
132
+ [0, -1],
133
+ [1, 1],
134
+ [1, -1],
135
+ [-1, 1],
136
+ [-1, -1]
137
+ ];
138
+ var AStarPathfinder = class {
139
+ constructor(grid) {
140
+ this.grid = grid;
141
+ const cells = grid.width * grid.height;
142
+ this.score = new Float64Array(cells);
143
+ this.seen = new Uint32Array(cells);
144
+ this.closed = new Uint32Array(cells);
145
+ }
146
+ grid;
147
+ score;
148
+ seen;
149
+ closed;
150
+ heap = new MinHeap();
151
+ generation = 0;
152
+ distance(from, to) {
153
+ if (!Number.isFinite(from?.x) || !Number.isFinite(from?.y) || !Number.isFinite(to?.x) || !Number.isFinite(to?.y)) {
154
+ throw new TypeError("Path distance points must contain finite x/y coordinates.");
155
+ }
156
+ const start = this.normalize(from);
157
+ const goal = this.normalize(to);
158
+ if (!start || !goal) return null;
159
+ if (start.cell === goal.cell) {
160
+ return Math.hypot(goal.point.x - start.point.x, goal.point.y - start.point.y);
161
+ }
162
+ const cellDistance = this.findCellDistance(start.cell, goal.cell);
163
+ return cellDistance == null ? null : this.measureCellDistance(start, goal, cellDistance);
164
+ }
165
+ /**
166
+ * Resolve arbitrary route pairs in input order. Repeated endpoints are
167
+ * grouped by their snapped grid cell on the smaller side of the batch so
168
+ * one graph scan serves every route in that group.
169
+ */
170
+ distances(queries) {
171
+ for (const { from, to } of queries) {
172
+ this.assertFinitePoint(from);
173
+ this.assertFinitePoint(to);
174
+ }
175
+ if (queries.length === 0) return [];
176
+ const results = new Array(queries.length).fill(null);
177
+ const pending = [];
178
+ for (const [index, query] of queries.entries()) {
179
+ const from = this.normalize(query.from);
180
+ const to = this.normalize(query.to);
181
+ if (!from || !to) continue;
182
+ if (from.cell !== to.cell) {
183
+ pending.push({ index, from, to });
184
+ continue;
185
+ }
186
+ results[index] = Math.hypot(
187
+ to.point.x - from.point.x,
188
+ to.point.y - from.point.y
189
+ );
190
+ }
191
+ if (pending.length === 0) return results;
192
+ const fromCells = new Set(pending.map(({ from }) => from.cell));
193
+ const toCells = new Set(pending.map(({ to }) => to.cell));
194
+ const reverse = toCells.size < fromCells.size;
195
+ const groups = /* @__PURE__ */ new Map();
196
+ for (const query of pending) {
197
+ const anchorCell = (reverse ? query.to : query.from).cell;
198
+ const group = groups.get(anchorCell) ?? [];
199
+ group.push(query);
200
+ groups.set(anchorCell, group);
201
+ }
202
+ for (const [anchorCell, entries] of groups) {
203
+ const targetCells = new Set(entries.map((query) => reverse ? query.from.cell : query.to.cell));
204
+ let cellDistances;
205
+ if (targetCells.size === 1) {
206
+ const targetCell = targetCells.values().next().value;
207
+ const distance = this.findCellDistance(anchorCell, targetCell);
208
+ cellDistances = distance === null ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map([[targetCell, distance]]);
209
+ } else {
210
+ cellDistances = this.findCellDistancesToGoals(anchorCell, targetCells);
211
+ }
212
+ for (const query of entries) {
213
+ const targetCell = (reverse ? query.from : query.to).cell;
214
+ const cellDistance = cellDistances.get(targetCell);
215
+ results[query.index] = cellDistance === void 0 ? null : this.measureCellDistance(query.from, query.to, cellDistance);
216
+ }
217
+ }
218
+ return results;
219
+ }
220
+ assertFinitePoint(point) {
221
+ if (!Number.isFinite(point?.x) || !Number.isFinite(point?.y)) {
222
+ throw new TypeError("Path distance points must contain finite x/y coordinates.");
223
+ }
224
+ }
225
+ measureCellDistance(start, goal, cellDistance) {
226
+ const startCenter = this.grid.cellToWorld(start.cell);
227
+ const goalCenter = this.grid.cellToWorld(goal.cell);
228
+ const distance = cellDistance + Math.hypot(start.point.x - startCenter.x, start.point.y - startCenter.y) + Math.hypot(goal.point.x - goalCenter.x, goal.point.y - goalCenter.y);
229
+ return Math.round(distance * 10) / 10;
230
+ }
231
+ normalize(point) {
232
+ const rawCell = this.grid.worldToCell(point.x, point.y);
233
+ const inside = point.x >= 0 && point.y >= 0 && point.x < this.grid.width * this.grid.tileSize && point.y < this.grid.height * this.grid.tileSize;
234
+ if (inside && this.grid.isWalkableCell(rawCell)) return { cell: rawCell, point };
235
+ const cell = this.grid.snapToWalkable(rawCell);
236
+ return cell < 0 ? null : { cell, point: this.grid.cellToWorld(cell) };
237
+ }
238
+ findCellDistance(start, goal) {
239
+ const generation = this.nextGeneration();
240
+ this.heap.clear();
241
+ this.seen[start] = generation;
242
+ this.score[start] = 0;
243
+ this.heap.push(start, this.heuristic(start, goal));
244
+ while (true) {
245
+ const next = this.heap.pop();
246
+ if (!next) return null;
247
+ const { cell } = next;
248
+ if (this.closed[cell] === generation) continue;
249
+ if (next.priority > this.score[cell] + this.heuristic(cell, goal) + Number.EPSILON) continue;
250
+ if (cell === goal) return this.score[cell];
251
+ this.closed[cell] = generation;
252
+ this.visitNeighbors(cell, goal, generation);
253
+ }
254
+ }
255
+ findCellDistancesToGoals(start, goals) {
256
+ if (goals.size === 0) return /* @__PURE__ */ new Map();
257
+ const generation = this.nextGeneration();
258
+ const remaining = new Set(goals);
259
+ const reached = /* @__PURE__ */ new Map();
260
+ this.heap.clear();
261
+ this.seen[start] = generation;
262
+ this.score[start] = 0;
263
+ this.heap.push(start, 0);
264
+ while (remaining.size > 0) {
265
+ const next = this.heap.pop();
266
+ if (!next) break;
267
+ const { cell } = next;
268
+ if (this.closed[cell] === generation) continue;
269
+ if (next.priority > this.score[cell] + Number.EPSILON) continue;
270
+ this.closed[cell] = generation;
271
+ if (remaining.delete(cell)) reached.set(cell, this.score[cell]);
272
+ if (remaining.size === 0) break;
273
+ this.visitNeighbors(cell, null, generation);
274
+ }
275
+ return reached;
276
+ }
277
+ visitNeighbors(cell, goal, generation) {
278
+ const x = cell % this.grid.width;
279
+ const y = Math.floor(cell / this.grid.width);
280
+ for (const [dx, dy] of NEIGHBORS) {
281
+ const nx = x + dx;
282
+ const ny = y + dy;
283
+ if (!this.grid.isWalkable(nx, ny)) continue;
284
+ if (dx !== 0 && dy !== 0) {
285
+ if (!this.grid.isWalkable(x + dx, y) || !this.grid.isWalkable(x, y + dy)) continue;
286
+ }
287
+ const neighbor = ny * this.grid.width + nx;
288
+ if (this.closed[neighbor] === generation) continue;
289
+ const tentative = this.score[cell] + (dx === 0 || dy === 0 ? this.grid.tileSize : this.grid.tileSize * Math.SQRT2);
290
+ if (this.seen[neighbor] === generation && this.score[neighbor] <= tentative) continue;
291
+ this.seen[neighbor] = generation;
292
+ this.score[neighbor] = tentative;
293
+ this.heap.push(neighbor, tentative + (goal == null ? 0 : this.heuristic(neighbor, goal)));
294
+ }
295
+ }
296
+ heuristic(from, to) {
297
+ const dx = Math.abs(from % this.grid.width - to % this.grid.width);
298
+ const dy = Math.abs(Math.floor(from / this.grid.width) - Math.floor(to / this.grid.width));
299
+ const diagonal = Math.min(dx, dy);
300
+ return this.grid.tileSize * (Math.max(dx, dy) + (Math.SQRT2 - 1) * diagonal);
301
+ }
302
+ nextGeneration() {
303
+ this.generation = this.generation + 1 >>> 0;
304
+ if (this.generation === 0) {
305
+ this.seen.fill(0);
306
+ this.closed.fill(0);
307
+ this.generation = 1;
308
+ }
309
+ return this.generation;
310
+ }
311
+ };
312
+ var defaultPathfinder = null;
313
+ function getLocalPathDistance(from, to) {
314
+ defaultPathfinder ??= new AStarPathfinder(loadWalkableGrid());
315
+ return defaultPathfinder.distance(from, to);
316
+ }
317
+ function getLocalPathDistances(queries) {
318
+ defaultPathfinder ??= new AStarPathfinder(loadWalkableGrid());
319
+ return defaultPathfinder.distances(queries);
320
+ }
321
+
322
+ // src/runtime/clawclaw/plugins/perception/spatial-facts.ts
323
+ import { readFileSync as readFileSync2 } from "fs";
324
+ import { inflateSync } from "node:zlib";
325
+
326
+ // src/runtime/clawclaw/spatial-api.ts
327
+ function pointInPolygon(x, y, polygon) {
328
+ let inside = false;
329
+ for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) {
330
+ const [xi, yi] = polygon[index];
331
+ const [xj, yj] = polygon[previous];
332
+ const intersects = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi || Number.EPSILON) + xi;
333
+ if (intersects) inside = !inside;
334
+ }
335
+ return inside;
336
+ }
337
+ function createSpatialApi(facts) {
338
+ const rooms = Object.freeze(facts.rooms.map((room) => Object.freeze({
339
+ name: room.name,
340
+ polygon: Object.freeze(room.polygon.map((point) => Object.freeze([point[0], point[1]]))),
341
+ bbox: Object.freeze({ ...room.bbox })
342
+ })));
343
+ const roomByName = new Map(rooms.map((room) => [room.name, room]));
344
+ const roomAt = (x, y) => rooms.find((room) => pointInPolygon(x, y, room.polygon)) ?? null;
345
+ const sideInRoom = (position) => {
346
+ const room = position.room ? roomByName.get(position.room) : void 0;
347
+ if (!room || !pointInPolygon(position.x, position.y, room.polygon)) return null;
348
+ const width = room.bbox.right - room.bbox.left;
349
+ const height = room.bbox.bottom - room.bbox.top;
350
+ if (width <= 0 || height <= 0) return null;
351
+ const rx = (position.x - room.bbox.left) / width;
352
+ const ry = (position.y - room.bbox.top) / height;
353
+ const horizontal = rx < 0.33 ? "\u5DE6" : rx > 0.67 ? "\u53F3" : "";
354
+ const vertical = ry < 0.33 ? "\u4E0A" : ry > 0.67 ? "\u4E0B" : "";
355
+ return horizontal || vertical ? `${horizontal}${vertical}\u4FA7` : "\u4E2D\u90E8";
356
+ };
357
+ return Object.freeze({
358
+ xPositive: facts.coordinates.xPositive,
359
+ yPositive: facts.coordinates.yPositive,
360
+ playerBodyLengthPx: facts.playerBodyLengthPx,
361
+ rooms,
362
+ roomAt,
363
+ sideInRoom,
364
+ placeLabel: (position) => {
365
+ if (!position.room) return "\u672A\u547D\u540D\u533A\u57DF";
366
+ const side = sideInRoom(position);
367
+ return side ? `${position.room}${side}` : position.room;
368
+ },
369
+ transitionIsMapped: (from, to) => !!from && !!to && from !== to && facts.roomTransitions.some((transition) => transition.a === from && transition.b === to || transition.a === to && transition.b === from)
370
+ });
371
+ }
372
+
373
+ // src/runtime/clawclaw/plugins/perception/spatial-facts.ts
374
+ function loadSpatialFacts() {
375
+ const parsed = JSON.parse(
376
+ readFileSync2(new URL("../../../../assets/clawclaw-spatial-facts.json", import.meta.url), "utf8")
377
+ );
378
+ if (parsed.schema_version !== 2 || parsed.coordinates?.x_positive !== "right" || parsed.coordinates?.y_positive !== "down" || parsed.room_lookup?.encoding !== "row-major-zlib-uint8-v1" || !Number.isInteger(parsed.room_lookup.width_tiles) || parsed.room_lookup.width_tiles <= 0 || !Number.isInteger(parsed.room_lookup.height_tiles) || parsed.room_lookup.height_tiles <= 0 || !Number.isFinite(parsed.room_lookup.tile_width_px) || parsed.room_lookup.tile_width_px <= 0 || !Number.isFinite(parsed.room_lookup.tile_height_px) || parsed.room_lookup.tile_height_px <= 0 || !Array.isArray(parsed.room_lookup.room_names) || parsed.room_lookup.room_names.length === 0 || typeof parsed.room_lookup.data_base64 !== "string" || parsed.room_lookup.data_base64.length === 0) {
379
+ throw new Error("Unsupported ClawClaw spatial facts");
380
+ }
381
+ return parsed;
382
+ }
383
+ var CLAWCLAW_SPATIAL_FACTS = loadSpatialFacts();
384
+ var PLAYER_BODY_LENGTH_PX = CLAWCLAW_SPATIAL_FACTS.player_body.body_length_px;
385
+ var RAW_ROOM_LOOKUP = CLAWCLAW_SPATIAL_FACTS.room_lookup;
386
+ var ROOM_LOOKUP_CELL_COUNT = RAW_ROOM_LOOKUP.width_tiles * RAW_ROOM_LOOKUP.height_tiles;
387
+ var ROOM_LOOKUP_BUFFER = inflateSync(Buffer.from(RAW_ROOM_LOOKUP.data_base64, "base64"));
388
+ if (ROOM_LOOKUP_BUFFER.byteLength !== ROOM_LOOKUP_CELL_COUNT) {
389
+ throw new Error("Invalid ClawClaw room lookup size");
390
+ }
391
+ var ROOM_LOOKUP = new Uint8Array(
392
+ ROOM_LOOKUP_BUFFER.buffer,
393
+ ROOM_LOOKUP_BUFFER.byteOffset,
394
+ ROOM_LOOKUP_BUFFER.byteLength
395
+ );
396
+ if (ROOM_LOOKUP.some((roomIndex) => roomIndex >= RAW_ROOM_LOOKUP.room_names.length)) {
397
+ throw new Error("Invalid ClawClaw room lookup index");
398
+ }
399
+ var ROOM_BY_NAME = new Map(
400
+ CLAWCLAW_SPATIAL_FACTS.rooms.map((room) => [room.name, room])
401
+ );
402
+ var CLAWCLAW_PERCEPTION_SPATIAL_FACTS = Object.freeze({
403
+ coordinates: Object.freeze({ xPositive: "right", yPositive: "down" }),
404
+ playerBodyLengthPx: PLAYER_BODY_LENGTH_PX,
405
+ rooms: CLAWCLAW_SPATIAL_FACTS.rooms,
406
+ roomTransitions: CLAWCLAW_SPATIAL_FACTS.room_transitions.map(({ a, b }) => ({ a, b }))
407
+ });
408
+ var CLAWCLAW_PERCEPTION_SPATIAL_API = createSpatialApi(
409
+ CLAWCLAW_PERCEPTION_SPATIAL_FACTS
410
+ );
411
+
412
+ // src/runtime/clawclaw/strategy-memory-rpc.ts
413
+ var strategy_memory_rpc_exports = {};
414
+ __reExport(strategy_memory_rpc_exports, strategy_memory_rpc_star);
415
+ import * as strategy_memory_rpc_star from "@myclaw163/game-agent-runtime/memory/strategy-memory-rpc.js";
416
+
417
+ // src/runtime/clawclaw/behavior-read-api.ts
418
+ function finitePoint(value) {
419
+ return Number.isFinite(value?.x) && Number.isFinite(value?.y);
420
+ }
421
+ function validPlayerSeat(value) {
422
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 10;
423
+ }
424
+ function requirePlayerSeat(value) {
425
+ if (!validPlayerSeat(value)) throw new Error("behavior_player_seat_invalid");
426
+ }
427
+ function currentObservation(input) {
428
+ return Object.freeze({
429
+ lastSeenPlayer: (targetSeat) => {
430
+ requirePlayerSeat(targetSeat);
431
+ const player = input.gameState.visible_players?.find((candidate) => candidate.player.seat === targetSeat);
432
+ return player === void 0 ? void 0 : Object.freeze({
433
+ name: player.player.name,
434
+ seat: player.player.seat,
435
+ x: player.x,
436
+ y: player.y,
437
+ room: player.room,
438
+ distance: player.distance,
439
+ observedAtMs: input.nowMs,
440
+ ageMs: 0
441
+ });
442
+ },
443
+ lastSeenCorpse: (targetSeat) => {
444
+ if (targetSeat !== void 0) requirePlayerSeat(targetSeat);
445
+ const corpse = targetSeat !== void 0 ? input.gameState.visible_corpses?.find((candidate) => candidate.player?.seat === targetSeat) : input.gameState.visible_corpses?.[0];
446
+ return corpse === void 0 ? void 0 : Object.freeze({
447
+ id: corpse.corpse_id,
448
+ ...corpse.player === void 0 ? {} : {
449
+ name: corpse.player.name,
450
+ seat: corpse.player.seat
451
+ },
452
+ x: corpse.x,
453
+ y: corpse.y,
454
+ room: corpse.room,
455
+ distance: corpse.distance,
456
+ observedAtMs: input.nowMs,
457
+ ageMs: 0
458
+ });
459
+ }
460
+ });
461
+ }
462
+ function snapshotObservation(snapshot) {
463
+ return Object.freeze({
464
+ lastSeenPlayer: (targetSeat) => {
465
+ requirePlayerSeat(targetSeat);
466
+ const player = snapshot.players.filter((candidate) => candidate.seat === targetSeat).sort((left, right) => right.observedAtMs - left.observedAtMs)[0];
467
+ return player;
468
+ },
469
+ lastSeenCorpse: (targetSeat) => {
470
+ if (targetSeat !== void 0) requirePlayerSeat(targetSeat);
471
+ const corpse = snapshot.corpses.filter((candidate) => targetSeat === void 0 || candidate.seat === targetSeat).sort((left, right) => right.observedAtMs - left.observedAtMs)[0];
472
+ return corpse;
473
+ }
474
+ });
475
+ }
476
+ function createBehaviorReadApi(input, options = {}) {
477
+ const isActive = options.isActive ?? (() => true);
478
+ const observation = options.observation ?? (options.observationSnapshot ? snapshotObservation(options.observationSnapshot) : currentObservation(input));
479
+ const requireActive = () => {
480
+ if (!isActive()) throw new Error("behavior_invocation_inactive");
481
+ };
482
+ const pathDistances = async (queries) => {
483
+ requireActive();
484
+ options.onQuery?.("path_distance");
485
+ if (!Array.isArray(queries) || queries.some(({ from, to }) => !finitePoint(from) || !finitePoint(to))) throw new Error("invalid_path_distance_points");
486
+ return getLocalPathDistances(queries);
487
+ };
488
+ return Object.freeze({
489
+ memory: options.memory ?? strategy_memory_rpc_exports.unavailableStrategyMemory,
490
+ spatial: CLAWCLAW_PERCEPTION_SPATIAL_API,
491
+ navigation: Object.freeze({
492
+ pathDistance: async (from, to) => {
493
+ requireActive();
494
+ options.onQuery?.("path_distance");
495
+ if (!finitePoint(from) || !finitePoint(to)) throw new Error("invalid_path_distance_points");
496
+ return getLocalPathDistance(from, to);
497
+ },
498
+ pathDistances
499
+ }),
500
+ observation: Object.freeze({
501
+ lastSeenPlayer: (targetSeat, maxAgeMs) => {
502
+ requireActive();
503
+ options.onQuery?.("observation");
504
+ requirePlayerSeat(targetSeat);
505
+ const value = observation.lastSeenPlayer(targetSeat, maxAgeMs);
506
+ if (value !== void 0 && maxAgeMs !== void 0 && value.ageMs > maxAgeMs) return void 0;
507
+ return value === void 0 ? void 0 : structuredClone(value);
508
+ },
509
+ lastSeenCorpse: (targetSeat) => {
510
+ requireActive();
511
+ options.onQuery?.("observation");
512
+ if (targetSeat !== void 0) requirePlayerSeat(targetSeat);
513
+ const value = observation.lastSeenCorpse(targetSeat);
514
+ return value === void 0 ? void 0 : structuredClone(value);
515
+ }
516
+ })
517
+ });
518
+ }
519
+
520
+ // src/runtime/framework/modules/runtime-module-output.ts
521
+ var runtime_module_output_exports = {};
522
+ __reExport(runtime_module_output_exports, runtime_module_output_star);
523
+ import * as runtime_module_output_star from "@myclaw163/game-agent-runtime/framework/modules/runtime-module-output.js";
524
+
525
+ // src/runtime/clawclaw/behavior-decision.ts
526
+ var DECISION_KEYS = /* @__PURE__ */ new Set(["actions", "status", "events", "delegate", "finish"]);
527
+ var STATUS_KEYS = /* @__PURE__ */ new Set(["summary", "activity", "room", "task", "targetPlayer", "data"]);
528
+ var EVENT_KEYS = /* @__PURE__ */ new Set(["type", "payload", "occurredAt"]);
529
+ var DELEGATE_KEYS = /* @__PURE__ */ new Set(["behavior", "strategy", "input"]);
530
+ var FINISH_KEYS = /* @__PURE__ */ new Set(["outcome", "reason", "summary"]);
531
+ function objectRecord(value, code) {
532
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(code);
533
+ return value;
534
+ }
535
+ function nonEmptyString(value, code) {
536
+ if (typeof value !== "string" || !value.trim()) throw new Error(code);
537
+ return value;
538
+ }
539
+ function rejectUnknownFields(value, allowed, code) {
540
+ for (const key of Object.keys(value)) {
541
+ if (!allowed.has(key)) throw new Error(`${code}:${key}`);
542
+ }
543
+ }
544
+ function normalizeBehaviorDecision(value, _options) {
545
+ if (value === void 0) return Object.freeze({});
546
+ const source = objectRecord(value, "behavior_decision_invalid");
547
+ for (const key of Object.keys(source)) {
548
+ if (!DECISION_KEYS.has(key)) throw new Error(`behavior_decision_field_unknown:${key}`);
549
+ }
550
+ if (source.actions !== void 0) {
551
+ if (!Array.isArray(source.actions)) throw new Error("behavior_actions_invalid");
552
+ for (const action of source.actions) objectRecord(action, "behavior_action_invalid");
553
+ }
554
+ if (source.status !== void 0) {
555
+ const status = objectRecord(source.status, "behavior_status_invalid");
556
+ rejectUnknownFields(status, STATUS_KEYS, "behavior_status_field_unknown");
557
+ nonEmptyString(status.summary, "behavior_status_summary_invalid");
558
+ for (const field of ["activity", "room", "task", "targetPlayer"]) {
559
+ if (status[field] !== void 0) {
560
+ nonEmptyString(status[field], `behavior_status_${field}_invalid`);
561
+ }
562
+ }
563
+ if (status.data !== void 0) {
564
+ objectRecord(status.data, "behavior_status_data_invalid");
565
+ }
566
+ }
567
+ if (source.events !== void 0) {
568
+ if (!Array.isArray(source.events)) throw new Error("behavior_events_invalid");
569
+ for (const raw of source.events) {
570
+ const event = objectRecord(raw, "behavior_event_invalid");
571
+ rejectUnknownFields(event, EVENT_KEYS, "behavior_event_field_unknown");
572
+ nonEmptyString(event.type, "behavior_event_type_invalid");
573
+ objectRecord(event.payload, "behavior_event_payload_invalid");
574
+ if (event.occurredAt !== void 0 && typeof event.occurredAt !== "string") {
575
+ throw new Error("behavior_event_occurred_at_invalid");
576
+ }
577
+ }
578
+ }
579
+ let normalizedDelegate;
580
+ if (source.delegate !== void 0) {
581
+ const delegate = objectRecord(source.delegate, "behavior_delegate_invalid");
582
+ rejectUnknownFields(delegate, DELEGATE_KEYS, "behavior_delegate_field_unknown");
583
+ if (delegate.behavior !== void 0 && delegate.strategy !== void 0) throw new Error("strategy_delegate_name_conflict");
584
+ const target = nonEmptyString(delegate.strategy ?? delegate.behavior, "behavior_delegate_id_invalid");
585
+ if (delegate.input !== void 0) objectRecord(delegate.input, "behavior_delegate_input_invalid");
586
+ normalizedDelegate = { behavior: target, ...delegate.input === void 0 ? {} : { input: delegate.input } };
587
+ }
588
+ if (source.finish !== void 0) {
589
+ const finish = objectRecord(source.finish, "behavior_finish_invalid");
590
+ rejectUnknownFields(finish, FINISH_KEYS, "behavior_finish_field_unknown");
591
+ if (finish.outcome !== "completed" && finish.outcome !== "failed") {
592
+ throw new Error("behavior_finish_outcome_invalid");
593
+ }
594
+ nonEmptyString(finish.reason, "behavior_finish_reason_invalid");
595
+ if (finish.summary !== void 0 && typeof finish.summary !== "string") {
596
+ throw new Error("behavior_finish_summary_invalid");
597
+ }
598
+ }
599
+ const normalized = Object.freeze(structuredClone({
600
+ ...source,
601
+ ...normalizedDelegate ? { delegate: normalizedDelegate } : {}
602
+ }));
603
+ (0, runtime_module_output_exports.assertRuntimeModuleOutputSize)(normalized, "behavior_output");
604
+ return normalized;
605
+ }
606
+
607
+ // src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts
608
+ import { createHash } from "node:crypto";
609
+ import { readFileSync as readFileSync3, readdirSync, realpathSync, statSync } from "node:fs";
610
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
611
+
612
+ // src/runtime/framework/modules/runtime-module-loader.ts
613
+ import * as loader from "@myclaw163/game-agent-runtime/framework/modules/runtime-module-loader.js";
614
+ var SDK_ALIASES = Object.freeze({
615
+ "@myclaw163/clawclaw-cli/strategy-plugin": new URL("../../../sdk/strategy-plugin/index.ts", import.meta.url).href,
616
+ "clawclaw-cli/strategy-plugin": new URL("../../../sdk/strategy-plugin/index.ts", import.meta.url).href,
617
+ "@myclaw163/clawclaw-cli": new URL("../../../sdk/index.ts", import.meta.url).href,
618
+ "@myclaw163/clawclaw-cli/sdk": new URL("../../../sdk/index.ts", import.meta.url).href,
619
+ "@myclaw163/clawclaw-cli/module-input": new URL(
620
+ "../../../sdk/module-input/index.ts",
621
+ import.meta.url
622
+ ).href,
623
+ "@myclaw163/clawclaw-cli/behavior-plugin": new URL(
624
+ "../../../sdk/behavior-plugin/index.ts",
625
+ import.meta.url
626
+ ).href,
627
+ "@myclaw163/clawclaw-cli/trigger-plugin": new URL(
628
+ "../../../sdk/trigger-plugin/index.ts",
629
+ import.meta.url
630
+ ).href,
631
+ "@myclaw163/clawclaw-cli/perception-plugin": new URL(
632
+ "../../../sdk/perception-plugin/index.ts",
633
+ import.meta.url
634
+ ).href,
635
+ "clawclaw-cli": new URL("../../../sdk/index.ts", import.meta.url).href,
636
+ "clawclaw-cli/sdk": new URL("../../../sdk/index.ts", import.meta.url).href,
637
+ "clawclaw-cli/module-input": new URL("../../../sdk/module-input/index.ts", import.meta.url).href,
638
+ "clawclaw-cli/behavior-plugin": new URL("../../../sdk/behavior-plugin/index.ts", import.meta.url).href,
639
+ "clawclaw-cli/trigger-plugin": new URL("../../../sdk/trigger-plugin/index.ts", import.meta.url).href,
640
+ "clawclaw-cli/perception-plugin": new URL(
641
+ "../../../sdk/perception-plugin/index.ts",
642
+ import.meta.url
643
+ ).href
644
+ });
645
+
646
+ // src/runtime/clawclaw/plugins/plugin-api-version.ts
647
+ function pluginApiVersionDiagnostic(code, expected, received) {
648
+ return `${code}:expected=${expected}:received=${received ?? "missing"}`;
649
+ }
650
+ function assertPluginApiVersion(code, expected, received) {
651
+ if (received !== expected) {
652
+ throw new Error(pluginApiVersionDiagnostic(code, expected, received));
653
+ }
654
+ }
655
+
656
+ // src/runtime/framework/events/event-catalog.ts
657
+ var event_catalog_exports = {};
658
+ __reExport(event_catalog_exports, event_catalog_star);
659
+ import * as event_catalog_star from "@myclaw163/game-agent-runtime/framework/events/event-catalog.js";
660
+
661
+ // src/runtime/clawclaw-event-catalog.ts
662
+ var CLAWCLAW_VISUAL_EVENT_TYPES = [
663
+ "visual.player_entered",
664
+ "visual.player_left",
665
+ "visual.player_reappeared",
666
+ "visual.corpse_entered",
667
+ "visual.corpse_left",
668
+ "visual.player_moved",
669
+ "visual.player_motion_changed",
670
+ "visual.player_stopped",
671
+ "visual.player_resumed",
672
+ "visual.player_stop_ended",
673
+ "visual.no_significant_stop",
674
+ "visual.player_area_changed",
675
+ "visual.player_position_changed",
676
+ "visual.player_turned",
677
+ "visual.player_reversed",
678
+ "visual.player_wandering",
679
+ "visual.players_moving_together",
680
+ "visual.players_stopped_moving_together",
681
+ "visual.following",
682
+ "visual.following_ended"
683
+ ];
684
+ var CLAWCLAW_BACKEND_AGENT_EVENT_TYPES = [
685
+ "service_status",
686
+ "move_interrupted",
687
+ "kill",
688
+ "killed",
689
+ "murder_witnessed",
690
+ "warrior_shrimp_self_destruct",
691
+ "body_dropped",
692
+ "corpse_spotted",
693
+ "octopus_time_start",
694
+ "emergency_started",
695
+ "emergency_resolved",
696
+ "exile",
697
+ "no_exile",
698
+ "vote_speech_phase_ended",
699
+ "death_speech",
700
+ "meeting_briefing",
701
+ "speech",
702
+ "speech_skipped",
703
+ "speech_your_turn",
704
+ "speech_next_turn",
705
+ "vote_phase_start",
706
+ "game_over",
707
+ "exile_game_over",
708
+ "game_started",
709
+ "role_assigned",
710
+ "emergency_interrupted",
711
+ "octopus_time_win",
712
+ "win_blocked_by_octopus",
713
+ "room.member_joined",
714
+ "room.member_status_changed",
715
+ "room.member_left",
716
+ "room.owner_changed",
717
+ "room.full",
718
+ "room.type_changed",
719
+ "room.chat",
720
+ "room.game_starting",
721
+ "room.game_started",
722
+ "room.game_start_failed",
723
+ "room.game_finished",
724
+ "room.cooldown",
725
+ "room.idle_warning",
726
+ "room.self_left"
727
+ ];
728
+ var CLAWCLAW_LOCAL_AGENT_EVENT_TYPES = [
729
+ "joined",
730
+ "room_created",
731
+ "room_joined",
732
+ "session_resumed",
733
+ "session_recovered",
734
+ "not_in_queue",
735
+ "poll_error",
736
+ "error",
737
+ "game_start_failed",
738
+ "game_over_recovered",
739
+ "game_terminal_missing",
740
+ "game_stream_disconnected",
741
+ "game_stream_reconnected",
742
+ "stop_requested",
743
+ "quit_requested",
744
+ "match_start",
745
+ "match_waiting",
746
+ "match_timeout",
747
+ "user_left_game",
748
+ "session_left",
749
+ "quit_failed",
750
+ "robot_speak_rule",
751
+ "room_attached",
752
+ "room_lobby_reconnect_failed",
753
+ "room_lobby_missing",
754
+ "room_ready_to_start",
755
+ "room_returning_to_lobby",
756
+ "room_ping_timeout",
757
+ "room_destroyed",
758
+ "strategy_alert",
759
+ "behavior.started",
760
+ "behavior.suspended",
761
+ "behavior.restarted",
762
+ "behavior.completed",
763
+ "behavior.failed",
764
+ "behavior.cancelled",
765
+ "behavior.replaced",
766
+ "players_changed",
767
+ "reminder.task",
768
+ "reminder.speech",
769
+ "perception.module_failed",
770
+ "perception.behavior_unavailable",
771
+ "emergency_countdown_warning",
772
+ "ability.ready",
773
+ "ability.unavailable",
774
+ "ability.remaining_uses_changed",
775
+ "ability.exhausted"
776
+ ];
777
+ var CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES = [
778
+ "wandering_speech",
779
+ "task_completed",
780
+ "task_interrupted",
781
+ "task_sabotaged",
782
+ "enter_room",
783
+ "move_start",
784
+ "move_end",
785
+ "move",
786
+ "task_started",
787
+ "task_progress",
788
+ "task_assigned",
789
+ "speech_turn",
790
+ "vote_cast",
791
+ "think",
792
+ "vote_speech",
793
+ "player_spotted",
794
+ "meeting_start",
795
+ "meeting_started",
796
+ "meeting_ended",
797
+ "meeting_result_pending"
798
+ ];
799
+ var CLAWCLAW_INTERNAL_LOCAL_EVENT_TYPES = [
800
+ "tasks_changed",
801
+ "meeting_state",
802
+ "runtime_started",
803
+ "runtime_stopped",
804
+ "stream_gap"
805
+ ];
806
+ var CLAWCLAW_FIXED_EVENT_TYPES = /* @__PURE__ */ new Set([
807
+ ...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES,
808
+ ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES,
809
+ ...CLAWCLAW_INTERNAL_BACKEND_EVENT_TYPES,
810
+ ...CLAWCLAW_INTERNAL_LOCAL_EVENT_TYPES,
811
+ ...CLAWCLAW_VISUAL_EVENT_TYPES
812
+ ]);
813
+ function isClawclawFixedEventType(type) {
814
+ return CLAWCLAW_FIXED_EVENT_TYPES.has(type);
815
+ }
816
+ var CLAWCLAW_MONITOR_AND_EVENTS_EVENT_TYPES = /* @__PURE__ */ new Set([
817
+ ...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES,
818
+ ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES
819
+ ]);
820
+
821
+ // src/runtime/clawclaw/behavior-input-fields.ts
822
+ var FIELD_TYPES = /* @__PURE__ */ new Set([
823
+ "string",
824
+ "number",
825
+ "boolean",
826
+ "enum",
827
+ "string_list",
828
+ "player_seat",
829
+ "player_seats"
830
+ ]);
831
+ var BASE_KEYS = /* @__PURE__ */ new Set(["id", "type", "description", "required", "default"]);
832
+ var ID_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{0,79}$/;
833
+ function own(value, key) {
834
+ return Object.prototype.hasOwnProperty.call(value, key);
835
+ }
836
+ function deepFreeze(value) {
837
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
838
+ Object.freeze(value);
839
+ for (const child of Object.values(value)) deepFreeze(child);
840
+ return value;
841
+ }
842
+ function fieldRecord(value) {
843
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
844
+ }
845
+ function valueDiagnostic(field, value, prefix) {
846
+ const id = String(field.id);
847
+ const type = field.type;
848
+ if (type === "string") {
849
+ if (typeof value !== "string") return `behavior_input_${prefix}_type_invalid:${id}`;
850
+ return value.trim() ? void 0 : `behavior_input_${prefix}_empty:${id}`;
851
+ }
852
+ if (type === "player_seat") {
853
+ if (typeof value !== "number" || !Number.isInteger(value)) {
854
+ return `behavior_input_${prefix}_type_invalid:${id}`;
855
+ }
856
+ return value >= 1 && value <= 10 ? void 0 : `behavior_input_${prefix}_range_invalid:${id}`;
857
+ }
858
+ if (type === "number") {
859
+ if (typeof value !== "number" || !Number.isFinite(value)) {
860
+ return `behavior_input_${prefix}_type_invalid:${id}`;
861
+ }
862
+ if (typeof field.min === "number" && value < field.min || typeof field.max === "number" && value > field.max) return `behavior_input_${prefix}_range_invalid:${id}`;
863
+ return void 0;
864
+ }
865
+ if (type === "boolean") {
866
+ return typeof value === "boolean" ? void 0 : `behavior_input_${prefix}_type_invalid:${id}`;
867
+ }
868
+ if (type === "enum") {
869
+ if (typeof value !== "string") return `behavior_input_${prefix}_type_invalid:${id}`;
870
+ return field.values.includes(value) ? void 0 : `behavior_input_${prefix}_enum_invalid:${id}`;
871
+ }
872
+ if (type === "player_seats") {
873
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "number" || !Number.isInteger(entry))) {
874
+ return `behavior_input_${prefix}_type_invalid:${id}`;
875
+ }
876
+ if (value.some((entry) => entry < 1 || entry > 10)) {
877
+ return `behavior_input_${prefix}_range_invalid:${id}`;
878
+ }
879
+ if (field.required === true && value.length === 0) {
880
+ return `behavior_input_required_empty:${id}`;
881
+ }
882
+ if (typeof field.maxItems === "number" && value.length > field.maxItems) {
883
+ return `behavior_input_${prefix}_max_items_exceeded:${id}`;
884
+ }
885
+ return void 0;
886
+ }
887
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string")) {
888
+ return `behavior_input_${prefix}_type_invalid:${id}`;
889
+ }
890
+ if (value.some((entry) => !entry.trim())) return `behavior_input_${prefix}_empty:${id}`;
891
+ if (field.required === true && value.length === 0) {
892
+ return `behavior_input_required_empty:${id}`;
893
+ }
894
+ if (typeof field.maxItems === "number" && value.length > field.maxItems) {
895
+ return `behavior_input_${prefix}_max_items_exceeded:${id}`;
896
+ }
897
+ return void 0;
898
+ }
899
+ function fieldDiagnostic(value, seenIds) {
900
+ const field = fieldRecord(value);
901
+ if (!field) return "behavior_input_field_invalid";
902
+ const id = typeof field.id === "string" ? field.id : "";
903
+ if (!ID_PATTERN.test(id)) return `behavior_input_id_invalid:${id || "missing"}`;
904
+ if (seenIds.has(id)) return `behavior_input_id_duplicate:${id}`;
905
+ seenIds.add(id);
906
+ if (typeof field.type !== "string" || !FIELD_TYPES.has(field.type)) {
907
+ return `behavior_input_type_invalid:${id}`;
908
+ }
909
+ if (typeof field.description !== "string" || !field.description.trim()) {
910
+ return `behavior_input_description_invalid:${id}`;
911
+ }
912
+ if (field.required !== void 0 && typeof field.required !== "boolean") {
913
+ return `behavior_input_required_invalid:${id}`;
914
+ }
915
+ const type = field.type;
916
+ const allowed = new Set(BASE_KEYS);
917
+ if (type === "number") {
918
+ allowed.add("min");
919
+ allowed.add("max");
920
+ } else if (type === "enum") {
921
+ allowed.add("values");
922
+ } else if (type === "string_list" || type === "player_seats") {
923
+ allowed.add("maxItems");
924
+ }
925
+ const unknown = Object.keys(field).find((key) => !allowed.has(key));
926
+ if (unknown) return `behavior_input_constraint_unknown:${id}:${unknown}`;
927
+ if (type === "number") {
928
+ if (field.min !== void 0 && (typeof field.min !== "number" || !Number.isFinite(field.min)) || field.max !== void 0 && (typeof field.max !== "number" || !Number.isFinite(field.max)) || typeof field.min === "number" && typeof field.max === "number" && field.min > field.max) return `behavior_input_number_bounds_invalid:${id}`;
929
+ }
930
+ if (type === "enum") {
931
+ if (!Array.isArray(field.values) || field.values.length === 0 || field.values.some((entry) => typeof entry !== "string") || field.values.some((entry) => !entry.trim()) || new Set(field.values).size !== field.values.length) return `behavior_input_enum_values_invalid:${id}`;
932
+ }
933
+ if (type === "string_list" || type === "player_seats") {
934
+ if (field.maxItems !== void 0 && (!Number.isSafeInteger(field.maxItems) || field.maxItems <= 0)) return `behavior_input_max_items_invalid:${id}`;
935
+ }
936
+ const hasDefault = own(field, "default");
937
+ if (field.required === true && hasDefault) {
938
+ return `behavior_input_required_default_conflict:${id}`;
939
+ }
940
+ return hasDefault ? valueDiagnostic(field, field.default, "default") : void 0;
941
+ }
942
+ function behaviorInputFieldsDiagnostic(value) {
943
+ try {
944
+ if (!Array.isArray(value)) return "behavior_inputs_invalid";
945
+ const seenIds = /* @__PURE__ */ new Set();
946
+ for (const field of value) {
947
+ const diagnostic = fieldDiagnostic(field, seenIds);
948
+ if (diagnostic) return diagnostic;
949
+ }
950
+ return void 0;
951
+ } catch {
952
+ return "behavior_inputs_invalid";
953
+ }
954
+ }
955
+ function normalizeBehaviorInputFields(value) {
956
+ const diagnostic = behaviorInputFieldsDiagnostic(value);
957
+ if (diagnostic) throw new Error(diagnostic);
958
+ try {
959
+ const normalized = value.map((field) => {
960
+ const result = {
961
+ id: field.id,
962
+ type: field.type,
963
+ description: field.description,
964
+ ...field.required === void 0 ? {} : { required: field.required },
965
+ ...own(field, "default") ? { default: structuredClone(field.default) } : {}
966
+ };
967
+ if (field.type === "number") {
968
+ if (field.min !== void 0) result.min = field.min;
969
+ if (field.max !== void 0) result.max = field.max;
970
+ }
971
+ if (field.type === "string_list" || field.type === "player_seats") {
972
+ if (field.maxItems !== void 0) result.maxItems = field.maxItems;
973
+ }
974
+ if (field.type === "enum") result.values = [...field.values];
975
+ return result;
976
+ });
977
+ return deepFreeze(normalized);
978
+ } catch {
979
+ throw new Error("behavior_inputs_not_cloneable");
980
+ }
981
+ }
982
+ function normalizeBehaviorInput(raw, fields, options = {}) {
983
+ const prototype = raw && typeof raw === "object" ? Object.getPrototypeOf(raw) : void 0;
984
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || prototype !== Object.prototype && prototype !== null) throw new Error("behavior_input_invalid");
985
+ const diagnostic = behaviorInputFieldsDiagnostic(fields);
986
+ if (diagnostic) throw new Error(diagnostic);
987
+ const source = raw;
988
+ const byId = new Map(fields.map((field) => [field.id, field]));
989
+ const allowedKeys = new Set(options.allowedKeys ?? []);
990
+ for (const key of Object.keys(source)) {
991
+ if (!byId.has(key) && !allowedKeys.has(key)) {
992
+ throw new Error(`behavior_input_field_unknown:${key}`);
993
+ }
994
+ }
995
+ const output = {};
996
+ const assignClone = (key, value) => {
997
+ try {
998
+ Object.defineProperty(output, key, {
999
+ configurable: true,
1000
+ enumerable: true,
1001
+ writable: true,
1002
+ value: structuredClone(value)
1003
+ });
1004
+ } catch {
1005
+ throw new Error(`behavior_input_value_not_cloneable:${key}`);
1006
+ }
1007
+ };
1008
+ for (const key of allowedKeys) {
1009
+ if (own(source, key)) assignClone(key, source[key]);
1010
+ }
1011
+ for (const field of fields) {
1012
+ if (own(source, field.id)) {
1013
+ const value = source[field.id];
1014
+ const valueError = valueDiagnostic(field, value, "value");
1015
+ if (valueError) throw new Error(valueError);
1016
+ assignClone(field.id, value);
1017
+ continue;
1018
+ }
1019
+ if (own(field, "default")) {
1020
+ assignClone(field.id, field.default);
1021
+ continue;
1022
+ }
1023
+ if (field.required === true && options.allowMissingRequired !== true) {
1024
+ throw new Error(`behavior_input_required:${field.id}`);
1025
+ }
1026
+ }
1027
+ return deepFreeze(output);
1028
+ }
1029
+
1030
+ // src/runtime/clawclaw/plugins/behavior/behavior-manifest.ts
1031
+ var EVENT_TYPE = /^[a-z][a-z0-9_.-]*$/;
1032
+ var BEHAVIOR_ID = /^[a-z0-9][a-z0-9._-]*$/;
1033
+ var MANIFEST_FIELDS = /* @__PURE__ */ new Set([
1034
+ "apiVersion",
1035
+ "id",
1036
+ "name",
1037
+ "description",
1038
+ "localizations",
1039
+ "inputs",
1040
+ "execution",
1041
+ "stateMode",
1042
+ "everyTicks",
1043
+ "produces",
1044
+ "runtime"
1045
+ ]);
1046
+ var RUNTIME_FIELDS = /* @__PURE__ */ new Set(["defaultMs", "deadlineOutcome", "controlGraceMs"]);
1047
+ function own2(value, key) {
1048
+ return Object.prototype.hasOwnProperty.call(value, key);
1049
+ }
1050
+ function deepFreezeBehaviorValue(value) {
1051
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
1052
+ Object.freeze(value);
1053
+ for (const child of Object.values(value)) {
1054
+ deepFreezeBehaviorValue(child);
1055
+ }
1056
+ return value;
1057
+ }
1058
+ function behaviorProducesDiagnostic(produces, options = {}) {
1059
+ if (!Array.isArray(produces)) return "behavior_produces_invalid";
1060
+ const seen = /* @__PURE__ */ new Set();
1061
+ const allowedReserved = new Set(options.allowReservedProduces ?? []);
1062
+ for (const candidate of produces) {
1063
+ if (typeof candidate !== "string" || !EVENT_TYPE.test(candidate)) {
1064
+ return `behavior_produces_invalid:${String(candidate)}`;
1065
+ }
1066
+ if (seen.has(candidate)) return `behavior_produces_duplicate:${candidate}`;
1067
+ seen.add(candidate);
1068
+ if (isClawclawFixedEventType(candidate) && !allowedReserved.has(candidate)) {
1069
+ return `behavior_produces_reserved:${candidate}`;
1070
+ }
1071
+ }
1072
+ return void 0;
1073
+ }
1074
+ function normalizeBehaviorRuntimeDefaults(value) {
1075
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1076
+ throw new Error("behavior_runtime_invalid");
1077
+ }
1078
+ const runtime = value;
1079
+ const unknownField = Object.keys(runtime).find((field) => !RUNTIME_FIELDS.has(field));
1080
+ if (unknownField) throw new Error(`behavior_runtime_field_unknown:${unknownField}`);
1081
+ if (!Number.isSafeInteger(runtime.defaultMs) || runtime.defaultMs < 1e3 || runtime.defaultMs > 12e4) {
1082
+ throw new Error("behavior_runtime_default_invalid");
1083
+ }
1084
+ if (runtime.deadlineOutcome !== void 0 && runtime.deadlineOutcome !== "completed" && runtime.deadlineOutcome !== "failed") throw new Error("behavior_runtime_deadline_outcome_invalid");
1085
+ if (runtime.controlGraceMs !== void 0 && (!Number.isSafeInteger(runtime.controlGraceMs) || runtime.controlGraceMs < 0 || runtime.controlGraceMs > 3e4)) throw new Error("behavior_runtime_control_grace_invalid");
1086
+ return deepFreezeBehaviorValue({
1087
+ defaultMs: runtime.defaultMs,
1088
+ ...runtime.deadlineOutcome === void 0 ? {} : { deadlineOutcome: runtime.deadlineOutcome },
1089
+ ...runtime.controlGraceMs === void 0 ? {} : { controlGraceMs: runtime.controlGraceMs }
1090
+ });
1091
+ }
1092
+ function nonEmpty(value) {
1093
+ return typeof value === "string" && value.trim().length > 0;
1094
+ }
1095
+ function normalizeClawclawBehaviorManifest(value, options = {}) {
1096
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1097
+ throw new Error("behavior_manifest_missing");
1098
+ }
1099
+ const manifest = value;
1100
+ const unknownField = Object.keys(manifest).find((field) => !MANIFEST_FIELDS.has(field));
1101
+ if (unknownField) throw new Error(`behavior_manifest_field_unknown:${unknownField}`);
1102
+ assertPluginApiVersion(
1103
+ "behavior_manifest_api_version_unsupported",
1104
+ BEHAVIOR_PLUGIN_API_VERSION,
1105
+ typeof manifest.apiVersion === "number" ? manifest.apiVersion : void 0
1106
+ );
1107
+ const id = nonEmpty(manifest.id) ? manifest.id.trim() : "";
1108
+ if (!BEHAVIOR_ID.test(id)) throw new Error("behavior_id_invalid");
1109
+ if (manifest.name !== void 0 && !nonEmpty(manifest.name)) throw new Error("behavior_name_invalid");
1110
+ if (!nonEmpty(manifest.description)) throw new Error("behavior_description_invalid");
1111
+ if (!hasValidClawclawResourceLocalizations(
1112
+ manifest.localizations
1113
+ )) throw new Error("behavior_localizations_invalid");
1114
+ if (!own2(manifest, "inputs")) throw new Error("behavior_inputs_missing");
1115
+ const inputs = normalizeBehaviorInputFields(manifest.inputs);
1116
+ const reserved = inputs.find(({ id: inputId }) => inputId === "timeout_ms" || inputId === "duration_ms");
1117
+ if (reserved) throw new Error(`behavior_input_id_reserved:${reserved.id}`);
1118
+ if (manifest.execution !== void 0 && manifest.execution !== "parallel" && manifest.execution !== "serial") throw new Error("behavior_execution_invalid");
1119
+ const everyTicks = manifest.everyTicks ?? 1;
1120
+ if (manifest.stateMode !== void 0 && manifest.stateMode !== "isolated" && manifest.stateMode !== "snapshot") {
1121
+ throw new Error("behavior_state_mode_invalid");
1122
+ }
1123
+ if (manifest.stateMode === "snapshot" && manifest.execution === "serial") {
1124
+ throw new Error("behavior_snapshot_requires_parallel");
1125
+ }
1126
+ if (!Number.isSafeInteger(everyTicks) || everyTicks <= 0) {
1127
+ throw new Error("behavior_every_ticks_invalid");
1128
+ }
1129
+ if (manifest.produces !== void 0) {
1130
+ const diagnostic = behaviorProducesDiagnostic(manifest.produces, options);
1131
+ if (diagnostic) throw new Error(diagnostic);
1132
+ }
1133
+ const runtime = manifest.runtime === void 0 ? void 0 : normalizeBehaviorRuntimeDefaults(manifest.runtime);
1134
+ let localizations;
1135
+ try {
1136
+ localizations = manifest.localizations === void 0 ? void 0 : structuredClone(manifest.localizations);
1137
+ } catch {
1138
+ throw new Error("behavior_localizations_not_cloneable");
1139
+ }
1140
+ return deepFreezeBehaviorValue({
1141
+ apiVersion: BEHAVIOR_PLUGIN_API_VERSION,
1142
+ id,
1143
+ name: (manifest.name ?? manifest.id).trim(),
1144
+ description: manifest.description.trim(),
1145
+ ...localizations === void 0 ? {} : { localizations },
1146
+ inputs,
1147
+ ...manifest.stateMode === void 0 ? {} : { stateMode: manifest.stateMode },
1148
+ ...manifest.execution === void 0 ? {} : { execution: manifest.execution },
1149
+ ...manifest.everyTicks === void 0 ? {} : { everyTicks },
1150
+ ...manifest.produces === void 0 ? {} : { produces: [...manifest.produces] },
1151
+ ...runtime === void 0 ? {} : { runtime }
1152
+ });
1153
+ }
1154
+
1155
+ // src/runtime/clawclaw/plugins/behavior/behavior-source.ts
1156
+ var MAX_BEHAVIOR_SOURCE_BYTES = 2 * 1024 * 1024;
1157
+
1158
+ // src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts
1159
+ function pathInside(root, candidate) {
1160
+ const child = relative(root, candidate);
1161
+ return child === "" || !child.startsWith("..") && !isAbsolute(child);
1162
+ }
1163
+ var MAX_BEHAVIOR_SOURCE_TREE_FILES = 2048;
1164
+ var MAX_BEHAVIOR_SOURCE_TREE_BYTES = 64 * 1024 * 1024;
1165
+ var RUNTIME_SOURCE_FILE = /\.(?:[cm]?[jt]sx?|json)$/i;
1166
+ function behaviorSourceTreeSha256(sourceRoot) {
1167
+ const root = realpathSync(resolve(sourceRoot));
1168
+ const files = [];
1169
+ const visit = (directory) => {
1170
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1171
+ const candidate = join(directory, entry.name);
1172
+ if (entry.isSymbolicLink()) throw new Error("behavior_source_tree_symlink_unsupported");
1173
+ if (entry.isDirectory()) {
1174
+ visit(candidate);
1175
+ continue;
1176
+ }
1177
+ if (!entry.isFile() || !RUNTIME_SOURCE_FILE.test(entry.name)) continue;
1178
+ const physical = realpathSync(candidate);
1179
+ if (!pathInside(root, physical)) throw new Error("behavior_source_tree_outside_root");
1180
+ const stats = statSync(physical);
1181
+ files.push({
1182
+ path: physical,
1183
+ relativePath: relative(root, physical).replaceAll("\\", "/"),
1184
+ size: stats.size
1185
+ });
1186
+ if (files.length > MAX_BEHAVIOR_SOURCE_TREE_FILES) {
1187
+ throw new Error("behavior_source_tree_file_limit_exceeded");
1188
+ }
1189
+ }
1190
+ };
1191
+ visit(root);
1192
+ files.sort((left, right) => left.relativePath.localeCompare(right.relativePath));
1193
+ const totalBytes = files.reduce((total, file) => total + file.size, 0);
1194
+ if (totalBytes > MAX_BEHAVIOR_SOURCE_TREE_BYTES) {
1195
+ throw new Error("behavior_source_tree_byte_limit_exceeded");
1196
+ }
1197
+ const hash = createHash("sha256");
1198
+ for (const file of files) {
1199
+ hash.update(file.relativePath);
1200
+ hash.update("\0");
1201
+ hash.update(readFileSync3(file.path));
1202
+ hash.update("\0");
1203
+ }
1204
+ return hash.digest("hex");
1205
+ }
1206
+ function equal(left, right) {
1207
+ return JSON.stringify(left) === JSON.stringify(right);
1208
+ }
1209
+ function assertSourceParity(manifest, source) {
1210
+ if ((manifest.stateMode ?? "isolated") !== (source.stateMode ?? "isolated")) {
1211
+ throw new Error("behavior_state_mode_source_mismatch");
1212
+ }
1213
+ if (manifest.id !== (source.declaredId ?? source.id)) throw new Error("behavior_id_source_mismatch");
1214
+ if (manifest.name !== source.name) throw new Error("behavior_name_source_mismatch");
1215
+ if (manifest.description !== source.description) {
1216
+ throw new Error("behavior_description_source_mismatch");
1217
+ }
1218
+ if (!equal(manifest.localizations, source.localizations)) {
1219
+ throw new Error("behavior_localizations_source_mismatch");
1220
+ }
1221
+ if (!equal(manifest.inputs, source.inputs)) {
1222
+ throw new Error("behavior_inputs_source_mismatch");
1223
+ }
1224
+ if ((manifest.execution ?? "parallel") !== source.execution) {
1225
+ throw new Error("behavior_execution_source_mismatch");
1226
+ }
1227
+ if ((manifest.everyTicks ?? 1) !== source.everyTicks) {
1228
+ throw new Error("behavior_every_ticks_source_mismatch");
1229
+ }
1230
+ if (!equal(manifest.produces ?? [], source.produces ?? [])) {
1231
+ throw new Error("behavior_produces_source_mismatch");
1232
+ }
1233
+ if (!equal(manifest.runtime, source.runtime)) {
1234
+ throw new Error("behavior_runtime_source_mismatch");
1235
+ }
1236
+ }
1237
+ function validateClawclawBehaviorModule(module, source) {
1238
+ const candidate = module.default;
1239
+ if (typeof candidate !== "function") throw new Error("behavior_default_class_missing");
1240
+ const descriptor = Object.getOwnPropertyDescriptor(candidate, "manifest");
1241
+ if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, "value")) {
1242
+ throw new Error("behavior_manifest_missing");
1243
+ }
1244
+ const BehaviorClass = candidate;
1245
+ if (typeof BehaviorClass.prototype.decide !== "function") {
1246
+ throw new Error("behavior_decide_missing");
1247
+ }
1248
+ if (BehaviorClass.prototype.normalize !== void 0 && typeof BehaviorClass.prototype.normalize !== "function") throw new Error("behavior_normalize_invalid");
1249
+ const manifest = normalizeClawclawBehaviorManifest(descriptor.value, {
1250
+ allowReservedProduces: source?.allowReservedProduces
1251
+ });
1252
+ if (source) assertSourceParity(manifest, source);
1253
+ const effectiveManifest = source && source.id !== manifest.id ? Object.freeze({ ...manifest, id: source.id }) : manifest;
1254
+ return Object.freeze({
1255
+ BehaviorClass,
1256
+ manifest: effectiveManifest,
1257
+ ...source === void 0 ? {} : { source }
1258
+ });
1259
+ }
1260
+ function resolveBehaviorSource(source) {
1261
+ const sourceRoot = realpathSync(resolve(source.sourceRoot));
1262
+ const sourcePath = realpathSync(resolve(source.sourcePath));
1263
+ if (!pathInside(sourceRoot, sourcePath) || dirname(sourcePath) !== sourceRoot || !statSync(sourcePath).isFile()) throw new Error(`Behavior '${source.id}' source is outside its root.`);
1264
+ if (source.trustedSourceSha256 !== void 0) {
1265
+ if (!/^[0-9a-f]{64}$/.test(source.trustedSourceSha256)) {
1266
+ throw new Error("behavior_trusted_source_hash_invalid");
1267
+ }
1268
+ const current = createHash("sha256").update(readFileSync3(sourcePath)).digest("hex");
1269
+ if (current !== source.trustedSourceSha256) {
1270
+ throw new Error("behavior_trusted_source_changed");
1271
+ }
1272
+ }
1273
+ if (source.trustedSourceTreeSha256 !== void 0) {
1274
+ if (!/^[0-9a-f]{64}$/.test(source.trustedSourceTreeSha256)) {
1275
+ throw new Error("behavior_source_tree_hash_invalid");
1276
+ }
1277
+ if (behaviorSourceTreeSha256(sourceRoot) !== source.trustedSourceTreeSha256) {
1278
+ throw new Error("behavior_source_tree_changed");
1279
+ }
1280
+ }
1281
+ return { ...source, sourceRoot, sourcePath };
1282
+ }
1283
+
1284
+ // src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts
1285
+ var MIN_RUNTIME_MS = 1e3;
1286
+ var MAX_RUNTIME_MS = 12e4;
1287
+ function own3(value, key) {
1288
+ return Object.prototype.hasOwnProperty.call(value, key);
1289
+ }
1290
+ function requestRecord(value) {
1291
+ const prototype = value && typeof value === "object" ? Object.getPrototypeOf(value) : void 0;
1292
+ if (!value || typeof value !== "object" || Array.isArray(value) || prototype !== Object.prototype && prototype !== null) throw new Error("behavior_request_invalid");
1293
+ return value;
1294
+ }
1295
+ function immutableRecord(value) {
1296
+ const record = requestRecord(value);
1297
+ try {
1298
+ return deepFreezeBehaviorValue(structuredClone(record));
1299
+ } catch {
1300
+ throw new Error("behavior_request_not_cloneable");
1301
+ }
1302
+ }
1303
+ function createBehaviorNormalizationApi(manifest) {
1304
+ const string = (value, field) => {
1305
+ if (typeof value !== "string" || !value.trim() || value.trim().length > 120) {
1306
+ throw new Error(`behavior_${field}_invalid`);
1307
+ }
1308
+ return value.trim();
1309
+ };
1310
+ return Object.freeze({
1311
+ manifest,
1312
+ timing: (input) => {
1313
+ if (input.duration_ms !== void 0 && input.timeout_ms !== void 0) {
1314
+ throw new Error("behavior_runtime_ms_ambiguous");
1315
+ }
1316
+ const explicitDuration = input.duration_ms !== void 0;
1317
+ const raw = input.duration_ms ?? input.timeout_ms ?? manifest.runtime?.defaultMs;
1318
+ if (raw === void 0) throw new Error("behavior_runtime_default_missing");
1319
+ const value = Number(raw);
1320
+ if (!Number.isSafeInteger(value) || value < MIN_RUNTIME_MS || value > MAX_RUNTIME_MS) {
1321
+ throw new Error("behavior_runtime_ms_invalid");
1322
+ }
1323
+ return explicitDuration ? { duration_ms: value } : { timeout_ms: value };
1324
+ },
1325
+ string,
1326
+ optionalString: (value, field) => value === void 0 || value === null || value === "" ? void 0 : string(value, field),
1327
+ number: (value, field, constraints = {}) => {
1328
+ const number = Number(value);
1329
+ if (!Number.isFinite(number) || constraints.integer === true && !Number.isInteger(number) || constraints.min !== void 0 && number < constraints.min || constraints.max !== void 0 && number > constraints.max) throw new Error(`behavior_${field}_invalid`);
1330
+ return number;
1331
+ },
1332
+ stringArray: (value, field, constraints = {}) => {
1333
+ if (!Array.isArray(value) || constraints.maxItems !== void 0 && value.length > constraints.maxItems) throw new Error(`behavior_${field}_invalid`);
1334
+ return Object.freeze(value.map((entry) => string(entry, field)));
1335
+ },
1336
+ choice: (value, field, values) => {
1337
+ if (typeof value !== "string" || !values.includes(value)) {
1338
+ throw new Error(`behavior_${field}_invalid`);
1339
+ }
1340
+ return value;
1341
+ }
1342
+ });
1343
+ }
1344
+ function materializedTiming(raw, normalized, api) {
1345
+ if (own3(raw, "duration_ms") && raw.duration_ms !== void 0 || own3(raw, "timeout_ms") && raw.timeout_ms !== void 0) return Object.freeze(api.timing(raw));
1346
+ if (own3(normalized, "duration_ms") && normalized.duration_ms !== void 0 || own3(normalized, "timeout_ms") && normalized.timeout_ms !== void 0) return Object.freeze(api.timing(normalized));
1347
+ return void 0;
1348
+ }
1349
+ function prepareClawclawBehavior(BehaviorClass, manifest, value, source) {
1350
+ const raw = requestRecord(value);
1351
+ if (raw.duration_ms !== void 0 && raw.timeout_ms !== void 0) {
1352
+ throw new Error("behavior_runtime_ms_ambiguous");
1353
+ }
1354
+ const declared = normalizeBehaviorInput(raw, manifest.inputs, {
1355
+ allowedKeys: ["timeout_ms", "duration_ms"]
1356
+ });
1357
+ const module = new BehaviorClass();
1358
+ const api = createBehaviorNormalizationApi(manifest);
1359
+ const normalized = typeof module.normalize === "function" ? immutableRecord(module.normalize(declared, api)) : immutableRecord(declared);
1360
+ const timing = materializedTiming(raw, normalized, api);
1361
+ return Object.freeze({
1362
+ module,
1363
+ rawInput: immutableRecord(declared),
1364
+ createModule: () => new BehaviorClass(),
1365
+ manifest,
1366
+ input: normalized,
1367
+ ...source === void 0 ? {} : { source },
1368
+ ...timing === void 0 ? {} : { timing }
1369
+ });
1370
+ }
1371
+
1372
+ // src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts
1373
+ await runStrategyWorker({
1374
+ async load(data) {
1375
+ resolveBehaviorSource(data.source);
1376
+ const module = await import(data.sourceUrl);
1377
+ resolveBehaviorSource(data.source);
1378
+ const loaded = validateClawclawBehaviorModule(module, data.source);
1379
+ return {
1380
+ execution: loaded.manifest.execution ?? "parallel",
1381
+ stateMode: loaded.manifest.stateMode,
1382
+ create: () => new loaded.BehaviorClass(),
1383
+ prepare: (input) => prepareClawclawBehavior(loaded.BehaviorClass, loaded.manifest, input, loaded.source)
1384
+ };
1385
+ },
1386
+ createApi: createBehaviorReadApi,
1387
+ normalize: (value) => normalizeBehaviorDecision(value, { finite: false })
1388
+ });