@myclaw163/clawclaw-cli 0.8.5 → 0.8.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 (119) hide show
  1. package/README.md +1 -1
  2. package/docs/configuration.md +2 -1
  3. package/docs/custom-modules/behavior.md +7 -18
  4. package/docs/custom-modules/trigger.md +3 -4
  5. package/docs/runtime/short-commands-and-capabilities.md +1 -1
  6. package/package.json +9 -3
  7. package/scripts/find-hide-spots.py +2 -2
  8. package/skills/clawclaw/SKILL.md +17 -13
  9. package/skills/clawclaw/references/BEHAVIORS.md +13 -9
  10. package/skills/clawclaw/references/COMMANDS.md +17 -29
  11. package/skills/clawclaw/references/TACTICS.md +1 -1
  12. package/src/commands/load.ts +245 -14
  13. package/src/commands/trigger.ts +22 -13
  14. package/src/lib/capability-load-diagnostics.ts +182 -0
  15. package/src/lib/gameplay-config.ts +10 -0
  16. package/src/lib/hub-reminder.ts +3 -5
  17. package/src/lib/trigger-config.ts +2 -10
  18. package/src/runtime/clawclaw/behavior-read-api.ts +1 -1
  19. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/astar-path.ts +1 -1
  20. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/escape-planner.ts +1 -1
  21. package/src/{strategies → runtime/clawclaw/navigation}/hide-spots.ts +2 -2
  22. package/src/{strategies → runtime/clawclaw/navigation}/off-route-points.ts +6 -3
  23. package/src/{strategies/pathfind → runtime/clawclaw/navigation}/walkable-grid.ts +1 -1
  24. package/src/runtime/clawclaw/owner.ts +4 -6
  25. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +1 -1
  26. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -54
  27. package/src/sdk/behavior-toolkit/escape.ts +2 -2
  28. package/scripts/build-official-hub-behaviors.mjs +0 -136
  29. package/scripts/build-official-hub-behaviors.test.mjs +0 -178
  30. package/scripts/compare-perception-replays.test.ts +0 -188
  31. package/scripts/enable_ccl_permissions.test.mjs +0 -167
  32. package/scripts/enable_monitor.test.mjs +0 -201
  33. package/scripts/sync-bundled-skill.test.mjs +0 -87
  34. package/scripts/watch-perception-events.test.ts +0 -43
  35. package/src/behaviors/official-finite/do-task.ts +0 -211
  36. package/src/behaviors/official-finite/evade.ts +0 -78
  37. package/src/behaviors/official-finite/find-player.ts +0 -50
  38. package/src/behaviors/official-finite/follow-player.ts +0 -70
  39. package/src/behaviors/official-finite/go-to.ts +0 -69
  40. package/src/behaviors/official-finite/hide-temporarily.ts +0 -77
  41. package/src/behaviors/official-finite/hold-position.ts +0 -48
  42. package/src/behaviors/official-finite/hunt-player.ts +0 -47
  43. package/src/behaviors/official-finite/index.ts +0 -44
  44. package/src/behaviors/official-finite/inspect-corpse.ts +0 -64
  45. package/src/behaviors/official-finite/patrol-area.ts +0 -80
  46. package/src/behaviors/official-finite/report-corpse.ts +0 -73
  47. package/src/behaviors/official-finite/seek-kill-opportunity.ts +0 -152
  48. package/src/behaviors/official-finite/shared.ts +0 -27
  49. package/src/hub-official-behaviors/kill-lone.ts +0 -138
  50. package/src/hub-official-behaviors/patrol.ts +0 -30
  51. package/src/hub-official-behaviors/shared.ts +0 -125
  52. package/src/hub-official-behaviors/task-only.ts +0 -158
  53. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -757
  54. package/src/strategies/avoid-lone.ts +0 -32
  55. package/src/strategies/avoid-players.ts +0 -43
  56. package/src/strategies/corpse-patrol.ts +0 -50
  57. package/src/strategies/crab-sabotage.ts +0 -48
  58. package/src/strategies/find-player.ts +0 -49
  59. package/src/strategies/game-utils.ts +0 -927
  60. package/src/strategies/goals/anchor-linger.ts +0 -77
  61. package/src/strategies/goals/avoid-lone-top.ts +0 -189
  62. package/src/strategies/goals/avoid-players-top.ts +0 -122
  63. package/src/strategies/goals/conversation-goal.ts +0 -51
  64. package/src/strategies/goals/corpse-patrol-top.ts +0 -120
  65. package/src/strategies/goals/crab-octopus-reflexes.ts +0 -109
  66. package/src/strategies/goals/crab-sabotage-top.ts +0 -139
  67. package/src/strategies/goals/emergency-hunt-goal.ts +0 -40
  68. package/src/strategies/goals/find-player-top.ts +0 -136
  69. package/src/strategies/goals/flee-players-goal.ts +0 -55
  70. package/src/strategies/goals/follow-companion-goal.ts +0 -130
  71. package/src/strategies/goals/goal-manager.ts +0 -41
  72. package/src/strategies/goals/goal-root-strategy.ts +0 -49
  73. package/src/strategies/goals/goal.ts +0 -28
  74. package/src/strategies/goals/hide-top.ts +0 -240
  75. package/src/strategies/goals/keep-away-goal.ts +0 -243
  76. package/src/strategies/goals/kill-frenzy-top.ts +0 -90
  77. package/src/strategies/goals/kill-lone-top.ts +0 -166
  78. package/src/strategies/goals/kill-target-goal.ts +0 -69
  79. package/src/strategies/goals/kill-target-top.ts +0 -121
  80. package/src/strategies/goals/leaf-goal.ts +0 -27
  81. package/src/strategies/goals/linger-corpse-goal.ts +0 -43
  82. package/src/strategies/goals/lone-kill-core.ts +0 -86
  83. package/src/strategies/goals/lone-kill-goal.ts +0 -24
  84. package/src/strategies/goals/lone-kill-task-top.ts +0 -133
  85. package/src/strategies/goals/move-room-goal.ts +0 -102
  86. package/src/strategies/goals/normal-shrimp-top.ts +0 -248
  87. package/src/strategies/goals/paradise-fish-top.ts +0 -234
  88. package/src/strategies/goals/patrol-top.ts +0 -68
  89. package/src/strategies/goals/report-patrol-top.ts +0 -97
  90. package/src/strategies/goals/safe-task-goal.ts +0 -130
  91. package/src/strategies/goals/social-task-top.ts +0 -192
  92. package/src/strategies/goals/task-kill-report-top.ts +0 -187
  93. package/src/strategies/goals/task-only-top.ts +0 -64
  94. package/src/strategies/goals/task-or-patrol-goal.ts +0 -59
  95. package/src/strategies/goals/task-report-top.ts +0 -57
  96. package/src/strategies/goals/wander-task-goal.ts +0 -33
  97. package/src/strategies/goals/warrior-shrimp-top.ts +0 -293
  98. package/src/strategies/greeting.ts +0 -60
  99. package/src/strategies/hide.ts +0 -51
  100. package/src/strategies/kill-frenzy.ts +0 -32
  101. package/src/strategies/kill-lone.ts +0 -52
  102. package/src/strategies/kill-target.ts +0 -48
  103. package/src/strategies/lone-kill-task.ts +0 -48
  104. package/src/strategies/meeting-gate.ts +0 -28
  105. package/src/strategies/move-room.ts +0 -46
  106. package/src/strategies/paradise-fish.ts +0 -70
  107. package/src/strategies/patrol.ts +0 -32
  108. package/src/strategies/player-targets.ts +0 -18
  109. package/src/strategies/report-patrol.ts +0 -32
  110. package/src/strategies/shrimp-memory.ts +0 -87
  111. package/src/strategies/social-task.ts +0 -67
  112. package/src/strategies/speech-module.ts +0 -123
  113. package/src/strategies/task-kill-report.ts +0 -49
  114. package/src/strategies/task-only.ts +0 -34
  115. package/src/strategies/task-report.ts +0 -50
  116. package/src/strategies/types.ts +0 -116
  117. package/src/strategies/warrior-memory.ts +0 -54
  118. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/clawclaw-walkable.bin +0 -0
  119. /package/src/{strategies/pathfind → runtime/clawclaw/navigation}/distance-field.ts +0 -0
