@myclaw163/clawclaw-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +434 -0
  2. package/bin/clawclaw-cli.mjs +4 -0
  3. package/package.json +48 -0
  4. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +50 -0
  5. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +51 -0
  6. package/personas//346/227/240/344/272/272/350/256/276.md +1 -0
  7. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +48 -0
  8. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +51 -0
  9. package/scripts/check-skill-command-surface.mjs +118 -0
  10. package/scripts/check_monitor.cjs +435 -0
  11. package/scripts/check_monitor.test.mjs +212 -0
  12. package/scripts/enable_ccl_permissions.cjs +164 -0
  13. package/scripts/enable_ccl_permissions.test.mjs +163 -0
  14. package/scripts/enable_monitor.cjs +677 -0
  15. package/scripts/enable_monitor.test.mjs +201 -0
  16. package/scripts/find-hide-spots.py +157 -0
  17. package/scripts/postinstall.mjs +20 -0
  18. package/scripts/sync-bundled-skill.mjs +254 -0
  19. package/scripts/sync-bundled-skill.test.mjs +152 -0
  20. package/skills/clawclaw/.gitkeep +0 -0
  21. package/skills/clawclaw/SKILL.md +275 -0
  22. package/skills/clawclaw/references/CHATTERBOX.md +142 -0
  23. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +224 -0
  24. package/skills/clawclaw/references/COMMANDS.md +165 -0
  25. package/skills/clawclaw/references/GAME-MECHANICS.md +195 -0
  26. package/skills/clawclaw/references/HUB.md +48 -0
  27. package/skills/clawclaw/references/KNOWLEDGE.md +42 -0
  28. package/skills/clawclaw/references/STRATEGIES.md +59 -0
  29. package/skills/clawclaw/references/STREAM.md +75 -0
  30. package/skills/clawclaw/references/TACTICS.md +65 -0
  31. package/src/assets/clawclaw-ascii-map.txt +40 -0
  32. package/src/cli.ts +113 -0
  33. package/src/commands/_schema.ts +124 -0
  34. package/src/commands/account.test.ts +391 -0
  35. package/src/commands/account.ts +338 -0
  36. package/src/commands/competition.ts +42 -0
  37. package/src/commands/config.ts +30 -0
  38. package/src/commands/data.test.ts +33 -0
  39. package/src/commands/data.ts +22 -0
  40. package/src/commands/do.test.ts +117 -0
  41. package/src/commands/do.ts +195 -0
  42. package/src/commands/events.test.ts +144 -0
  43. package/src/commands/events.ts +268 -0
  44. package/src/commands/game-map.test.ts +28 -0
  45. package/src/commands/game-monitor-status.test.ts +58 -0
  46. package/src/commands/game-start-plan.test.ts +356 -0
  47. package/src/commands/game.ts +2046 -0
  48. package/src/commands/history-player.test.ts +105 -0
  49. package/src/commands/history.ts +573 -0
  50. package/src/commands/hub.test.ts +134 -0
  51. package/src/commands/hub.ts +249 -0
  52. package/src/commands/knowledge.test.ts +13 -0
  53. package/src/commands/knowledge.ts +176 -0
  54. package/src/commands/load.test.ts +107 -0
  55. package/src/commands/load.ts +26 -0
  56. package/src/commands/meeting-history.test.ts +106 -0
  57. package/src/commands/memory.ts +40 -0
  58. package/src/commands/peek.ts +45 -0
  59. package/src/commands/persona.ts +62 -0
  60. package/src/commands/setup/codex.ts +266 -0
  61. package/src/commands/setup/hermes.test.ts +96 -0
  62. package/src/commands/setup/hermes.ts +76 -0
  63. package/src/commands/setup/index.ts +13 -0
  64. package/src/commands/setup/openclaw.test.ts +124 -0
  65. package/src/commands/setup/openclaw.ts +162 -0
  66. package/src/commands/skill.ts +128 -0
  67. package/src/commands/state.ts +46 -0
  68. package/src/commands/strategy.test.ts +172 -0
  69. package/src/commands/strategy.ts +170 -0
  70. package/src/commands/upgrade.test.ts +82 -0
  71. package/src/commands/upgrade.ts +157 -0
  72. package/src/commands/watch.test.ts +1313 -0
  73. package/src/commands/watch.ts +824 -0
  74. package/src/lib/account-guidance.test.ts +32 -0
  75. package/src/lib/account-guidance.ts +62 -0
  76. package/src/lib/auth.test.ts +116 -0
  77. package/src/lib/auth.ts +189 -0
  78. package/src/lib/command-meta.ts +37 -0
  79. package/src/lib/competition.ts +79 -0
  80. package/src/lib/custom-tts.test.ts +387 -0
  81. package/src/lib/custom-tts.ts +463 -0
  82. package/src/lib/game-client-tts.test.ts +151 -0
  83. package/src/lib/game-client.test.ts +82 -0
  84. package/src/lib/game-client.ts +472 -0
  85. package/src/lib/game-context.ts +92 -0
  86. package/src/lib/host-config-patcher.test.ts +130 -0
  87. package/src/lib/host-config-patcher.ts +151 -0
  88. package/src/lib/http-keepalive.ts +15 -0
  89. package/src/lib/http-transport.test.ts +61 -0
  90. package/src/lib/http-transport.ts +118 -0
  91. package/src/lib/hub-client.test.ts +57 -0
  92. package/src/lib/hub-client.ts +88 -0
  93. package/src/lib/hub-install.test.ts +157 -0
  94. package/src/lib/hub-install.ts +213 -0
  95. package/src/lib/hub-reminder.ts +69 -0
  96. package/src/lib/hub-unzip.test.ts +69 -0
  97. package/src/lib/hub-unzip.ts +62 -0
  98. package/src/lib/init-command.test.ts +79 -0
  99. package/src/lib/init-command.ts +136 -0
  100. package/src/lib/knowledge-store.test.ts +170 -0
  101. package/src/lib/knowledge-store.ts +369 -0
  102. package/src/lib/load-context.test.ts +62 -0
  103. package/src/lib/load-context.ts +49 -0
  104. package/src/lib/match-state.test.ts +134 -0
  105. package/src/lib/match-state.ts +94 -0
  106. package/src/lib/normalize.ts +42 -0
  107. package/src/lib/persona.test.ts +84 -0
  108. package/src/lib/persona.ts +120 -0
  109. package/src/lib/room.test.ts +74 -0
  110. package/src/lib/room.ts +129 -0
  111. package/src/lib/server-registry.test.ts +54 -0
  112. package/src/lib/server-registry.ts +185 -0
  113. package/src/lib/skill-version.test.ts +48 -0
  114. package/src/lib/skill-version.ts +19 -0
  115. package/src/lib/strategy-export.test.ts +314 -0
  116. package/src/lib/strategy-export.ts +352 -0
  117. package/src/lib/user-data.test.ts +98 -0
  118. package/src/lib/user-data.ts +370 -0
  119. package/src/lib/workspace-argv.test.ts +49 -0
  120. package/src/lib/workspace-argv.ts +44 -0
  121. package/src/perception/player-history-store.test.ts +177 -0
  122. package/src/perception/player-history-store.ts +262 -0
  123. package/src/pipeline/event-format.test.ts +327 -0
  124. package/src/pipeline/event-format.ts +595 -0
  125. package/src/pipeline/event-hints.ts +204 -0
  126. package/src/pipeline/event-store.test.ts +28 -0
  127. package/src/pipeline/event-store.ts +193 -0
  128. package/src/pipeline/pipeline.ts +35 -0
  129. package/src/pipeline/player-projection.test.ts +168 -0
  130. package/src/pipeline/player-projection.ts +370 -0
  131. package/src/runtime/auto-upgrade.test.ts +66 -0
  132. package/src/runtime/auto-upgrade.ts +31 -0
  133. package/src/runtime/event-daemon.test.ts +268 -0
  134. package/src/runtime/event-daemon.ts +531 -0
  135. package/src/runtime/owner-control.ts +150 -0
  136. package/src/runtime/raw-ws-log.test.ts +33 -0
  137. package/src/runtime/raw-ws-log.ts +32 -0
  138. package/src/runtime/room-lobby-runtime.test.ts +95 -0
  139. package/src/runtime/room-lobby-runtime.ts +367 -0
  140. package/src/runtime/runtime-logger.ts +107 -0
  141. package/src/runtime/ws-client.test.ts +169 -0
  142. package/src/runtime/ws-client.ts +280 -0
  143. package/src/sdk/action.ts +155 -0
  144. package/src/sdk/index.ts +112 -0
  145. package/src/sdk/types.ts +163 -0
  146. package/src/strategies/avoid-lone.ts +14 -0
  147. package/src/strategies/avoid-players.knowledge.md +19 -0
  148. package/src/strategies/avoid-players.ts +18 -0
  149. package/src/strategies/corpse-patrol.ts +21 -0
  150. package/src/strategies/crab-sabotage.ts +24 -0
  151. package/src/strategies/custom-module.test.ts +270 -0
  152. package/src/strategies/find-player.ts +19 -0
  153. package/src/strategies/game-utils.test.ts +242 -0
  154. package/src/strategies/game-utils.ts +853 -0
  155. package/src/strategies/goals/anchor-linger.ts +77 -0
  156. package/src/strategies/goals/avoid-lone-top.ts +168 -0
  157. package/src/strategies/goals/avoid-players-top.test.ts +83 -0
  158. package/src/strategies/goals/avoid-players-top.ts +121 -0
  159. package/src/strategies/goals/conversation-goal.ts +51 -0
  160. package/src/strategies/goals/corpse-patrol-top.ts +113 -0
  161. package/src/strategies/goals/crab-octopus-reflexes.ts +101 -0
  162. package/src/strategies/goals/crab-sabotage-top.ts +226 -0
  163. package/src/strategies/goals/emergency-hunt-goal.ts +28 -0
  164. package/src/strategies/goals/find-player-top.ts +93 -0
  165. package/src/strategies/goals/flee-players-goal.ts +53 -0
  166. package/src/strategies/goals/follow-companion-goal.ts +106 -0
  167. package/src/strategies/goals/goal-manager.ts +41 -0
  168. package/src/strategies/goals/goal-root-strategy.ts +49 -0
  169. package/src/strategies/goals/goal.ts +28 -0
  170. package/src/strategies/goals/hide-top.ts +197 -0
  171. package/src/strategies/goals/keep-away-goal.ts +221 -0
  172. package/src/strategies/goals/kill-frenzy-top.ts +80 -0
  173. package/src/strategies/goals/kill-lone-top.ts +160 -0
  174. package/src/strategies/goals/kill-target-goal.ts +59 -0
  175. package/src/strategies/goals/kill-target-top.ts +109 -0
  176. package/src/strategies/goals/leaf-goal.ts +27 -0
  177. package/src/strategies/goals/linger-corpse-goal.ts +35 -0
  178. package/src/strategies/goals/lone-kill-core.ts +82 -0
  179. package/src/strategies/goals/lone-kill-goal.ts +24 -0
  180. package/src/strategies/goals/lone-kill-task-top.test.ts +85 -0
  181. package/src/strategies/goals/lone-kill-task-top.ts +133 -0
  182. package/src/strategies/goals/move-room-goal.ts +60 -0
  183. package/src/strategies/goals/normal-shrimp-top.test.ts +97 -0
  184. package/src/strategies/goals/normal-shrimp-top.ts +248 -0
  185. package/src/strategies/goals/paradise-fish-top.test.ts +126 -0
  186. package/src/strategies/goals/paradise-fish-top.ts +224 -0
  187. package/src/strategies/goals/patrol-top.ts +57 -0
  188. package/src/strategies/goals/report-patrol-top.ts +86 -0
  189. package/src/strategies/goals/safe-task-goal.ts +102 -0
  190. package/src/strategies/goals/social-task-top.ts +161 -0
  191. package/src/strategies/goals/task-kill-report-top.ts +163 -0
  192. package/src/strategies/goals/task-only-top.ts +57 -0
  193. package/src/strategies/goals/task-or-patrol-goal.ts +41 -0
  194. package/src/strategies/goals/task-report-top.ts +57 -0
  195. package/src/strategies/goals/wander-task-goal.ts +33 -0
  196. package/src/strategies/goals/warrior-shrimp-top.test.ts +87 -0
  197. package/src/strategies/goals/warrior-shrimp-top.ts +267 -0
  198. package/src/strategies/greeting.ts +53 -0
  199. package/src/strategies/hide-spots.ts +59 -0
  200. package/src/strategies/hide.ts +26 -0
  201. package/src/strategies/kill-frenzy.ts +15 -0
  202. package/src/strategies/kill-lone.knowledge.md +17 -0
  203. package/src/strategies/kill-lone.ts +16 -0
  204. package/src/strategies/kill-target.ts +21 -0
  205. package/src/strategies/knowledge-contract.ts +85 -0
  206. package/src/strategies/loader.test.ts +710 -0
  207. package/src/strategies/loader.ts +183 -0
  208. package/src/strategies/lone-kill-task.ts +24 -0
  209. package/src/strategies/meeting-gate.test.ts +59 -0
  210. package/src/strategies/meeting-gate.ts +28 -0
  211. package/src/strategies/move-room.ts +18 -0
  212. package/src/strategies/new-events-backfill.ts +98 -0
  213. package/src/strategies/off-route-points.ts +105 -0
  214. package/src/strategies/paradise-fish.knowledge.md +19 -0
  215. package/src/strategies/paradise-fish.ts +24 -0
  216. package/src/strategies/pathfind/clawclaw-walkable.bin +0 -0
  217. package/src/strategies/pathfind/distance-field.ts +150 -0
  218. package/src/strategies/pathfind/escape-planner.test.ts +197 -0
  219. package/src/strategies/pathfind/escape-planner.ts +355 -0
  220. package/src/strategies/pathfind/walkable-grid.ts +117 -0
  221. package/src/strategies/patrol.ts +14 -0
  222. package/src/strategies/player-targets.ts +13 -0
  223. package/src/strategies/report-patrol.ts +14 -0
  224. package/src/strategies/scanner.ts +238 -0
  225. package/src/strategies/shrimp-memory.knowledge.md +19 -0
  226. package/src/strategies/shrimp-memory.ts +24 -0
  227. package/src/strategies/social-task.test.ts +28 -0
  228. package/src/strategies/social-task.ts +52 -0
  229. package/src/strategies/spawn.ts +82 -0
  230. package/src/strategies/speech-module.ts +123 -0
  231. package/src/strategies/strategy-loop.test.ts +15 -0
  232. package/src/strategies/strategy-loop.ts +748 -0
  233. package/src/strategies/task-kill-report.ts +20 -0
  234. package/src/strategies/task-only.ts +14 -0
  235. package/src/strategies/task-report.ts +21 -0
  236. package/src/strategies/types.ts +155 -0
  237. package/src/strategies/warrior-memory.knowledge.md +21 -0
  238. package/src/strategies/warrior-memory.ts +19 -0
