castle-web-cli 0.4.232 → 0.4.233

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 (355) hide show
  1. package/dist/agent-failures.d.ts +8 -0
  2. package/dist/agent-failures.js +19 -2
  3. package/dist/agent-prompts.d.ts +1 -1
  4. package/dist/agent-prompts.js +10 -3
  5. package/dist/agent.d.ts +64 -3
  6. package/dist/agent.js +170 -81
  7. package/dist/castle-host/host.d.ts +1 -0
  8. package/dist/castle-host/host.js +51 -3
  9. package/dist/castleJson.d.ts +4 -2
  10. package/dist/castleJson.js +2 -0
  11. package/dist/check.d.ts +3 -1
  12. package/dist/check.js +11 -1
  13. package/dist/devSessionStorage.js +47 -1
  14. package/dist/importPinMismatch.d.ts +22 -0
  15. package/dist/importPinMismatch.js +77 -0
  16. package/dist/importRegression.js +3 -15
  17. package/dist/imports.d.ts +10 -3
  18. package/dist/imports.js +88 -20
  19. package/dist/index.js +5 -4
  20. package/dist/init.js +1 -1
  21. package/dist/platformDoc.js +22 -0
  22. package/dist/routerFences.d.ts +5 -0
  23. package/dist/routerFences.js +12 -2
  24. package/dist/save-deck.d.ts +5 -0
  25. package/dist/save-deck.js +37 -4
  26. package/dist/serve.js +3 -0
  27. package/dist/shell/assets/{index-D2tWM896.js → index-BjOxR-lW.js} +4 -4
  28. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  29. package/dist/shell/index.html +2 -2
  30. package/dist/taskSteer.d.ts +13 -0
  31. package/dist/taskSteer.js +22 -2
  32. package/kits/base/castle.json +1 -1
  33. package/kits/base/package-lock.json +1 -1
  34. package/kits/base/sdk/README.md +79 -2
  35. package/kits/base/sdk/avatar.d.ts +6 -2
  36. package/kits/base/sdk/avatar.js +12 -4
  37. package/kits/base/sdk/castle.d.ts +1 -1
  38. package/kits/base/sdk/commands.d.ts +14 -0
  39. package/kits/base/sdk/hub.d.ts +6 -2
  40. package/kits/base/sdk/hub.js +13 -0
  41. package/kits/base/sdk/multiplayer.js +17 -1
  42. package/kits/base/sdk/save.js +2 -1
  43. package/kits/base/sdk/server/hub.d.ts +87 -0
  44. package/kits/base/sdk/server/hub.js +70 -0
  45. package/kits/base/sdk/server/platformHandle.d.ts +31 -1
  46. package/kits/base/sdk/server/storage.d.ts +13 -0
  47. package/kits/base/sdk/server/storage.js +46 -0
  48. package/kits/base/sdk/server/wrapper.d.ts +36 -5
  49. package/kits/base/sdk/server/wrapper.js +83 -8
  50. package/kits/hub-game/CLAUDE.md +329 -11
  51. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  52. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  53. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  54. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  55. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  56. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  57. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  58. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  59. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  60. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  61. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  62. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  63. package/kits/hub-game/code/client/actorBudget.js +47 -0
  64. package/kits/hub-game/code/client/attention.js +11 -2
  65. package/kits/hub-game/code/client/avatar.js +309 -35
  66. package/kits/hub-game/code/client/avatarCap.js +228 -0
  67. package/kits/hub-game/code/client/avatarColors.js +70 -0
  68. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  69. package/kits/hub-game/code/client/avatarShare.js +251 -0
  70. package/kits/hub-game/code/client/ballot.js +467 -0
  71. package/kits/hub-game/code/client/build.js +22 -0
  72. package/kits/hub-game/code/client/chrome.js +1144 -50
  73. package/kits/hub-game/code/client/companion.js +716 -0
  74. package/kits/hub-game/code/client/companionDress.js +99 -0
  75. package/kits/hub-game/code/client/decor.js +509 -0
  76. package/kits/hub-game/code/client/earned.js +131 -0
  77. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  78. package/kits/hub-game/code/client/grab.js +339 -20
  79. package/kits/hub-game/code/client/hookLayer.js +299 -13
  80. package/kits/hub-game/code/client/idle.js +163 -22
  81. package/kits/hub-game/code/client/interestCap.js +81 -0
  82. package/kits/hub-game/code/client/keys.js +36 -0
  83. package/kits/hub-game/code/client/labelsNear.js +205 -0
  84. package/kits/hub-game/code/client/menuIcons.js +34 -0
  85. package/kits/hub-game/code/client/pack.js +6 -2
  86. package/kits/hub-game/code/client/packFormat.js +3 -3
  87. package/kits/hub-game/code/client/rehello.js +167 -0
  88. package/kits/hub-game/code/client/shot.js +92 -0
  89. package/kits/hub-game/code/client/sound.js +63 -8
  90. package/kits/hub-game/code/client/soundscape.js +1151 -0
  91. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  92. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  93. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  94. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  95. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  96. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  97. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  98. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  99. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  100. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  101. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  102. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  103. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  104. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  105. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  106. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  107. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  108. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  109. package/kits/hub-game/code/client/spin.js +101 -0
  110. package/kits/hub-game/code/client/state.js +109 -1
  111. package/kits/hub-game/code/client/stuck.js +259 -0
  112. package/kits/hub-game/code/client/talk.js +538 -47
  113. package/kits/hub-game/code/client/tiers.js +516 -27
  114. package/kits/hub-game/code/client/toastBand.js +37 -0
  115. package/kits/hub-game/code/client/together.js +32 -0
  116. package/kits/hub-game/code/client/visibility.js +43 -0
  117. package/kits/hub-game/code/client/wear.js +461 -170
  118. package/kits/hub-game/code/client/yours.js +199 -0
  119. package/kits/hub-game/code/companionSpec.js +45 -0
  120. package/kits/hub-game/code/privateText.js +7 -0
  121. package/kits/hub-game/code/server/actions.js +133 -0
  122. package/kits/hub-game/code/server/actors.js +9 -1
  123. package/kits/hub-game/code/server/ask.js +155 -0
  124. package/kits/hub-game/code/server/ballot.js +539 -0
  125. package/kits/hub-game/code/server/cells.js +100 -0
  126. package/kits/hub-game/code/server/companion.js +82 -0
  127. package/kits/hub-game/code/server/cues.js +70 -0
  128. package/kits/hub-game/code/server/decor.js +269 -0
  129. package/kits/hub-game/code/server/earned.js +461 -0
  130. package/kits/hub-game/code/server/friendBests.js +166 -0
  131. package/kits/hub-game/code/server/friendsAmong.js +232 -0
  132. package/kits/hub-game/code/server/history.js +5 -0
  133. package/kits/hub-game/code/server/hub.js +1254 -50
  134. package/kits/hub-game/code/server/idle.js +30 -11
  135. package/kits/hub-game/code/server/index.js +2 -2
  136. package/kits/hub-game/code/server/labels.js +28 -2
  137. package/kits/hub-game/code/server/manifest.js +378 -7
  138. package/kits/hub-game/code/server/menu.js +133 -0
  139. package/kits/hub-game/code/server/npcs.js +830 -80
  140. package/kits/hub-game/code/server/party.js +2 -2
  141. package/kits/hub-game/code/server/players.js +22 -0
  142. package/kits/hub-game/code/server/shot.js +110 -0
  143. package/kits/hub-game/code/server/standing.js +124 -0
  144. package/kits/hub-game/code/server/vis.js +113 -0
  145. package/kits/hub-game/code/server/wear.js +12 -0
  146. package/kits/hub-game/code/server/yours.js +59 -0
  147. package/kits/hub-game/code/shared/cues.js +9 -0
  148. package/kits/hub-game/code/shared/decor.js +41 -0
  149. package/kits/hub-game/code/shared/shot.js +19 -0
  150. package/kits/hub-game/code/shared/spin.js +57 -0
  151. package/kits/hub-game/code/systems/hub.js +845 -95
  152. package/kits/hub-game/docs/content-pack.md +1 -1
  153. package/kits/hub-game/docs/contract.md +2244 -61
  154. package/kits/hub-game/docs/home-pieces.md +64 -0
  155. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  156. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  157. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  158. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  159. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  160. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  161. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  162. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  163. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  164. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  165. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  166. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  167. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  168. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  169. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  170. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  171. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  172. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  173. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  174. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  175. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  176. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  177. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  178. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  179. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  180. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  181. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  182. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  183. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  184. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  185. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  186. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  187. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  188. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  189. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  190. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  191. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  192. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  193. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  194. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  195. package/kits/hub-game/package-lock.json +2 -0
  196. package/kits/hub-game/package.json +2 -1
  197. package/kits/hub-game/scripts/check.mjs +78 -11
  198. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  199. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +121 -0
  200. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  201. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +23 -0
  202. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +107 -0
  203. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  204. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  205. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  206. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  207. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  208. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  209. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  210. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  211. package/kits/hub-game/scripts/test-actions-client.mjs +488 -0
  212. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  213. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  214. package/kits/hub-game/scripts/test-actors.mjs +19 -17
  215. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  216. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  217. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  218. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  219. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  220. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  221. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  222. package/kits/hub-game/scripts/test-avatar-wire.mjs +753 -0
  223. package/kits/hub-game/scripts/test-avatar.mjs +540 -7
  224. package/kits/hub-game/scripts/test-ballot.mjs +1001 -0
  225. package/kits/hub-game/scripts/test-build.mjs +31 -0
  226. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  227. package/kits/hub-game/scripts/test-chat.mjs +662 -0
  228. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  229. package/kits/hub-game/scripts/test-companion-chat.mjs +198 -0
  230. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  231. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  232. package/kits/hub-game/scripts/test-decor-client.mjs +303 -0
  233. package/kits/hub-game/scripts/test-decor.mjs +457 -0
  234. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  235. package/kits/hub-game/scripts/test-earned.mjs +1194 -0
  236. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  237. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  238. package/kits/hub-game/scripts/test-grab-orbit.mjs +918 -0
  239. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  240. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  241. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  242. package/kits/hub-game/scripts/test-hub-ops.mjs +439 -2
  243. package/kits/hub-game/scripts/test-hub-trip.mjs +716 -2
  244. package/kits/hub-game/scripts/test-hud-clear.mjs +328 -4
  245. package/kits/hub-game/scripts/test-idle.mjs +361 -1
  246. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  247. package/kits/hub-game/scripts/test-interest-cells.mjs +493 -0
  248. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  249. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  250. package/kits/hub-game/scripts/test-labels.mjs +596 -0
  251. package/kits/hub-game/scripts/test-manifest.mjs +207 -0
  252. package/kits/hub-game/scripts/test-menu-client.mjs +480 -0
  253. package/kits/hub-game/scripts/test-menu.mjs +296 -0
  254. package/kits/hub-game/scripts/test-npcs.mjs +1718 -12
  255. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  256. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  257. package/kits/hub-game/scripts/test-picker.mjs +314 -0
  258. package/kits/hub-game/scripts/test-rehello.mjs +1039 -0
  259. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  260. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  261. package/kits/hub-game/scripts/test-shot.mjs +756 -0
  262. package/kits/hub-game/scripts/test-soundscape.mjs +5432 -0
  263. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  264. package/kits/hub-game/scripts/test-standing.mjs +416 -0
  265. package/kits/hub-game/scripts/test-stuck.mjs +1903 -0
  266. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  267. package/kits/hub-game/scripts/test-tiers-render.mjs +339 -0
  268. package/kits/hub-game/scripts/test-tiers.mjs +477 -2
  269. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  270. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  271. package/kits/hub-game/scripts/test-vis.mjs +343 -0
  272. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  273. package/kits/hub-game/scripts/test-yours-chrome.mjs +166 -0
  274. package/kits/hub-game/scripts/test-yours.mjs +372 -0
  275. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  276. package/kits/multiplayer-3d/castle.json +5 -5
  277. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  278. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  279. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  280. package/kits/multiplayer-3d/code/options.js +5 -0
  281. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  282. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  283. package/kits/multiplayer-3d/code/server/world.js +7 -0
  284. package/kits/multiplayer-3d/code/systems/multiplayer.js +74 -4
  285. package/kits/multiplayer-3d/package.json +2 -1
  286. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  287. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  288. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  289. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  290. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  291. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  292. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  293. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  294. package/kits/physics-2d/CLAUDE.md +9 -0
  295. package/kits/physics-2d/castle.json +2 -2
  296. package/kits/physics-2d/engine/scene.js +253 -1
  297. package/kits/physics-2d/engine/skyKey.js +129 -0
  298. package/kits/physics-2d/engine/stillClock.js +106 -0
  299. package/kits/physics-2d/engine/updateBudget.js +21 -0
  300. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  301. package/kits/physics-3d/CLAUDE.md +1169 -30
  302. package/kits/physics-3d/behaviors/Player.jsx +629 -72
  303. package/kits/physics-3d/castle.json +3 -3
  304. package/kits/physics-3d/docs/pxmodel-format.md +8 -0
  305. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +69 -13
  306. package/kits/physics-3d/engine3d/actornode.js +86 -0
  307. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  308. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  309. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  310. package/kits/physics-3d/engine3d/framecap.js +96 -0
  311. package/kits/physics-3d/engine3d/gait.js +118 -0
  312. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  313. package/kits/physics-3d/engine3d/look.js +507 -48
  314. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  315. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  316. package/kits/physics-3d/engine3d/motion.js +39 -10
  317. package/kits/physics-3d/engine3d/nearshadows.js +37 -19
  318. package/kits/physics-3d/engine3d/optimize.js +9 -5
  319. package/kits/physics-3d/engine3d/orbitinput.js +487 -9
  320. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  321. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  322. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  323. package/kits/physics-3d/engine3d/shadowfade.js +882 -0
  324. package/kits/physics-3d/engine3d/sky.js +547 -0
  325. package/kits/physics-3d/engine3d/skylife.js +306 -0
  326. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  327. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  328. package/kits/physics-3d/engine3d/world3d.js +796 -69
  329. package/kits/physics-3d/main.jsx +5 -0
  330. package/kits/physics-3d/package.json +1 -1
  331. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  332. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2563 -80
  333. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +1 -1
  334. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +435 -0
  335. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  336. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  337. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  338. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  339. package/kits/physics-3d/scripts/test-near-shadows.mjs +3 -0
  340. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +1920 -0
  341. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +545 -0
  342. package/kits/physics-3d/scripts/test-orbit-shot.mjs +583 -0
  343. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  344. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  345. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  346. package/kits/physics-3d/scripts/test-static-actors.mjs +8 -1
  347. package/kits/physics-3d/scripts/test-static-scenery.mjs +2171 -0
  348. package/kits/physics-3d/scripts/test-steady-hover.mjs +2 -0
  349. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  350. package/kits/physics-3d/systems/physics3d.js +383 -6
  351. package/kits/real-time/castle.json +2 -2
  352. package/kits/real-time/code/server/gameHooks.js +7 -0
  353. package/kits/real-time/code/server/session.js +97 -19
  354. package/package.json +2 -2
  355. package/dist/shell/assets/index-Cf61cNfT.css +0 -1