@@ -41,6 +41,7 @@ const GAMEPLAY_CONFIG_FIELDS = new Set([
41
41
  'disabled_perception_modules',
42
42
  'fallback_behaviors',
43
43
  'disabled_behaviors',
44
+ 'disabled_triggers',
44
45
  'idle_ms',
45
46
  'triggers',
46
47
  ]);
@@ -62,6 +63,7 @@ export interface GameplayConfig {
62
63
  disabled_perception_modules: string[];
63
64
  fallback_behaviors: GameplayFallbackBehaviors;
64
65
  disabled_behaviors: string[];
66
+ disabled_triggers: string[];
65
67
  idle_ms: number;
66
68
  triggers: GameplayTriggerConfigs;
67
69
  }
@@ -73,6 +75,7 @@ export function defaultGameplayConfig(): GameplayConfig {
73
75
  disabled_perception_modules: [],
74
76
  fallback_behaviors: { ...NPM_ROLE_FALLBACK_BEHAVIORS },
75
77
  disabled_behaviors: [],
78
+ disabled_triggers: [],
76
79
  idle_ms: DEFAULT_BEHAVIOR_IDLE_MS,
77
80
  triggers: {},
78
81
  };
@@ -165,6 +168,12 @@ export function parseGameplayConfig(value: unknown): GameplayConfig {
165
168
  root.disabled_behaviors,
166
169
  'user-data/gameplay.json disabled_behaviors',
167
170
  ),
171
+ disabled_triggers: hasOwn(root, 'disabled_triggers')
172
+ ? resourceIds(
173
+ root.disabled_triggers,
174
+ 'user-data/gameplay.json disabled_triggers',
175
+ )
176
+ : [],
168
177
  idle_ms: behaviorIdleMs(root.idle_ms),
169
178
  triggers: parseGameplayTriggerConfigs(root.triggers),
170
179
  };
@@ -231,6 +240,7 @@ function migrateLegacyGameplayConfig(root: Record<string, unknown>): GameplayCon
231
240
  ...legacyDisabledStrategies,
232
241
  ...legacyDisabledIntents,
233
242
  ],
243
+ disabled_triggers: hasOwn(root, 'disabled_triggers') ? root.disabled_triggers : [],
234
244
  idle_ms: migratedIdleMs(root),
