cortico 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 (311) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -0
  3. package/package.json +43 -0
  4. package/src/boot.ts +46 -0
  5. package/src/bot.ts +1342 -0
  6. package/src/config-file.ts +41 -0
  7. package/src/core/README.md +92 -0
  8. package/src/core/billing.ts +26 -0
  9. package/src/core/blobs.ts +106 -0
  10. package/src/core/bus.ts +311 -0
  11. package/src/core/config-schema.ts +201 -0
  12. package/src/core/config.ts +262 -0
  13. package/src/core/core.ts +699 -0
  14. package/src/core/cost.ts +244 -0
  15. package/src/core/event-store.ts +304 -0
  16. package/src/core/fork.ts +113 -0
  17. package/src/core/generation.ts +118 -0
  18. package/src/core/instance-lock.ts +215 -0
  19. package/src/core/ipc-logger.ts +105 -0
  20. package/src/core/language.ts +62 -0
  21. package/src/core/log-context.ts +38 -0
  22. package/src/core/loop.ts +1858 -0
  23. package/src/core/markers.ts +48 -0
  24. package/src/core/prefix.ts +121 -0
  25. package/src/core/run.ts +95 -0
  26. package/src/core/secrets.ts +18 -0
  27. package/src/core/session.ts +56 -0
  28. package/src/core/sessions.ts +261 -0
  29. package/src/core/state.ts +104 -0
  30. package/src/core/template.ts +72 -0
  31. package/src/core/timers.ts +129 -0
  32. package/src/core/tool-log.ts +135 -0
  33. package/src/core/transcript.ts +92 -0
  34. package/src/core/truncate.ts +121 -0
  35. package/src/core/types.ts +1140 -0
  36. package/src/core/usage-log.ts +79 -0
  37. package/src/core/util.ts +386 -0
  38. package/src/deploy-listing.ts +160 -0
  39. package/src/deploy.ts +162 -0
  40. package/src/extensions/README.md +72 -0
  41. package/src/extensions/dry-mount.ts +390 -0
  42. package/src/extensions/manifest.ts +153 -0
  43. package/src/extensions/runtime.ts +42 -0
  44. package/src/extensions.ts +519 -0
  45. package/src/launcher.ts +285 -0
  46. package/src/paths.ts +155 -0
  47. package/src/protocol/open-responses/LICENSE +201 -0
  48. package/src/protocol/open-responses/README.md +14 -0
  49. package/src/protocol/open-responses/context-helpers.ts +27 -0
  50. package/src/protocol/open-responses/context-log.ts +59 -0
  51. package/src/protocol/open-responses/context.ts +89 -0
  52. package/src/protocol/open-responses/generated.ts +115 -0
  53. package/src/protocol/open-responses/index.ts +33 -0
  54. package/src/protocol/open-responses/openapi.json +4230 -0
  55. package/src/protocol/open-responses/stream.ts +146 -0
  56. package/src/protocol/open-responses/tokens.ts +31 -0
  57. package/src/providers/README.md +86 -0
  58. package/src/providers/base.ts +111 -0
  59. package/src/providers/configuration.ts +97 -0
  60. package/src/providers/console/config.ts +21 -0
  61. package/src/providers/console/settings.ts +443 -0
  62. package/src/providers/console/strings.ts +74 -0
  63. package/src/providers/console/types.ts +11 -0
  64. package/src/providers/llamacpp/archive.ts +148 -0
  65. package/src/providers/llamacpp/catalog.ts +247 -0
  66. package/src/providers/llamacpp/config.ts +36 -0
  67. package/src/providers/llamacpp/console/client.ts +6 -0
  68. package/src/providers/llamacpp/console/models-panel.ts +120 -0
  69. package/src/providers/llamacpp/console/runtime-panel.ts +173 -0
  70. package/src/providers/llamacpp/console/server.ts +153 -0
  71. package/src/providers/llamacpp/index.ts +95 -0
  72. package/src/providers/llamacpp/native.ts +51 -0
  73. package/src/providers/llamacpp/options.ts +117 -0
  74. package/src/providers/llamacpp/runtime-store.ts +139 -0
  75. package/src/providers/llamacpp/runtime.ts +214 -0
  76. package/src/providers/llamacpp/server.ts +286 -0
  77. package/src/providers/llamacpp/strings.ts +230 -0
  78. package/src/providers/openai-responses-compat/config.ts +20 -0
  79. package/src/providers/openai-responses-compat/index.ts +89 -0
  80. package/src/providers/openai-responses-compat/native.ts +127 -0
  81. package/src/providers/openai-responses-compat/strings.ts +19 -0
  82. package/src/providers/pricebook.ts +75 -0
  83. package/src/providers/registry.ts +137 -0
  84. package/src/providers/strings.ts +71 -0
  85. package/src/providers/transport/chat.ts +156 -0
  86. package/src/providers/transport/errors.ts +48 -0
  87. package/src/providers/transport/history.ts +68 -0
  88. package/src/providers/transport/native-input.ts +83 -0
  89. package/src/providers/transport/native-types.ts +13 -0
  90. package/src/providers/transport/response-assembly.ts +191 -0
  91. package/src/providers/transport/response-http.ts +196 -0
  92. package/src/providers/transport/response-meters.ts +27 -0
  93. package/src/providers/transport/responses-input.ts +56 -0
  94. package/src/web/README.md +84 -0
  95. package/src/web/client/console-pages/builtins/llm-settings/panel.ts +625 -0
  96. package/src/web/client/console-pages/builtins/llm-settings/pricing-panel.ts +168 -0
  97. package/src/web/client/console-pages/builtins/llm-settings/strings.ts +213 -0
  98. package/src/web/client/console-pages/builtins.ts +10 -0
  99. package/src/web/client/console-pages/context.ts +135 -0
  100. package/src/web/client/console-pages/host.ts +633 -0
  101. package/src/web/client/console-pages/loader.ts +132 -0
  102. package/src/web/client/console-pages/strings.ts +90 -0
  103. package/src/web/client/console-pages/tools/strings.ts +49 -0
  104. package/src/web/client/console-pages/tools/view.ts +215 -0
  105. package/src/web/client/core/api.ts +200 -0
  106. package/src/web/client/core/language.ts +56 -0
  107. package/src/web/client/core/lifecycle.ts +132 -0
  108. package/src/web/client/core/router.ts +199 -0
  109. package/src/web/client/core/stream.ts +157 -0
  110. package/src/web/client/core/websocket.ts +82 -0
  111. package/src/web/client/features/appearance/index.ts +333 -0
  112. package/src/web/client/features/appearance/strings.ts +87 -0
  113. package/src/web/client/features/config/index.ts +11 -0
  114. package/src/web/client/features/config/strings.ts +41 -0
  115. package/src/web/client/features/config/view.ts +428 -0
  116. package/src/web/client/features/core/events.ts +197 -0
  117. package/src/web/client/features/core/index.ts +254 -0
  118. package/src/web/client/features/core/run.ts +56 -0
  119. package/src/web/client/features/core/runlog.ts +214 -0
  120. package/src/web/client/features/core/sessions.ts +53 -0
  121. package/src/web/client/features/core/strings.ts +157 -0
  122. package/src/web/client/features/extensions/index.ts +422 -0
  123. package/src/web/client/features/extensions/strings.ts +164 -0
  124. package/src/web/client/features/feature.ts +93 -0
  125. package/src/web/client/features/live/context.ts +280 -0
  126. package/src/web/client/features/live/fork.ts +156 -0
  127. package/src/web/client/features/live/index.ts +392 -0
  128. package/src/web/client/features/live/onboarding.ts +113 -0
  129. package/src/web/client/features/live/protocol.ts +122 -0
  130. package/src/web/client/features/live/sessions.ts +71 -0
  131. package/src/web/client/features/live/status.ts +68 -0
  132. package/src/web/client/features/live/strings.ts +252 -0
  133. package/src/web/client/features/live/timeline.ts +590 -0
  134. package/src/web/client/features/prompts/editor.ts +292 -0
  135. package/src/web/client/features/prompts/index.ts +346 -0
  136. package/src/web/client/features/prompts/strings.ts +136 -0
  137. package/src/web/client/features/prompts/view.ts +256 -0
  138. package/src/web/client/features/providers/index.ts +100 -0
  139. package/src/web/client/features/providers/strings.ts +23 -0
  140. package/src/web/client/features/settings/general.ts +28 -0
  141. package/src/web/client/features/settings/index.ts +82 -0
  142. package/src/web/client/features/settings/strings.ts +33 -0
  143. package/src/web/client/features/storage/index.ts +1 -0
  144. package/src/web/client/features/storage/strings.ts +45 -0
  145. package/src/web/client/features/storage/view.ts +154 -0
  146. package/src/web/client/features/usage/chart.ts +486 -0
  147. package/src/web/client/features/usage/index.ts +407 -0
  148. package/src/web/client/features/usage/labels.ts +46 -0
  149. package/src/web/client/features/usage/range.ts +36 -0
  150. package/src/web/client/features/usage/state.ts +37 -0
  151. package/src/web/client/features/usage/strings.ts +191 -0
  152. package/src/web/client/features/usage/tooltip.ts +86 -0
  153. package/src/web/client/features/usage/types.ts +96 -0
  154. package/src/web/client/features/worlds/index.ts +424 -0
  155. package/src/web/client/features/worlds/strings.ts +121 -0
  156. package/src/web/client/main.ts +273 -0
  157. package/src/web/client/shell/avatar.ts +233 -0
  158. package/src/web/client/shell/index.ts +549 -0
  159. package/src/web/client/shell/strings.ts +89 -0
  160. package/src/web/client/theme/handoff.ts +43 -0
  161. package/src/web/client/theme/palette.ts +109 -0
  162. package/src/web/client/theme/registry.ts +130 -0
  163. package/src/web/client/theme/storage.ts +72 -0
  164. package/src/web/client/theme/strings.ts +123 -0
  165. package/src/web/client/theme/studio.ts +366 -0
  166. package/src/web/client/ui/actions.ts +109 -0
  167. package/src/web/client/ui/data.ts +185 -0
  168. package/src/web/client/ui/dom.ts +23 -0
  169. package/src/web/client/ui/fields.ts +191 -0
  170. package/src/web/client/ui/format.ts +75 -0
  171. package/src/web/client/ui/icons.ts +183 -0
  172. package/src/web/client/ui/images.ts +91 -0
  173. package/src/web/client/ui/index.ts +89 -0
  174. package/src/web/client/ui/lamp.ts +125 -0
  175. package/src/web/client/ui/log.ts +98 -0
  176. package/src/web/client/ui/overlay.ts +184 -0
  177. package/src/web/client/ui/page.ts +8 -0
  178. package/src/web/client/ui/prompt-input.tsx +311 -0
  179. package/src/web/client/ui/sheet.ts +131 -0
  180. package/src/web/client/ui/strings.ts +71 -0
  181. package/src/web/console-pages.ts +367 -0
  182. package/src/web/files.ts +107 -0
  183. package/src/web/path-picker.ts +296 -0
  184. package/src/web/public/index.html +17 -0
  185. package/src/web/public/styles.css +1715 -0
  186. package/src/web/server.ts +1883 -0
  187. package/src/web/shared/client-panel.ts +603 -0
  188. package/src/web/shared/console-protocol.ts +560 -0
  189. package/src/web/shared/css.d.ts +1 -0
  190. package/src/web/shared/path-picker.ts +23 -0
  191. package/src/web/shared/theme.ts +256 -0
  192. package/src/web/theme-store.ts +37 -0
  193. package/src/world.ts +449 -0
  194. package/src/worlds/bilibili/ENV_PROMPT.md +5 -0
  195. package/src/worlds/bilibili/README.md +176 -0
  196. package/src/worlds/bilibili/audience-admission.ts +995 -0
  197. package/src/worlds/bilibili/client.ts +528 -0
  198. package/src/worlds/bilibili/coalescing-buffer.ts +125 -0
  199. package/src/worlds/bilibili/config.ts +185 -0
  200. package/src/worlds/bilibili/console/client.ts +202 -0
  201. package/src/worlds/bilibili/definition.ts +35 -0
  202. package/src/worlds/bilibili/gift-frame.ts +131 -0
  203. package/src/worlds/bilibili/normalize.ts +452 -0
  204. package/src/worlds/bilibili/overlay/announcement.ts +76 -0
  205. package/src/worlds/bilibili/overlay/assets.ts +82 -0
  206. package/src/worlds/bilibili/overlay/model.ts +494 -0
  207. package/src/worlds/bilibili/overlay/project.ts +202 -0
  208. package/src/worlds/bilibili/overlay/server.ts +286 -0
  209. package/src/worlds/bilibili/overlay/types.ts +217 -0
  210. package/src/worlds/bilibili/overlay/web/app.js +690 -0
  211. package/src/worlds/bilibili/overlay/web/editor.css +297 -0
  212. package/src/worlds/bilibili/overlay/web/editor.html +102 -0
  213. package/src/worlds/bilibili/overlay/web/editor.js +2116 -0
  214. package/src/worlds/bilibili/overlay/web/overlay.html +13 -0
  215. package/src/worlds/bilibili/overlay/web/styles.css +258 -0
  216. package/src/worlds/bilibili/protobuf.ts +123 -0
  217. package/src/worlds/bilibili/wire.ts +94 -0
  218. package/src/worlds/bilibili/world.ts +1389 -0
  219. package/src/worlds/console-fixture/ENV_PROMPT.md +1 -0
  220. package/src/worlds/console-fixture/console/client.ts +72 -0
  221. package/src/worlds/console-fixture/world.ts +73 -0
  222. package/src/worlds/index.ts +15 -0
  223. package/src/worlds/minecraft/ENV_PROMPT.md +32 -0
  224. package/src/worlds/minecraft/ENV_PROMPT_CAMERA.md +2 -0
  225. package/src/worlds/minecraft/LICENSE-mineflayer-pathfinder.txt +21 -0
  226. package/src/worlds/minecraft/README.md +917 -0
  227. package/src/worlds/minecraft/blueprint-plan.ts +915 -0
  228. package/src/worlds/minecraft/blueprint-registry.ts +566 -0
  229. package/src/worlds/minecraft/blueprint-repair.ts +236 -0
  230. package/src/worlds/minecraft/blueprint-resource.ts +272 -0
  231. package/src/worlds/minecraft/blueprint.ts +492 -0
  232. package/src/worlds/minecraft/body-lease.ts +340 -0
  233. package/src/worlds/minecraft/bridge.ts +749 -0
  234. package/src/worlds/minecraft/check.ts +651 -0
  235. package/src/worlds/minecraft/chests.ts +292 -0
  236. package/src/worlds/minecraft/client-launch.ts +272 -0
  237. package/src/worlds/minecraft/client-options.ts +85 -0
  238. package/src/worlds/minecraft/client-skins.ts +164 -0
  239. package/src/worlds/minecraft/client-window.ps1 +91 -0
  240. package/src/worlds/minecraft/client.ts +423 -0
  241. package/src/worlds/minecraft/combat-context.ts +109 -0
  242. package/src/worlds/minecraft/combat.ts +1552 -0
  243. package/src/worlds/minecraft/config.ts +499 -0
  244. package/src/worlds/minecraft/console/access.ts +218 -0
  245. package/src/worlds/minecraft/console/client.ts +244 -0
  246. package/src/worlds/minecraft/console/log.ts +110 -0
  247. package/src/worlds/minecraft/console/mount.ts +420 -0
  248. package/src/worlds/minecraft/console/skin.ts +257 -0
  249. package/src/worlds/minecraft/console/style.css +154 -0
  250. package/src/worlds/minecraft/console/world.ts +449 -0
  251. package/src/worlds/minecraft/deaths.ts +135 -0
  252. package/src/worlds/minecraft/definition.ts +18 -0
  253. package/src/worlds/minecraft/engine-child.ts +274 -0
  254. package/src/worlds/minecraft/engine-ipc.ts +98 -0
  255. package/src/worlds/minecraft/entity-facts.ts +132 -0
  256. package/src/worlds/minecraft/escape.ts +407 -0
  257. package/src/worlds/minecraft/executor.ts +14494 -0
  258. package/src/worlds/minecraft/explored.ts +156 -0
  259. package/src/worlds/minecraft/geometry.ts +205 -0
  260. package/src/worlds/minecraft/goal-plan.ts +647 -0
  261. package/src/worlds/minecraft/item-break.ts +126 -0
  262. package/src/worlds/minecraft/item-facts.ts +146 -0
  263. package/src/worlds/minecraft/item-pick.ts +67 -0
  264. package/src/worlds/minecraft/level-dat.ts +176 -0
  265. package/src/worlds/minecraft/log.ts +132 -0
  266. package/src/worlds/minecraft/mineflayer-fixes.ts +1180 -0
  267. package/src/worlds/minecraft/names.ts +377 -0
  268. package/src/worlds/minecraft/pathfinder-lib.d.ts +13 -0
  269. package/src/worlds/minecraft/pathfinder-perf.ts +796 -0
  270. package/src/worlds/minecraft/piglin.ts +49 -0
  271. package/src/worlds/minecraft/policy.ts +547 -0
  272. package/src/worlds/minecraft/precheck.ts +655 -0
  273. package/src/worlds/minecraft/proxy.ts +445 -0
  274. package/src/worlds/minecraft/ranged.ts +635 -0
  275. package/src/worlds/minecraft/readouts.ts +102 -0
  276. package/src/worlds/minecraft/round.ts +26 -0
  277. package/src/worlds/minecraft/search-observation.ts +92 -0
  278. package/src/worlds/minecraft/server-config.ts +467 -0
  279. package/src/worlds/minecraft/server.ts +658 -0
  280. package/src/worlds/minecraft/show.ts +84 -0
  281. package/src/worlds/minecraft/skills.ts +1763 -0
  282. package/src/worlds/minecraft/terrain.ts +1735 -0
  283. package/src/worlds/minecraft/window.ts +96 -0
  284. package/src/worlds/minecraft/works.ts +179 -0
  285. package/src/worlds/minecraft/world.ts +6438 -0
  286. package/src/worlds/qq/ENV_PROMPT.md +5 -0
  287. package/src/worlds/qq/config.ts +108 -0
  288. package/src/worlds/qq/console/client.ts +126 -0
  289. package/src/worlds/qq/console/events.ts +155 -0
  290. package/src/worlds/qq/console/gate.ts +232 -0
  291. package/src/worlds/qq/console/roster.ts +203 -0
  292. package/src/worlds/qq/console/style.css +65 -0
  293. package/src/worlds/qq/conversation.ts +28 -0
  294. package/src/worlds/qq/definition.ts +62 -0
  295. package/src/worlds/qq/driver.ts +375 -0
  296. package/src/worlds/qq/history-tools.ts +209 -0
  297. package/src/worlds/qq/normalize.ts +323 -0
  298. package/src/worlds/qq/qface-map.ts +282 -0
  299. package/src/worlds/qq/vision-prompt.ts +27 -0
  300. package/src/worlds/qq/vision.ts +642 -0
  301. package/src/worlds/qq/vlm.ts +142 -0
  302. package/src/worlds/qq/world.ts +1503 -0
  303. package/src/worlds/terminal/ENV_PROMPT.md +11 -0
  304. package/src/worlds/terminal/config.ts +9 -0
  305. package/src/worlds/terminal/definition.ts +14 -0
  306. package/src/worlds/terminal/world.ts +700 -0
  307. package/src/worlds/websearch/ENV_PROMPT.md +1 -0
  308. package/src/worlds/websearch/brave-client.ts +261 -0
  309. package/src/worlds/websearch/config.ts +75 -0
  310. package/src/worlds/websearch/definition.ts +20 -0
  311. package/src/worlds/websearch/world.ts +171 -0