@@ -0,0 +1,183 @@
1
+ import { existsSync, readFileSync, realpathSync, mkdtempSync, writeFileSync, rmSync } from 'fs';
2
+ import { dirname, join, resolve, basename } from 'path';
3
+ import { tmpdir } from 'os';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
+ import { getWorkspaceDir } from '../lib/init-command.js';
6
+ import { ensureUserDataLayout, getUserDataStrategiesDir } from '../lib/user-data.js';
7
+ import { scanStrategyDirectory } from './scanner.js';
8
+ import type { StrategyDescriptor, StrategySummary } from './scanner.js';
9
+ import type { Plugin, OnResolveArgs } from 'esbuild';
10
+ import type { Strategy, StrategyEntry } from './types.js';
11
+
12
+ export type { StrategySummary } from './scanner.js';
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = dirname(__filename);
16
+
17
+ // Resolve SDK path for the one selected strategy import (raw filesystem path, not URL).
18
+ const SDK_PATH = realpathSync(resolve(__dirname, '../sdk/index.ts'));
19
+
20
+ const strategyCatalog = new Map<string, StrategyDescriptor>();
21
+ const runtimeEntryCache = new Map<string, StrategyEntry>();
22
+ let catalogLoaded = false;
23
+ let loadedWorkspaceDir: string | undefined;
24
+
25
+ function resolveUserStrategiesDir(): string | undefined {
26
+ const workspaceDir = getWorkspaceDir();
27
+ if (!existsSync(workspaceDir)) return undefined;
28
+ ensureUserDataLayout(workspaceDir);
29
+ const strategiesDir = getUserDataStrategiesDir(workspaceDir);
30
+ if (!existsSync(strategiesDir)) return undefined;
31
+ return strategiesDir;
32
+ }
33
+
34
+ function createSdkPlugin(): { plugin: Plugin } {
35
+ const sdkUrl = pathToFileURL(SDK_PATH).href;
36
+ const plugin: Plugin = {
37
+ name: 'clawclaw-cli-sdk',
38
+ setup(build) {
39
+ build.onResolve({ filter: /^(?:@myclaw163\/)?clawclaw-cli(?:\/.*)?$/ }, (args: OnResolveArgs) => {
40
+ if (args.kind === 'require-call') {
41
+ return {
42
+ errors: [{
43
+ text: `require('${args.path}') is not supported in user strategies. Use static imports: import { ... } from '${args.path}'.`,
44
+ }],
45
+ };
46
+ }
47
+ return { path: sdkUrl, external: true };
48
+ });
49
+ },
50
+ };
51
+ return { plugin };
52
+ }
53
+
54
+ /** Import exactly one strategy selected for execution. Catalog discovery never calls this. */
55
+ export async function importUserFile(filePath: string): Promise<Record<string, unknown>> {
56
+ const { plugin } = createSdkPlugin();
57
+ const { build } = await import('esbuild');
58
+ const result = await build({
59
+ stdin: {
60
+ contents: readFileSync(filePath, 'utf8'),
61
+ resolveDir: dirname(filePath),
62
+ sourcefile: basename(filePath),
63
+ loader: filePath.endsWith('.ts') ? 'ts' : 'js',
64
+ },
65
+ bundle: true,
66
+ format: 'esm',
67
+ write: false,
68
+ platform: 'node',
69
+ packages: 'external',
70
+ plugins: [plugin],
71
+ });
72
+
73
+ const tmpDir = mkdtempSync(join(tmpdir(), 'ccl-strategy-'));
74
+ const tmpFile = join(tmpDir, basename(filePath).replace(/\.(ts|js)$/, '.mjs'));
75
+ try {
76
+ writeFileSync(tmpFile, result.outputFiles[0].text);
77
+ return await import(pathToFileURL(tmpFile).href);
78
+ } finally {
79
+ try { rmSync(tmpDir, { recursive: true, force: true }); } catch {}
80
+ }
81
+ }
82
+
83
+ async function ensureCatalog(): Promise<void> {
84
+ const workspaceDir = getWorkspaceDir();
85
+ if (catalogLoaded && loadedWorkspaceDir === workspaceDir) return;
86
+ strategyCatalog.clear();
87
+ runtimeEntryCache.clear();
88
+ catalogLoaded = true;
89
+ loadedWorkspaceDir = workspaceDir;
90
+
91
+ let officialIds = new Set<string>();
92
+ try {
93
+ const { readManifest, syncOfficialStrategies } = await import('../lib/strategy-export.js');
94
+ await syncOfficialStrategies();
95
+ officialIds = new Set(Object.keys(readManifest()));
96
+ } catch (error) {
97
+ const message = error instanceof Error ? error.message : String(error);
98
+ console.error(`[ccl] Failed to initialize official strategies: ${message}`);
99
+ }
100
+
101
+ const userDir = resolveUserStrategiesDir();
102
+ if (!userDir) return;
103
+ const scan = scanStrategyDirectory(userDir, officialIds);
104
+ for (const error of scan.errors) {
105
+ console.error(`[ccl] Failed to inspect user strategy ${error.file}: ${error.message}`);
106
+ }
107
+ for (const descriptor of scan.descriptors) strategyCatalog.set(descriptor.id, descriptor);
108
+ }
109
+
110
+ async function findStrategyDescriptor(idOrName: string): Promise<StrategyDescriptor | undefined> {
111
+ await ensureCatalog();
112
+ const byId = strategyCatalog.get(idOrName);
113
+ if (byId) return byId;
114
+ for (const descriptor of strategyCatalog.values()) {
115
+ if (descriptor.name === idOrName) return descriptor;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ export async function getStrategySummary(idOrName: string): Promise<StrategySummary | undefined> {
121
+ const descriptor = await findStrategyDescriptor(idOrName);
122
+ if (!descriptor) return undefined;
123
+ return { id: descriptor.id, name: descriptor.name, description: descriptor.description };
124
+ }
125
+
126
+ /** Load only the strategy explicitly selected by id or display name. */
127
+ export async function getStrategyEntry(idOrName: string): Promise<StrategyEntry | undefined> {
128
+ const descriptor = await findStrategyDescriptor(idOrName);
129
+ if (!descriptor) return undefined;
130
+ const cached = runtimeEntryCache.get(descriptor.filePath);
131
+ if (cached) return cached;
132
+
133
+ const mod = await importUserFile(descriptor.filePath);
134
+ const entry = mod.strategy as StrategyEntry | undefined;
135
+ if (!entry?.id || typeof entry.description !== 'string' || typeof entry.create !== 'function') {
136
+ throw new Error(`Strategy '${descriptor.id}' does not export a valid strategy object.`);
137
+ }
138
+ if (entry.id !== descriptor.id) {
139
+ throw new Error(`Strategy metadata changed while loading '${descriptor.id}'. Run the command again.`);
140
+ }
141
+ runtimeEntryCache.set(descriptor.filePath, entry);
142
+ return entry;
143
+ }
144
+
145
+ /** Compatibility name for internal callers: returns static metadata and never executes modules. */
146
+ export async function listStrategyEntries(): Promise<StrategySummary[]> {
147
+ return listStrategySummaries();
148
+ }
149
+
150
+ export async function listStrategySummaries(): Promise<StrategySummary[]> {
151
+ await ensureCatalog();
152
+ return [...strategyCatalog.values()].map(descriptor => ({
153
+ id: descriptor.id,
154
+ name: descriptor.name,
155
+ description: descriptor.description,
156
+ }));
157
+ }
158
+
159
+ export async function getStrategyKnowledgeDoc(id: string): Promise<string | undefined> {
160
+ const descriptor = await findStrategyDescriptor(id);
161
+ const path = descriptor?.knowledgeDocPath;
162
+ if (!path || !existsSync(path)) return undefined;
163
+ try {
164
+ return readFileSync(path, 'utf8');
165
+ } catch {
166
+ return undefined;
167
+ }
168
+ }
169
+
170
+ export async function resolveStrategy(id: string, args?: string[]): Promise<Strategy> {
171
+ const entry = await getStrategyEntry(id);
172
+ if (!entry) throw new Error(`Unknown strategy '${id}'. Use 'strategy list' to see available strategies.`);
173
+ return entry.create(args);
174
+ }
175
+
176
+ /** Reset and statically re-scan after a strategy file is installed, removed, or replaced. */
177
+ export async function reload(): Promise<void> {
178
+ catalogLoaded = false;
179
+ loadedWorkspaceDir = undefined;
180
+ strategyCatalog.clear();
181
+ runtimeEntryCache.clear();
182
+ await ensureCatalog();
183
+ }
@@ -0,0 +1,24 @@
1
+ import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
3
+ import { GoalRootStrategy } from './goals/goal-root-strategy.js';
4
+ import { LoneKillTaskTop } from './goals/lone-kill-task-top.js';
5
+ import { ConversationGoal } from './goals/conversation-goal.js';
6
+ import { SpeechModule, getSpeechConfigForRole } from './speech-module.js';
7
+
8
+ export const strategy: StrategyEntry = {
9
+ id: 'lone-kill-task',
10
+ name: '潜伏猎手',
11
+ ...noKnowledgeContract('潜伏猎手'),
12
+ description: '视野里只有一个非队友且冷却可用就靠近,进入50距离就立刻出刀;刀在冷却时不追不等、改做低优先级任务伪装,冷却好且目标仍落单可见再出刀(贴脸且刀好仍会立刻出刀)。发现尸体且附近有非队友、但当前不能原地出刀时,会靠近并报告尸体。视野里出现两人以上时,暂停攻击10秒并做任意阵营的真实任务伪装;选任务时会跳过紧挨已知尸体(含看见过、已离开视野的)的任务,不在命案现场做任务。没有可做任务时按房间巡逻,绝不停在原地。残局(已知存活≤6)出现紧急维修任务时,会高优先级抢着去做(仍低于击杀落单),阻止蟹靠破坏倒计时取胜。(章鱼默认)',
13
+ create(args?: string[]) {
14
+ const role = args?.[0] ?? 'neutral_octopus';
15
+ let convo: ConversationGoal | null = null;
16
+ return new GoalRootStrategy('lone-kill-task', () => {
17
+ convo = new ConversationGoal(() => new LoneKillTaskTop(), new SpeechModule(getSpeechConfigForRole(role)));
18
+ return convo;
19
+ }, {
20
+ resetOnMeetingResume: false,
21
+ onUpdateRole: role => convo?.updateConfig(role),
22
+ });
23
+ },
24
+ };
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ meetingEndedInEvents,
4
+ meetingStartedInEvents,
5
+ shouldPauseForMeeting,
6
+ } from './meeting-gate.js';
7
+ import type { GameState } from '../sdk/types.js';
8
+
9
+ function baseState(overrides: Partial<GameState> = {}): GameState {
10
+ return {
11
+ phase: 'wandering',
12
+ tick: 1,
13
+ you: {
14
+ name: 'me',
15
+ x: 0,
16
+ y: 0,
17
+ room: '酒吧',
18
+ role: 'crab_generic',
19
+ faction: 'crab',
20
+ is_alive: true,
21
+ },
22
+ your_tasks: [],
23
+ players: [],
24
+ corpses: [],
25
+ stale: false,
26
+ ...overrides,
27
+ };
28
+ }
29
+
30
+ describe('meeting-gate', () => {
31
+ it('detects meeting end events', () => {
32
+ expect(meetingEndedInEvents([{ type: 'meeting_ended' }])).toBe(true);
33
+ expect(meetingEndedInEvents([{ type: 'meeting_result_pending' }])).toBe(true);
34
+ expect(meetingEndedInEvents([{ type: 'speech' }])).toBe(false);
35
+ });
36
+
37
+ it('keeps pausing during meeting until end events arrive', () => {
38
+ const during = baseState({ phase: 'meeting', new_events: [{ type: 'speech' }] });
39
+ expect(shouldPauseForMeeting(during)).toBe(true);
40
+
41
+ const ending = baseState({ phase: 'meeting', new_events: [{ type: 'meeting_ended' }] });
42
+ expect(shouldPauseForMeeting(ending)).toBe(false);
43
+
44
+ const wandering = baseState({ phase: 'wandering' });
45
+ expect(shouldPauseForMeeting(wandering)).toBe(false);
46
+ });
47
+
48
+ it('does not re-pause after releasedEarly while HTTP phase still meeting', () => {
49
+ const lingering = baseState({ phase: 'meeting', new_events: [] });
50
+ expect(shouldPauseForMeeting(lingering, true)).toBe(false);
51
+ expect(shouldPauseForMeeting(lingering, false)).toBe(true);
52
+ });
53
+
54
+ it('detects meeting start events for cycle reset', () => {
55
+ expect(meetingStartedInEvents([{ type: 'meeting_start' }])).toBe(true);
56
+ expect(meetingStartedInEvents([{ type: 'meeting_started' }])).toBe(true);
57
+ expect(meetingStartedInEvents([{ type: 'speech' }])).toBe(false);
58
+ });
59
+ });
@@ -0,0 +1,28 @@
1
+ import type { GameState } from '../sdk/types.js';
2
+
3
+ const MEETING_END_EVENT_TYPES = new Set(['meeting_ended', 'meeting_result_pending']);
4
+ const MEETING_START_EVENT_TYPES = new Set(['meeting_start', 'meeting_started']);
5
+ const OCTOPUS_TIME_START_EVENT_TYPES = new Set(['octopus_time_start']);
6
+
7
+ export function meetingEndedInEvents(events: any[] | undefined): boolean {
8
+ return (events ?? []).some((e) => MEETING_END_EVENT_TYPES.has(e.type));
9
+ }
10
+
11
+ export function meetingStartedInEvents(events: any[] | undefined): boolean {
12
+ return (events ?? []).some((e) => MEETING_START_EVENT_TYPES.has(e.type));
13
+ }
14
+
15
+ export function octopusTimeStartedInEvents(events: any[] | undefined): boolean {
16
+ return (events ?? []).some((e) => OCTOPUS_TIME_START_EVENT_TYPES.has(e.type));
17
+ }
18
+
19
+ /**
20
+ * Keep pausing while HTTP phase is still `meeting`.
21
+ * `releasedEarly` is set after we have seen meeting end once — avoids re-pausing
22
+ * on later polls where phase lags but `new_events` no longer repeats `meeting_ended`.
23
+ */
24
+ export function shouldPauseForMeeting(state: GameState, releasedEarly = false): boolean {
25
+ if (state.phase !== 'meeting') return false;
26
+ if (releasedEarly) return false;
27
+ return !meetingEndedInEvents(state.new_events);
28
+ }
@@ -0,0 +1,18 @@
1
+ import type { StrategyEntry } from './types.js';
2
+ import { noKnowledgeContract } from './knowledge-contract.js';
3
+ import { GoalRootStrategy } from './goals/goal-root-strategy.js';
4
+ import { MoveRoomGoal } from './goals/move-room-goal.js';
5
+
6
+ export const strategy: StrategyEntry = {
7
+ id: 'move-room',
8
+ name: '前往',
9
+ ...noKnowledgeContract('前往'),
10
+ description: '前往指定房间,到达后停下。参数为目标房间名(如 酒吧)。单纯走位,不做任务、不打人、不报告。',
11
+ create(args?: string[]) {
12
+ const targetRoom = args?.join(' ').trim() ?? '';
13
+ if (!targetRoom) {
14
+ throw new Error('move-room strategy requires a room name. Example: move-room 酒吧');
15
+ }
16
+ return new GoalRootStrategy('move-room', () => new MoveRoomGoal(targetRoom));
17
+ },
18
+ };
@@ -0,0 +1,98 @@
1
+ import { closeSync, existsSync, openSync, readSync, statSync } from 'fs';
2
+ import { extractNewEvents } from '../pipeline/event-store.js';
3
+
4
+ const SUPPLEMENTAL_TYPES = new Set([
5
+ 'corpse_spotted', 'crab_teammates',
6
+ 'meeting_ended', 'meeting_result_pending', 'meeting_start', 'meeting_started',
7
+ 'move_end', 'move_interrupted', 'octopus_time_start',
8
+ 'wandering_speech',
9
+ ]);
10
+
11
+ const KEY_FIELDS = [
12
+ 'type', 'tick', 'actor_name', 'spotted_name', 'killer_name', 'result_target',
13
+ 'target_name', 'corpse_name', 'task_name', 'reason', 'text', 'content',
14
+ ];
15
+
16
+ export function createStrategyNewEventsBackfill(eventLogPath: string): {
17
+ correct(stateNewEvents: any): Record<string, any>[];
18
+ } {
19
+ let pos = sizeOf(eventLogPath);
20
+
21
+ return {
22
+ correct(stateNewEvents: any): Record<string, any>[] {
23
+ const httpEvents = extractNewEvents(stateNewEvents);
24
+ const httpKeys = new Set(httpEvents.map(eventKey));
25
+ const out: Array<{ event: Record<string, any>; order: number }> = [];
26
+ const seen = new Set<string>();
27
+ let order = 0;
28
+ const add = (evt: any, supplemental = false) => {
29
+ if (!evt || typeof evt !== 'object' || typeof evt.type !== 'string' || evt.synthetic) return;
30
+ if (supplemental && !SUPPLEMENTAL_TYPES.has(evt.type)) return;
31
+ const key = eventKey(evt);
32
+ if (supplemental && httpKeys.has(key)) return;
33
+ if (seen.has(key)) return;
34
+ seen.add(key);
35
+ out.push({ event: evt, order: order++ });
36
+ };
37
+
38
+ for (const line of readNewLines()) {
39
+ const events = extractNewEvents(line);
40
+ for (const evt of events.length > 0 ? events : [line]) add(evt, true);
41
+ }
42
+ for (const evt of httpEvents) add(evt);
43
+ return out.sort(compareEvents).map(item => item.event);
44
+ },
45
+ };
46
+
47
+ function readNewLines(): Record<string, any>[] {
48
+ if (!existsSync(eventLogPath)) { pos = 0; return []; }
49
+ let stat;
50
+ try { stat = statSync(eventLogPath); } catch { return []; }
51
+ if (stat.size < pos) pos = 0;
52
+ if (stat.size === pos) return [];
53
+
54
+ let fd: number;
55
+ try { fd = openSync(eventLogPath, 'r'); } catch { return []; }
56
+ const buf = Buffer.alloc(stat.size - pos);
57
+ try {
58
+ readSync(fd, buf, 0, buf.length, pos);
59
+ } finally {
60
+ closeSync(fd);
61
+ }
62
+
63
+ const cut = buf.lastIndexOf(0x0A);
64
+ if (cut < 0) return [];
65
+ const chunk = buf.subarray(0, cut).toString('utf8');
66
+ pos += cut + 1;
67
+ return chunk.split('\n').flatMap(parseLine);
68
+ }
69
+ }
70
+
71
+ function eventKey(evt: Record<string, any>): string {
72
+ return evt.tick == null ? JSON.stringify(evt) : KEY_FIELDS.map(k => evt[k] ?? '').join('|');
73
+ }
74
+
75
+ function compareEvents(a: { event: Record<string, any>; order: number }, b: { event: Record<string, any>; order: number }): number {
76
+ const at = typeof a.event.tick === 'number' && Number.isFinite(a.event.tick) ? a.event.tick : null;
77
+ const bt = typeof b.event.tick === 'number' && Number.isFinite(b.event.tick) ? b.event.tick : null;
78
+ if (at != null && bt != null && at !== bt) return at - bt;
79
+ return a.order - b.order;
80
+ }
81
+
82
+ function parseLine(line: string): Record<string, any>[] {
83
+ if (!line.trim()) return [];
84
+ try {
85
+ const obj = JSON.parse(line);
86
+ return obj && typeof obj === 'object' ? [obj] : [];
87
+ } catch {
88
+ return [];
89
+ }
90
+ }
91
+
92
+ function sizeOf(path: string): number {
93
+ try {
94
+ return existsSync(path) ? statSync(path).size : 0;
95
+ } catch {
96
+ return 0;
97
+ }
98
+ }
@@ -0,0 +1,105 @@
1
+ import type { Position } from '../sdk/types.js';
2
+ import { dist } from './game-utils.js';
3
+ import { assessRoutes } from './pathfind/escape-planner.js';
4
+
5
+ /**
6
+ * 离线从烘焙地图算出的「离路点」:远离任务点/出生点、避开走廊与枢纽的低人流坐标
7
+ * (世界像素,与 GameState / 可行走网格同坐标系)。HIDE_SPOTS(藏身角落)是它的具体集合,
8
+ * 共用下面的选点器。
9
+ */
10
+ export interface OffRoutePoint extends Position {
11
+ /** 所在房间,仅供日志/调试。 */
12
+ room: string;
13
+ }
14
+
15
+ export interface NearestSafePointOptions<T extends Position = Position> {
16
+ /** 点离任一威胁多近就硬排除。 */
17
+ threatExcludeRadius: number;
18
+ /** 去该点的测地路径经过威胁这个距离内也排除(避免走向把守者)。 */
19
+ pathThreatRadius: number;
20
+ /** 当前已选点:仍是合法候选就保持不变,杜绝等距摇摆。 */
21
+ stickyTo?: T | null;
22
+ /** 被标记为不可达的移动目标:在其附近的点跳过。 */
23
+ blockedTarget?: Position | null;
24
+ }
25
+
26
+ const BLOCKED_RADIUS = 12;
27
+
28
+ function samePoint(a: Position, b: Position): boolean {
29
+ return a.x === b.x && a.y === b.y;
30
+ }
31
+
32
+ /** 所有点都被威胁封死时的兜底:离威胁最远的点(仍好过原地等死)。 */
33
+ function farthestFromThreats<T extends Position>(
34
+ points: readonly T[],
35
+ threatPoints: Position[],
36
+ blocked?: Position | null,
37
+ ): T | null {
38
+ let best: T | null = null;
39
+ let bestMin = -Infinity;
40
+ for (const s of points) {
41
+ if (blocked && dist(s.x, s.y, blocked.x, blocked.y) <= BLOCKED_RADIUS) continue;
42
+ const minD = threatPoints.length === 0 ? 0 : Math.min(...threatPoints.map(p => dist(s.x, s.y, p.x, p.y)));
43
+ if (minD > bestMin) {
44
+ bestMin = minD;
45
+ best = s;
46
+ }
47
+ }
48
+ return best;
49
+ }
50
+
51
+ /**
52
+ * 从离线点集里选「测地最近的安全点」:威胁旁的点硬排除、去路经过威胁附近的点排除,余者取测地最近
53
+ * (distance-field 一次扫描;测地不可达按欧氏垫底),带粘性(当前点仍合法就不换)。全部被威胁封死
54
+ * 时退回「离威胁最远」的点。nearestSafeHideSpot 复用此选点器。
55
+ */
56
+ export function nearestSafePoint<T extends Position>(
57
+ points: readonly T[],
58
+ from: Position,
59
+ threatPoints: Position[],
60
+ opts: NearestSafePointOptions<T>,
61
+ ): T | null {
62
+ const excludeR = opts.threatExcludeRadius;
63
+ const blocked = opts.blockedTarget ?? null;
64
+
65
+ const candidates = points.filter(s =>
66
+ (!blocked || dist(s.x, s.y, blocked.x, blocked.y) > BLOCKED_RADIUS)
67
+ && !threatPoints.some(p => dist(s.x, s.y, p.x, p.y) <= excludeR));
68
+
69
+ if (candidates.length === 0) return farthestFromThreats(points, threatPoints, blocked);
70
+
71
+ // 无威胁时粘性可零成本短路(不必为路径检查扫距离场)。
72
+ if (opts.stickyTo && threatPoints.length === 0) {
73
+ const sticky = candidates.find(c => samePoint(c, opts.stickyTo!));
74
+ if (sticky) return sticky;
75
+ }
76
+
77
+ const routes = assessRoutes(
78
+ from,
79
+ candidates.map(c => ({ x: c.x, y: c.y })),
80
+ threatPoints,
81
+ opts.pathThreatRadius,
82
+ );
83
+ const indexed = candidates.map((c, i) => ({ c, i }));
84
+ const viable = routes == null ? indexed : indexed.filter(({ i }) => !routes[i].nearThreat);
85
+ const pool = viable.length > 0 ? viable : indexed;
86
+
87
+ if (opts.stickyTo) {
88
+ const sticky = pool.find(({ c }) => samePoint(c, opts.stickyTo!));
89
+ if (sticky) return sticky.c;
90
+ }
91
+
92
+ // 测地最近(distance-field 距离;测地不可达按欧氏垫底)。
93
+ let best = pool[0].c;
94
+ let bestScore = Infinity;
95
+ for (const { c, i } of pool) {
96
+ const euclid = dist(from.x, from.y, c.x, c.y);
97
+ const geo = routes?.[i].distancePx;
98
+ const score = geo == null ? euclid : geo !== Infinity ? geo : euclid + 1e6;
99
+ if (score < bestScore) {
100
+ bestScore = score;
101
+ best = c;
102
+ }
103
+ }
104
+ return best;
105
+ }
@@ -0,0 +1,19 @@
1
+ # paradise-fish 知识契约
2
+
3
+ `paradise-fish` 只读取两档玩家标记,**未标记的一律默认「被怀疑」**:
4
+
5
+ | 标记 | 行为 |
6
+ |------|------|
7
+ | `hostile`(坏人) | 敌对带刀者:无尸体时进入视野便硬寻路远离 |
8
+ | `trusted`(好人) | 可信:可与其抱团、靠近站定伪装做任务 |
9
+ | 未标记(被怀疑) | 无尸体、无可信同伴且单人贴近时保持距离;多人互为目击者则照常活动 |
10
+
11
+ 天堂鱼不出刀,因此坏人与被怀疑者都表现为回避(坏人硬躲、被怀疑者按目击者规则保持距离)。发现尸体时仍优先执行尸体旁游走逻辑,不报警。
12
+
13
+ ```bash
14
+ ccl knowledge mark 5 hostile --note "确认危险"
15
+ ccl knowledge mark 3 trusted --note "可以抱团"
16
+ ccl knowledge del player 5 # 取消标记 → 回到默认「被怀疑」
17
+ ```
18
+
19
+ `role` 是纯身份事实,不直接控制策略。
@@ -0,0 +1,24 @@
1
+ import type { StrategyEntry } from './types.js';
2
+ import { playerMarkContract } from './knowledge-contract.js';
3
+ import { GoalRootStrategy } from './goals/goal-root-strategy.js';
4
+ import { ParadiseFishTop } from './goals/paradise-fish-top.js';
5
+ import { parseGreetingArgs } from './greeting.js';
6
+
7
+ class ParadiseFishStrategy extends GoalRootStrategy {
8
+ constructor(greetingPhrases: string[]) {
9
+ super('paradise-fish', () => new ParadiseFishTop(greetingPhrases), {
10
+ resetOnMeetingResume: false,
11
+ });
12
+ }
13
+ }
14
+
15
+ export const strategy: StrategyEntry = {
16
+ id: 'paradise-fish',
17
+ name: '天堂鱼',
18
+ ...playerMarkContract('天堂鱼'),
19
+ description:
20
+ '天堂鱼·进阶版(中立,不报警、不做任务,靠第二轮及以后被投票出局取胜;corpse-patrol 的带记忆升级)。读取 ccl knowledge 两档标记(hostile=坏人 / trusted=好人),未标记的一律默认被怀疑:hostile 视为危险硬寻路远离,被怀疑者按目击者规则保持距离,trusted 视为可抱团的可信同伴。发现尸体绝不报警,贴着尸体游走制造嫌疑;附近有人时远离那人但仍在尸体附近活动。残局(已知存活≤6)出现紧急维修任务时,会在没有带刀坏人需要躲避时优先抢着去做(先于对陌生人保持距离/贴尸/抱团),阻止蟹靠破坏倒计时取胜。传入打招呼话术时,视野内出现人就随机发送一条,之后120秒内不再发言。',
21
+ create(args?: string[]) {
22
+ return new ParadiseFishStrategy(parseGreetingArgs(args, 'paradise-fish'));
23
+ },
24
+ };