235
245
  triggers: hasOwn(root, 'triggers') ? root.triggers : {},
236
246
  });
@@ -12,10 +12,8 @@ import { getUserDataAccountBehaviorsDir } from './user-data.js';
12
12
  export const HUB_URL = 'https://myclaw.163.com/hub';
13
13
 
14
14
  /**
15
- * True when CCL can only see the default customization surface: no
16
- * selected Hub Skill/Strategy and no custom or modified Behavior in
17
- * `<workspace>/user-data/behaviors`. Materialized official Behaviors that
18
- * still match their manifest baseline count as defaults.
15
+ * True when CCL sees no selected Hub Skill/Behavior and no pure-local
16
+ * Behavior for the active account.
19
17
  */
20
18
  export function usesOnlyDefaultSkillAndBehaviors(): boolean {
21
19
  try {
@@ -49,7 +47,7 @@ export function usesOnlyDefaultSkillAndBehaviors(): boolean {
49
47
  export function hubReminder(gamesPlayed?: number): string | undefined {
50
48
  if (!usesOnlyDefaultSkillAndBehaviors()) return undefined;
51
49
  if (typeof gamesPlayed !== 'number' || gamesPlayed > 10) return undefined;
52
- return `玩家已经玩了 ${gamesPlayed} 局,且还没有用过自定义 Skill 或 Behavior。请在本局复盘后,提醒玩家可以根据复盘内容调整 Skill 或 Behavior,让龙虾打法更符合玩家偏好。提醒要用第一人称龙虾身份融入收尾,语气温和,不要硬推。首轮建议表达为:“这已经是我们一起打的第 ${gamesPlayed} 局了。到目前为止,我一直用的是官方默认 Skill 和默认 Behavior。如果你愿意,我们可以根据刚才这局的复盘调整 Skill 或 Behavior,让我的打法更符合你的偏好。要不要我帮你看看怎么改?”如果玩家表示想了解或需要修改,再说明三种方式:我帮你浏览 Skill Hub 上的 Skill 或 Behavior,按玩家想要的打法挑候选,玩家确认后再下载并安装;把 Skill Hub 链接 ${HUB_URL} 给玩家自行选择;告诉玩家当前游戏 Skill 和 Behavior 文件的存放路径,并根据本局复盘给出具体修改建议。路径信息只在玩家首次提出修改现有文件时主动给出;后续对局结束不要重复主动提示。`;
50
+ return `玩家已经玩了 ${gamesPlayed} 局,且当前账号还没有通过 Hub 或纯本地文件装配 Skill/Behavior。请在本局复盘后,提醒玩家可以根据复盘内容选择或创建 Skill/Behavior,让龙虾打法更符合玩家偏好。提醒要用第一人称龙虾身份融入收尾,语气温和,不要硬推。首轮建议表达为:“这已经是我们一起打的第 ${gamesPlayed} 局了。目前这个账号还没有装配自己的 Skill 或 Behavior。如果你愿意,我们可以根据刚才这局的复盘挑一个或新建一个,让我的打法更符合你的偏好。要不要我帮你看看?”如果玩家表示想了解或需要修改,再说明三种方式:我帮你浏览 Skill Hub 上的 Skill 或 Behavior,按玩家想要的打法挑候选,玩家确认后再下载并安装;把 Skill Hub 链接 ${HUB_URL} 给玩家自行选择;告诉玩家当前游戏 Skill 和 Behavior 文件的存放路径,并根据本局复盘给出具体修改建议。路径信息只在玩家首次提出修改现有文件时主动给出;后续对局结束不要重复主动提示。`;
53
51
  }
54
52
 
55
53
  const ACCOUNT_CACHE_FILE = 'account-cache.json';
@@ -2,11 +2,7 @@ import { MAX_TRIGGER_RUNTIME_MS } from '../sdk/trigger-plugin/index.js';
2
2
 
3
3
  export type GameplayTriggerRearm = 'after_clear' | 'after_cooldown';
4
4
 
5
- /** New community Trigger modules are inert until explicitly enabled. */
6
- export const DEFAULT_GAMEPLAY_TRIGGER_ENABLED = false;
7
-
8
5
  export interface GameplayTriggerConfig {
9
- enabled?: boolean;
10
6
  input?: Record<string, unknown>;
11
7
  behavior?: string;
12
8
  behavior_input?: Record<string, unknown>;
@@ -25,7 +21,6 @@ export type GameplayTriggerConfigs = Record<string, GameplayTriggerConfig>;
25
21
  */
26
22
  export interface TriggerRegistrationOverride {
27
23
  readonly id: string;
28
- readonly enabled?: boolean;
29
24
  readonly input?: Readonly<Record<string, unknown>>;
30
25
  readonly behavior?: string;
31
26
  readonly behaviorInput?: Readonly<Record<string, unknown>>;
@@ -37,6 +32,8 @@ export interface TriggerRegistrationOverride {
37
32
 
38
33
  const RESOURCE_ID = /^[a-z0-9][a-z0-9._-]*$/;
39
34
  const TRIGGER_FIELDS = new Set([
35
+ // Legacy persisted field: accepted but deliberately ignored. Enablement is
36
+ // controlled only by gameplay.disabled_triggers.
40
37
  'enabled',
41
38
  'input',
42
39
  'behavior',
@@ -139,9 +136,6 @@ function parseTriggerConfig(value: unknown, field: string): GameplayTriggerConfi
139
136
  if (unknown.length > 0) {
140
137
  throw new Error(`${field} contains unknown fields: ${unknown.sort().join(', ')}.`);
141
138
  }
142
- if (source.enabled !== undefined && typeof source.enabled !== 'boolean') {
143
- throw new Error(`${field}.enabled must be a boolean.`);
144
- }
145
139
  if (
146
140
  source.behavior !== undefined
147
141
  && (typeof source.behavior !== 'string' || !RESOURCE_ID.test(source.behavior))
@@ -164,7 +158,6 @@ function parseTriggerConfig(value: unknown, field: string): GameplayTriggerConfi
164
158
  }
165
159
 
166
160
  return {
167
- ...(source.enabled === undefined ? {} : { enabled: source.enabled }),
168
161
  ...(source.input === undefined ? {} : { input: jsonObject(source.input, `${field}.input`) }),
169
162
  ...(source.behavior === undefined ? {} : { behavior: source.behavior }),
170
163
  ...(source.behavior_input === undefined ? {} : {
@@ -201,7 +194,6 @@ export function toTriggerRegistrationOverrides(
201
194
  const normalized = parseGameplayTriggerConfigs(configs);
202
195
  return Object.entries(normalized).map(([id, config]) => Object.freeze({
203
196
  id,
204
- ...(config.enabled === undefined ? {} : { enabled: config.enabled }),
205
197
  ...(config.input === undefined ? {} : { input: Object.freeze(config.input) }),
206
198
  ...(config.behavior === undefined ? {} : { behavior: config.behavior }),
207
199
  ...(config.behavior_input === undefined ? {} : {
@@ -9,7 +9,7 @@ import type {
9
9
  import {
10
10
  getLocalPathDistance,
11
11
  getLocalPathDistances,
12
- } from '../../strategies/pathfind/astar-path.js';
12
+ } from './navigation/astar-path.js';
13
13
  import { CLAWCLAW_PERCEPTION_SPATIAL_API } from './plugins/perception/spatial-facts.js';
14
14
  import type { ClawclawBehaviorObservationSnapshot } from './behavior-observation-memory.js';
15
15
 
@@ -1,4 +1,4 @@
1
- import type { Position } from '../../sdk/types.js';
1
+ import type { Position } from '../../../sdk/types.js';
2
2
  import { loadWalkableGrid, type WalkableGrid } from './walkable-grid.js';
3
3
 
4
4
  interface NormalizedEndpoint {
@@ -1,4 +1,4 @@
1
- import type { Position } from '../../sdk/types.js';
1
+ import type { Position } from '../../../sdk/types.js';
2
2
  import { COST_DIAG, COST_STRAIGHT, FieldCalculator, PX_PER_UNIT, UNITS_PER_PX, type FieldResult } from './distance-field.js';
3
3
  import { loadWalkableGrid, type WalkableGrid } from './walkable-grid.js';
4
4
 
@@ -1,6 +1,6 @@
1
- import type { Position } from '../sdk/types.js';
1
+ import type { Position } from '../../../sdk/types.js';
2
2
  import { nearestSafePoint, type OffRoutePoint } from './off-route-points.js';
3
- import type { RouteEvidence } from './pathfind/escape-planner.js';
3
+ import type { RouteEvidence } from './escape-planner.js';
4
4
 
5
5
  /** 藏身角落,离路点的一种(见 OffRoutePoint)。 */
6
6
  export type HideSpot = OffRoutePoint;
@@ -1,10 +1,13 @@
1
- import type { Position } from '../sdk/types.js';
2
- import { dist } from './game-utils.js';
1
+ import type { Position } from '../../../sdk/types.js';
3
2
  import {
4
3
  assessRoutes,
5
4
  assessRoutesFromEvidence,
6
5
  type RouteEvidence,
7
- } from './pathfind/escape-planner.js';
6
+ } from './escape-planner.js';
7
+
8
+ function dist(ax: number, ay: number, bx: number, by: number): number {
9
+ return Math.hypot(ax - bx, ay - by);
10
+ }
8
11
 
9
12
  /**
10
13
  * 离线从烘焙地图算出的「离路点」:远离任务点/出生点、避开走廊与枢纽的低人流坐标
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from 'fs';
2
- import type { Position } from '../../sdk/types.js';
2
+ import type { Position } from '../../../sdk/types.js';
3
3
 
4
4
  // Walkability bitmap baked from the server's inflated_weights (walls already
5
5
  // inflated by the agent collision radius, so a walkable tile means the agent
@@ -19,10 +19,7 @@ import {
19
19
  readGameplayConfig,
20
20
  type GameplayConfig,
21
21
  } from '../../lib/gameplay-config.js';
22
- import {
23
- DEFAULT_GAMEPLAY_TRIGGER_ENABLED,
24
- toTriggerRegistrationOverrides,
25
- } from '../../lib/trigger-config.js';
22
+ import { toTriggerRegistrationOverrides } from '../../lib/trigger-config.js';
26
23
  import {
27
24
  isRoomMode,
28
25
  isTrainingRoomMode,
@@ -292,7 +289,7 @@ export function roleFallbackBehaviors(
292
289
 
293
290
  export function triggerRegistrations(
294
291
  sources: readonly ResolvedClawclawTriggerSource[],
295
- config: Pick<GameplayConfig, 'triggers'>,
292
+ config: Pick<GameplayConfig, 'triggers' | 'disabled_triggers'>,
296
293
  catalog: Pick<ClawclawBehaviorCatalog, 'list'>,
297
294
  warning: ConfigurationWarning = () => {},
298
295
  ): readonly ClawclawTriggerRegistration[] {
@@ -302,6 +299,7 @@ export function triggerRegistrations(
302
299
  const overrides = new Map(
303
300
  toTriggerRegistrationOverrides(config.triggers).map((override) => [override.id, override]),
304
301
  );
302
+ const disabledTriggers = new Set(config.disabled_triggers);
305
303
  const sourceIds = new Set(sources.map((source) => source.id));
306
304
  for (const id of overrides.keys()) {
307
305
  if (!sourceIds.has(id)) warning('trigger_source_unavailable', { trigger_id: id });
@@ -309,7 +307,7 @@ export function triggerRegistrations(
309
307
  return Object.freeze(sources.map((source): ClawclawTriggerRegistration => {
310
308
  const override = overrides.get(source.id);
311
309
  const behavior = override?.behavior ?? source.manifest.defaultBehavior;
312
- const requestedEnabled = override?.enabled ?? DEFAULT_GAMEPLAY_TRIGGER_ENABLED;
310
+ const requestedEnabled = !disabledTriggers.has(source.id);
313
311
  const enabled = requestedEnabled
314
312
  && source.apiVersion === TRIGGER_PLUGIN_API_VERSION
315
313
  && loadableBehaviors.has(behavior);
@@ -3,7 +3,7 @@ import type {
3
3
  BehaviorPathQuery,
4
4
  Position,
5
5
  } from '../../../../sdk/behavior-plugin/index.js';
6
- import { getLocalPathDistances } from '../../../../strategies/pathfind/astar-path.js';
6
+ import { getLocalPathDistances } from '../../navigation/astar-path.js';
7
7
  import type {
8
8
  RuntimeEpochPlugin,
9
9
  RuntimeEpochPluginContext,
@@ -8,61 +8,7 @@ import {
8
8
  resolve as resolveRuntimeModule,
9
9
  } from './runtime-module-loader-hooks.mjs';
10
10
 
11
- const INTERNAL_OFFICIAL_LONG_BEHAVIOR_IDS = [
12
- 'avoid-lone',
13
- 'avoid-players',
14
- 'corpse-patrol',
15
- 'crab-sabotage',
16
- 'find-player',
17
- 'hide',
18
- 'kill-frenzy',
19
- 'kill-lone',
20
- 'kill-target',
21
- 'lone-kill-task',
22
- 'move-room',
23
- 'paradise-fish',
24
- 'patrol',
25
- 'report-patrol',
26
- 'shrimp-memory',
27
- 'social-task',
28
- 'task-kill-report',
29
- 'task-only',
30
- 'task-report',
31
- 'warrior-memory',
32
- ] as const;
33
-
34
- const INTERNAL_OFFICIAL_FINITE_BEHAVIOR_IDS = [
35
- 'do_task',
36
- 'evade',
37
- 'find_player',
38
- 'follow_player',
39
- 'go_to',
40
- 'hide_temporarily',
41
- 'hold_position',
42
- 'hunt_player',
43
- 'inspect_corpse',
44
- 'patrol_area',
45
- 'report_corpse',
46
- 'seek_kill_opportunity',
47
- ] as const;
48
-
49
- const INTERNAL_OFFICIAL_BEHAVIOR_ALIASES = Object.freeze({
50
- ...Object.fromEntries(
51
- INTERNAL_OFFICIAL_LONG_BEHAVIOR_IDS.map((id) => [
52
- `clawclaw-internal:official-behavior/${id}`,
53
- new URL(`../../../strategies/${id}.ts`, import.meta.url).href,
54
- ]),
55
- ),
56
- ...Object.fromEntries(
57
- INTERNAL_OFFICIAL_FINITE_BEHAVIOR_IDS.map((id) => [
58
- `clawclaw-internal:official-behavior/${id}`,
59
- new URL(`../../../behaviors/official-finite/${id.replaceAll('_', '-')}.ts`, import.meta.url).href,
60
- ]),
61
- ),
62
- });
63
-
64
11
  const SDK_ALIASES = Object.freeze({
65
- ...INTERNAL_OFFICIAL_BEHAVIOR_ALIASES,
66
12
  '@myclaw163/clawclaw-cli': new URL('../../../sdk/index.ts', import.meta.url).href,
67
13
  '@myclaw163/clawclaw-cli/sdk': new URL('../../../sdk/index.ts', import.meta.url).href,
68
14
  '@myclaw163/clawclaw-cli/module-input': new URL(
@@ -3,12 +3,12 @@ import {
3
3
  planEscape,
4
4
  type EscapeOptions,
5
5
  type EscapePlan,
6
- } from '../../strategies/pathfind/escape-planner.js';
6
+ } from '../../runtime/clawclaw/navigation/escape-planner.js';
7
7
  import {
8
8
  HIDE_SPOTS,
9
9
  nearestSafeHideSpot,
10
10
  type HideSpot,
11
- } from '../../strategies/hide-spots.js';
11
+ } from '../../runtime/clawclaw/navigation/hide-spots.js';
12
12
 
13
13
  /** Public deterministic planning over the packaged read-only walkable grid. */
14
14
  export function planBehaviorEscape(
@@ -1,136 +0,0 @@
1
- #!/usr/bin/env node
2
- import { build } from 'esbuild';
3
- import { createHash } from 'node:crypto';
4
- import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
- import { dirname, join, resolve } from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
-
8
- const scriptDir = dirname(fileURLToPath(import.meta.url));
9
- const packageRoot = resolve(scriptDir, '..');
10
- const PUBLIC_BEHAVIOR_PLUGIN = '@myclaw163/clawclaw-cli/behavior-plugin';
11
-
12
- export const OFFICIAL_HUB_BEHAVIORS = Object.freeze([
13
- { id: 'task-only', resourceId: '24b6cdd8-4766-40e8-b1c4-e669db00a3ed', className: 'TaskOnlyStrategy', source: 'src/hub-official-behaviors/task-only.ts' },
14
- { id: 'patrol', resourceId: 'a73edbd3-5476-4d23-9164-03d2655fc7c3', className: 'PatrolStrategy', source: 'src/hub-official-behaviors/patrol.ts' },
15
- { id: 'do_task', resourceId: 'fbbbc2b1-9b71-49d1-9c48-5e5392f551dc', className: 'DoTaskBehavior', source: 'src/behaviors/official-finite/do-task.ts' },
16
- { id: 'kill-lone', resourceId: '5dc062b3-aa53-4155-ab56-15b7b20eaf63', className: 'KillLoneStrategy', source: 'src/hub-official-behaviors/kill-lone.ts' },
17
- { id: 'report_corpse', resourceId: '59bdc29e-1b8a-4ac4-99dc-9df359ce3b42', className: 'ReportCorpseBehavior', source: 'src/behaviors/official-finite/report-corpse.ts' },
18
- { id: 'hunt_player', resourceId: 'd3f15d94-edca-4acb-accc-a0d0b6583ad7', className: 'HuntPlayerBehavior', source: 'src/behaviors/official-finite/hunt-player.ts' },
19
- ]);
20
-
21
- function externalizePublicBehaviorPlugin() {
22
- return {
23
- name: 'externalize-public-behavior-plugin',
24
- setup(buildApi) {
25
- buildApi.onResolve({ filter: /sdk[\\/]behavior-plugin[\\/]index\.js$/ }, () => ({
26
- path: PUBLIC_BEHAVIOR_PLUGIN,
27
- external: true,
28
- }));
29
- },
30
- };
31
- }
32
-
33
- function restoreStaticDefaultClass(source, definition) {
34
- const declaration = new RegExp(
35
- `var\\s+${definition.className}\\s*=\\s*class\\s+extends\\s+ClawclawBehavior`,
36
- );
37
- if (!declaration.test(source)) {
38
- throw new Error(`bundled_default_class_not_found:${definition.id}`);
39
- }
40
- const restored = source
41
- .replace(
42
- declaration,
43
- `export default class ${definition.className} extends ClawclawBehavior`,
44
- )
45
- .replace(
46
- new RegExp(`\\nexport\\s*\\{\\s*${definition.className}\\s+as\\s+default\\s*\\};?\\s*$`),
47
- '\n',
48
- );
49
- if (!restored.includes(`export default class ${definition.className} extends ClawclawBehavior`)) {
50
- throw new Error(`bundled_default_class_restore_failed:${definition.id}`);
51
- }
52
- return restored;
53
- }
54
-
55
- function assertSelfContained(source, definition) {
56
- if (/clawclaw-internal:/.test(source)) {
57
- throw new Error(`bundled_internal_alias_remaining:${definition.id}`);
58
- }
59
- const imports = [...source.matchAll(/(?:from\s+|import\s*)["']([^"']+)["']/g)]
60
- .map((match) => match[1]);
61
- const unsupported = imports.filter((specifier) => specifier !== PUBLIC_BEHAVIOR_PLUGIN);
62
- if (unsupported.length > 0) {
63
- throw new Error(`bundled_external_import_remaining:${definition.id}:${unsupported.join(',')}`);
64
- }
65
- if (!source.includes(`id: "${definition.id}"`) && !source.includes(`id: '${definition.id}'`)) {
66
- throw new Error(`bundled_manifest_id_missing:${definition.id}`);
67
- }
68
- }
69
-
70
- export async function buildOfficialHubBehaviors(outDir) {
71
- const outputRoot = resolve(outDir);
72
- rmSync(outputRoot, { recursive: true, force: true });
73
- mkdirSync(outputRoot, { recursive: true });
74
- const built = [];
75
- for (const definition of OFFICIAL_HUB_BEHAVIORS) {
76
- const outputPath = join(outputRoot, `${definition.id}.ts`);
77
- await build({
78
- entryPoints: [resolve(packageRoot, definition.source)],
79
- outfile: outputPath,
80
- bundle: true,
81
- write: true,
82
- format: 'esm',
83
- platform: 'node',
84
- target: 'node22',
85
- charset: 'utf8',
86
- legalComments: 'none',
87
- sourcemap: false,
88
- minify: false,
89
- treeShaking: true,
90
- external: [PUBLIC_BEHAVIOR_PLUGIN],
91
- plugins: [externalizePublicBehaviorPlugin()],
92
- banner: {
93
- js: `// Self-contained official Hub Behavior '${definition.id}'.\n// Generated from ${definition.source}; only the public Behavior SDK remains external.`,
94
- },
95
- });
96
- const bundled = restoreStaticDefaultClass(readFileSync(outputPath, 'utf8'), definition);
97
- assertSelfContained(bundled, definition);
98
- writeFileSync(outputPath, bundled, 'utf8');
99
- built.push({
100
- ...definition,
101
- outputPath,
102
- bytes: Buffer.byteLength(bundled),
103
- sha256: createHash('sha256').update(bundled).digest('hex'),
104
- });
105
- }
106
- writeFileSync(join(outputRoot, 'manifest.json'), `${JSON.stringify({
107
- schema: 'clawclaw.official-hub-behaviors.v1',
108
- generatedAt: new Date().toISOString(),
109
- behaviors: built.map(({ id, resourceId, source, outputPath, bytes, sha256 }) => ({
110
- id,
111
- resourceId,
112
- source,
113
- file: outputPath.slice(outputRoot.length + 1).replaceAll('\\', '/'),
114
- bytes,
115
- sha256,
116
- })),
117
- }, null, 2)}\n`, 'utf8');
118
- return built;
119
- }
120
-
121
- function parseOutDir(argv) {
122
- const index = argv.indexOf('--out-dir');
123
- if (index < 0 || !argv[index + 1]) {
124
- throw new Error('Usage: npm run build:hub-official-behaviors -- --out-dir <directory>');
125
- }
126
- return argv[index + 1];
127
- }
128
-
129
- const entry = process.argv[1] ? pathToFileURL(resolve(process.argv[1])).href : '';
130
- if (import.meta.url === entry) {
131
- const built = await buildOfficialHubBehaviors(parseOutDir(process.argv.slice(2)));
132
- process.stdout.write(`${JSON.stringify({
133
- output_dir: resolve(parseOutDir(process.argv.slice(2))),
134
- behaviors: built.map(({ id, outputPath, bytes, sha256 }) => ({ id, path: outputPath, bytes, sha256 })),
135
- }, null, 2)}\n`);
136
- }
@@ -1,178 +0,0 @@
1
- import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join } from 'node:path';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import {
6
- buildOfficialHubBehaviors,
7
- OFFICIAL_HUB_BEHAVIORS,
8
- } from './build-official-hub-behaviors.mjs';
9
- import { listClawclawBehaviorSources } from '../src/runtime/clawclaw/plugins/behavior/behavior-source.js';
10
- import { loadClawclawBehaviorModule } from '../src/runtime/clawclaw/plugins/behavior/behavior-module-loader.js';
11
-
12
- const roots = [];
13
- const rooms = [{
14
- name: '厨房',
15
- polygon: [[100, 0], [200, 0], [200, 100], [100, 100]],
16
- bbox: { left: 100, top: 0, right: 200, bottom: 100 },
17
- }, {
18
- name: '酒吧',
19
- polygon: [[300, 0], [400, 0], [400, 100], [300, 100]],
20
- bbox: { left: 300, top: 0, right: 400, bottom: 100 },
21
- }];
22
-
23
- function api() {
24
- const distance = (from, to) => Math.hypot(from.x - to.x, from.y - to.y);
25
- return {
26
- spatial: {
27
- xPositive: 'right', yPositive: 'down', playerBodyLengthPx: 64, rooms,
28
- roomAt: () => null, sideInRoom: () => null, placeLabel: () => '',
29
- transitionIsMapped: () => true,
30
- },
31
- navigation: {
32
- pathDistance: async (from, to) => distance(from, to),
33
- pathDistances: async (queries) => queries.map(({ from, to }) => distance(from, to)),
34
- },
35
- observation: {
36
- lastSeenPlayer: () => undefined,
37
- lastSeenCorpse: () => undefined,
38
- },
39
- };
40
- }
41
-
42
- function state(overrides = {}) {
43
- return {
44
- game_id: 'game', tick: 1, phase: 'wandering',
45
- you: {
46
- player: { seat: 1, name: 'Self', is_alive: true },
47
- x: 0, y: 0, room: '走廊', role: 'shrimp_generic', faction: 'lobster',
48
- is_alive: true, activity: { kind: 'idle' }, tasks: [],
49
- },
50
- players: [], visible_players: [], visible_corpses: [],
51
- ...overrides,
52
- };
53
- }
54
-
55
- function frame(gameState, input, epochId = 1) {
56
- return {
57
- epochId,
58
- scope: { sessionId: 'session', segmentId: 'segment' },
59
- nowMs: 1_000,
60
- gameState,
61
- events: [],
62
- input,
63
- };
64
- }
65
-
66
- afterEach(() => {
67
- for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });
68
- });
69
-
70
- describe('official Hub Behavior bundling', () => {
71
- it('builds six statically discoverable and dynamically loadable self-contained modules', async () => {
72
- const root = mkdtempSync(join(tmpdir(), 'official-hub-behaviors-'));
73
- roots.push(root);
74
- const built = await buildOfficialHubBehaviors(root);
75
- expect(built.map(({ id }) => id)).toEqual(OFFICIAL_HUB_BEHAVIORS.map(({ id }) => id));
76
- expect(built.every(({ bytes }) => bytes < 50_000)).toBe(true);
77
-
78
- const sources = listClawclawBehaviorSources(root);
79
- expect(sources.map(({ id }) => id).sort()).toEqual(
80
- OFFICIAL_HUB_BEHAVIORS.map(({ id }) => id).sort(),
81
- );
82
- const classes = new Map();
83
- for (const source of sources) {
84
- const text = readFileSync(source.sourcePath, 'utf8');
85
- expect(text).not.toContain('clawclaw-internal:');
86
- expect(text).not.toContain('clawclaw-walkable.bin');
87
- expect(text).not.toContain('clawclaw-map.json');
88
- expect(text).not.toMatch(/from\s+["']\.\.?\//);
89
- const loaded = await loadClawclawBehaviorModule(source);
90
- expect(loaded.manifest.id).toBe(source.id);
91
- expect(typeof loaded.BehaviorClass.prototype.decide).toBe('function');
92
- classes.set(source.id, loaded.BehaviorClass);
93
- }
94
-
95
- const patrol = new (classes.get('patrol'))();
96
- await expect(patrol.decide(frame(state(), {}), api())).resolves.toEqual(
97
- expect.objectContaining({ status: expect.any(Object) }),
98
- );
99
-
100
- const taskOnly = new (classes.get('task-only'))();
101
- const longTaskState = state({
102
- you: {
103
- ...state().you,
104
- tasks: [{ task_id: 'wires', name: '接线', room: '走廊', x: 5, y: 0, is_fake_shrimp: false, status: 'normal' }],
105
- },
106
- });
107
- await expect(taskOnly.decide(frame(longTaskState, {}), api())).resolves.toEqual(
108
- expect.objectContaining({
109
- actions: [expect.objectContaining({ action: 'task', task_name: '接线' })],
110
- }),
111
- );
112
-
113
- const doTask = new (classes.get('do_task'))();
114
- const taskState = state({
115
- you: {
116
- ...state().you,
117
- tasks: [{ task_id: 'wires', name: '接线', room: '走廊', x: 5, y: 0, is_fake_shrimp: false, status: 'normal' }],
118
- },
119
- });
120
- await expect(doTask.decide(frame(taskState, { task: 'wires', timeout_ms: 60_000 }), api()))
121
- .resolves.toEqual(expect.objectContaining({
122
- actions: [expect.objectContaining({ action: 'task', task_name: '接线' })],
123
- }));
124
-
125
- const report = new (classes.get('report_corpse'))();
126
- const corpseState = state({
127
- visible_corpses: [{ corpse_id: 'corpse-2', player: { seat: 2, name: 'Dead' }, x: 10, y: 0, room: '走廊', distance: 10 }],
128
- });
129
- await expect(report.decide(frame(corpseState, { corpse_seat: 2, timeout_ms: 45_000 }), api()))
130
- .resolves.toEqual(expect.objectContaining({
131
- actions: [expect.objectContaining({ action: 'report' })],
132
- }));
133
-
134
- const hunt = new (classes.get('hunt_player'))();
135
- const huntingState = state({
136
- you: { ...state().you, role: 'crab_generic', faction: 'crab', kills_remaining: 1, crab_teammates: [] },
137
- players: [{ seat: 2, name: 'Target', known_status: { is_alive: true } }],
138
- visible_players: [{ player: { seat: 2, name: 'Target' }, x: 10, y: 0, room: '走廊', distance: 10, is_alive: true }],
139
- });
140
- await expect(hunt.decide(frame(huntingState, {
141
- player_seat: 2,
142
- after_kill: 'replan',
143
- timeout_ms: 60_000,
144
- }), api())).resolves.toEqual(expect.objectContaining({
145
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
146
- }));
147
-
148
- const killLone = new (classes.get('kill-lone'))();
149
- await expect(killLone.decide(frame(huntingState, {
150
- protectedTargets: [],
151
- huntTargets: [],
152
- }), api())).resolves.toEqual(expect.objectContaining({
153
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
154
- }));
155
-
156
- const protectedKillLone = new (classes.get('kill-lone'))();
157
- const protectedDecision = await protectedKillLone.decide(frame(huntingState, {
158
- protectedTargets: [2],
159
- huntTargets: [2],
160
- }), api());
161
- expect(protectedDecision?.actions ?? []).not.toContainEqual(expect.objectContaining({ action: 'kill' }));
162
-
163
- const huntCrowd = new (classes.get('kill-lone'))();
164
- const crowdState = state({
165
- ...huntingState,
166
- visible_players: [
167
- ...huntingState.visible_players,
168
- { player: { seat: 3, name: 'Other' }, x: 20, y: 0, room: '走廊', distance: 20, is_alive: true },
169
- ],
170
- });
171
- await expect(huntCrowd.decide(frame(crowdState, {
172
- protectedTargets: [],
173
- huntTargets: [2],
174
- }), api())).resolves.toEqual(expect.objectContaining({
175
- actions: [expect.objectContaining({ action: 'kill', target_seat: 2 })],
176
- }));
177
- }, 30_000);
178
- });