@@ -0,0 +1,445 @@
1
+ /** 主进程中的 Minecraft World 代理。游戏连接、执行器和客户端管理在引擎子进程;此处转发工具、事件、控制台及存储请求,并每秒推送配置。 */
2
+ import { fork, type ChildProcess } from 'node:child_process';
3
+ import { nowIso } from '../../core/util.ts';
4
+ import { emitLogNote, logChildStdio } from '../../core/ipc-logger.ts';
5
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import type {
9
+ World,
10
+ WorldHost,
11
+ WorldConsoleDecl,
12
+ StoragePart,
13
+ ToolDef,
14
+ } from '../../core/types.ts';
15
+ import { COGNITION_ABSENT, MINECRAFT_PANEL_DECLS, MINECRAFT_STORAGE_DECLS, MINECRAFT_TOOL_DECLS, type MinecraftWorldOptions } from './world.ts';
16
+ import { MINECRAFT_CLIENT_CONFIG_GROUP, MINECRAFT_CONFIG_GROUP, MINECRAFT_PLAYER_CONFIG_GROUP, MINECRAFT_RHYTHM_CONFIG_GROUP } from './config.ts';
17
+ import type {
18
+ ChildToMain,
19
+ EngineCast,
20
+ EngineNote,
21
+ EngineRequest,
22
+ HostRequest,
23
+ StorageStat,
24
+ } from './engine-ipc.ts';
25
+ import { roundTokenOf } from './round.ts';
26
+ import { loadExplored, renderExploredLedger } from './explored.ts';
27
+ import { loadPolicy, renderPolicyEnv } from './policy.ts';
28
+ import { worldEnvLine, worldIdentityOf } from './server-config.ts';
29
+
30
+ const ENV_PROMPT_FILE = fileURLToPath(new URL('./ENV_PROMPT.md', import.meta.url));
31
+ const CAMERA_NOTE_FILE = fileURLToPath(new URL('./ENV_PROMPT_CAMERA.md', import.meta.url));
32
+ const CHILD_ENTRY = fileURLToPath(new URL('./engine-child.ts', import.meta.url));
33
+
34
+ const CONFIG_SAMPLE_MS = 1000;
35
+ const RESTART_DELAY_MS = 3000;
36
+ /** Windows STATUS_CONTROL_C_EXIT。 */
37
+ const CONSOLE_KILL_EXIT_CODE = 3221225786;
38
+ /** 工具 RPC 超时。 */
39
+ const RPC_TIMEOUT_MS = 150_000;
40
+ /** 延迟事件渲染的 RPC 超时须短于主循环的 3 秒等待上限。 */
41
+ const DEFERRED_RENDER_TIMEOUT_MS = 2500;
42
+ const PANEL_RPC_TIMEOUT_MS = 150_000;
43
+ /** 初始化确认只表示请求已受理,不等待游戏连接完成。 */
44
+ const INIT_TIMEOUT_MS = 30_000;
45
+
46
+ interface PendingRpc {
47
+ resolve: (value: unknown) => void;
48
+ reject: (err: Error) => void;
49
+ timer: ReturnType<typeof setTimeout>;
50
+ }
51
+
52
+ export class MinecraftWorldProxy implements World {
53
+ readonly id = 'minecraft';
54
+
55
+ private host: WorldHost | null = null;
56
+ private child: ChildProcess | null = null;
57
+ private ready = false;
58
+ private stopping = false;
59
+ private nextReqId = 1;
60
+ private readonly pending = new Map<number, PendingRpc>();
61
+ private declCache: Pick<WorldConsoleDecl, 'lamps' | 'badges' | 'links'> = {};
62
+ private storageCache: StorageStat[] = [];
63
+ private lastConfigJson = '';
64
+ private lastCaps: boolean | null = null;
65
+ private configTimer: ReturnType<typeof setInterval> | null = null;
66
+ private restartTimer: ReturnType<typeof setTimeout> | null = null;
67
+
68
+ constructor(private readonly opts: MinecraftWorldOptions) {}
69
+
70
+ /**
71
+ * 前缀从子进程持有的落盘文件读取探索摘要与常驻规则,并从 server.properties 读取世界身份。
72
+ * 快照锚点由子进程设置。
73
+ */
74
+ envPromptVars(): Record<string, string> {
75
+ return {
76
+ 'minecraft.world': worldEnvLine(worldIdentityOf(
77
+ this.opts.cfg.local.serverDir,
78
+ `${this.opts.cfg.host}:${this.opts.cfg.port}`,
79
+ )),
80
+ 'minecraft.explored': renderExploredLedger(loadExplored(this.storageFileOf('minecraft-explored'))),
81
+ 'minecraft.policy': renderPolicyEnv(loadPolicy(this.storageFileOf('minecraft-policy'))),
82
+ 'minecraft.camera': this.opts.cfg.client.enabled
83
+ ? readFileSync(CAMERA_NOTE_FILE, 'utf8').trim()
84
+ : '',
85
+ };
86
+ }
87
+
88
+ tools(): ToolDef[] {
89
+ return MINECRAFT_TOOL_DECLS.map((decl) => ({
90
+ ...decl,
91
+ handler: async (args, ctx) => {
92
+ try {
93
+ return (await this.rpc(
94
+ {
95
+ kind: 'tool', name: decl.name, args, role: ctx.role,
96
+ callId: ctx.callId ?? null,
97
+ round: roundTokenOf(ctx),
98
+ },
99
+ RPC_TIMEOUT_MS,
100
+ )) as string;
101
+ } catch (err) {
102
+ return `[${decl.name} 失败] 引擎进程不可用:${err instanceof Error ? err.message : String(err)}`;
103
+ }
104
+ },
105
+ }));
106
+ }
107
+
108
+ console(): WorldConsoleDecl {
109
+ return {
110
+ lamps: this.declCache.lamps ?? [this.child
111
+ ? { label: '引擎', state: 'loading' as const, hint: '启动中' }
112
+ : { label: '引擎', state: 'offline' as const, hint: '未启动' }],
113
+ badges: this.declCache.badges ?? [
114
+ { label: '引擎', value: this.child ? '启动中' : '未启动', tone: 'off' },
115
+ ],
116
+ panels: [...MINECRAFT_PANEL_DECLS],
117
+ invoke: (panel, method, args) => {
118
+ // 路径选择保存后紧接着会读状态或启动;同一 IPC 通道先投最新配置,
119
+ // 让这次面板调用看到刚写入的值。
120
+ this.pushConfigIfChanged();
121
+ return this.rpc({ kind: 'panel', panel, method, args }, PANEL_RPC_TIMEOUT_MS);
122
+ },
123
+ promptDocs: [
124
+ {
125
+ key: 'worlds.minecraft.envPrompt',
126
+ title: 'Minecraft · 环境提示词',
127
+ description: 'Minecraft World 的常驻事实(技能序列、世界观察、反射层)。',
128
+ path: ENV_PROMPT_FILE,
129
+ role: 'envPrompt',
130
+ vars: [
131
+ {
132
+ name: 'minecraft.world',
133
+ description: '世界身份:本地托管=「当前存档:名字」,外部服务器=「当前服务器:地址」。她的位置类记忆按它划界。',
134
+ },
135
+ {
136
+ name: 'minecraft.explored',
137
+ description: '探索覆盖摘要(8 方向历史最远与末端群系);一处没探过时为空。',
138
+ },
139
+ {
140
+ name: 'minecraft.policy',
141
+ description: 'mc_policy 六格里与默认不同的那几条;全默认时为空。',
142
+ },
143
+ {
144
+ name: 'minecraft.camera',
145
+ description: '观察者摄像机说明;没开客户端时为空。措辞在「摄像机说明」那份里改。',
146
+ multiline: true,
147
+ },
148
+ ],
149
+ },
150
+ {
151
+ key: 'worlds.minecraft.cameraNote',
152
+ title: 'Minecraft · 摄像机说明',
153
+ description: '开了观察者客户端时,追加到环境提示词末尾的那一段。',
154
+ path: CAMERA_NOTE_FILE,
155
+ },
156
+ ],
157
+ storage: MINECRAFT_STORAGE_DECLS.map((d): StoragePart => ({
158
+ ...d,
159
+ stat: () =>
160
+ this.storageCache.find((s) => s.key === d.key)?.stat ?? this.storageStatOffline(d.key),
161
+ clear: async () => this.storageClear(d.key),
162
+ })),
163
+ links: this.declCache.links ?? [],
164
+ config: [
165
+ MINECRAFT_CONFIG_GROUP,
166
+ MINECRAFT_RHYTHM_CONFIG_GROUP,
167
+ MINECRAFT_CLIENT_CONFIG_GROUP,
168
+ MINECRAFT_PLAYER_CONFIG_GROUP,
169
+ ],
170
+ };
171
+ }
172
+
173
+ private storageFileOf(key: string): string | null {
174
+ if (!this.opts.dataDir) return null;
175
+ if (key === 'minecraft-chests') return join(this.opts.dataDir, 'minecraft-chests.json');
176
+ if (key === 'minecraft-deaths') return join(this.opts.dataDir, 'minecraft-deaths.json');
177
+ if (key === 'minecraft-explored') return join(this.opts.dataDir, 'minecraft-explored.json');
178
+ if (key === 'minecraft-policy') return join(this.opts.dataDir, 'minecraft-policy.json');
179
+ if (key === 'minecraft-blueprints') return join(this.opts.dataDir, 'minecraft-blueprints.json');
180
+ return null;
181
+ }
182
+
183
+ private storageStatOffline(key: string): string {
184
+ const file = this.storageFileOf(key);
185
+ if (!file || !existsSync(file)) return '(无文件)';
186
+ try {
187
+ return `${(statSync(file).size / 1024).toFixed(1)}KB(引擎未启动)`;
188
+ } catch {
189
+ return '(读不了)';
190
+ }
191
+ }
192
+
193
+ /** 在线存储操作经 RPC 转发;引擎启动中拒绝操作,离线时直接清理文件。 */
194
+ private async storageClear(key: string): Promise<string> {
195
+ if (this.child?.connected) {
196
+ if (!this.ready) throw new Error('引擎子进程正在启动,稍后再清');
197
+ return String(await this.rpc({ kind: 'storage-clear', key }, RPC_TIMEOUT_MS));
198
+ }
199
+ const file = this.storageFileOf(key);
200
+ if (!file || !existsSync(file)) return '没有落盘文件,无需清除';
201
+ writeFileSync(file, '{}\n', 'utf8');
202
+ return '已清空(引擎未启动,直清文件)';
203
+ }
204
+
205
+ async start(host: WorldHost): Promise<void> {
206
+ this.host = host;
207
+ this.stopping = false;
208
+ await this.spawn();
209
+ this.configTimer = setInterval(() => this.pushConfigIfChanged(), CONFIG_SAMPLE_MS);
210
+ this.configTimer.unref?.();
211
+ }
212
+
213
+ async stop(): Promise<void> {
214
+ this.stopping = true;
215
+ if (this.restartTimer) clearTimeout(this.restartTimer);
216
+ this.restartTimer = null;
217
+ if (this.configTimer) clearInterval(this.configTimer);
218
+ this.configTimer = null;
219
+ const child = this.child;
220
+ if (child) {
221
+ try {
222
+ await this.rpc({ kind: 'shutdown' }, 15_000);
223
+ } catch {
224
+ /** shutdown RPC 超时后终止子进程。 */
225
+ }
226
+ await waitExit(child, 5000);
227
+ if (child.exitCode === null && !child.killed) child.kill();
228
+ }
229
+ this.teardownChild();
230
+ this.host = null;
231
+ }
232
+
233
+
234
+ private async spawn(): Promise<void> {
235
+ const child = fork(CHILD_ENTRY, [], {
236
+ execArgv: ['--import', 'tsx'],
237
+ stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
238
+ });
239
+ this.child = child;
240
+ if (this.host) logChildStdio(child, this.host.log);
241
+ child.on('message', (msg) => this.onMessage(msg as ChildToMain));
242
+ child.on('exit', (code) => this.onExit(code));
243
+ child.on('error', (err) => this.host?.log.error('Minecraft 引擎子进程出错', { err: String(err) }));
244
+ this.lastConfigJson = JSON.stringify(this.opts.cfg);
245
+ await this.rpc(
246
+ {
247
+ kind: 'init',
248
+ init: {
249
+ timezone: this.opts.timezone ?? 'Asia/Shanghai',
250
+ botName: this.opts.botName ?? 'bot',
251
+ dataDir: this.opts.dataDir ?? null,
252
+ cfg: JSON.parse(this.lastConfigJson) as MinecraftWorldOptions['cfg'],
253
+ },
254
+ },
255
+ INIT_TIMEOUT_MS,
256
+ );
257
+ this.ready = true;
258
+ this.lastCaps = null;
259
+ this.pushCapsIfChanged();
260
+ this.host?.log.info(`Minecraft 引擎子进程已就绪 pid=${child.pid}`);
261
+ }
262
+
263
+ private teardownChild(): void {
264
+ this.child = null;
265
+ this.ready = false;
266
+ this.declCache = {};
267
+ this.storageCache = [];
268
+ for (const [, p] of this.pending) {
269
+ clearTimeout(p.timer);
270
+ p.reject(new Error('Minecraft 引擎子进程已退出'));
271
+ }
272
+ this.pending.clear();
273
+ }
274
+
275
+ private onExit(code: number | null): void {
276
+ const wasStopping = this.stopping;
277
+ this.teardownChild();
278
+ if (wasStopping) return;
279
+ if (code === CONSOLE_KILL_EXIT_CODE) {
280
+ this.host?.log.warn('Minecraft 引擎子进程收到 0xC000013A 退出状态,宿主退出');
281
+ if (process.listenerCount('SIGINT') > 0) process.emit('SIGINT');
282
+ else process.exit(0);
283
+ return;
284
+ }
285
+ this.host?.log.error(`Minecraft 引擎子进程意外退出(code=${code}),${RESTART_DELAY_MS / 1000}s 后重启`);
286
+ this.host?.pushEvent(
287
+ {
288
+ ts: nowIso(this.opts.timezone ?? 'Asia/Shanghai'),
289
+ source: this.id,
290
+ type: 'minecraft.event',
291
+ text: '[Minecraft] 游戏引擎崩了,正在自动重启;重新连上之前,游戏里的动作都不会生效。',
292
+ senderKey: 'minecraft',
293
+ },
294
+ { trigger: 'flush' },
295
+ ).catch(() => { });
296
+ this.scheduleRestart();
297
+ }
298
+
299
+ private scheduleRestart(): void {
300
+ if (this.restartTimer || this.stopping) return;
301
+ this.restartTimer = setTimeout(() => {
302
+ this.restartTimer = null;
303
+ if (this.stopping) return;
304
+ void this.spawn().catch((err: unknown) => {
305
+ this.host?.log.error('Minecraft 引擎子进程重启失败,继续重试', { err: String(err) });
306
+ this.teardownChild();
307
+ this.scheduleRestart();
308
+ });
309
+ }, RESTART_DELAY_MS);
310
+ this.restartTimer.unref?.();
311
+ }
312
+
313
+
314
+ private onMessage(msg: ChildToMain): void {
315
+ if (msg.t === 'rep') {
316
+ const p = this.pending.get(msg.id);
317
+ if (!p) return;
318
+ this.pending.delete(msg.id);
319
+ clearTimeout(p.timer);
320
+ if (msg.ok) p.resolve(msg.value);
321
+ else p.reject(new Error(msg.error ?? '子进程报错'));
322
+ return;
323
+ }
324
+ if (msg.t === 'hreq') {
325
+ void this.onHostRequest(msg.id, msg.req);
326
+ return;
327
+ }
328
+ this.onNote(msg.note);
329
+ }
330
+
331
+ private async onHostRequest(id: number, req: HostRequest): Promise<void> {
332
+ const child = this.child;
333
+ try {
334
+ const host = this.host;
335
+ if (!host) throw new Error('宿主未接线');
336
+ let value: unknown;
337
+ if (req.kind === 'push') {
338
+ value = await host.pushEvent(req.evt, req.opts);
339
+ } else if (req.kind === 'drain') {
340
+ value = await host.drainPendingEvents((e) => e.source === this.id);
341
+ } else if (req.kind === 'cognition') {
342
+ /** 能力按当前 getter 读取,跨进程只发送白名单字段。 */
343
+ const port = host.cognition;
344
+ value = port
345
+ ? await port.request(req.req)
346
+ : { error: `${COGNITION_ABSENT}(问的时候句柄已经不在了)` };
347
+ }
348
+ child?.send({ t: 'hrep', id, ok: true, value });
349
+ } catch (err) {
350
+ child?.send({ t: 'hrep', id, ok: false, error: err instanceof Error ? err.message : String(err) });
351
+ }
352
+ }
353
+
354
+ private onNote(note: EngineNote): void {
355
+ const host = this.host;
356
+ if (!host) return;
357
+ switch (note.kind) {
358
+ case 'log':
359
+ emitLogNote(host.log, note, this.opts.timezone ?? 'Asia/Shanghai');
360
+ return;
361
+ case 'usage':
362
+ host.reportUsage(note.usage, note.opts);
363
+ return;
364
+ case 'arm-deferred': {
365
+ /** 事件消费时请求子进程渲染;RPC 失败返回 null。 */
366
+ const type = note.type;
367
+ host.pushDeferred(
368
+ {
369
+ type,
370
+ ...(note.senderKey !== undefined ? { senderKey: note.senderKey } : {}),
371
+ ...(note.meta !== undefined ? { meta: note.meta } : {}),
372
+ ...(note.tags !== undefined ? { tags: note.tags } : {}),
373
+ render: async () => {
374
+ try {
375
+ return (await this.rpc(
376
+ { kind: 'render-deferred', type },
377
+ DEFERRED_RENDER_TIMEOUT_MS,
378
+ )) as string | null;
379
+ } catch {
380
+ return null;
381
+ }
382
+ },
383
+ },
384
+ note.trigger !== undefined ? { trigger: note.trigger } : undefined,
385
+ );
386
+ return;
387
+ }
388
+ case 'status':
389
+ this.declCache = note.decl;
390
+ this.storageCache = note.storage;
391
+ return;
392
+ }
393
+ }
394
+
395
+ private rpc(req: EngineRequest, timeoutMs: number): Promise<unknown> {
396
+ const child = this.child;
397
+ if (!child || !child.connected) return Promise.reject(new Error('Minecraft 引擎子进程未运行'));
398
+ const id = this.nextReqId++;
399
+ return new Promise((resolve, reject) => {
400
+ const timer = setTimeout(() => {
401
+ this.pending.delete(id);
402
+ reject(new Error(`子进程 ${timeoutMs / 1000}s 未回执(${req.kind})`));
403
+ }, timeoutMs);
404
+ timer.unref?.();
405
+ this.pending.set(id, { resolve, reject, timer });
406
+ child.send({ t: 'req', id, req });
407
+ });
408
+ }
409
+
410
+ private cast(cast: EngineCast): void {
411
+ const child = this.child;
412
+ if (!child || !child.connected) return;
413
+ child.send({ t: 'cast', cast });
414
+ }
415
+
416
+ /** 每秒采样并推送配置。 */
417
+ private pushConfigIfChanged(): void {
418
+ if (!this.ready) return;
419
+ this.pushCapsIfChanged();
420
+ const json = JSON.stringify(this.opts.cfg);
421
+ if (json === this.lastConfigJson) return;
422
+ this.lastConfigJson = json;
423
+ this.cast({ kind: 'config', cfg: JSON.parse(json) as MinecraftWorldOptions['cfg'] });
424
+ }
425
+
426
+ /** 每次采样调用能力 getter。 */
427
+ private pushCapsIfChanged(): void {
428
+ const on = this.host?.cognition !== undefined;
429
+ if (on === this.lastCaps) return;
430
+ this.lastCaps = on;
431
+ this.cast({ kind: 'caps', cognition: on });
432
+ }
433
+ }
434
+
435
+ function waitExit(child: ChildProcess, timeoutMs: number): Promise<void> {
436
+ if (child.exitCode !== null) return Promise.resolve();
437
+ return new Promise((resolve) => {
438
+ const timer = setTimeout(resolve, timeoutMs);
439
+ timer.unref?.();
440
+ child.once('exit', () => {
441
+ clearTimeout(timer);
442
+ resolve();
443
+ });
444
+ });
445
+ }