@@ -3,9 +3,9 @@
3
3
  // character in ghost. This module is the body and the seam to the mind:
4
4
  //
5
5
  // body a `HubNpc` scene actor (kinematic) the kit moves: it faces
6
- // whoever is talking to it and holds still until they are done,
6
+ // a speaker while idle; one-slot bodies hold still until done,
7
7
  // follows a player, walks where the place sends it, goes home
8
- // conversation one player at a time per body. In a session the host brokers
8
+ // conversation one to three speakers per body. In a session the host brokers
9
9
  // the place's characters into (each layer of the place; on an
10
10
  // older SDK, a world joined through the place's `npcs.route`)
11
11
  // the player's words go to the character through the host's
@@ -33,6 +33,22 @@
33
33
  // read from the world's public projection after each reply, so a client
34
34
  // message can neither start nor aim it.
35
35
 
36
+ import { EMOTES } from './idle.js';
37
+ import { warnOnce } from './actors.js';
38
+ import { readNpcTurnsAtOnce } from './manifest.js';
39
+
40
+ // v1.47: a crowd answers a gesture without calling a mind.
41
+ const REACT_RANGE_M = 6;
42
+ const REACT_PLAYER_MS = 4000;
43
+ const REACT_NPC_MS = 8000;
44
+ const REACTIONS = {
45
+ wave: { emote: 'wave', lines: ['Hello there!', 'Hi!', 'Hey, hi!'] },
46
+ dance: { emote: 'dance', lines: ['Nice moves!', 'Ooh, let me try!'] },
47
+ cheer: { emote: 'cheer', lines: ['Woo!', 'Yay!'] },
48
+ bow: { emote: 'bow', lines: ['Likewise!', 'Oh, how polite!'] },
49
+ spin: { emote: 'cheer', lines: ['Whee!', 'Dizzy yet?'] },
50
+ };
51
+
36
52
  const TALK_RANGE_M = 3.5;
37
53
  // A speaker who walks this far from the body has left the conversation.
38
54
  const LEAVE_RANGE_M = 8;
@@ -41,6 +57,18 @@ const FOLLOW_GAP_M = 1.6;
41
57
  const SPEECH_MS = 7000;
42
58
  const SPEECH_MAX = 240;
43
59
  const INPUT_MAX = 280;
60
+ // v1.37: the questions an opening suggests, and how long each may be.
61
+ const ASKS_MAX = 3;
62
+ const ASK_MAX = 40;
63
+ const PERSISTENT_ASKS_MAX = 2;
64
+ // v1.46: questions to offer after the first answer.
65
+ const MORE_MAX = 9;
66
+ const DEFAULT_ASKS = ['Who are you?', 'What do you do here?', 'Tell me a secret!'];
67
+ const DEFAULT_MORE = ["What's your favourite thing here?", 'What should I try first?', 'Do you have any friends here?', "What's the funniest thing you've seen?", 'What do you dream about?', 'What makes you laugh?'];
68
+ // ...and how many players an NPC remembers having met (`npcOpening`'s `met`).
69
+ const MET_MAX = 500;
70
+ // The opening's line in a conversation's notes is not kept under this length.
71
+ const OPENED_MIN = 60;
44
72
  // A conversation nobody has said anything in for this long is over.
45
73
  const IDLE_END_MS = 90_000;
46
74
  // Authored-mode words from one player, at most one per this.
@@ -61,6 +89,15 @@ const FOLLOW_WATCH_MS = 60_000;
61
89
  // NOTES_KEPT issued within NOTES_KEEP_MS is accepted (the speaker's client
62
90
  // may be a moment behind; the newest is accepted however old).
63
91
  export const NOTES_MAX = 700;
92
+ // v1.66 place tools (§13 tools): what a place may declare for one lookup per
93
+ // reply. The same caps as the host's, so a list the kit sends is never dropped
94
+ // there.
95
+ const TOOLS_MAX = 8;
96
+ const TOOL_NAME = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
97
+ const TOOL_RESERVED = new Set(['perform_action', 'capture_claim']);
98
+ const TOOL_DESCRIPTION_MAX = 300;
99
+ const TOOL_SCHEMA_BYTES = 1024;
100
+ const TOOLS_BYTES = 6144;
64
101
  const NOTES_EVERY_MS = 1000;
65
102
  const NOTES_KEPT = 6;
66
103
  const NOTES_KEEP_MS = 60_000;
@@ -71,12 +108,22 @@ export const NOTES_SAYS = '\n[The speaker says]\n';
71
108
  export function makeNpcs(h) {
72
109
  const n = {
73
110
  bodies: new Map(),
111
+ preferred: new Map(),
74
112
  // `${playerId}:${operationId}` -> { npc, speaker, at, delivered }
75
113
  turns: new Map(),
76
114
  // playerId -> durable participant id, from that player's own inspect read
77
115
  participants: new Map(),
116
+ // v1.47: player id -> { userId, body, characters }, private to this visit.
117
+ greetings: new Map(),
118
+ inspectReads: new Map(),
119
+ reactAt: new Map(),
120
+ emotes: new Map(),
121
+ emotesUsed: false,
78
122
  // playerId -> sim time of their last authored-mode words
79
123
  saidAt: new Map(),
124
+ // npc id -> the players (by user id, else player id) who have said
125
+ // something to it since this process started (v1.37, `npcOpening`'s `met`)
126
+ met: new Map(),
80
127
  watchUntil: 0,
81
128
  polledAt: -Infinity,
82
129
  polling: false,
@@ -92,6 +139,7 @@ export function makeNpcs(h) {
92
139
  if (!body) {
93
140
  continue;
94
141
  }
142
+ const turnsAtOnce = readNpcTurnsAtOnce(props.turnsAtOnce, h.place.npcs?.turnsAtOnce ?? 1);
95
143
  const t = actor.components.Transform ?? {};
96
144
  const at = body.translation();
97
145
  n.bodies.set(actor.id, {
@@ -104,8 +152,13 @@ export function makeNpcs(h) {
104
152
  body,
105
153
  home: { x: at.x, y: at.y, z: at.z, yaw: ((t.rotationY ?? 0) * Math.PI) / 180 },
106
154
  yaw: ((t.rotationY ?? 0) * Math.PI) / 180,
107
- // { playerId, at } while someone is talking to it
155
+ // Monotonic per-body sequence, retained when a conversation ends.
156
+ conversation: 0,
157
+ // { playerId, at, conversation, accountKey, body, said } while talking
108
158
  talking: null,
159
+ // Only multi-slot bodies allocate speaker state; the default record
160
+ // and every wire message retain their original shape.
161
+ ...(turnsAtOnce > 1 ? { turnsAtOnce, speakers: new Map() } : {}),
109
162
  // the turn admitted and not yet answered, so a second waits
110
163
  pending: null,
111
164
  // playerId it follows, when that began, and whether the character's
@@ -124,13 +177,16 @@ export function makeNpcs(h) {
124
177
  // { playerId, list: [{ prefix, at }], readAt } the notes issued to
125
178
  // whoever is talking to it
126
179
  notes: null,
180
+ reactedAt: -Infinity,
181
+ speakingUntil: 0,
182
+ reaction: null,
127
183
  });
128
184
  }
129
185
  },
130
186
 
131
187
  // The handle `hub.npc(id)` returns, or null for an actor that is not one.
132
188
  handle(id) {
133
- const npc = n.bodies.get(id);
189
+ const npc = recordOf(n, id);
134
190
  return npc ? handleOf(h, n, npc) : null;
135
191
  },
136
192
 
@@ -138,23 +194,89 @@ export function makeNpcs(h) {
138
194
  return [...n.bodies.values()].map((npc) => handleOf(h, n, npc));
139
195
  },
140
196
 
197
+ // Private, optional hint; admission and range checks are unchanged.
198
+ prefer(playerId, npcId) {
199
+ if (!h.sim?.players.has(playerId) || (npcId !== null && !n.bodies.has(npcId))) {
200
+ return false;
201
+ }
202
+ if ((n.preferred.get(playerId) ?? null) === npcId) {
203
+ return true;
204
+ }
205
+ n.preferred.set(playerId, npcId);
206
+ h.ctx.send(playerId, { k: 'hub-npc-preferred', npc: npcId });
207
+ return true;
208
+ },
209
+
210
+ replayPreferred(playerId, held = false) {
211
+ const npc = n.preferred.get(playerId);
212
+ if (npc || (held && n.preferred.has(playerId))) {
213
+ h.ctx.send(playerId, { k: 'hub-npc-preferred', npc: npc ?? null });
214
+ }
215
+ },
216
+
141
217
  // Before the physics step: where each body goes this tick.
142
218
  place(dt) {
143
219
  for (const npc of n.bodies.values()) {
144
220
  moveBody(h, n, npc, dt);
145
- if (npc.talking && h.sim.timeMs - (npc.notes?.readAt ?? -Infinity) >= NOTES_EVERY_MS) {
146
- issueNotes(h, npc, npc.talking.playerId);
221
+ for (const talking of conversations(npc)) {
222
+ if (h.sim.timeMs - (speakerState(npc, talking.playerId).notes?.readAt ?? -Infinity) >= NOTES_EVERY_MS) {
223
+ issueNotes(h, npc, talking.playerId);
224
+ }
225
+ }
226
+ }
227
+ if (h.place.companionChat) {
228
+ for (const npc of n.virtuals?.values() ?? []) {
229
+ if (!companionOwnerPresent(h, npc.owner)) {
230
+ endTalk(h, n, npc.id, npc.owner, 'left');
231
+ forgetVirtual(n, npc.owner);
232
+ continue;
233
+ }
234
+ if (npc.talking && h.sim.timeMs - npc.talking.at > IDLE_END_MS) {
235
+ endTalk(h, n, npc.id, npc.owner, 'idle');
236
+ }
237
+ if (npc.talking && h.sim.timeMs - (npc.notes?.readAt ?? -Infinity) >= NOTES_EVERY_MS) {
238
+ issueNotes(h, npc, npc.owner);
239
+ }
147
240
  }
148
241
  }
149
242
  pollFollow(h, n);
150
243
  },
151
244
 
245
+ // How many players this NPC is keeping as met (tests).
246
+ metCount: (npcId) => n.met.get(npcId)?.size ?? 0,
247
+
248
+ react(playerId, emote) {
249
+ react(h, n, playerId, emote);
250
+ },
251
+
252
+ // v1.47: even an empty field is withheld until a body has emoted.
253
+ emoteFields() {
254
+ if (!n.emotesUsed) {
255
+ return {};
256
+ }
257
+ const now = h.sim?.timeMs ?? 0;
258
+ for (const [id, emote] of n.emotes) {
259
+ if (now >= emote.until) {
260
+ n.emotes.delete(id);
261
+ }
262
+ }
263
+ return { hubNpcEmotes: Object.fromEntries(n.emotes) };
264
+ },
265
+
152
266
  leave(playerId) {
267
+ n.preferred.delete(playerId);
268
+ if (h.place.companionChat) {
269
+ forgetVirtual(n, playerId);
270
+ }
153
271
  n.participants.delete(playerId);
272
+ n.greetings.delete(playerId);
273
+ n.inspectReads.delete(playerId);
274
+ n.reactAt.delete(playerId);
154
275
  n.saidAt.delete(playerId);
276
+ metLeft(n, playerId);
155
277
  for (const npc of n.bodies.values()) {
156
- if (npc.talking?.playerId === playerId) {
157
- npc.talking = null;
278
+ if (talkingOf(npc, playerId)) {
279
+ clearTalk(npc, playerId);
158
280
  }
159
281
  if (npc.following === playerId) {
160
282
  npc.following = null;
@@ -169,7 +291,7 @@ export function makeNpcs(h) {
169
291
  open(h, n, player.playerId, data.npc);
170
292
  return true;
171
293
  case 'hub-npc-say':
172
- authoredSay(h, n, player.playerId, data.npc, data.text);
294
+ authoredSay(h, n, player.playerId, data.npc, data.text, data.rid);
173
295
  return true;
174
296
  case 'hub-npc-end':
175
297
  endTalk(h, n, data.npc, player.playerId, 'end');
@@ -191,22 +313,97 @@ export function makeNpcs(h) {
191
313
  async onRead(request) {
192
314
  await routeRead(h, n, request);
193
315
  },
316
+ // v1.66: a mind's one lookup for a turn this place admitted (§13 tools).
317
+ async onTool(request) {
318
+ return await answerTool(h, n, request);
319
+ },
194
320
  };
195
321
  return api;
196
322
  }
197
323
 
324
+ // Virtual companions never enter the physical-body registry. No chat key:
325
+ // no virtual registry, records, movement, reactions, or public speech.
326
+ function recordOf(n, id) {
327
+ return n.bodies.get(id) ?? n.virtuals?.get(id);
328
+ }
329
+ function* talkRecords(n) {
330
+ yield* n.bodies.values();
331
+ if (n.virtuals) {
332
+ yield* n.virtuals.values();
333
+ }
334
+ }
335
+ // Speaker state is opt-in: legacy bodies and owner-only virtual companions
336
+ // retain the old fields, including a pending turn after a conversation ends.
337
+ function speakerState(npc, playerId) {
338
+ return npc.speakers ? npc.speakers.get(playerId) : npc;
339
+ }
340
+ function talkingOf(npc, playerId) {
341
+ const talking = speakerState(npc, playerId)?.talking;
342
+ return talking?.playerId === playerId ? talking : null;
343
+ }
344
+ function conversations(npc) {
345
+ return npc.speakers ? [...npc.speakers.values()].flatMap((state) => state.talking ? [state.talking] : []) : npc.talking ? [npc.talking] : [];
346
+ }
347
+ function fullFor(npc, playerId) {
348
+ return !talkingOf(npc, playerId) && conversations(npc).length >= (npc.turnsAtOnce ?? 1);
349
+ }
350
+ function pendingTurn(npc, key) {
351
+ return npc.speakers ? [...npc.speakers.values()].find((state) => state.pending?.key === key)?.pending : npc.pending?.key === key ? npc.pending : null;
352
+ }
353
+ function companionOwnerPresent(h, playerId) {
354
+ const entry = h.players.get(playerId);
355
+ return entry?.arrived && !entry.ended && h.sim?.players.has(playerId) && h.session?.players?.some((p) => p.playerId === playerId);
356
+ }
357
+ function forgetVirtual(n, playerId) {
358
+ const id = `companion:${playerId}`;
359
+ n.virtuals?.delete(id);
360
+ n.met.delete(id);
361
+ for (const [key, turn] of n.turns) {
362
+ if (turn.npc === id) {
363
+ n.turns.delete(key);
364
+ }
365
+ }
366
+ }
367
+ function virtualForOpen(h, n, playerId, id) {
368
+ if (typeof playerId !== 'string' || !playerId || id !== `companion:${playerId}` || !companionOwnerPresent(h, playerId)) {
369
+ return null;
370
+ }
371
+ let npc = n.virtuals?.get(id);
372
+ if (!npc) {
373
+ const { name, character } = h.place.companionChat;
374
+ npc = {
375
+ id, owner: playerId, name, character,
376
+ props: { role: 'companion', name, character },
377
+ talkRange: TALK_RANGE_M, conversation: 0, talking: null, pending: null,
378
+ following: null, walk: null, recent: [], notes: null, followDone: new Set(),
379
+ };
380
+ (n.virtuals ??= new Map()).set(id, npc);
381
+ }
382
+ return npc;
383
+ }
384
+
198
385
  function handleOf(h, n, npc) {
199
386
  return {
200
387
  id: npc.id,
201
388
  name: npc.name,
202
389
  character: npc.character,
203
390
  props: npc.props,
391
+ ...(npc.owner ? { owner: npc.owner } : {}),
204
392
  get at() {
205
- const p = npc.body.translation();
393
+ const p = npc.owner ? h.sim.players.get(npc.owner)?.at : npc.body.translation();
394
+ if (!p) {
395
+ return null;
396
+ }
206
397
  return { x: p.x, y: p.y, z: p.z };
207
398
  },
208
399
  get talkingTo() {
209
- return npc.talking?.playerId ?? null;
400
+ return conversations(npc)[0]?.playerId ?? null;
401
+ },
402
+ get turnsAtOnce() {
403
+ return npc.turnsAtOnce ?? 1;
404
+ },
405
+ get talkingWith() {
406
+ return conversations(npc).map((talking) => talking.playerId);
210
407
  },
211
408
  get following() {
212
409
  return npc.following;
@@ -215,46 +412,159 @@ function handleOf(h, n, npc) {
215
412
  return npc.walk !== null;
216
413
  },
217
414
  get busy() {
218
- return npc.talking !== null || npc.walk !== null || npc.following !== null;
415
+ return !npc.owner && (conversations(npc).length >= (npc.turnsAtOnce ?? 1) || npc.walk !== null || npc.following !== null);
219
416
  },
220
417
  say(text, options = {}) {
418
+ if (npc.owner) {
419
+ return;
420
+ }
221
421
  say(h, npc, text, options);
222
422
  },
223
423
  face(target) {
424
+ if (npc.owner) {
425
+ return;
426
+ }
224
427
  npc.faceTo = target ?? null;
225
428
  },
226
429
  walkTo(at, { stopAt = 0.3, then } = {}) {
430
+ if (npc.owner || npc.movementHeld) {
431
+ return;
432
+ }
227
433
  if (!at || !Number.isFinite(at.x) || !Number.isFinite(at.z)) {
228
434
  return;
229
435
  }
230
436
  npc.walk = { x: at.x, z: at.z, stopAt, then: typeof then === 'function' ? then : null };
231
437
  },
232
438
  home(then) {
439
+ if (npc.owner || npc.movementHeld) {
440
+ return;
441
+ }
233
442
  npc.walk = { x: npc.home.x, z: npc.home.z, stopAt: 0.2, then: typeof then === 'function' ? then : null, home: true };
234
443
  },
235
444
  follow(playerId) {
445
+ if (npc.owner || npc.movementHeld) {
446
+ return;
447
+ }
236
448
  npc.following = playerId ?? null;
237
449
  npc.followSince = h.sim?.timeMs ?? 0;
238
450
  npc.followByToken = false;
239
451
  },
452
+ holdMovement(held) {
453
+ if (npc.owner || Boolean(npc.movementHeld) === Boolean(held)) {
454
+ return;
455
+ }
456
+ npc.movementHeld = Boolean(held);
457
+ if (npc.movementHeld) {
458
+ npc.walk = null;
459
+ npc.following = null;
460
+ // A place can engage its hold after place() queued this tick's step.
461
+ npc.body.setNextKinematicTranslation(npc.body.translation());
462
+ }
463
+ },
240
464
  stop() {
465
+ if (npc.owner) {
466
+ return;
467
+ }
241
468
  npc.walk = null;
242
469
  npc.following = null;
243
470
  },
244
471
  end() {
245
- if (npc.talking) {
246
- endTalk(h, n, npc.id, npc.talking.playerId, 'place');
472
+ for (const talking of conversations(npc)) {
473
+ endTalk(h, n, npc.id, talking.playerId, 'place');
247
474
  }
248
475
  },
249
476
  };
250
477
  }
251
478
 
252
479
  function say(h, npc, text, { to, ttlMs = SPEECH_MS, about } = {}) {
480
+ if (npc.owner) {
481
+ return; // No body, label, snapshot, or public bubble, even for scripted lines.
482
+ }
253
483
  const line = `${npc.name}: ${String(text ?? '')}`.slice(0, SPEECH_MAX);
254
484
  h.npcLabel(npc.id, line, { style: 'speech', ttlMs, to, about });
485
+ // v1.47: gestures wait until even a private line has finished.
486
+ npc.speakingUntil = Math.max(npc.speakingUntil, ttlMs ? (h.sim?.timeMs ?? 0) + ttlMs : Infinity);
487
+ }
488
+
489
+ function react(h, n, playerId, emote) {
490
+ const player = h.sim?.players.get(playerId);
491
+ const entry = h.players?.get(playerId);
492
+ const now = h.sim?.timeMs ?? 0;
493
+ if (!player || (h.players && (!entry?.arrived || entry.ended)) || !Object.hasOwn(REACTIONS, emote) || !n.bodies.size || now - (n.reactAt.get(playerId) ?? -Infinity) < REACT_PLAYER_MS) {
494
+ return;
495
+ }
496
+ n.reactAt.set(playerId, now);
497
+ const nearby = [...n.bodies.values()]
498
+ .filter((npc) => !conversations(npc).length && !(npc.speakers ? [...npc.speakers.values()].some((state) => state.pending) : npc.pending) && !npc.following && !npc.walk && !h.held?.has(npc.id) && !h.moves?.has(npc.id) && !h.resetHolds?.has(npc.id) && !h.hidden?.has(npc.id) && now >= npc.speakingUntil && now - npc.reactedAt >= REACT_NPC_MS)
499
+ .map((npc) => ({ npc, d: distanceTo(h, npc, playerId) }))
500
+ .filter(({ d }) => d <= REACT_RANGE_M)
501
+ .sort((a, b) => a.d - b.d || a.npc.id.localeCompare(b.npc.id));
502
+ let count = 0;
503
+ for (const { npc } of nearby) {
504
+ let override;
505
+ try {
506
+ override = syncHookResult(h, 'npcReact', h.hooks.npcReact?.(h.ctx, handleOf(h, n, npc), playerId, { emote }));
507
+ } catch {
508
+ // No error detail: a place hook may have read private character data.
509
+ warnOnce(h, 'npcReact', 'npcReact hook failed; using the default');
510
+ }
511
+ if (override === false) {
512
+ continue;
513
+ }
514
+ const defaults = REACTIONS[emote];
515
+ const props = npc.props.reactions?.[emote];
516
+ let id = reactionEmote(props?.emote, defaults.emote);
517
+ const lines = Array.isArray(props?.lines) ? props.lines.filter((line) => typeof line === 'string').slice(0, 6).map((line) => cleanLine(line, 80)).filter(Boolean) : defaults.lines;
518
+ // A stable choice per body and tick; no client or model chooses it.
519
+ let seed = Math.floor(now);
520
+ for (const char of npc.id) {
521
+ seed = (Math.imul(seed, 31) + char.charCodeAt(0)) >>> 0;
522
+ }
523
+ let text = seed % 3 === 0 ? lines[Math.floor(seed / 3) % lines.length] : null;
524
+ if (override && typeof override === 'object') {
525
+ id = reactionEmote(override.emote, id);
526
+ if (Object.hasOwn(override, 'line')) {
527
+ text = cleanLine(override.line, 80);
528
+ }
529
+ }
530
+ npc.reactedAt = now;
531
+ npc.reaction = { at: { ...player.at }, until: now + (EMOTES[id] ?? 2000) };
532
+ faceToward(npc, player.at);
533
+ npc.body.setNextKinematicRotation({ x: 0, y: Math.sin(npc.yaw / 2), z: 0, w: Math.cos(npc.yaw / 2) });
534
+ if (id) {
535
+ n.emotesUsed = true;
536
+ n.emotes.set(npc.id, { id, at: now, until: now + EMOTES[id] });
537
+ }
538
+ if (text) {
539
+ say(h, npc, text, { ttlMs: 3000 });
540
+ }
541
+ if (++count === 3) {
542
+ break;
543
+ }
544
+ }
545
+ }
546
+
547
+ function reactionEmote(value, fallback) {
548
+ return value === null ? null : typeof value === 'string' && Object.hasOwn(EMOTES, value) ? value : fallback;
549
+ }
550
+
551
+ function cleanLine(value, max) {
552
+ return typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim().slice(0, max) : '';
553
+ }
554
+
555
+ // v1.47: these hooks answer now; a rejected promise must not expose its error.
556
+ function syncHookResult(h, name, result) {
557
+ if (typeof result?.then === 'function') {
558
+ Promise.resolve(result).catch(() => warnOnce(h, `${name}:async`, `${name} async hook failed; using the default`));
559
+ return null;
560
+ }
561
+ return result;
255
562
  }
256
563
 
257
564
  function distanceTo(h, npc, playerId) {
565
+ if (npc.owner) {
566
+ return 0;
567
+ }
258
568
  const player = h.sim?.players.get(playerId);
259
569
  if (!player) {
260
570
  return Infinity;
@@ -278,23 +588,43 @@ function sessionCharacters(h) {
278
588
  }
279
589
 
280
590
  function open(h, n, playerId, npcId) {
281
- const npc = n.bodies.get(npcId);
591
+ const npc = h.place.companionChat && typeof npcId === 'string' && npcId.startsWith('companion:')
592
+ ? virtualForOpen(h, n, playerId, npcId) : n.bodies.get(npcId);
282
593
  if (!npc || distanceTo(h, npc, playerId) > npc.talkRange) {
283
594
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why: 'far' });
284
595
  return;
285
596
  }
286
- if (npc.talking && npc.talking.playerId !== playerId) {
597
+ if (fullFor(npc, playerId)) {
287
598
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why: 'busy' });
288
599
  line(h, npc, playerId, 'busy');
289
600
  return;
290
601
  }
291
- npc.talking = { playerId, at: h.sim.timeMs };
602
+ const talking = { playerId, at: h.sim.timeMs, conversation: ++npc.conversation, accountKey: metKey(h, playerId), body: h.sim.players.get(playerId), said: false };
603
+ let state = speakerState(npc, playerId);
604
+ if (npc.speakers && !state?.talking) {
605
+ // Reopening a closed slot goes to the back, retaining its in-flight turn.
606
+ npc.speakers.delete(playerId);
607
+ state ??= { talking: null, pending: null, notes: null, opening: null };
608
+ npc.speakers.set(playerId, state);
609
+ }
610
+ state.talking = talking;
292
611
  // A new conversation can ask again for what an earlier one finished.
293
612
  const participant = n.participants.get(playerId);
294
613
  if (participant) {
295
614
  npc.followDone.delete(participant);
296
615
  }
297
616
  const mind = hasMind(h, npc);
617
+ const greeting = mind && !npc.owner ? greetingOf(h, n, playerId, npc.character) : null;
618
+ // v1.46: a mind speaks first even where the place gives it no words.
619
+ let opening = openingOf(h, n, npc, playerId, greeting, talking.conversation) ?? (mind ? { text: `Hi, I'm ${npc.name.split(',')[0].trim()}! Ask me anything.`, asks: [...DEFAULT_ASKS], more: [...DEFAULT_MORE] } : null);
620
+ // v1.47: memory changes this speaker's first words, never the questions.
621
+ if (greeting) {
622
+ opening = { ...opening, text: greeting };
623
+ }
624
+ // v1.47: a place hook may have replaced the speaker while choosing words.
625
+ if (!conversationOf(h, npc, playerId, talking)) {
626
+ return;
627
+ }
298
628
  h.ctx.send(playerId, {
299
629
  k: 'hub-npc',
300
630
  npc: npcId,
@@ -306,53 +636,242 @@ function open(h, n, playerId, npcId) {
306
636
  // turn's listeners: zero has it name nobody.
307
637
  hearRange: 0,
308
638
  disclosure: 'participants',
639
+ // A body without a mind or a place opening keeps its hello line.
640
+ ...(opening ? { opening } : {}),
309
641
  });
310
- npc.notes = null;
642
+ state.notes = null;
643
+ state.opening = opening ? { playerId, text: opening.text } : null;
311
644
  if (!mind) {
312
- line(h, npc, playerId, 'hello');
645
+ // An opening is the NPC's hello; without one, the place's or the kit's.
646
+ if (!opening) {
647
+ line(h, npc, playerId, 'hello');
648
+ }
313
649
  return;
314
650
  }
315
651
  issueNotes(h, npc, playerId);
316
652
  }
317
653
 
654
+ // How this player is known to `met`: their account where they have one.
655
+ function userIdOf(h, playerId) {
656
+ const userId = h.session?.players?.find?.((p) => p.playerId === playerId)?.userId;
657
+ return typeof userId === 'string' && userId ? userId : null;
658
+ }
659
+
660
+ function metKey(h, playerId) {
661
+ const userId = userIdOf(h, playerId);
662
+ return userId ? `u:${userId}` : `p:${playerId}`;
663
+ }
664
+
665
+ function clearTalk(npc, playerId) {
666
+ const state = speakerState(npc, playerId);
667
+ if (!state) {
668
+ return;
669
+ }
670
+ state.talking = null;
671
+ state.opening = null;
672
+ state.notes = null;
673
+ }
674
+
675
+ // v1.47: copies of a greeting in the conversation belong to its account/body too.
676
+ function conversationOf(h, npc, playerId, expected = talkingOf(npc, playerId)) {
677
+ const talking = talkingOf(npc, playerId);
678
+ if (!talking || talking !== expected || talking.playerId !== playerId) {
679
+ return null;
680
+ }
681
+ const body = h.sim?.players.get(playerId);
682
+ if (!body || talking.accountKey !== metKey(h, playerId) || talking.body !== body) {
683
+ clearTalk(npc, playerId);
684
+ if (body) {
685
+ h.ctx.send(playerId, { k: 'hub-npc', npc: npc.id, open: false, why: 'left' });
686
+ }
687
+ return null;
688
+ }
689
+ return talking;
690
+ }
691
+
692
+ function greetingOf(h, n, playerId, character) {
693
+ const cached = n.greetings.get(playerId);
694
+ if (!cached) {
695
+ return null;
696
+ }
697
+ // v1.47: a recycled player id is neither the account nor the body we read.
698
+ if (!cached.userId || cached.userId !== userIdOf(h, playerId) || cached.body !== h.sim?.players.get(playerId)) {
699
+ n.greetings.delete(playerId);
700
+ return null;
701
+ }
702
+ return cached.characters.get(character) ?? null;
703
+ }
704
+
705
+ function refreshOpening(h, n, npc, playerId) {
706
+ const talking = conversationOf(h, npc, playerId);
707
+ const state = speakerState(npc, playerId);
708
+ if (!talking || talking.said || state.opening?.playerId !== playerId || !hasMind(h, npc)) {
709
+ return;
710
+ }
711
+ const text = greetingOf(h, n, playerId, npc.character);
712
+ if (!text || text === state.opening.text) {
713
+ return;
714
+ }
715
+ // v1.47: an approach read can finish after the panel showed its first words.
716
+ state.opening.text = text;
717
+ h.ctx.send(playerId, { k: 'hub-npc-opening', npc: npc.id, text });
718
+ issueNotes(h, npc, playerId, { force: true });
719
+ }
720
+
721
+ // The player said something to this NPC: they have met. Kept only where a
722
+ // place asks (`npcOpening`), for at most MET_MAX players an NPC, the longest
723
+ // ago first to go; a guest (no account) is forgotten when they leave.
724
+ function metNow(h, n, npc, playerId) {
725
+ if (typeof h.hooks.npcOpening !== 'function') {
726
+ return;
727
+ }
728
+ let set = n.met.get(npc.id);
729
+ if (!set) {
730
+ n.met.set(npc.id, (set = new Set()));
731
+ }
732
+ const key = metKey(h, playerId);
733
+ set.delete(key);
734
+ set.add(key);
735
+ while (set.size > MET_MAX) {
736
+ set.delete(set.values().next().value);
737
+ }
738
+ }
739
+
740
+ // A player left: an NPC has not met a guest it could not know again.
741
+ function metLeft(n, playerId) {
742
+ for (const set of n.met.values()) {
743
+ set.delete(`p:${playerId}`);
744
+ }
745
+ }
746
+
747
+ // What an NPC says first when a player opens its chat, and up to three things
748
+ // the player might ask it (v1.37): the place's `npcOpening` hook, shown in
749
+ // that player's panel at once, with no model called. A string is the words
750
+ // alone. v1.46: `more` holds later questions; no words leaves a mind's default.
751
+ function openingOf(h, n, npc, playerId, greeting, conversation) {
752
+ if (typeof h.hooks.npcOpening !== 'function') {
753
+ return null;
754
+ }
755
+ let said = null;
756
+ try {
757
+ said = syncHookResult(h, 'npcOpening', h.hooks.npcOpening(h.ctx, h.ctx.npc(npc.id), playerId, { met: n.met.get(npc.id)?.has(metKey(h, playerId)) === true, greeting, conversation })) ?? null;
758
+ } catch (err) {
759
+ // v1.47: the hook's error may quote this speaker's greeting.
760
+ console.warn(greeting || npc.owner ? '[hub] npcOpening failed' : `[hub] npcOpening failed: ${err?.stack ?? err}`);
761
+ return null;
762
+ }
763
+ const words = typeof said === 'string' ? said : said?.text;
764
+ const text = typeof words === 'string' ? words.trim().slice(0, SPEECH_MAX) : '';
765
+ if (!text) {
766
+ return null;
767
+ }
768
+ const asks = [];
769
+ for (const ask of Array.isArray(said?.asks) ? said.asks : []) {
770
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
771
+ if (question && !asks.includes(question) && asks.length < ASKS_MAX) {
772
+ asks.push(question);
773
+ }
774
+ }
775
+ const more = [];
776
+ for (const ask of Array.isArray(said?.more) ? said.more : []) {
777
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
778
+ if (question && !asks.includes(question) && !more.includes(question) && more.length < MORE_MAX) {
779
+ more.push(question);
780
+ }
781
+ }
782
+ return { text, asks, ...(more.length ? { more } : {}) };
783
+ }
784
+
318
785
  // The place's notes for the character about this speaker now, framed as the
319
786
  // prefix their client sends ahead of their words, or null for none.
320
787
  function notesPrefix(h, npc, playerId) {
788
+ const state = speakerState(npc, playerId);
321
789
  let notes = null;
322
790
  try {
323
791
  notes = h.hooks.npcContext?.(h.ctx, h.ctx.npc(npc.id), playerId) ?? null;
324
792
  } catch (err) {
325
- console.warn(`[hub] npcContext failed: ${err?.stack ?? err}`);
793
+ console.warn(npc.owner ? '[hub] npcContext failed' : `[hub] npcContext failed: ${err?.stack ?? err}`);
326
794
  }
327
- if (typeof notes !== 'string') {
795
+ // v1.37: what the NPC opened this conversation with, so its mind does not
796
+ // greet again or contradict it. Only a place that gives notes at all has
797
+ // any (one without `npcContext` sends its turns as the words alone).
798
+ const opened =
799
+ typeof h.hooks.npcContext === 'function' && state.opening?.playerId === playerId
800
+ ? `You opened this conversation by saying: "${state.opening.text}"`.replace(/[[\]]/g, '')
801
+ : null;
802
+ if (typeof notes !== 'string' && !opened) {
328
803
  return null;
329
804
  }
330
805
  // The frame's brackets are the kit's alone, so nothing in the notes (a
331
806
  // username) can close it early.
332
- const text = notes.replace(/[[\]]/g, '').trim().slice(0, NOTES_MAX);
807
+ let text = typeof notes === 'string' ? notes.replace(/[[\]]/g, '').trim().slice(0, NOTES_MAX) : '';
808
+ // The place's notes come first and whole; the opening has what is left of
809
+ // NOTES_MAX, and is left out where that is too little to say it.
810
+ const room = NOTES_MAX - text.length - (text ? 1 : 0);
811
+ if (opened && room >= Math.min(opened.length, OPENED_MIN)) {
812
+ text = `${text}${text ? '\n' : ''}${opened.slice(0, room)}`;
813
+ }
333
814
  return text ? `${NOTES_HEAD}${text}${NOTES_SAYS}` : null;
334
815
  }
335
816
 
817
+ // v1.80: questions the place keeps on offer, only for this speaker.
818
+ function persistentAsksOf(h, npc, playerId) {
819
+ try {
820
+ const offered = syncHookResult(h, 'npcAsks', h.hooks.npcAsks(h.ctx, h.ctx.npc(npc.id), playerId));
821
+ const asks = [];
822
+ for (const ask of Array.isArray(offered?.persistentAsks) ? offered.persistentAsks : []) {
823
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
824
+ if (question && !asks.includes(question)) {
825
+ asks.push(question);
826
+ if (asks.length === PERSISTENT_ASKS_MAX) {
827
+ break;
828
+ }
829
+ }
830
+ }
831
+ return asks;
832
+ } catch {
833
+ // A hook's error may contain the player's private words.
834
+ warnOnce(h, 'npcAsks', 'npcAsks failed');
835
+ return [];
836
+ }
837
+ }
838
+
336
839
  // Reads the notes for the speaker of a body with a mind and, when they
337
840
  // changed (or `force`, after a turn was refused for its notes), sends them to
338
- // that speaker's client.
841
+ // that speaker's client. A changed chip offer also issues the latest notes.
339
842
  function issueNotes(h, npc, playerId, { force = false } = {}) {
843
+ const talking = conversationOf(h, npc, playerId);
844
+ const state = speakerState(npc, playerId);
340
845
  const now = h.sim.timeMs;
341
- if (!hasMind(h, npc)) {
846
+ if (!talking || !hasMind(h, npc)) {
342
847
  return;
343
848
  }
344
- if (npc.notes?.playerId !== playerId) {
345
- npc.notes = { playerId, list: [], readAt: -Infinity };
849
+ if (state.notes?.playerId !== playerId) {
850
+ state.notes = { playerId, list: [], readAt: -Infinity };
346
851
  }
347
- npc.notes.readAt = now;
852
+ state.notes.readAt = now;
348
853
  const prefix = notesPrefix(h, npc, playerId);
349
- const list = npc.notes.list;
854
+ // v1.80: the place may keep up to two questions on offer after a reply.
855
+ // An absent hook keeps the old notes state and message bytes.
856
+ const persistentAsks = typeof h.hooks.npcAsks === 'function' ? persistentAsksOf(h, npc, playerId) : undefined;
857
+ // Recheck after npcContext and npcAsks, before sending anything private.
858
+ if (!conversationOf(h, npc, playerId, talking)) {
859
+ return;
860
+ }
861
+ const list = state.notes.list;
862
+ let asksChanged = false;
863
+ if (persistentAsks !== undefined) {
864
+ const previous = state.notes.persistentAsks ?? [];
865
+ asksChanged = previous.length !== persistentAsks.length || previous.some((ask, i) => ask !== persistentAsks[i]);
866
+ state.notes.persistentAsks = persistentAsks;
867
+ }
868
+ const asks = persistentAsks === undefined ? {} : { persistentAsks };
350
869
  if ((list.at(-1)?.prefix ?? null) === prefix) {
351
870
  if (list.length) {
352
871
  list.at(-1).at = now;
353
872
  }
354
- if (force) {
355
- h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix });
873
+ if (force || asksChanged) {
874
+ h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix, ...asks });
356
875
  }
357
876
  return;
358
877
  }
@@ -360,7 +879,7 @@ function issueNotes(h, npc, playerId, { force = false } = {}) {
360
879
  while (list.length > NOTES_KEPT) {
361
880
  list.shift();
362
881
  }
363
- h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix });
882
+ h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix, ...asks });
364
883
  }
365
884
 
366
885
  // The player's own words in a turn's input, or null when the input does not
@@ -375,7 +894,8 @@ function wordsOf(h, npc, speaker, input) {
375
894
  return input;
376
895
  }
377
896
  const now = h.sim.timeMs;
378
- const list = npc.notes?.playerId === speaker ? npc.notes.list : [];
897
+ const notes = speakerState(npc, speaker)?.notes;
898
+ const list = notes?.playerId === speaker ? notes.list : [];
379
899
  const accepted = list.filter((e, i) => i === list.length - 1 || now - e.at <= NOTES_KEEP_MS);
380
900
  // Notes first: an accepted empty entry (the place gave none a moment ago)
381
901
  // matches every input, so it is tried last.
@@ -395,21 +915,21 @@ function wordsOf(h, npc, speaker, input) {
395
915
  }
396
916
 
397
917
  function endTalk(h, n, npcId, playerId, why) {
398
- const npc = n.bodies.get(npcId);
399
- if (!npc || npc.talking?.playerId !== playerId) {
918
+ const npc = recordOf(n, npcId);
919
+ if (!npc || !talkingOf(npc, playerId)) {
400
920
  return;
401
921
  }
402
- npc.talking = null;
922
+ clearTalk(npc, playerId);
403
923
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why });
404
924
  }
405
925
 
406
926
  // The place's authored words for this moment (`npcLine`), or the kit's.
407
- function line(h, npc, playerId, why, text) {
927
+ function line(h, npc, playerId, why, text, op, rid, conversation) {
408
928
  let said = null;
409
929
  try {
410
- said = h.hooks.npcLine?.(h.ctx, h.ctx.npc(npc.id), playerId, { why, text: text ?? null }) ?? null;
930
+ said = h.hooks.npcLine?.(h.ctx, h.ctx.npc(npc.id), playerId, { why, text: text ?? null, ...(conversation !== undefined ? { conversation } : {}) }) ?? null;
411
931
  } catch (err) {
412
- console.warn(`[hub] npcLine failed: ${err?.stack ?? err}`);
932
+ console.warn(text !== undefined || npc.owner ? '[hub] npcLine failed' : `[hub] npcLine failed: ${err?.stack ?? err}`);
413
933
  }
414
934
  if (said === null || said === undefined) {
415
935
  said = DEFAULT_LINES[why]?.(npc.name, h.ctx.username(playerId)) ?? null;
@@ -417,9 +937,9 @@ function line(h, npc, playerId, why, text) {
417
937
  if (said) {
418
938
  // The line may name the player (the kit's hello does): nobody a block
419
939
  // hides them from is ever sent it, a player who arrives later included.
420
- say(h, npc, said, { about: playerId });
940
+ say(h, npc, said, { about: playerId, ...(npc.speakers && text !== undefined ? { to: [playerId] } : {}) });
421
941
  // `why` lets the speaker's panel say an answer was scripted, not the mind's.
422
- h.ctx.send(playerId, { k: 'hub-npc-line', npc: npc.id, text: String(said).slice(0, SPEECH_MAX), why });
942
+ h.ctx.send(playerId, { k: 'hub-npc-line', npc: npc.id, text: String(said).slice(0, SPEECH_MAX), why, ...(op ? { op } : {}), ...(rid ? { rid } : {}) });
423
943
  }
424
944
  }
425
945
 
@@ -432,9 +952,13 @@ const DEFAULT_LINES = {
432
952
 
433
953
  // Words to a body with no mind here (the dev serve, a session the host brokers
434
954
  // no characters into): the place answers from its authored lines.
435
- function authoredSay(h, n, playerId, npcId, text) {
436
- const npc = n.bodies.get(npcId);
437
- if (!npc || npc.talking?.playerId !== playerId || typeof text !== 'string') {
955
+ function authoredSay(h, n, playerId, npcId, text, rid) {
956
+ const npc = recordOf(n, npcId);
957
+ if (!npc || typeof text !== 'string') {
958
+ return;
959
+ }
960
+ const talking = conversationOf(h, npc, playerId);
961
+ if (!talking) {
438
962
  return;
439
963
  }
440
964
  const now = h.sim.timeMs;
@@ -442,8 +966,12 @@ function authoredSay(h, n, playerId, npcId, text) {
442
966
  return;
443
967
  }
444
968
  n.saidAt.set(playerId, now);
445
- npc.talking.at = now;
446
- line(h, npc, playerId, 'authored', text.slice(0, INPUT_MAX));
969
+ talking.said = true;
970
+ talking.at = now;
971
+ metNow(h, n, npc, playerId);
972
+ // v1.46: echo only this send's short request id, when its client gave one.
973
+ const requestId = typeof rid === 'string' && rid.length <= 64 ? rid : null;
974
+ line(h, npc, playerId, 'authored', text.slice(0, INPUT_MAX), undefined, requestId, talking.conversation);
447
975
  }
448
976
 
449
977
  // A turn the host granted: the kit admits it only for the player this body is
@@ -452,20 +980,33 @@ function authoredSay(h, n, playerId, npcId, text) {
452
980
  // the speaker's words), inside the character's budget. Anything else is
453
981
  // refused before a model is called.
454
982
  async function admitTurn(h, n, turn) {
983
+ // v1.76: greeting status reads can never name an admitted turn.
984
+ if (typeof turn.operationId === 'string' && turn.operationId.startsWith('greeting:')) {
985
+ turn.reject('HUB_NPC_OPERATION_RESERVED');
986
+ return;
987
+ }
455
988
  const speaker = turn.speaker.playerId;
456
989
  // Several bodies may share one character (the town's barkers): the one this
457
990
  // speaker is talking to.
458
- const bodies = [...n.bodies.values()].filter((b) => b.character === turn.characterId);
459
- const npc = bodies.find((b) => b.talking?.playerId === speaker) ?? bodies[0];
991
+ const bodies = [...talkRecords(n)].filter((b) => b.character === turn.characterId);
992
+ const npc = bodies.find((b) => talkingOf(b, speaker)) ?? bodies[0];
460
993
  const npcs = h.place.npcs;
461
994
  if (!npc || !npcs || !hasMind(h, npc)) {
462
995
  turn.reject('HUB_NPC_UNKNOWN');
463
996
  return;
464
997
  }
465
- if (npc.talking?.playerId !== speaker || distanceTo(h, npc, speaker) > npc.talkRange + 1) {
998
+ if (npc.speakers && fullFor(npc, speaker)) {
999
+ turn.reject('HUB_NPC_BUSY');
1000
+ line(h, npc, speaker, 'busy', undefined, turn.operationId);
1001
+ return;
1002
+ }
1003
+ const talking = conversationOf(h, npc, speaker);
1004
+ if (!talking || distanceTo(h, npc, speaker) > npc.talkRange + 1) {
466
1005
  turn.reject('HUB_NPC_NOT_TALKING');
467
1006
  return;
468
1007
  }
1008
+ const state = speakerState(npc, speaker);
1009
+ const conversation = talking.conversation;
469
1010
  const audience = turn.audience;
470
1011
  if (audience.disclosure !== 'participants' || audience.characterIds.length || audience.players.length) {
471
1012
  turn.reject('HUB_NPC_AUDIENCE');
@@ -475,7 +1016,11 @@ async function admitTurn(h, n, turn) {
475
1016
  // turn already admitted: ghost replays it, so it neither waits behind
476
1017
  // itself nor spends the budget twice.
477
1018
  const key = `${speaker}:${turn.operationId}`;
478
- const existing = n.turns.get(key) ?? (npc.pending?.key === key ? npc.pending : null);
1019
+ const existing = n.turns.get(key) ?? (state.pending?.key === key ? state.pending : null);
1020
+ // v1.47: a sent turn fixes the opening, even if its notes need a retry.
1021
+ if (typeof turn.input === 'string' && turn.input.trim()) {
1022
+ talking.said = true;
1023
+ }
479
1024
  // A replay was checked when it was first admitted; its notes may be gone.
480
1025
  const words = existing ? null : wordsOf(h, npc, speaker, turn.input);
481
1026
  if (!existing && words === null) {
@@ -485,20 +1030,21 @@ async function admitTurn(h, n, turn) {
485
1030
  return;
486
1031
  }
487
1032
  if (!existing) {
488
- if (npc.pending && !npc.pending.delivered && h.sim.timeMs - npc.pending.at < PENDING_MS) {
1033
+ if (state.pending && !state.pending.delivered && h.sim.timeMs - state.pending.at < PENDING_MS) {
489
1034
  turn.reject('HUB_NPC_BUSY');
1035
+ line(h, npc, speaker, 'busy', undefined, turn.operationId);
490
1036
  return;
491
1037
  }
492
1038
  const now = Date.now();
493
1039
  npc.recent = npc.recent.filter((at) => now - at < 60_000);
494
1040
  if (npc.recent.length >= npcs.turnsPerMinute) {
495
1041
  turn.reject('HUB_NPC_BUDGET');
496
- line(h, npc, speaker, 'budget');
1042
+ line(h, npc, speaker, 'budget', undefined, turn.operationId);
497
1043
  return;
498
1044
  }
499
1045
  npc.recent.push(now);
500
1046
  }
501
- npc.talking.at = h.sim.timeMs;
1047
+ talking.at = h.sim.timeMs;
502
1048
  const record = existing ?? {
503
1049
  key,
504
1050
  npc: npc.id,
@@ -508,16 +1054,25 @@ async function admitTurn(h, n, turn) {
508
1054
  };
509
1055
  // Only a new turn takes the body; a replay leaves whatever holds it.
510
1056
  if (!existing) {
511
- npc.pending = record;
1057
+ state.pending = record;
1058
+ }
1059
+ // v1.66: the place's tools ride with a new turn; a replay keeps the first
1060
+ // admission's. Without `npcTools` this is the send as it always was.
1061
+ if (!existing && typeof h.hooks.npcTools === 'function') {
1062
+ record.tools = placeTools(h, npc, speaker);
512
1063
  }
513
1064
  try {
514
- await turn.send();
1065
+ if (record.tools) {
1066
+ await turn.send({ tools: record.tools.list });
1067
+ } else {
1068
+ await turn.send();
1069
+ }
515
1070
  } catch (err) {
516
- if (npc.pending === record && !existing) {
517
- npc.pending = null;
1071
+ if (state.pending === record && !existing) {
1072
+ state.pending = null;
518
1073
  }
519
- // Ghost's place-mind queue for this character is full (one running, ten
520
- // waiting town-wide): the place's busy line, not its unavailable one.
1074
+ // Ghost's place-mind capacity for this character is full: the place's
1075
+ // busy line, not its unavailable one.
521
1076
  // Ghost's town-wide budget for this character is spent this minute: the
522
1077
  // place's budget line, as for its own per-character budget.
523
1078
  const why =
@@ -526,19 +1081,130 @@ async function admitTurn(h, n, turn) {
526
1081
  : err?.code === 'CAULDRON_SHARED_CHARACTER_BUDGET'
527
1082
  ? 'budget'
528
1083
  : 'unavailable';
529
- line(h, npc, speaker, why);
1084
+ if (!npc.owner || recordOf(n, npc.id) === npc) {
1085
+ line(h, npc, speaker, why, undefined, turn.operationId);
1086
+ }
530
1087
  throw err;
531
1088
  }
532
1089
  // A replayed admission keeps the first record, so a reply is shown once.
533
1090
  if (!existing) {
1091
+ if (npc.owner && recordOf(n, npc.id) !== npc) {
1092
+ return;
1093
+ }
534
1094
  n.turns.set(key, record);
535
1095
  trimTurns(h, n);
536
- // What the speaker said, for the place (a quest-giver asked for another).
537
- try {
538
- h.hooks.npcHeard?.(h.ctx, h.ctx.npc(npc.id), speaker, { text: words });
539
- } catch (err) {
540
- console.warn(`[hub] npcHeard failed: ${err?.stack ?? err}`);
1096
+ // The words belong to the opening and identity that admitted them,
1097
+ // even when the same player id opens another conversation mid-send.
1098
+ if (talkingOf(npc, speaker)?.conversation === conversation && conversationOf(h, npc, speaker, talking)) {
1099
+ metNow(h, n, npc, speaker);
1100
+ try {
1101
+ syncHookResult(h, 'npcHeard', h.hooks.npcHeard?.(h.ctx, h.ctx.npc(npc.id), speaker, { text: words, conversation }));
1102
+ } catch {
1103
+ console.warn('[hub] npcHeard failed');
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+
1109
+ // The place's declarations for this turn, kept only when every cap holds;
1110
+ // a bad entry is dropped, so a place's mistake costs a lookup, never a turn.
1111
+ function placeTools(h, npc, speaker) {
1112
+ let declared;
1113
+ try {
1114
+ // Read at admission and answered at once: a promise is no declarations.
1115
+ declared = syncHookResult(h, 'npcTools', h.hooks.npcTools(h.ctx, h.ctx.npc(npc.id), speaker));
1116
+ } catch {
1117
+ console.warn('[hub] npcTools failed');
1118
+ return null;
1119
+ }
1120
+ if (!Array.isArray(declared)) {
1121
+ return null;
1122
+ }
1123
+ try {
1124
+ return toolList(declared);
1125
+ } catch {
1126
+ console.warn('[hub] npcTools declarations unusable');
1127
+ return null;
1128
+ }
1129
+ }
1130
+
1131
+ function toolList(declared) {
1132
+ const list = [];
1133
+ const names = new Set();
1134
+ for (const tool of declared) {
1135
+ if (list.length >= TOOLS_MAX) {
1136
+ break;
541
1137
  }
1138
+ const entry = toolEntry(tool);
1139
+ if (!entry || names.has(entry.name)) {
1140
+ continue;
1141
+ }
1142
+ if (Buffer.byteLength(JSON.stringify([...list, entry]), 'utf8') > TOOLS_BYTES) {
1143
+ break;
1144
+ }
1145
+ names.add(entry.name);
1146
+ list.push(entry);
1147
+ }
1148
+ return list.length ? { list, names, used: false } : null;
1149
+ }
1150
+
1151
+ function toolEntry(tool) {
1152
+ if (!tool || typeof tool !== 'object') {
1153
+ return null;
1154
+ }
1155
+ const { name, description, input_schema: schema } = tool;
1156
+ if (typeof name !== 'string' || !TOOL_NAME.test(name) || TOOL_RESERVED.has(name)) {
1157
+ return null;
1158
+ }
1159
+ if (typeof description !== 'string' || !description.trim() || description.length > TOOL_DESCRIPTION_MAX) {
1160
+ return null;
1161
+ }
1162
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
1163
+ return null;
1164
+ }
1165
+ let text;
1166
+ try {
1167
+ text = JSON.stringify(schema);
1168
+ } catch {
1169
+ return null;
1170
+ }
1171
+ // A toJSON can make an object serialize as anything, or nothing.
1172
+ if (typeof text !== 'string' || !text.startsWith('{') || Buffer.byteLength(text, 'utf8') > TOOL_SCHEMA_BYTES) {
1173
+ return null;
1174
+ }
1175
+ return { name, description, input_schema: JSON.parse(text) };
1176
+ }
1177
+
1178
+ // One lookup: only for a turn this place admitted for that speaker and
1179
+ // character, only a tool it declared for that turn, and once. Anything else
1180
+ // answers an error and runs no hook. The place's answer goes to the mind
1181
+ // alone; the SDK caps and sends it.
1182
+ async function answerTool(h, n, request) {
1183
+ const { operationId, characterId, playerId, name, input } = request ?? {};
1184
+ const key = `${playerId}:${operationId}`;
1185
+ const record = n.turns.get(key) ?? [...talkRecords(n)].map((b) => pendingTurn(b, key)).find(Boolean) ?? null;
1186
+ const npc = record ? recordOf(n, record.npc) : null;
1187
+ if (
1188
+ !record?.tools ||
1189
+ record.speaker !== playerId ||
1190
+ !npc ||
1191
+ npc.character !== characterId ||
1192
+ !record.tools.names.has(name) ||
1193
+ record.tools.used ||
1194
+ !h.sim?.players.has(playerId) ||
1195
+ typeof h.hooks.npcTool !== 'function'
1196
+ ) {
1197
+ return { error: 'not available' };
1198
+ }
1199
+ record.tools.used = true;
1200
+ const started = Date.now();
1201
+ try {
1202
+ const answer = await h.hooks.npcTool(h.ctx, h.ctx.npc(npc.id), playerId, name, input ?? {});
1203
+ console.log(`[hub] npc tool ${name} ${Date.now() - started}ms`);
1204
+ return answer ?? { error: 'no answer' };
1205
+ } catch {
1206
+ console.warn(`[hub] npc tool ${name} failed`);
1207
+ return { error: 'tool failed' };
542
1208
  }
543
1209
  }
544
1210
 
@@ -561,15 +1227,80 @@ async function routeRead(h, n, request) {
561
1227
  request.reject('HUB_NPC_READ_NOT_ALLOWED');
562
1228
  return;
563
1229
  }
564
- const result = await request.read();
565
1230
  const speaker = request.speaker.playerId;
566
- if (type === 'inspect' && typeof result?.participantId === 'string') {
567
- n.participants.set(speaker, result.participantId);
1231
+ const body = h.sim?.players.get(speaker);
1232
+ const userId = userIdOf(h, speaker);
1233
+ const operationId = request.query.operationId;
1234
+ const read = {};
1235
+ if (type === 'inspect') {
1236
+ n.inspectReads.set(speaker, read);
1237
+ }
1238
+ let result;
1239
+ try {
1240
+ result = await request.read();
1241
+ } catch (err) {
1242
+ if (n.inspectReads.get(speaker) === read) {
1243
+ n.inspectReads.delete(speaker);
1244
+ }
1245
+ throw err;
1246
+ }
1247
+ if (type === 'inspect') {
1248
+ // v1.47: a read finishing after departure cannot restore private data.
1249
+ if (n.inspectReads.get(speaker) !== read) {
1250
+ return;
1251
+ }
1252
+ n.inspectReads.delete(speaker);
1253
+ if (!body || h.sim?.players.get(speaker) !== body || userIdOf(h, speaker) !== userId) {
1254
+ return;
1255
+ }
1256
+ if (typeof result?.participantId === 'string') {
1257
+ n.participants.set(speaker, result.participantId);
1258
+ }
1259
+ if (!userId) {
1260
+ n.greetings.delete(speaker);
1261
+ return;
1262
+ }
1263
+ const greetings = new Map();
1264
+ for (const character of Array.isArray(result?.characters) ? result.characters : []) {
1265
+ const text = cleanLine(character?.privateState?.nextGreeting?.text, SPEECH_MAX);
1266
+ if (typeof character?.characterId === 'string' && text) {
1267
+ greetings.set(character.characterId, text);
1268
+ }
1269
+ }
1270
+ n.greetings.set(speaker, { userId, body, characters: greetings });
1271
+ const hooks = [];
1272
+ for (const npc of n.bodies.values()) {
1273
+ refreshOpening(h, n, npc, speaker);
1274
+ if (!npc.owner && hasMind(h, npc) && h.sim.bodies.get(npc.id) === npc.body && greetings.has(npc.character)) {
1275
+ hooks.push({ npc: npc.id, character: npc.character });
1276
+ }
1277
+ }
1278
+ if (hooks.length && h.sim?.players.get(speaker) === body && userIdOf(h, speaker) === userId) {
1279
+ h.ctx.send(speaker, { k: 'hub-npc-hooks', hooks });
1280
+ }
568
1281
  return;
569
1282
  }
570
1283
  if (type !== 'status') {
571
1284
  return;
572
1285
  }
1286
+ // v1.76: ghost consumes this hook once, separately from turn status.
1287
+ if (typeof operationId === 'string' && operationId.startsWith('greeting:')) {
1288
+ const character = operationId.slice('greeting:'.length);
1289
+ const text = cleanLine(result?.greeting?.text, SPEECH_MAX);
1290
+ if (!userId || !body || h.sim?.players.get(speaker) !== body || userIdOf(h, speaker) !== userId || !character || result?.characterId !== character || !text) {
1291
+ return;
1292
+ }
1293
+ const nearby = [...n.bodies.values()]
1294
+ .filter((npc) => !npc.owner && npc.character === character && hasMind(h, npc) && h.sim.bodies.get(npc.id) === npc.body && !fullFor(npc, speaker))
1295
+ .map((npc) => ({ npc, d: distanceTo(h, npc, speaker) }))
1296
+ // The Chat prompt's range plus 2 m allows for movement during the read.
1297
+ .filter(({ npc, d }) => d <= npc.talkRange + 2)
1298
+ .sort((a, b) => a.d - b.d || a.npc.id.localeCompare(b.npc.id));
1299
+ if (nearby.length) {
1300
+ say(h, nearby[0].npc, text, { to: [speaker], about: speaker });
1301
+ }
1302
+ return;
1303
+ }
573
1304
  const turn = n.turns.get(`${speaker}:${request.query.operationId}`);
574
1305
  const done = result?.status === 'completed' || result?.status === 'interrupted';
575
1306
  if (!turn || turn.delivered || !done) {
@@ -578,16 +1309,20 @@ async function routeRead(h, n, request) {
578
1309
  // Finished, with words or without (an interrupted turn may have none):
579
1310
  // either way the body is free for its next turn.
580
1311
  turn.delivered = true;
581
- const npc = n.bodies.get(turn.npc);
1312
+ const npc = recordOf(n, turn.npc);
582
1313
  if (!npc) {
583
1314
  return;
584
1315
  }
585
- if (npc.pending === turn) {
586
- npc.pending = null;
1316
+ const state = speakerState(npc, speaker);
1317
+ if (state?.pending === turn) {
1318
+ state.pending = null;
587
1319
  }
588
1320
  if (typeof result.response === 'string' && result.response.trim() && h.sim?.players.has(turn.speaker)) {
589
1321
  say(h, npc, unquote(result.response), { to: [turn.speaker], about: turn.speaker });
590
1322
  }
1323
+ if (npc.owner) {
1324
+ return; // The owner reads the reply in the panel; no follow or public read.
1325
+ }
591
1326
  // The reply may have come with the character's follow action.
592
1327
  n.watchUntil = h.sim.timeMs + FOLLOW_WATCH_MS;
593
1328
  n.polledAt = -Infinity;
@@ -628,7 +1363,7 @@ function pollFollow(h, n) {
628
1363
  function applyFollow(h, n, view) {
629
1364
  const objects = view?.gameplay?.objects ?? {};
630
1365
  for (const npc of n.bodies.values()) {
631
- if (!npc.followObject) {
1366
+ if (!npc.followObject || npc.movementHeld) {
632
1367
  continue;
633
1368
  }
634
1369
  const holder = objects[npc.followObject]?.holderId ?? null;
@@ -645,18 +1380,29 @@ function applyFollow(h, n, view) {
645
1380
  }
646
1381
  }
647
1382
 
648
- // One body's tick: a conversation holds it facing its speaker; otherwise it
649
- // walks where the place sent it, or follows, or faces what it was told to.
1383
+ // One body's tick: a conversation holds it facing its speaker; a reaction
1384
+ // holds it until expiry, then queued place movement and idle facing resume.
650
1385
  function moveBody(h, n, npc, dt) {
651
1386
  const now = h.sim.timeMs;
652
- if (npc.talking) {
653
- const gone = !h.sim.players.has(npc.talking.playerId);
654
- const idle = now - npc.talking.at > IDLE_END_MS;
655
- const far = distanceTo(h, npc, npc.talking.playerId) > LEAVE_RANGE_M;
1387
+ for (const talking of conversations(npc)) {
1388
+ const gone = !h.sim.players.has(talking.playerId);
1389
+ const idle = now - talking.at > IDLE_END_MS;
1390
+ const far = distanceTo(h, npc, talking.playerId) > LEAVE_RANGE_M;
656
1391
  if (gone || idle || far) {
657
- endTalk(h, n, npc.id, npc.talking.playerId, gone ? 'left' : idle ? 'idle' : 'far');
1392
+ endTalk(h, n, npc.id, talking.playerId, gone ? 'left' : idle ? 'idle' : 'far');
658
1393
  }
659
1394
  }
1395
+ // A closed speaker retains its turn until delivered or timed out, just as
1396
+ // the legacy body does, without retaining notes or occupying a slot.
1397
+ for (const [playerId, state] of npc.speakers ?? []) {
1398
+ if (!state.talking && (!state.pending || state.pending.delivered || now - state.pending.at >= PENDING_MS)) {
1399
+ npc.speakers.delete(playerId);
1400
+ }
1401
+ }
1402
+ if (npc.movementHeld) {
1403
+ npc.body.setNextKinematicTranslation(npc.body.translation());
1404
+ return;
1405
+ }
660
1406
  const followLimit = (h.place.npcs?.followSec ?? 120) * 1000;
661
1407
  if (npc.following && (!h.sim.players.has(npc.following) || now - npc.followSince > followLimit)) {
662
1408
  const participant = n.participants.get(npc.following);
@@ -668,8 +1414,12 @@ function moveBody(h, n, npc, dt) {
668
1414
  }
669
1415
 
670
1416
  let next = null;
671
- if (npc.talking) {
672
- faceToward(npc, h.sim.players.get(npc.talking.playerId)?.at);
1417
+ const talking = conversations(npc)[0];
1418
+ if (talking && (!npc.speakers || (!npc.walk && !npc.following))) {
1419
+ faceToward(npc, h.sim.players.get(talking.playerId)?.at);
1420
+ } else if (npc.reaction && now < npc.reaction.until) {
1421
+ // A place may queue a station return while this reaction is under way.
1422
+ faceToward(npc, npc.reaction.at);
673
1423
  } else if (npc.walk) {
674
1424
  const w = npc.walk;
675
1425
  const step = stepToward(npc, w.x, w.z, w.stopAt, dt);