castle-web-cli 0.4.232 → 0.4.234

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 (587) 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/api.d.ts +11 -0
  8. package/dist/api.js +43 -0
  9. package/dist/bundle.d.ts +64 -0
  10. package/dist/bundle.js +558 -2
  11. package/dist/castle-host/host.d.ts +18 -2
  12. package/dist/castle-host/host.js +844 -39
  13. package/dist/castleJson.d.ts +23 -2
  14. package/dist/castleJson.js +46 -2
  15. package/dist/check.d.ts +3 -1
  16. package/dist/check.js +20 -3
  17. package/dist/chunkLoader.d.ts +3 -0
  18. package/dist/chunkLoader.js +111 -0
  19. package/dist/devParty.d.ts +26 -0
  20. package/dist/devParty.js +231 -0
  21. package/dist/devSaveStorage.js +4 -0
  22. package/dist/devSessionStorage.js +50 -2
  23. package/dist/devSocial.d.ts +24 -0
  24. package/dist/devSocial.js +70 -0
  25. package/dist/ide.d.ts +2 -0
  26. package/dist/ide.js +119 -15
  27. package/dist/importPinMismatch.d.ts +22 -0
  28. package/dist/importPinMismatch.js +77 -0
  29. package/dist/importRegression.js +3 -15
  30. package/dist/imports.d.ts +10 -3
  31. package/dist/imports.js +88 -20
  32. package/dist/index.js +11 -4
  33. package/dist/init.js +1 -1
  34. package/dist/platformDoc.js +22 -0
  35. package/dist/routerFences.d.ts +5 -0
  36. package/dist/routerFences.js +12 -2
  37. package/dist/save-deck.d.ts +25 -1
  38. package/dist/save-deck.js +178 -9
  39. package/dist/serve.js +32 -11
  40. package/dist/shell/assets/{index-D2tWM896.js → index-DulbYIJm.js} +97 -97
  41. package/dist/shell/assets/index-MVLfNYd9.css +1 -0
  42. package/dist/shell/index.html +2 -2
  43. package/dist/taskSteer.d.ts +13 -0
  44. package/dist/taskSteer.js +22 -2
  45. package/dist/vitePlugins.d.ts +2 -1
  46. package/dist/vitePlugins.js +13 -0
  47. package/kits/base/castle.json +1 -1
  48. package/kits/base/package-lock.json +1 -1
  49. package/kits/base/sdk/README.md +339 -5
  50. package/kits/base/sdk/avatar.d.ts +6 -2
  51. package/kits/base/sdk/avatar.js +12 -4
  52. package/kits/base/sdk/castle.d.ts +7 -3
  53. package/kits/base/sdk/castle.js +2 -0
  54. package/kits/base/sdk/commands.d.ts +176 -1
  55. package/kits/base/sdk/commands.js +3 -0
  56. package/kits/base/sdk/display.d.ts +3 -0
  57. package/kits/base/sdk/display.js +9 -3
  58. package/kits/base/sdk/hub.d.ts +37 -6
  59. package/kits/base/sdk/hub.js +63 -4
  60. package/kits/base/sdk/multiplayer.d.ts +7 -1
  61. package/kits/base/sdk/multiplayer.js +148 -32
  62. package/kits/base/sdk/multiplayerProtocol.d.ts +2 -0
  63. package/kits/base/sdk/party.d.ts +23 -0
  64. package/kits/base/sdk/party.js +91 -0
  65. package/kits/base/sdk/reconnectBudget.d.ts +23 -0
  66. package/kits/base/sdk/reconnectBudget.js +96 -0
  67. package/kits/base/sdk/save.d.ts +38 -1
  68. package/kits/base/sdk/save.js +81 -7
  69. package/kits/base/sdk/server/hub.d.ts +117 -0
  70. package/kits/base/sdk/server/hub.js +119 -2
  71. package/kits/base/sdk/server/platformHandle.d.ts +43 -1
  72. package/kits/base/sdk/server/storage.d.ts +17 -0
  73. package/kits/base/sdk/server/storage.js +65 -3
  74. package/kits/base/sdk/server/wrapper.d.ts +43 -6
  75. package/kits/base/sdk/server/wrapper.js +93 -9
  76. package/kits/base/sdk/social.d.ts +9 -0
  77. package/kits/base/sdk/social.js +5 -0
  78. package/kits/hub-game/CLAUDE.md +451 -13
  79. package/kits/hub-game/README.md +63 -0
  80. package/kits/hub-game/blueprints/avatar-10.scene +28 -0
  81. package/kits/hub-game/blueprints/avatar-11.scene +28 -0
  82. package/kits/hub-game/blueprints/avatar-12.scene +28 -0
  83. package/kits/hub-game/blueprints/avatar-13.scene +28 -0
  84. package/kits/hub-game/blueprints/avatar-14.scene +28 -0
  85. package/kits/hub-game/blueprints/avatar-15.scene +28 -0
  86. package/kits/hub-game/blueprints/avatar-4.scene +28 -0
  87. package/kits/hub-game/blueprints/avatar-5.scene +28 -0
  88. package/kits/hub-game/blueprints/avatar-6.scene +28 -0
  89. package/kits/hub-game/blueprints/avatar-7.scene +28 -0
  90. package/kits/hub-game/blueprints/avatar-8.scene +28 -0
  91. package/kits/hub-game/blueprints/avatar-9.scene +28 -0
  92. package/kits/hub-game/castle.json +5 -5
  93. package/kits/hub-game/code/client/act.js +312 -0
  94. package/kits/hub-game/code/client/actionLayout.js +147 -0
  95. package/kits/hub-game/code/client/actionOverflow.js +556 -0
  96. package/kits/hub-game/code/client/actorBudget.js +47 -0
  97. package/kits/hub-game/code/client/arrivalCamera.js +50 -0
  98. package/kits/hub-game/code/client/askSlot.js +117 -0
  99. package/kits/hub-game/code/client/attention.js +11 -2
  100. package/kits/hub-game/code/client/avatar.js +311 -35
  101. package/kits/hub-game/code/client/avatarCap.js +228 -0
  102. package/kits/hub-game/code/client/avatarColors.js +70 -0
  103. package/kits/hub-game/code/client/avatarFaces.js +21 -0
  104. package/kits/hub-game/code/client/avatarShare.js +253 -0
  105. package/kits/hub-game/code/client/backVisibility.js +13 -0
  106. package/kits/hub-game/code/client/ballot.js +472 -0
  107. package/kits/hub-game/code/client/build.js +38 -0
  108. package/kits/hub-game/code/client/chat.js +41 -5
  109. package/kits/hub-game/code/client/chatModeration.js +5 -0
  110. package/kits/hub-game/code/client/chrome.js +2144 -160
  111. package/kits/hub-game/code/client/companion.js +716 -0
  112. package/kits/hub-game/code/client/companionDress.js +99 -0
  113. package/kits/hub-game/code/client/crowdNames.js +241 -0
  114. package/kits/hub-game/code/client/decor.js +515 -0
  115. package/kits/hub-game/code/client/defaultEnvironment.js +194 -0
  116. package/kits/hub-game/code/client/doorErrors.js +39 -0
  117. package/kits/hub-game/code/client/earned.js +131 -0
  118. package/kits/hub-game/code/client/emoteBubble.js +75 -0
  119. package/kits/hub-game/code/client/fall.js +18 -0
  120. package/kits/hub-game/code/client/farAvatars.js +233 -0
  121. package/kits/hub-game/code/client/firstJoin.js +9 -2
  122. package/kits/hub-game/code/client/fpsTelemetry.js +50 -0
  123. package/kits/hub-game/code/client/frameBatch.js +5 -0
  124. package/kits/hub-game/code/client/grab.js +368 -29
  125. package/kits/hub-game/code/client/hookLayer.js +385 -20
  126. package/kits/hub-game/code/client/hudCopy.js +51 -0
  127. package/kits/hub-game/code/client/hudRate.js +20 -0
  128. package/kits/hub-game/code/client/idle.js +177 -24
  129. package/kits/hub-game/code/client/interestCap.js +81 -0
  130. package/kits/hub-game/code/client/invites.js +231 -0
  131. package/kits/hub-game/code/client/joinError.js +9 -0
  132. package/kits/hub-game/code/client/keys.js +36 -0
  133. package/kits/hub-game/code/client/labelsNear.js +234 -0
  134. package/kits/hub-game/code/client/landscapeLayout.js +17 -0
  135. package/kits/hub-game/code/client/layoutCache.js +264 -0
  136. package/kits/hub-game/code/client/loadTelemetry.js +20 -0
  137. package/kits/hub-game/code/client/loadingCover.js +148 -0
  138. package/kits/hub-game/code/client/loadingEntry.js +8 -0
  139. package/kits/hub-game/code/client/menuIcons.js +34 -0
  140. package/kits/hub-game/code/client/menuRows.js +43 -0
  141. package/kits/hub-game/code/client/modelReady.js +7 -0
  142. package/kits/hub-game/code/client/pack.js +6 -2
  143. package/kits/hub-game/code/client/packFormat.js +3 -3
  144. package/kits/hub-game/code/client/padCueArrival.js +23 -0
  145. package/kits/hub-game/code/client/padCues.js +112 -0
  146. package/kits/hub-game/code/client/padOccupancy.js +88 -0
  147. package/kits/hub-game/code/client/padReadability.js +26 -0
  148. package/kits/hub-game/code/client/padRings.js +69 -0
  149. package/kits/hub-game/code/client/pushVisit.js +14 -0
  150. package/kits/hub-game/code/client/quality.js +205 -0
  151. package/kits/hub-game/code/client/qualityEntry.js +55 -0
  152. package/kits/hub-game/code/client/rehello.js +167 -0
  153. package/kits/hub-game/code/client/safeLayout.js +338 -0
  154. package/kits/hub-game/code/client/safeStyle.js +42 -0
  155. package/kits/hub-game/code/client/say.js +12 -3
  156. package/kits/hub-game/code/client/shot.js +146 -0
  157. package/kits/hub-game/code/client/shotFit.js +56 -0
  158. package/kits/hub-game/code/client/signIn.js +28 -0
  159. package/kits/hub-game/code/client/sound.js +63 -8
  160. package/kits/hub-game/code/client/soundscape.js +1151 -0
  161. package/kits/hub-game/code/client/soundscapeActions.js +99 -0
  162. package/kits/hub-game/code/client/soundscapeAmbience.js +453 -0
  163. package/kits/hub-game/code/client/soundscapeBaked.js +143 -0
  164. package/kits/hub-game/code/client/soundscapeBusker.js +217 -0
  165. package/kits/hub-game/code/client/soundscapeCourt.js +200 -0
  166. package/kits/hub-game/code/client/soundscapeCrowd.js +331 -0
  167. package/kits/hub-game/code/client/soundscapeCues.js +362 -0
  168. package/kits/hub-game/code/client/soundscapeMap.js +181 -0
  169. package/kits/hub-game/code/client/soundscapeMarket.js +176 -0
  170. package/kits/hub-game/code/client/soundscapeMusic.js +126 -0
  171. package/kits/hub-game/code/client/soundscapeMusicEngine.js +460 -0
  172. package/kits/hub-game/code/client/soundscapeSimlish.js +737 -0
  173. package/kits/hub-game/code/client/soundscapeSongs.js +127 -0
  174. package/kits/hub-game/code/client/soundscapeSongsRound3.js +63 -0
  175. package/kits/hub-game/code/client/soundscapeSynthesis.js +168 -0
  176. package/kits/hub-game/code/client/soundscapeUi.js +211 -0
  177. package/kits/hub-game/code/client/soundscapeVoice.js +1209 -0
  178. package/kits/hub-game/code/client/soundscapeWaves.js +206 -0
  179. package/kits/hub-game/code/client/spin.js +101 -0
  180. package/kits/hub-game/code/client/state.js +162 -1
  181. package/kits/hub-game/code/client/stuck.js +259 -0
  182. package/kits/hub-game/code/client/talk.js +714 -59
  183. package/kits/hub-game/code/client/tiers.js +543 -52
  184. package/kits/hub-game/code/client/toastBand.js +37 -0
  185. package/kits/hub-game/code/client/together.js +39 -2
  186. package/kits/hub-game/code/client/visibility.js +43 -0
  187. package/kits/hub-game/code/client/weakestLookBake.js +92 -0
  188. package/kits/hub-game/code/client/weakestTier.js +295 -0
  189. package/kits/hub-game/code/client/wear.js +461 -170
  190. package/kits/hub-game/code/client/worldLabels.js +241 -0
  191. package/kits/hub-game/code/client/yours.js +200 -0
  192. package/kits/hub-game/code/companionSpec.js +45 -0
  193. package/kits/hub-game/code/npcDisplayText.js +55 -0
  194. package/kits/hub-game/code/privateText.js +7 -0
  195. package/kits/hub-game/code/server/act.js +124 -0
  196. package/kits/hub-game/code/server/actions.js +138 -0
  197. package/kits/hub-game/code/server/actors.js +11 -2
  198. package/kits/hub-game/code/server/analytics.js +83 -0
  199. package/kits/hub-game/code/server/anonymousEntry.js +49 -0
  200. package/kits/hub-game/code/server/arrivalPose.js +36 -0
  201. package/kits/hub-game/code/server/ask.js +155 -0
  202. package/kits/hub-game/code/server/ballot.js +539 -0
  203. package/kits/hub-game/code/server/cells.js +100 -0
  204. package/kits/hub-game/code/server/companion.js +107 -0
  205. package/kits/hub-game/code/server/cues.js +70 -0
  206. package/kits/hub-game/code/server/decor.js +269 -0
  207. package/kits/hub-game/code/server/doorAnalytics.js +52 -0
  208. package/kits/hub-game/code/server/earned.js +478 -0
  209. package/kits/hub-game/code/server/frameBatch.js +183 -0
  210. package/kits/hub-game/code/server/friendBests.js +166 -0
  211. package/kits/hub-game/code/server/friendsAmong.js +272 -0
  212. package/kits/hub-game/code/server/history.js +7 -0
  213. package/kits/hub-game/code/server/hub.js +2510 -95
  214. package/kits/hub-game/code/server/idle.js +60 -12
  215. package/kits/hub-game/code/server/index.js +28 -6
  216. package/kits/hub-game/code/server/invites.js +19 -0
  217. package/kits/hub-game/code/server/labels.js +36 -2
  218. package/kits/hub-game/code/server/loadAbandon.js +106 -0
  219. package/kits/hub-game/code/server/manifest.js +586 -7
  220. package/kits/hub-game/code/server/menu.js +161 -0
  221. package/kits/hub-game/code/server/npcs.js +1025 -113
  222. package/kits/hub-game/code/server/observe.js +408 -0
  223. package/kits/hub-game/code/server/padOccupancy.js +85 -0
  224. package/kits/hub-game/code/server/party.js +2 -2
  225. package/kits/hub-game/code/server/players.js +30 -0
  226. package/kits/hub-game/code/server/resumePose.js +152 -0
  227. package/kits/hub-game/code/server/say.js +1 -1
  228. package/kits/hub-game/code/server/shot.js +110 -0
  229. package/kits/hub-game/code/server/standing.js +123 -0
  230. package/kits/hub-game/code/server/storageLimit.js +187 -0
  231. package/kits/hub-game/code/server/vis.js +175 -0
  232. package/kits/hub-game/code/server/wear.js +12 -0
  233. package/kits/hub-game/code/server/yours.js +59 -0
  234. package/kits/hub-game/code/shared/act.js +35 -0
  235. package/kits/hub-game/code/shared/cues.js +9 -0
  236. package/kits/hub-game/code/shared/danceIdle.js +28 -0
  237. package/kits/hub-game/code/shared/decor.js +41 -0
  238. package/kits/hub-game/code/shared/loadStages.js +12 -0
  239. package/kits/hub-game/code/shared/quality.js +74 -0
  240. package/kits/hub-game/code/shared/say.js +2 -0
  241. package/kits/hub-game/code/shared/shot.js +53 -0
  242. package/kits/hub-game/code/shared/spin.js +57 -0
  243. package/kits/hub-game/code/systems/hub.js +1753 -202
  244. package/kits/hub-game/docs/analytics.md +279 -0
  245. package/kits/hub-game/docs/content-pack.md +1 -1
  246. package/kits/hub-game/docs/contract.md +3475 -77
  247. package/kits/hub-game/docs/home-pieces.md +71 -0
  248. package/kits/hub-game/docs/observed-progress.md +252 -0
  249. package/kits/hub-game/main.jsx +2 -0
  250. package/kits/hub-game/models/avatar-10.pxmodel +28 -0
  251. package/kits/hub-game/models/avatar-11.pxmodel +28 -0
  252. package/kits/hub-game/models/avatar-12.pxmodel +27 -0
  253. package/kits/hub-game/models/avatar-13.pxmodel +24 -0
  254. package/kits/hub-game/models/avatar-14.pxmodel +29 -0
  255. package/kits/hub-game/models/avatar-15.pxmodel +24 -0
  256. package/kits/hub-game/models/avatar-4.pxmodel +29 -0
  257. package/kits/hub-game/models/avatar-5.pxmodel +27 -0
  258. package/kits/hub-game/models/avatar-6.pxmodel +26 -0
  259. package/kits/hub-game/models/avatar-7.pxmodel +25 -0
  260. package/kits/hub-game/models/avatar-8.pxmodel +24 -0
  261. package/kits/hub-game/models/avatar-9.pxmodel +30 -0
  262. package/kits/hub-game/models/earned/badge-round.pxmodel +100 -0
  263. package/kits/hub-game/models/earned/badge-shield.pxmodel +117 -0
  264. package/kits/hub-game/models/earned/badge-star.pxmodel +87 -0
  265. package/kits/hub-game/models/earned/belt-plain.pxmodel +72 -0
  266. package/kits/hub-game/models/earned/held-ball.pxmodel +43 -0
  267. package/kits/hub-game/models/earned/held-lantern.pxmodel +85 -0
  268. package/kits/hub-game/models/earned/held-net.pxmodel +57 -0
  269. package/kits/hub-game/models/earned/held-trophy.pxmodel +109 -0
  270. package/kits/hub-game/models/earned/pin-round.pxmodel +62 -0
  271. package/kits/hub-game/models/earned/sash-plain.pxmodel +66 -0
  272. package/kits/hub-game/models/earned/square/belt-plain.pxmodel +104 -0
  273. package/kits/hub-game/models/earned/square/sash-plain.pxmodel +98 -0
  274. package/kits/hub-game/models/hats/bat-clip.pxmodel +206 -0
  275. package/kits/hub-game/models/hats/beekeeper.pxmodel +149 -0
  276. package/kits/hub-game/models/hats/cap.pxmodel +162 -0
  277. package/kits/hub-game/models/hats/captain.pxmodel +178 -0
  278. package/kits/hub-game/models/hats/crooked-top.pxmodel +172 -0
  279. package/kits/hub-game/models/hats/flower-crown.pxmodel +451 -0
  280. package/kits/hub-game/models/hats/foam-crown.pxmodel +179 -0
  281. package/kits/hub-game/models/hats/lantern.pxmodel +230 -0
  282. package/kits/hub-game/models/hats/laurel.pxmodel +533 -0
  283. package/kits/hub-game/models/hats/lighthouse.pxmodel +96 -0
  284. package/kits/hub-game/models/hats/sailor.pxmodel +141 -0
  285. package/kits/hub-game/models/hats/souwester.pxmodel +131 -0
  286. package/kits/hub-game/models/hats/straw.pxmodel +139 -0
  287. package/kits/hub-game/models/hats/sunflower.pxmodel +406 -0
  288. package/kits/hub-game/models/hats/sweatband.pxmodel +112 -0
  289. package/kits/hub-game/models/hats/witch.pxmodel +147 -0
  290. package/kits/hub-game/package-lock.json +10 -1
  291. package/kits/hub-game/package.json +6 -2
  292. package/kits/hub-game/play/player.js +142 -0
  293. package/kits/hub-game/play/registry.js +47 -0
  294. package/kits/hub-game/play.jsx +37 -0
  295. package/kits/hub-game/scripts/check.mjs +117 -16
  296. package/kits/hub-game/scripts/companion-follower-wire.json +1 -0
  297. package/kits/hub-game/scripts/fixtures/decor-keyless-draw.json +132 -0
  298. package/kits/hub-game/scripts/fixtures/decor-keyless.json +293 -0
  299. package/kits/hub-game/scripts/fixtures/engine-models-stub.mjs +26 -0
  300. package/kits/hub-game/scripts/fixtures/fake-dom.mjs +123 -0
  301. package/kits/hub-game/scripts/fixtures/interest-legacy.json +385 -0
  302. package/kits/hub-game/scripts/fixtures/npc-notes-v1.77.jsonl +4 -0
  303. package/kits/hub-game/scripts/fixtures/vis-shared-wire.json +1 -0
  304. package/kits/hub-game/scripts/gen-avatars.mjs +933 -16
  305. package/kits/hub-game/scripts/gen-earned.mjs +285 -0
  306. package/kits/hub-game/scripts/gen-hats.mjs +827 -0
  307. package/kits/hub-game/scripts/grab.before-orbit.mjs +400 -0
  308. package/kits/hub-game/scripts/pose-storage-fixture.mjs +46 -0
  309. package/kits/hub-game/scripts/soundscape-wave-analysis.mjs +125 -0
  310. package/kits/hub-game/scripts/test-act-client.mjs +186 -0
  311. package/kits/hub-game/scripts/test-act.mjs +171 -0
  312. package/kits/hub-game/scripts/test-action-layout.mjs +80 -0
  313. package/kits/hub-game/scripts/test-action-observers.mjs +46 -0
  314. package/kits/hub-game/scripts/test-actions-client.mjs +853 -0
  315. package/kits/hub-game/scripts/test-actions.mjs +298 -0
  316. package/kits/hub-game/scripts/test-actor-budget.mjs +44 -0
  317. package/kits/hub-game/scripts/test-actors.mjs +38 -23
  318. package/kits/hub-game/scripts/test-analytics.mjs +76 -0
  319. package/kits/hub-game/scripts/test-anonymous-entry.mjs +28 -0
  320. package/kits/hub-game/scripts/test-arrival-pose-server.mjs +196 -0
  321. package/kits/hub-game/scripts/test-arrival-pose.mjs +24 -0
  322. package/kits/hub-game/scripts/test-ask-client.mjs +358 -0
  323. package/kits/hub-game/scripts/test-ask-slot.mjs +85 -0
  324. package/kits/hub-game/scripts/test-ask.mjs +269 -0
  325. package/kits/hub-game/scripts/test-attention.mjs +10 -1
  326. package/kits/hub-game/scripts/test-avatar-cap.mjs +379 -0
  327. package/kits/hub-game/scripts/test-avatar-colors.mjs +72 -0
  328. package/kits/hub-game/scripts/test-avatar-models.mjs +181 -0
  329. package/kits/hub-game/scripts/test-avatar-share.mjs +318 -0
  330. package/kits/hub-game/scripts/test-avatar-wire.mjs +792 -0
  331. package/kits/hub-game/scripts/test-avatar.mjs +584 -7
  332. package/kits/hub-game/scripts/test-back-visibility.mjs +82 -0
  333. package/kits/hub-game/scripts/test-ballot.mjs +1008 -0
  334. package/kits/hub-game/scripts/test-ban-join.mjs +121 -13
  335. package/kits/hub-game/scripts/test-build.mjs +49 -0
  336. package/kits/hub-game/scripts/test-cells.mjs +71 -0
  337. package/kits/hub-game/scripts/test-chat.mjs +863 -0
  338. package/kits/hub-game/scripts/test-classic.mjs +2 -0
  339. package/kits/hub-game/scripts/test-companion-chat.mjs +216 -0
  340. package/kits/hub-game/scripts/test-companion-client.mjs +1167 -0
  341. package/kits/hub-game/scripts/test-companion.mjs +259 -0
  342. package/kits/hub-game/scripts/test-control-layout-dom.mjs +120 -0
  343. package/kits/hub-game/scripts/test-crowd-names.mjs +205 -0
  344. package/kits/hub-game/scripts/test-decor-client.mjs +344 -0
  345. package/kits/hub-game/scripts/test-decor.mjs +464 -0
  346. package/kits/hub-game/scripts/test-default-environment-root.mjs +95 -0
  347. package/kits/hub-game/scripts/test-default-environment.mjs +267 -0
  348. package/kits/hub-game/scripts/test-door-analytics.mjs +58 -0
  349. package/kits/hub-game/scripts/test-door-jump.mjs +100 -0
  350. package/kits/hub-game/scripts/test-earned-client.mjs +459 -0
  351. package/kits/hub-game/scripts/test-earned.mjs +1224 -0
  352. package/kits/hub-game/scripts/test-emote-bubble.mjs +110 -0
  353. package/kits/hub-game/scripts/test-far-avatars.mjs +340 -0
  354. package/kits/hub-game/scripts/test-fps-telemetry.mjs +112 -0
  355. package/kits/hub-game/scripts/test-frame-batch.mjs +252 -0
  356. package/kits/hub-game/scripts/test-fresh-friends.mjs +118 -0
  357. package/kits/hub-game/scripts/test-friend-bests.mjs +435 -0
  358. package/kits/hub-game/scripts/test-grab-orbit.mjs +961 -0
  359. package/kits/hub-game/scripts/test-grab.mjs +7 -0
  360. package/kits/hub-game/scripts/test-hats.mjs +422 -168
  361. package/kits/hub-game/scripts/test-high-only.mjs +170 -0
  362. package/kits/hub-game/scripts/test-hub-leaving.mjs +203 -0
  363. package/kits/hub-game/scripts/test-hub-ops.mjs +758 -2
  364. package/kits/hub-game/scripts/test-hub-trip.mjs +1594 -12
  365. package/kits/hub-game/scripts/test-hud-clear.mjs +484 -57
  366. package/kits/hub-game/scripts/test-hud-defects-dom.mjs +100 -0
  367. package/kits/hub-game/scripts/test-hud-rate.mjs +224 -0
  368. package/kits/hub-game/scripts/test-hud-safe-visibility-dom.mjs +83 -0
  369. package/kits/hub-game/scripts/test-idle.mjs +427 -1
  370. package/kits/hub-game/scripts/test-interest-cap.mjs +36 -0
  371. package/kits/hub-game/scripts/test-interest-cells.mjs +513 -0
  372. package/kits/hub-game/scripts/test-interest-client.mjs +118 -0
  373. package/kits/hub-game/scripts/test-interest.mjs +15 -0
  374. package/kits/hub-game/scripts/test-invites-client.mjs +430 -0
  375. package/kits/hub-game/scripts/test-invites.mjs +109 -0
  376. package/kits/hub-game/scripts/test-keys.mjs +46 -1
  377. package/kits/hub-game/scripts/test-labels.mjs +664 -0
  378. package/kits/hub-game/scripts/test-landscape-layout.mjs +194 -0
  379. package/kits/hub-game/scripts/test-list-scroll-dom.mjs +49 -0
  380. package/kits/hub-game/scripts/test-load-abandon.mjs +246 -0
  381. package/kits/hub-game/scripts/test-loading-cover.mjs +162 -0
  382. package/kits/hub-game/scripts/test-manifest.mjs +472 -0
  383. package/kits/hub-game/scripts/test-menu-client.mjs +585 -0
  384. package/kits/hub-game/scripts/test-menu.mjs +319 -0
  385. package/kits/hub-game/scripts/test-npcs.mjs +2528 -13
  386. package/kits/hub-game/scripts/test-object-entry.mjs +76 -0
  387. package/kits/hub-game/scripts/test-observed.mjs +745 -0
  388. package/kits/hub-game/scripts/test-pack.mjs +7 -0
  389. package/kits/hub-game/scripts/test-pad-cues.mjs +304 -0
  390. package/kits/hub-game/scripts/test-pad-occupancy.mjs +177 -0
  391. package/kits/hub-game/scripts/test-picker.mjs +541 -0
  392. package/kits/hub-game/scripts/test-placement-cache.mjs +690 -0
  393. package/kits/hub-game/scripts/test-progress-reset.mjs +559 -0
  394. package/kits/hub-game/scripts/test-push-visit.mjs +26 -0
  395. package/kits/hub-game/scripts/test-quality.mjs +385 -0
  396. package/kits/hub-game/scripts/test-rehello.mjs +1733 -0
  397. package/kits/hub-game/scripts/test-relations-among.mjs +222 -0
  398. package/kits/hub-game/scripts/test-relations-refresh.mjs +188 -0
  399. package/kits/hub-game/scripts/test-resume-action-order.mjs +598 -0
  400. package/kits/hub-game/scripts/test-resume-held.mjs +239 -0
  401. package/kits/hub-game/scripts/test-resume-pose.mjs +142 -0
  402. package/kits/hub-game/scripts/test-safe-events-dom.mjs +116 -0
  403. package/kits/hub-game/scripts/test-safe-layout.mjs +330 -0
  404. package/kits/hub-game/scripts/test-say.mjs +1 -1
  405. package/kits/hub-game/scripts/test-shot.mjs +901 -0
  406. package/kits/hub-game/scripts/test-signin-client.mjs +45 -0
  407. package/kits/hub-game/scripts/test-soundscape.mjs +5437 -0
  408. package/kits/hub-game/scripts/test-spin.mjs +314 -0
  409. package/kits/hub-game/scripts/test-standing.mjs +449 -0
  410. package/kits/hub-game/scripts/test-storage-limit.mjs +333 -0
  411. package/kits/hub-game/scripts/test-stuck.mjs +1904 -0
  412. package/kits/hub-game/scripts/test-talk-overlay-dom.mjs +130 -0
  413. package/kits/hub-game/scripts/test-tier-cells.mjs +706 -0
  414. package/kits/hub-game/scripts/test-tiers-render.mjs +412 -0
  415. package/kits/hub-game/scripts/test-tiers.mjs +476 -2
  416. package/kits/hub-game/scripts/test-toast-band.mjs +61 -0
  417. package/kits/hub-game/scripts/test-try-on.mjs +22 -22
  418. package/kits/hub-game/scripts/test-vis.mjs +770 -0
  419. package/kits/hub-game/scripts/test-visibility.mjs +134 -0
  420. package/kits/hub-game/scripts/test-weakest-tier.mjs +924 -0
  421. package/kits/hub-game/scripts/test-world-labels.mjs +367 -0
  422. package/kits/hub-game/scripts/test-yours-chrome.mjs +210 -0
  423. package/kits/hub-game/scripts/test-yours.mjs +403 -0
  424. package/kits/multiplayer-3d/CLAUDE.md +50 -0
  425. package/kits/multiplayer-3d/castle.json +5 -5
  426. package/kits/multiplayer-3d/code/client/avatars.js +7 -0
  427. package/kits/multiplayer-3d/code/client/gait.js +65 -0
  428. package/kits/multiplayer-3d/code/client/joinFailure.js +27 -0
  429. package/kits/multiplayer-3d/code/client/nameTags.js +59 -4
  430. package/kits/multiplayer-3d/code/client/resumeGate.js +139 -0
  431. package/kits/multiplayer-3d/code/options.js +5 -0
  432. package/kits/multiplayer-3d/code/server/ownership.js +10 -2
  433. package/kits/multiplayer-3d/code/server/sceneBodies.js +12 -0
  434. package/kits/multiplayer-3d/code/server/world.js +7 -0
  435. package/kits/multiplayer-3d/code/systems/multiplayer.js +443 -34
  436. package/kits/multiplayer-3d/package-lock.json +8 -1
  437. package/kits/multiplayer-3d/package.json +3 -1
  438. package/kits/multiplayer-3d/scripts/fixtures/README.md +11 -0
  439. package/kits/multiplayer-3d/scripts/fixtures/ownership-legacy.json +2 -0
  440. package/kits/multiplayer-3d/scripts/ownership-harness.mjs +102 -0
  441. package/kits/multiplayer-3d/scripts/ownership-loader.mjs +46 -0
  442. package/kits/multiplayer-3d/scripts/ownership-worker.mjs +15 -0
  443. package/kits/multiplayer-3d/scripts/record-ownership-session.mjs +98 -0
  444. package/kits/multiplayer-3d/scripts/test-eligible-claims.mjs +167 -0
  445. package/kits/multiplayer-3d/scripts/test-join-watchdog.mjs +436 -0
  446. package/kits/multiplayer-3d/scripts/test-own-name-tag.mjs +247 -0
  447. package/kits/multiplayer-3d/scripts/test-resume-gate.mjs +624 -0
  448. package/kits/physics-2d/CLAUDE.md +19 -1
  449. package/kits/physics-2d/castle.json +2 -2
  450. package/kits/physics-2d/engine/frozenActors.js +233 -0
  451. package/kits/physics-2d/engine/scene.js +337 -3
  452. package/kits/physics-2d/engine/skyKey.js +129 -0
  453. package/kits/physics-2d/engine/stillClock.js +106 -0
  454. package/kits/physics-2d/engine/updateBudget.js +21 -0
  455. package/kits/physics-2d/eslint.config.js +1 -1
  456. package/kits/physics-2d/play/behaviors/AnalogStick.js +198 -0
  457. package/kits/physics-2d/play/behaviors/Camera.js +40 -0
  458. package/kits/physics-2d/play/behaviors/Collider.js +122 -0
  459. package/kits/physics-2d/play/behaviors/Draggable.js +115 -0
  460. package/kits/physics-2d/play/behaviors/Goal.js +46 -0
  461. package/kits/physics-2d/play/behaviors/Joints.js +126 -0
  462. package/kits/physics-2d/play/behaviors/Layout.js +71 -0
  463. package/kits/physics-2d/play/behaviors/RigidBody.js +57 -0
  464. package/kits/physics-2d/play/behaviors/Slingshot.js +142 -0
  465. package/kits/physics-2d/play/behaviors/SoundPlayer.js +263 -0
  466. package/kits/physics-2d/play/behaviors/Sprite.js +406 -0
  467. package/kits/physics-2d/play/behaviors/Style.js +209 -0
  468. package/kits/physics-2d/play/behaviors/Text.js +85 -0
  469. package/kits/physics-2d/play/behaviors/Video.js +93 -0
  470. package/kits/physics-2d/scripts/test-skip-unchanged.mjs +326 -1
  471. package/kits/physics-3d/CLAUDE.md +42 -529
  472. package/kits/physics-3d/behaviors/Body.jsx +3 -0
  473. package/kits/physics-3d/behaviors/Model.jsx +3 -0
  474. package/kits/physics-3d/behaviors/Player.jsx +661 -87
  475. package/kits/physics-3d/behaviors/Shape.jsx +3 -0
  476. package/kits/physics-3d/behaviors/Solid.jsx +3 -0
  477. package/kits/physics-3d/behaviors/Transform.jsx +3 -0
  478. package/kits/physics-3d/castle.json +3 -3
  479. package/kits/physics-3d/docs/engine-camera.md +542 -0
  480. package/kits/physics-3d/docs/engine-frame-cap.md +136 -0
  481. package/kits/physics-3d/docs/engine-load.md +149 -0
  482. package/kits/physics-3d/docs/engine-look.md +114 -0
  483. package/kits/physics-3d/docs/engine-shadows.md +372 -0
  484. package/kits/physics-3d/docs/engine-skip-work.md +187 -0
  485. package/kits/physics-3d/docs/engine-sky.md +198 -0
  486. package/kits/physics-3d/docs/engine-static-actors.md +226 -0
  487. package/kits/physics-3d/docs/engine-view.md +37 -0
  488. package/kits/physics-3d/docs/pxmodel-format.md +9 -1
  489. package/kits/physics-3d/engine3d/PlayOnly3D.jsx +5 -1
  490. package/kits/physics-3d/engine3d/Scene3DPlayer.jsx +19 -277
  491. package/kits/physics-3d/engine3d/actornode.js +87 -0
  492. package/kits/physics-3d/engine3d/animationBudget.js +23 -0
  493. package/kits/physics-3d/engine3d/branches.js +3 -13
  494. package/kits/physics-3d/engine3d/cage.js +2 -7
  495. package/kits/physics-3d/engine3d/cageops.js +2 -17
  496. package/kits/physics-3d/engine3d/dataBehaviors.js +12 -0
  497. package/kits/physics-3d/engine3d/editorWorld.js +6 -0
  498. package/kits/physics-3d/engine3d/emptynodes.js +232 -0
  499. package/kits/physics-3d/engine3d/framecap.js +99 -0
  500. package/kits/physics-3d/engine3d/frozenphysics.js +140 -0
  501. package/kits/physics-3d/engine3d/frozenstatics.js +273 -0
  502. package/kits/physics-3d/engine3d/gait.js +126 -0
  503. package/kits/physics-3d/engine3d/initialModelFiles.js +18 -0
  504. package/kits/physics-3d/engine3d/kithooks.js +47 -0
  505. package/kits/physics-3d/engine3d/look.js +514 -48
  506. package/kits/physics-3d/engine3d/lookbake.js +208 -0
  507. package/kits/physics-3d/engine3d/materialpresets.js +2 -0
  508. package/kits/physics-3d/engine3d/modelFiles.js +3 -17
  509. package/kits/physics-3d/engine3d/modelMath.js +49 -0
  510. package/kits/physics-3d/engine3d/modelready.js +16 -0
  511. package/kits/physics-3d/engine3d/motion.js +39 -10
  512. package/kits/physics-3d/engine3d/nearshadows.js +106 -21
  513. package/kits/physics-3d/engine3d/optimize.js +9 -5
  514. package/kits/physics-3d/engine3d/orbitinput.js +522 -10
  515. package/kits/physics-3d/engine3d/orbitlens.js +48 -0
  516. package/kits/physics-3d/engine3d/ownmodel.js +213 -0
  517. package/kits/physics-3d/engine3d/partgeometry.js +1 -16
  518. package/kits/physics-3d/engine3d/paths.js +1 -9
  519. package/kits/physics-3d/engine3d/playTimings.js +50 -0
  520. package/kits/physics-3d/engine3d/playerRun.js +372 -0
  521. package/kits/physics-3d/engine3d/pxmodel.js +42 -11
  522. package/kits/physics-3d/engine3d/rapier.js +27 -0
  523. package/kits/physics-3d/engine3d/scatter.js +1 -11
  524. package/kits/physics-3d/engine3d/shadowfade.js +890 -0
  525. package/kits/physics-3d/engine3d/sky.js +547 -0
  526. package/kits/physics-3d/engine3d/skylife.js +306 -0
  527. package/kits/physics-3d/engine3d/squarefirst.js +177 -0
  528. package/kits/physics-3d/engine3d/stillshadows.js +399 -0
  529. package/kits/physics-3d/engine3d/sweep.js +1 -25
  530. package/kits/physics-3d/engine3d/unchanged.js +11 -0
  531. package/kits/physics-3d/engine3d/viewrange.js +52 -0
  532. package/kits/physics-3d/engine3d/world3d.js +1253 -76
  533. package/kits/physics-3d/eslint.config.js +2 -1
  534. package/kits/physics-3d/main.jsx +10 -2
  535. package/kits/physics-3d/package-lock.json +7 -0
  536. package/kits/physics-3d/package.json +5 -1
  537. package/kits/physics-3d/play/behaviors/Body.js +31 -0
  538. package/kits/physics-3d/play/behaviors/Door.js +37 -0
  539. package/kits/physics-3d/play/behaviors/Lookable.js +16 -0
  540. package/kits/physics-3d/play/behaviors/Model.js +23 -0
  541. package/kits/physics-3d/play/behaviors/Pickup.js +46 -0
  542. package/kits/physics-3d/play/behaviors/Player.js +1204 -0
  543. package/kits/physics-3d/play/behaviors/Shape.js +47 -0
  544. package/kits/physics-3d/play/behaviors/Solid.js +16 -0
  545. package/kits/physics-3d/play/behaviors/Transform.js +29 -0
  546. package/kits/physics-3d/pnpm-lock.yaml +8 -0
  547. package/kits/physics-3d/scripts/bench-shadow-fade.mjs +37 -0
  548. package/kits/physics-3d/scripts/build-rapier-gz.mjs +56 -0
  549. package/kits/physics-3d/scripts/frozen-statics-fixture.mjs +141 -0
  550. package/kits/physics-3d/scripts/look-baseline.mjs +155 -0
  551. package/kits/physics-3d/scripts/test-camera-follow.mjs +5 -1
  552. package/kits/physics-3d/scripts/test-camera-orbit.mjs +2613 -82
  553. package/kits/physics-3d/scripts/test-drop-empty-parts.mjs +2 -2
  554. package/kits/physics-3d/scripts/test-empty-gait-hints.mjs +89 -0
  555. package/kits/physics-3d/scripts/test-frame-cap-bob.mjs +438 -0
  556. package/kits/physics-3d/scripts/test-frame-cap.mjs +452 -0
  557. package/kits/physics-3d/scripts/test-frozen-nested.mjs +49 -0
  558. package/kits/physics-3d/scripts/test-frozen-statics-legacy-physics2d.mjs +123 -0
  559. package/kits/physics-3d/scripts/test-frozen-statics.mjs +434 -0
  560. package/kits/physics-3d/scripts/test-gait.mjs +387 -0
  561. package/kits/physics-3d/scripts/test-look-bake.mjs +1056 -0
  562. package/kits/physics-3d/scripts/test-model-parse-cache.mjs +92 -0
  563. package/kits/physics-3d/scripts/test-near-shadows.mjs +5 -2
  564. package/kits/physics-3d/scripts/test-orbit-shadow-fade.mjs +2001 -0
  565. package/kits/physics-3d/scripts/test-orbit-shift-lock.mjs +582 -0
  566. package/kits/physics-3d/scripts/test-orbit-shot.mjs +657 -0
  567. package/kits/physics-3d/scripts/test-orbit-view.mjs +230 -0
  568. package/kits/physics-3d/scripts/test-rapier-gz.mjs +106 -0
  569. package/kits/physics-3d/scripts/test-skip-empty-nodes.mjs +845 -0
  570. package/kits/physics-3d/scripts/test-sky.mjs +2470 -0
  571. package/kits/physics-3d/scripts/test-square-first.mjs +921 -0
  572. package/kits/physics-3d/scripts/test-static-actors.mjs +10 -1
  573. package/kits/physics-3d/scripts/test-static-physics.mjs +4 -1
  574. package/kits/physics-3d/scripts/test-static-scenery.mjs +2174 -0
  575. package/kits/physics-3d/scripts/test-steady-hover.mjs +7 -2
  576. package/kits/physics-3d/scripts/test-still-shadows.mjs +477 -0
  577. package/kits/physics-3d/scripts/test-view-range.mjs +260 -0
  578. package/kits/physics-3d/systems/physics3d.js +419 -9
  579. package/kits/real-time/castle.json +2 -2
  580. package/kits/real-time/code/client/connection.js +33 -10
  581. package/kits/real-time/code/client/gameHooks.js +2 -0
  582. package/kits/real-time/code/client/joinOverlay.js +9 -4
  583. package/kits/real-time/code/server/gameHooks.js +7 -0
  584. package/kits/real-time/code/server/session.js +102 -22
  585. package/kits/real-time/package-lock.json +1 -1
  586. package/package.json +2 -2
  587. 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,23 @@
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 { npcDisplayText } from '../npcDisplayText.js';
38
+ import { warnOnce } from './actors.js';
39
+ import { readNpcTurnsAtOnce } from './manifest.js';
40
+
41
+ // v1.47: a crowd answers a gesture without calling a mind.
42
+ const REACT_RANGE_M = 6;
43
+ const REACT_PLAYER_MS = 4000;
44
+ const REACT_NPC_MS = 8000;
45
+ const REACTIONS = {
46
+ wave: { emote: 'wave', lines: ['Hello there!', 'Hi!', 'Hey, hi!'] },
47
+ dance: { emote: 'dance', lines: ['Nice moves!', 'Ooh, let me try!'] },
48
+ cheer: { emote: 'cheer', lines: ['Woo!', 'Yay!'] },
49
+ bow: { emote: 'bow', lines: ['Likewise!', 'Oh, how polite!'] },
50
+ spin: { emote: 'cheer', lines: ['Whee!', 'Dizzy yet?'] },
51
+ };
52
+
36
53
  const TALK_RANGE_M = 3.5;
37
54
  // A speaker who walks this far from the body has left the conversation.
38
55
  const LEAVE_RANGE_M = 8;
@@ -41,6 +58,18 @@ const FOLLOW_GAP_M = 1.6;
41
58
  const SPEECH_MS = 7000;
42
59
  const SPEECH_MAX = 240;
43
60
  const INPUT_MAX = 280;
61
+ // v1.37: the questions an opening suggests, and how long each may be.
62
+ const ASKS_MAX = 3;
63
+ const ASK_MAX = 40;
64
+ const PERSISTENT_ASKS_MAX = 2;
65
+ // v1.46: questions to offer after the first answer.
66
+ const MORE_MAX = 9;
67
+ const DEFAULT_ASKS = ['Who are you?', 'What do you do here?', 'Tell me a secret!'];
68
+ 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?'];
69
+ // ...and how many players an NPC remembers having met (`npcOpening`'s `met`).
70
+ const MET_MAX = 500;
71
+ // The opening's line in a conversation's notes is not kept under this length.
72
+ const OPENED_MIN = 60;
44
73
  // A conversation nobody has said anything in for this long is over.
45
74
  const IDLE_END_MS = 90_000;
46
75
  // Authored-mode words from one player, at most one per this.
@@ -55,12 +84,23 @@ const TURNS_KEPT = 128;
55
84
  // After a reply the world's public projection is read every this long, for
56
85
  // this long, to see whether the character chose to follow someone.
57
86
  const FOLLOW_POLL_MS = 2000;
87
+ // A failing public read backs off by doubling, to this.
88
+ const FOLLOW_POLL_MAX_MS = 300_000;
58
89
  const FOLLOW_WATCH_MS = 60_000;
59
90
  // The place's notes for a turn (`npcContext`): at most NOTES_MAX characters,
60
91
  // read for the body's speaker every NOTES_EVERY_MS, and any of the last
61
92
  // NOTES_KEPT issued within NOTES_KEEP_MS is accepted (the speaker's client
62
93
  // may be a moment behind; the newest is accepted however old).
63
94
  export const NOTES_MAX = 700;
95
+ // v1.66 place tools (§13 tools): what a place may declare for one lookup per
96
+ // reply. The same caps as the host's, so a list the kit sends is never dropped
97
+ // there.
98
+ const TOOLS_MAX = 8;
99
+ const TOOL_NAME = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
100
+ const TOOL_RESERVED = new Set(['perform_action', 'capture_claim']);
101
+ const TOOL_DESCRIPTION_MAX = 300;
102
+ const TOOL_SCHEMA_BYTES = 1024;
103
+ const TOOLS_BYTES = 6144;
64
104
  const NOTES_EVERY_MS = 1000;
65
105
  const NOTES_KEPT = 6;
66
106
  const NOTES_KEEP_MS = 60_000;
@@ -71,12 +111,22 @@ export const NOTES_SAYS = '\n[The speaker says]\n';
71
111
  export function makeNpcs(h) {
72
112
  const n = {
73
113
  bodies: new Map(),
114
+ preferred: new Map(),
74
115
  // `${playerId}:${operationId}` -> { npc, speaker, at, delivered }
75
116
  turns: new Map(),
76
117
  // playerId -> durable participant id, from that player's own inspect read
77
118
  participants: new Map(),
119
+ // v1.47: player id -> { userId, body, characters }, private to this visit.
120
+ greetings: new Map(),
121
+ inspectReads: new Map(),
122
+ reactAt: new Map(),
123
+ emotes: new Map(),
124
+ emotesUsed: false,
78
125
  // playerId -> sim time of their last authored-mode words
79
126
  saidAt: new Map(),
127
+ // npc id -> the players (by user id, else player id) who have said
128
+ // something to it since this process started (v1.37, `npcOpening`'s `met`)
129
+ met: new Map(),
80
130
  watchUntil: 0,
81
131
  polledAt: -Infinity,
82
132
  polling: false,
@@ -92,6 +142,7 @@ export function makeNpcs(h) {
92
142
  if (!body) {
93
143
  continue;
94
144
  }
145
+ const turnsAtOnce = readNpcTurnsAtOnce(props.turnsAtOnce, h.place.npcs?.turnsAtOnce ?? 1);
95
146
  const t = actor.components.Transform ?? {};
96
147
  const at = body.translation();
97
148
  n.bodies.set(actor.id, {
@@ -104,8 +155,13 @@ export function makeNpcs(h) {
104
155
  body,
105
156
  home: { x: at.x, y: at.y, z: at.z, yaw: ((t.rotationY ?? 0) * Math.PI) / 180 },
106
157
  yaw: ((t.rotationY ?? 0) * Math.PI) / 180,
107
- // { playerId, at } while someone is talking to it
158
+ // Monotonic per-body sequence, retained when a conversation ends.
159
+ conversation: 0,
160
+ // { playerId, at, conversation, accountKey, body, said } while talking
108
161
  talking: null,
162
+ // Only multi-slot bodies allocate speaker state; the default record
163
+ // and every wire message retain their original shape.
164
+ ...(turnsAtOnce > 1 ? { turnsAtOnce, speakers: new Map() } : {}),
109
165
  // the turn admitted and not yet answered, so a second waits
110
166
  pending: null,
111
167
  // playerId it follows, when that began, and whether the character's
@@ -124,13 +180,16 @@ export function makeNpcs(h) {
124
180
  // { playerId, list: [{ prefix, at }], readAt } the notes issued to
125
181
  // whoever is talking to it
126
182
  notes: null,
183
+ reactedAt: -Infinity,
184
+ speakingUntil: 0,
185
+ reaction: null,
127
186
  });
128
187
  }
129
188
  },
130
189
 
131
190
  // The handle `hub.npc(id)` returns, or null for an actor that is not one.
132
191
  handle(id) {
133
- const npc = n.bodies.get(id);
192
+ const npc = recordOf(n, id);
134
193
  return npc ? handleOf(h, n, npc) : null;
135
194
  },
136
195
 
@@ -138,23 +197,89 @@ export function makeNpcs(h) {
138
197
  return [...n.bodies.values()].map((npc) => handleOf(h, n, npc));
139
198
  },
140
199
 
200
+ // Private, optional hint; admission and range checks are unchanged.
201
+ prefer(playerId, npcId) {
202
+ if (!h.sim?.players.has(playerId) || (npcId !== null && !n.bodies.has(npcId))) {
203
+ return false;
204
+ }
205
+ if ((n.preferred.get(playerId) ?? null) === npcId) {
206
+ return true;
207
+ }
208
+ n.preferred.set(playerId, npcId);
209
+ h.ctx.send(playerId, { k: 'hub-npc-preferred', npc: npcId });
210
+ return true;
211
+ },
212
+
213
+ replayPreferred(playerId, held = false) {
214
+ const npc = n.preferred.get(playerId);
215
+ if (npc || (held && n.preferred.has(playerId))) {
216
+ h.ctx.send(playerId, { k: 'hub-npc-preferred', npc: npc ?? null });
217
+ }
218
+ },
219
+
141
220
  // Before the physics step: where each body goes this tick.
142
221
  place(dt) {
143
222
  for (const npc of n.bodies.values()) {
144
223
  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);
224
+ for (const talking of conversations(npc)) {
225
+ if (h.sim.timeMs - (speakerState(npc, talking.playerId).notes?.readAt ?? -Infinity) >= NOTES_EVERY_MS) {
226
+ issueNotes(h, npc, talking.playerId);
227
+ }
228
+ }
229
+ }
230
+ if (h.place.companionChat) {
231
+ for (const npc of n.virtuals?.values() ?? []) {
232
+ if (!companionOwnerPresent(h, npc.owner)) {
233
+ endTalk(h, n, npc.id, npc.owner, 'left');
234
+ forgetVirtual(n, npc.owner);
235
+ continue;
236
+ }
237
+ if (npc.talking && h.sim.timeMs - npc.talking.at > IDLE_END_MS) {
238
+ endTalk(h, n, npc.id, npc.owner, 'idle');
239
+ }
240
+ if (npc.talking && h.sim.timeMs - (npc.notes?.readAt ?? -Infinity) >= NOTES_EVERY_MS) {
241
+ issueNotes(h, npc, npc.owner);
242
+ }
147
243
  }
148
244
  }
149
245
  pollFollow(h, n);
150
246
  },
151
247
 
248
+ // How many players this NPC is keeping as met (tests).
249
+ metCount: (npcId) => n.met.get(npcId)?.size ?? 0,
250
+
251
+ react(playerId, emote) {
252
+ react(h, n, playerId, emote);
253
+ },
254
+
255
+ // v1.47: even an empty field is withheld until a body has emoted.
256
+ emoteFields() {
257
+ if (!n.emotesUsed) {
258
+ return {};
259
+ }
260
+ const now = h.sim?.timeMs ?? 0;
261
+ for (const [id, emote] of n.emotes) {
262
+ if (now >= emote.until) {
263
+ n.emotes.delete(id);
264
+ }
265
+ }
266
+ return { hubNpcEmotes: Object.fromEntries(n.emotes) };
267
+ },
268
+
152
269
  leave(playerId) {
270
+ n.preferred.delete(playerId);
271
+ if (h.place.companionChat) {
272
+ forgetVirtual(n, playerId);
273
+ }
153
274
  n.participants.delete(playerId);
275
+ n.greetings.delete(playerId);
276
+ n.inspectReads.delete(playerId);
277
+ n.reactAt.delete(playerId);
154
278
  n.saidAt.delete(playerId);
279
+ metLeft(n, playerId);
155
280
  for (const npc of n.bodies.values()) {
156
- if (npc.talking?.playerId === playerId) {
157
- npc.talking = null;
281
+ if (talkingOf(npc, playerId)) {
282
+ clearTalk(npc, playerId);
158
283
  }
159
284
  if (npc.following === playerId) {
160
285
  npc.following = null;
@@ -169,7 +294,7 @@ export function makeNpcs(h) {
169
294
  open(h, n, player.playerId, data.npc);
170
295
  return true;
171
296
  case 'hub-npc-say':
172
- authoredSay(h, n, player.playerId, data.npc, data.text);
297
+ authoredSay(h, n, player.playerId, data.npc, data.text, data.rid);
173
298
  return true;
174
299
  case 'hub-npc-end':
175
300
  endTalk(h, n, data.npc, player.playerId, 'end');
@@ -191,22 +316,97 @@ export function makeNpcs(h) {
191
316
  async onRead(request) {
192
317
  await routeRead(h, n, request);
193
318
  },
319
+ // v1.66: a mind's one lookup for a turn this place admitted (§13 tools).
320
+ async onTool(request) {
321
+ return await answerTool(h, n, request);
322
+ },
194
323
  };
195
324
  return api;
196
325
  }
197
326
 
327
+ // Virtual companions never enter the physical-body registry. No chat key:
328
+ // no virtual registry, records, movement, reactions, or public speech.
329
+ function recordOf(n, id) {
330
+ return n.bodies.get(id) ?? n.virtuals?.get(id);
331
+ }
332
+ function* talkRecords(n) {
333
+ yield* n.bodies.values();
334
+ if (n.virtuals) {
335
+ yield* n.virtuals.values();
336
+ }
337
+ }
338
+ // Speaker state is opt-in: legacy bodies and owner-only virtual companions
339
+ // retain the old fields, including a pending turn after a conversation ends.
340
+ function speakerState(npc, playerId) {
341
+ return npc.speakers ? npc.speakers.get(playerId) : npc;
342
+ }
343
+ function talkingOf(npc, playerId) {
344
+ const talking = speakerState(npc, playerId)?.talking;
345
+ return talking?.playerId === playerId ? talking : null;
346
+ }
347
+ function conversations(npc) {
348
+ return npc.speakers ? [...npc.speakers.values()].flatMap((state) => state.talking ? [state.talking] : []) : npc.talking ? [npc.talking] : [];
349
+ }
350
+ function fullFor(npc, playerId) {
351
+ return !talkingOf(npc, playerId) && conversations(npc).length >= (npc.turnsAtOnce ?? 1);
352
+ }
353
+ function pendingTurn(npc, key) {
354
+ return npc.speakers ? [...npc.speakers.values()].find((state) => state.pending?.key === key)?.pending : npc.pending?.key === key ? npc.pending : null;
355
+ }
356
+ function companionOwnerPresent(h, playerId) {
357
+ const entry = h.players.get(playerId);
358
+ return entry?.arrived && !entry.ended && h.sim?.players.has(playerId) && h.session?.players?.some((p) => p.playerId === playerId);
359
+ }
360
+ function forgetVirtual(n, playerId) {
361
+ const id = `companion:${playerId}`;
362
+ n.virtuals?.delete(id);
363
+ n.met.delete(id);
364
+ for (const [key, turn] of n.turns) {
365
+ if (turn.npc === id) {
366
+ n.turns.delete(key);
367
+ }
368
+ }
369
+ }
370
+ function virtualForOpen(h, n, playerId, id) {
371
+ if (typeof playerId !== 'string' || !playerId || id !== `companion:${playerId}` || !companionOwnerPresent(h, playerId)) {
372
+ return null;
373
+ }
374
+ let npc = n.virtuals?.get(id);
375
+ if (!npc) {
376
+ const { name, character } = h.place.companionChat;
377
+ npc = {
378
+ id, owner: playerId, name, character,
379
+ props: { role: 'companion', name, character },
380
+ talkRange: TALK_RANGE_M, conversation: 0, talking: null, pending: null,
381
+ following: null, walk: null, recent: [], notes: null, followDone: new Set(),
382
+ };
383
+ (n.virtuals ??= new Map()).set(id, npc);
384
+ }
385
+ return npc;
386
+ }
387
+
198
388
  function handleOf(h, n, npc) {
199
389
  return {
200
390
  id: npc.id,
201
391
  name: npc.name,
202
392
  character: npc.character,
203
393
  props: npc.props,
394
+ ...(npc.owner ? { owner: npc.owner } : {}),
204
395
  get at() {
205
- const p = npc.body.translation();
396
+ const p = npc.owner ? h.sim.players.get(npc.owner)?.at : npc.body.translation();
397
+ if (!p) {
398
+ return null;
399
+ }
206
400
  return { x: p.x, y: p.y, z: p.z };
207
401
  },
208
402
  get talkingTo() {
209
- return npc.talking?.playerId ?? null;
403
+ return conversations(npc)[0]?.playerId ?? null;
404
+ },
405
+ get turnsAtOnce() {
406
+ return npc.turnsAtOnce ?? 1;
407
+ },
408
+ get talkingWith() {
409
+ return conversations(npc).map((talking) => talking.playerId);
210
410
  },
211
411
  get following() {
212
412
  return npc.following;
@@ -215,46 +415,166 @@ function handleOf(h, n, npc) {
215
415
  return npc.walk !== null;
216
416
  },
217
417
  get busy() {
218
- return npc.talking !== null || npc.walk !== null || npc.following !== null;
418
+ return !npc.owner && (conversations(npc).length >= (npc.turnsAtOnce ?? 1) || npc.walk !== null || npc.following !== null);
219
419
  },
420
+ ...(h.firstVisit ? {
421
+ open(playerId) {
422
+ if (!h.players.get(playerId)?.arrived || talkingOf(npc, playerId) || fullFor(npc, playerId) || distanceTo(h, npc, playerId) > npc.talkRange) {return false;}
423
+ open(h, n, playerId, npc.id);
424
+ return Boolean(talkingOf(npc, playerId));
425
+ },
426
+ } : {}),
220
427
  say(text, options = {}) {
428
+ if (npc.owner) {
429
+ return;
430
+ }
221
431
  say(h, npc, text, options);
222
432
  },
223
433
  face(target) {
434
+ if (npc.owner) {
435
+ return;
436
+ }
224
437
  npc.faceTo = target ?? null;
225
438
  },
226
439
  walkTo(at, { stopAt = 0.3, then } = {}) {
440
+ if (npc.owner || npc.movementHeld) {
441
+ return;
442
+ }
227
443
  if (!at || !Number.isFinite(at.x) || !Number.isFinite(at.z)) {
228
444
  return;
229
445
  }
230
446
  npc.walk = { x: at.x, z: at.z, stopAt, then: typeof then === 'function' ? then : null };
231
447
  },
232
448
  home(then) {
449
+ if (npc.owner || npc.movementHeld) {
450
+ return;
451
+ }
233
452
  npc.walk = { x: npc.home.x, z: npc.home.z, stopAt: 0.2, then: typeof then === 'function' ? then : null, home: true };
234
453
  },
235
454
  follow(playerId) {
455
+ if (npc.owner || npc.movementHeld) {
456
+ return;
457
+ }
236
458
  npc.following = playerId ?? null;
237
459
  npc.followSince = h.sim?.timeMs ?? 0;
238
460
  npc.followByToken = false;
239
461
  },
462
+ holdMovement(held) {
463
+ if (npc.owner || Boolean(npc.movementHeld) === Boolean(held)) {
464
+ return;
465
+ }
466
+ npc.movementHeld = Boolean(held);
467
+ if (npc.movementHeld) {
468
+ npc.walk = null;
469
+ npc.following = null;
470
+ // A place can engage its hold after place() queued this tick's step.
471
+ npc.body.setNextKinematicTranslation(npc.body.translation());
472
+ }
473
+ },
240
474
  stop() {
475
+ if (npc.owner) {
476
+ return;
477
+ }
241
478
  npc.walk = null;
242
479
  npc.following = null;
243
480
  },
244
481
  end() {
245
- if (npc.talking) {
246
- endTalk(h, n, npc.id, npc.talking.playerId, 'place');
482
+ for (const talking of conversations(npc)) {
483
+ endTalk(h, n, npc.id, talking.playerId, 'place');
247
484
  }
248
485
  },
249
486
  };
250
487
  }
251
488
 
252
489
  function say(h, npc, text, { to, ttlMs = SPEECH_MS, about } = {}) {
490
+ if (npc.owner) {
491
+ return; // No body, label, snapshot, or public bubble, even for scripted lines.
492
+ }
253
493
  const line = `${npc.name}: ${String(text ?? '')}`.slice(0, SPEECH_MAX);
254
494
  h.npcLabel(npc.id, line, { style: 'speech', ttlMs, to, about });
495
+ // v1.47: gestures wait until even a private line has finished.
496
+ npc.speakingUntil = Math.max(npc.speakingUntil, ttlMs ? (h.sim?.timeMs ?? 0) + ttlMs : Infinity);
497
+ }
498
+
499
+ function react(h, n, playerId, emote) {
500
+ const player = h.sim?.players.get(playerId);
501
+ const entry = h.players?.get(playerId);
502
+ const now = h.sim?.timeMs ?? 0;
503
+ if (!player || (h.players && (!entry?.arrived || entry.ended)) || !Object.hasOwn(REACTIONS, emote) || !n.bodies.size || now - (n.reactAt.get(playerId) ?? -Infinity) < REACT_PLAYER_MS) {
504
+ return;
505
+ }
506
+ n.reactAt.set(playerId, now);
507
+ const nearby = [...n.bodies.values()]
508
+ .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)
509
+ .map((npc) => ({ npc, d: distanceTo(h, npc, playerId) }))
510
+ .filter(({ d }) => d <= REACT_RANGE_M)
511
+ .sort((a, b) => a.d - b.d || a.npc.id.localeCompare(b.npc.id));
512
+ let count = 0;
513
+ for (const { npc } of nearby) {
514
+ let override;
515
+ try {
516
+ override = syncHookResult(h, 'npcReact', h.hooks.npcReact?.(h.ctx, handleOf(h, n, npc), playerId, { emote }));
517
+ } catch {
518
+ // No error detail: a place hook may have read private character data.
519
+ warnOnce(h, 'npcReact', 'npcReact hook failed; using the default');
520
+ }
521
+ if (override === false) {
522
+ continue;
523
+ }
524
+ const defaults = REACTIONS[emote];
525
+ const props = npc.props.reactions?.[emote];
526
+ let id = reactionEmote(props?.emote, defaults.emote);
527
+ 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;
528
+ // A stable choice per body and tick; no client or model chooses it.
529
+ let seed = Math.floor(now);
530
+ for (const char of npc.id) {
531
+ seed = (Math.imul(seed, 31) + char.charCodeAt(0)) >>> 0;
532
+ }
533
+ let text = seed % 3 === 0 ? lines[Math.floor(seed / 3) % lines.length] : null;
534
+ if (override && typeof override === 'object') {
535
+ id = reactionEmote(override.emote, id);
536
+ if (Object.hasOwn(override, 'line')) {
537
+ text = cleanLine(override.line, 80);
538
+ }
539
+ }
540
+ npc.reactedAt = now;
541
+ npc.reaction = { at: { ...player.at }, until: now + (EMOTES[id] ?? 2000) };
542
+ faceToward(npc, player.at);
543
+ npc.body.setNextKinematicRotation({ x: 0, y: Math.sin(npc.yaw / 2), z: 0, w: Math.cos(npc.yaw / 2) });
544
+ if (id) {
545
+ n.emotesUsed = true;
546
+ n.emotes.set(npc.id, { id, at: now, until: now + EMOTES[id] });
547
+ }
548
+ if (text) {
549
+ say(h, npc, text, { ttlMs: 3000 });
550
+ }
551
+ if (++count === 3) {
552
+ break;
553
+ }
554
+ }
555
+ }
556
+
557
+ function reactionEmote(value, fallback) {
558
+ return value === null ? null : typeof value === 'string' && Object.hasOwn(EMOTES, value) ? value : fallback;
559
+ }
560
+
561
+ function cleanLine(value, max) {
562
+ return typeof value === 'string' ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim().slice(0, max) : '';
563
+ }
564
+
565
+ // v1.47: these hooks answer now; a rejected promise must not expose its error.
566
+ function syncHookResult(h, name, result) {
567
+ if (typeof result?.then === 'function') {
568
+ Promise.resolve(result).catch(() => warnOnce(h, `${name}:async`, `${name} async hook failed; using the default`));
569
+ return null;
570
+ }
571
+ return result;
255
572
  }
256
573
 
257
574
  function distanceTo(h, npc, playerId) {
575
+ if (npc.owner) {
576
+ return 0;
577
+ }
258
578
  const player = h.sim?.players.get(playerId);
259
579
  if (!player) {
260
580
  return Infinity;
@@ -277,82 +597,351 @@ function sessionCharacters(h) {
277
597
  return h.session?.characters ?? h.session?.world?.characters ?? null;
278
598
  }
279
599
 
600
+ const CHILD_ASKS = ['What can I do here?', 'Tell me about yourself.', 'Where should I go next?'];
601
+
602
+ function under13(h, playerId) {
603
+ return h.session?.players?.find?.((p) => p.playerId === playerId)?.under13 === true;
604
+ }
605
+
606
+ function choicesOnly(h, playerId) {
607
+ return h.place.under13Choices === true && under13(h, playerId);
608
+ }
609
+
610
+ // v1.142: bundle chips apply in every place, independently of legacy choices.
611
+ function childAsks(h, npc, playerId) {
612
+ if (!under13(h, playerId) || !hasMind(h, npc)) {
613
+ return null;
614
+ }
615
+ const asks = h.characterBundle?.characters?.find((c) => c.id === npc.character)?.childAsks;
616
+ return Array.isArray(asks) && asks.length ? asks : null;
617
+ }
618
+
280
619
  function open(h, n, playerId, npcId) {
281
- const npc = n.bodies.get(npcId);
620
+ const npc = h.place.companionChat && typeof npcId === 'string' && npcId.startsWith('companion:')
621
+ ? virtualForOpen(h, n, playerId, npcId) : n.bodies.get(npcId);
282
622
  if (!npc || distanceTo(h, npc, playerId) > npc.talkRange) {
283
623
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why: 'far' });
284
624
  return;
285
625
  }
286
- if (npc.talking && npc.talking.playerId !== playerId) {
626
+ if (fullFor(npc, playerId)) {
287
627
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why: 'busy' });
288
- line(h, npc, playerId, 'busy');
628
+ line(h, n, npc, playerId, 'busy');
289
629
  return;
290
630
  }
291
- npc.talking = { playerId, at: h.sim.timeMs };
631
+ const talking = { playerId, at: h.sim.timeMs, conversation: ++npc.conversation, accountKey: metKey(h, playerId), body: h.sim.players.get(playerId), said: false };
632
+ let state = speakerState(npc, playerId);
633
+ if (npc.speakers && !state?.talking) {
634
+ // Reopening a closed slot goes to the back, retaining its in-flight turn.
635
+ npc.speakers.delete(playerId);
636
+ state ??= { talking: null, pending: null, notes: null, opening: null };
637
+ npc.speakers.set(playerId, state);
638
+ }
639
+ state.talking = talking;
640
+ h.ctx.track?.(playerId, 'npc_chat_count', { subject: 9, value: 1 });
292
641
  // A new conversation can ask again for what an earlier one finished.
293
642
  const participant = n.participants.get(playerId);
294
643
  if (participant) {
295
644
  npc.followDone.delete(participant);
296
645
  }
297
646
  const mind = hasMind(h, npc);
298
- h.ctx.send(playerId, {
299
- k: 'hub-npc',
300
- npc: npcId,
301
- open: true,
302
- mind,
303
- character: mind ? npc.character : null,
304
- name: npc.name,
305
- // A client from before v1.17 named the players within `hearRange` as a
306
- // turn's listeners: zero has it name nobody.
307
- hearRange: 0,
308
- disclosure: 'participants',
309
- });
310
- npc.notes = null;
311
- if (!mind) {
312
- line(h, npc, playerId, 'hello');
647
+ const bundled = childAsks(h, npc, playerId);
648
+ const greeting = !bundled && mind && !npc.owner ? greetingOf(h, n, playerId, npc.character) : null;
649
+ const placed = openingOf(h, n, npc, playerId, greeting, talking.conversation);
650
+ // v1.148: an under-13 speaker taps the place's own authored asks (its
651
+ // answers, never a mind turn) ahead of any bundle chips.
652
+ const taps = mind && under13(h, playerId) && !choicesOnly(h, playerId) && placed?.authored ? placed.asks : null;
653
+ const child = taps ? null : bundled;
654
+ state.taps = taps;
655
+ // v1.46: a mind speaks first even where the place gives it no words.
656
+ let opening = child
657
+ ? { text: `Tap a question to talk with ${npc.name.split(',')[0].trim()}.` }
658
+ : placed ?? (mind ? { text: `Hi, I'm ${npc.name.split(',')[0].trim()}! Ask me anything.`, asks: [...DEFAULT_ASKS], more: [...DEFAULT_MORE] } : null);
659
+ // v1.47: memory changes this speaker's first words, never the questions.
660
+ if (greeting) {
661
+ opening = { ...opening, text: greeting };
662
+ }
663
+ // v1.47: a place hook may have replaced the speaker while choosing words.
664
+ if (!conversationOf(h, npc, playerId, talking)) {
665
+ return;
666
+ }
667
+ const emit = () => {
668
+ if (!conversationOf(h, npc, playerId, talking)) {
669
+ return;
670
+ }
671
+ h.ctx.send(playerId, {
672
+ k: 'hub-npc',
673
+ npc: npcId,
674
+ open: true,
675
+ mind,
676
+ character: mind ? npc.character : null,
677
+ name: npc.name,
678
+ // A client from before v1.17 named the players within `hearRange` as a
679
+ // turn's listeners: zero has it name nobody.
680
+ hearRange: 0,
681
+ disclosure: 'participants',
682
+ ...(child ? { choices: child.map(({ id, label }) => ({ id, label })) } : taps ? { choices: [...taps], authoredChoices: true } : choicesOnly(h, playerId) ? { choices: [...CHILD_ASKS] } : {}),
683
+ // A mind's under-13 speaker, by the trusted identity alone and in every
684
+ // place: their own panel may say why typing is off. Only to them.
685
+ ...(mind && under13(h, playerId) ? { ageOff: true } : {}),
686
+ // A body without a mind or a place opening keeps its hello line.
687
+ ...(opening ? { opening } : {}),
688
+ });
689
+ state.notes = null;
690
+ state.opening = opening ? { playerId, text: opening.text } : null;
691
+ if (!mind) {
692
+ // An opening is the NPC's hello; without one, the place's or the kit's.
693
+ if (!opening) {
694
+ line(h, n, npc, playerId, 'hello');
695
+ }
696
+ return;
697
+ }
698
+ issueNotes(h, npc, playerId);
699
+ };
700
+ if (!child && h.place.talkLog === true && typeof opening?.text === 'string' && opening.text) {
701
+ Promise.resolve().then(() => archiveTalk(h, npc, playerId, {
702
+ operationId: logOperation('opening', talking.conversation), conversationId: String(talking.conversation), reply: opening.text,
703
+ })).then(emit).catch(() => logRefused(h, n, npc, playerId));
704
+ } else {
705
+ emit();
706
+ }
707
+
708
+ }
709
+
710
+ // How this player is known to `met`: their account where they have one.
711
+ function userIdOf(h, playerId) {
712
+ const userId = h.session?.players?.find?.((p) => p.playerId === playerId)?.userId;
713
+ return typeof userId === 'string' && userId ? userId : null;
714
+ }
715
+
716
+ function metKey(h, playerId) {
717
+ const userId = userIdOf(h, playerId);
718
+ return userId ? `u:${userId}` : `p:${playerId}`;
719
+ }
720
+
721
+ function clearTalk(npc, playerId) {
722
+ const state = speakerState(npc, playerId);
723
+ if (!state) {
724
+ return;
725
+ }
726
+ state.talking = null;
727
+ state.opening = null;
728
+ state.notes = null;
729
+ state.taps = null;
730
+ }
731
+
732
+ // v1.47: copies of a greeting in the conversation belong to its account/body too.
733
+ function conversationOf(h, npc, playerId, expected = talkingOf(npc, playerId)) {
734
+ const talking = talkingOf(npc, playerId);
735
+ if (!talking || talking !== expected || talking.playerId !== playerId) {
736
+ return null;
737
+ }
738
+ const body = h.sim?.players.get(playerId);
739
+ if (!body || talking.accountKey !== metKey(h, playerId) || talking.body !== body) {
740
+ clearTalk(npc, playerId);
741
+ if (body) {
742
+ h.ctx.send(playerId, { k: 'hub-npc', npc: npc.id, open: false, why: 'left' });
743
+ }
744
+ return null;
745
+ }
746
+ return talking;
747
+ }
748
+
749
+ function greetingOf(h, n, playerId, character) {
750
+ const cached = n.greetings.get(playerId);
751
+ if (!cached) {
752
+ return null;
753
+ }
754
+ // v1.47: a recycled player id is neither the account nor the body we read.
755
+ if (!cached.userId || cached.userId !== userIdOf(h, playerId) || cached.body !== h.sim?.players.get(playerId)) {
756
+ n.greetings.delete(playerId);
757
+ return null;
758
+ }
759
+ return cached.characters.get(character) ?? null;
760
+ }
761
+
762
+ function refreshOpening(h, n, npc, playerId) {
763
+ const talking = conversationOf(h, npc, playerId);
764
+ const state = speakerState(npc, playerId);
765
+ if (childAsks(h, npc, playerId) || state?.taps || !talking || talking.said || state.opening?.playerId !== playerId || !hasMind(h, npc)) {
766
+ return;
767
+ }
768
+ const text = greetingOf(h, n, playerId, npc.character);
769
+ if (!text || text === state.opening.text) {
770
+ return;
771
+ }
772
+ // v1.47: an approach read can finish after the panel showed its first words.
773
+ const emit = () => {
774
+ if (!conversationOf(h, npc, playerId, talking) || talking.said) {
775
+ return;
776
+ }
777
+ state.opening.text = text;
778
+ h.ctx.send(playerId, { k: 'hub-npc-opening', npc: npc.id, text });
779
+ issueNotes(h, npc, playerId, { force: true });
780
+ };
781
+ if (h.place.talkLog === true) {
782
+ Promise.resolve().then(() => archiveTalk(h, npc, playerId, {
783
+ operationId: logOperation('opening-refresh', talking.conversation), conversationId: String(talking.conversation), reply: text,
784
+ })).then(emit).catch(() => logRefused(h, n, npc, playerId));
785
+ } else {
786
+ emit();
787
+ }
788
+ }
789
+
790
+ // The player said something to this NPC: they have met. Kept only where a
791
+ // place asks (`npcOpening`), for at most MET_MAX players an NPC, the longest
792
+ // ago first to go; a guest (no account) is forgotten when they leave.
793
+ function metNow(h, n, npc, playerId) {
794
+ if (typeof h.hooks.npcOpening !== 'function') {
313
795
  return;
314
796
  }
315
- issueNotes(h, npc, playerId);
797
+ let set = n.met.get(npc.id);
798
+ if (!set) {
799
+ n.met.set(npc.id, (set = new Set()));
800
+ }
801
+ const key = metKey(h, playerId);
802
+ set.delete(key);
803
+ set.add(key);
804
+ while (set.size > MET_MAX) {
805
+ set.delete(set.values().next().value);
806
+ }
807
+ }
808
+
809
+ // A player left: an NPC has not met a guest it could not know again.
810
+ function metLeft(n, playerId) {
811
+ for (const set of n.met.values()) {
812
+ set.delete(`p:${playerId}`);
813
+ }
814
+ }
815
+
816
+ // What an NPC says first when a player opens its chat, and up to three things
817
+ // the player might ask it (v1.37): the place's `npcOpening` hook, shown in
818
+ // that player's panel at once, with no model called. A string is the words
819
+ // alone. v1.46: `more` holds later questions; no words leaves a mind's default.
820
+ function openingOf(h, n, npc, playerId, greeting, conversation) {
821
+ if (typeof h.hooks.npcOpening !== 'function') {
822
+ return null;
823
+ }
824
+ let said = null;
825
+ try {
826
+ 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;
827
+ } catch (err) {
828
+ // v1.47: the hook's error may quote this speaker's greeting.
829
+ console.warn(greeting || npc.owner ? '[hub] npcOpening failed' : `[hub] npcOpening failed: ${err?.stack ?? err}`);
830
+ return null;
831
+ }
832
+ const words = typeof said === 'string' ? said : said?.text;
833
+ const text = typeof words === 'string' ? words.trim().slice(0, SPEECH_MAX) : '';
834
+ if (!text) {
835
+ return null;
836
+ }
837
+ const asks = [];
838
+ for (const ask of Array.isArray(said?.asks) ? said.asks : []) {
839
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
840
+ if (question && !asks.includes(question) && asks.length < ASKS_MAX) {
841
+ asks.push(question);
842
+ }
843
+ }
844
+ const more = [];
845
+ for (const ask of Array.isArray(said?.more) ? said.more : []) {
846
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
847
+ if (question && !asks.includes(question) && !more.includes(question) && more.length < MORE_MAX) {
848
+ more.push(question);
849
+ }
850
+ }
851
+ // v1.148: the place answers these asks itself (npcLine 'authored').
852
+ return { text, asks, ...(more.length ? { more } : {}), ...(said?.authored === true && asks.length ? { authored: true } : {}) };
316
853
  }
317
854
 
318
855
  // The place's notes for the character about this speaker now, framed as the
319
856
  // prefix their client sends ahead of their words, or null for none.
320
857
  function notesPrefix(h, npc, playerId) {
858
+ const state = speakerState(npc, playerId);
321
859
  let notes = null;
322
860
  try {
323
861
  notes = h.hooks.npcContext?.(h.ctx, h.ctx.npc(npc.id), playerId) ?? null;
324
862
  } catch (err) {
325
- console.warn(`[hub] npcContext failed: ${err?.stack ?? err}`);
863
+ console.warn(npc.owner ? '[hub] npcContext failed' : `[hub] npcContext failed: ${err?.stack ?? err}`);
326
864
  }
327
- if (typeof notes !== 'string') {
865
+ // v1.37: what the NPC opened this conversation with, so its mind does not
866
+ // greet again or contradict it. Only a place that gives notes at all has
867
+ // any (one without `npcContext` sends its turns as the words alone).
868
+ const opened =
869
+ typeof h.hooks.npcContext === 'function' && state.opening?.playerId === playerId
870
+ ? `You opened this conversation by saying: "${state.opening.text}"`.replace(/[[\]]/g, '')
871
+ : null;
872
+ if (typeof notes !== 'string' && !opened) {
328
873
  return null;
329
874
  }
330
875
  // The frame's brackets are the kit's alone, so nothing in the notes (a
331
876
  // username) can close it early.
332
- const text = notes.replace(/[[\]]/g, '').trim().slice(0, NOTES_MAX);
877
+ let text = typeof notes === 'string' ? notes.replace(/[[\]]/g, '').trim().slice(0, NOTES_MAX) : '';
878
+ // The place's notes come first and whole; the opening has what is left of
879
+ // NOTES_MAX, and is left out where that is too little to say it.
880
+ const room = NOTES_MAX - text.length - (text ? 1 : 0);
881
+ if (opened && room >= Math.min(opened.length, OPENED_MIN)) {
882
+ text = `${text}${text ? '\n' : ''}${opened.slice(0, room)}`;
883
+ }
333
884
  return text ? `${NOTES_HEAD}${text}${NOTES_SAYS}` : null;
334
885
  }
335
886
 
887
+ // v1.80: questions the place keeps on offer, only for this speaker.
888
+ function persistentAsksOf(h, npc, playerId) {
889
+ try {
890
+ const offered = syncHookResult(h, 'npcAsks', h.hooks.npcAsks(h.ctx, h.ctx.npc(npc.id), playerId));
891
+ const asks = [];
892
+ for (const ask of Array.isArray(offered?.persistentAsks) ? offered.persistentAsks : []) {
893
+ const question = typeof ask === 'string' ? ask.trim().slice(0, ASK_MAX) : '';
894
+ if (question && !asks.includes(question)) {
895
+ asks.push(question);
896
+ if (asks.length === PERSISTENT_ASKS_MAX) {
897
+ break;
898
+ }
899
+ }
900
+ }
901
+ return asks;
902
+ } catch {
903
+ // A hook's error may contain the player's private words.
904
+ warnOnce(h, 'npcAsks', 'npcAsks failed');
905
+ return [];
906
+ }
907
+ }
908
+
336
909
  // Reads the notes for the speaker of a body with a mind and, when they
337
910
  // changed (or `force`, after a turn was refused for its notes), sends them to
338
- // that speaker's client.
911
+ // that speaker's client. A changed chip offer also issues the latest notes.
339
912
  function issueNotes(h, npc, playerId, { force = false } = {}) {
913
+ const talking = conversationOf(h, npc, playerId);
914
+ const state = speakerState(npc, playerId);
340
915
  const now = h.sim.timeMs;
341
- if (!hasMind(h, npc)) {
916
+ if (!talking || !hasMind(h, npc) || childAsks(h, npc, playerId)) {
342
917
  return;
343
918
  }
344
- if (npc.notes?.playerId !== playerId) {
345
- npc.notes = { playerId, list: [], readAt: -Infinity };
919
+ if (state.notes?.playerId !== playerId) {
920
+ state.notes = { playerId, list: [], readAt: -Infinity };
346
921
  }
347
- npc.notes.readAt = now;
922
+ state.notes.readAt = now;
348
923
  const prefix = notesPrefix(h, npc, playerId);
349
- const list = npc.notes.list;
924
+ // v1.80: the place may keep up to two questions on offer after a reply.
925
+ // An absent hook keeps the old notes state and message bytes.
926
+ const persistentAsks = typeof h.hooks.npcAsks === 'function' ? persistentAsksOf(h, npc, playerId) : undefined;
927
+ // Recheck after npcContext and npcAsks, before sending anything private.
928
+ if (!conversationOf(h, npc, playerId, talking)) {
929
+ return;
930
+ }
931
+ const list = state.notes.list;
932
+ let asksChanged = false;
933
+ if (persistentAsks !== undefined) {
934
+ const previous = state.notes.persistentAsks ?? [];
935
+ asksChanged = previous.length !== persistentAsks.length || previous.some((ask, i) => ask !== persistentAsks[i]);
936
+ state.notes.persistentAsks = persistentAsks;
937
+ }
938
+ const asks = persistentAsks === undefined ? {} : { persistentAsks };
350
939
  if ((list.at(-1)?.prefix ?? null) === prefix) {
351
940
  if (list.length) {
352
941
  list.at(-1).at = now;
353
942
  }
354
- if (force) {
355
- h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix });
943
+ if (force || asksChanged) {
944
+ h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix, ...asks });
356
945
  }
357
946
  return;
358
947
  }
@@ -360,7 +949,7 @@ function issueNotes(h, npc, playerId, { force = false } = {}) {
360
949
  while (list.length > NOTES_KEPT) {
361
950
  list.shift();
362
951
  }
363
- h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix });
952
+ h.ctx.send(playerId, { k: 'hub-npc-notes', npc: npc.id, prefix, ...asks });
364
953
  }
365
954
 
366
955
  // The player's own words in a turn's input, or null when the input does not
@@ -375,7 +964,8 @@ function wordsOf(h, npc, speaker, input) {
375
964
  return input;
376
965
  }
377
966
  const now = h.sim.timeMs;
378
- const list = npc.notes?.playerId === speaker ? npc.notes.list : [];
967
+ const notes = speakerState(npc, speaker)?.notes;
968
+ const list = notes?.playerId === speaker ? notes.list : [];
379
969
  const accepted = list.filter((e, i) => i === list.length - 1 || now - e.at <= NOTES_KEEP_MS);
380
970
  // Notes first: an accepted empty entry (the place gave none a moment ago)
381
971
  // matches every input, so it is tried last.
@@ -395,32 +985,71 @@ function wordsOf(h, npc, speaker, input) {
395
985
  }
396
986
 
397
987
  function endTalk(h, n, npcId, playerId, why) {
398
- const npc = n.bodies.get(npcId);
399
- if (!npc || npc.talking?.playerId !== playerId) {
988
+ const npc = recordOf(n, npcId);
989
+ if (!npc || !talkingOf(npc, playerId)) {
400
990
  return;
401
991
  }
402
- npc.talking = null;
992
+ clearTalk(npc, playerId);
403
993
  h.ctx.send(playerId, { k: 'hub-npc', npc: npcId, open: false, why });
404
994
  }
405
995
 
996
+ // No read API: identity/deck/place are stamped by the platform, not the client.
997
+ // Absent talkLog never calls storage or changes the synchronous delivery path.
998
+ // Ghost refuses archive writes for any player under 13, so none is attempted:
999
+ // a refusal would close their opening (and its 13+ line) as unavailable.
1000
+ function archiveTalk(h, npc, playerId, entry) {
1001
+ if (under13(h, playerId)) {return;}
1002
+ return h.session.hub.archiveText(playerId, {
1003
+ npcId: npc.id,
1004
+ ...(typeof npc.character === 'string' && npc.character ? { characterId: npc.character } : {}),
1005
+ ...entry,
1006
+ });
1007
+ }
1008
+
1009
+ function logRefused(h, n, npc, playerId) {
1010
+ console.warn('[hub] NPC transcript unavailable');
1011
+ endTalk(h, n, npc.id, playerId, 'unavailable');
1012
+ }
1013
+
1014
+ function logOperation(why, conversation) {
1015
+ return `${why}:${conversation ?? ''}:${Date.now()}:${Math.random().toString(36).slice(2)}`;
1016
+ }
1017
+
406
1018
  // The place's authored words for this moment (`npcLine`), or the kit's.
407
- function line(h, npc, playerId, why, text) {
1019
+ function line(h, n, npc, playerId, why, text, op, rid, conversation, fallback = why) {
1020
+ // v1.148: authored taps lead bundle chips, so their answers are said.
1021
+ if (childAsks(h, npc, playerId) && !(why === 'authored' && speakerState(npc, playerId)?.taps)) {return;}
408
1022
  let said = null;
409
1023
  try {
410
- said = h.hooks.npcLine?.(h.ctx, h.ctx.npc(npc.id), playerId, { why, text: text ?? null }) ?? null;
1024
+ said = h.hooks.npcLine?.(h.ctx, h.ctx.npc(npc.id), playerId, { why, text: text ?? null, ...(conversation !== undefined ? { conversation } : {}) }) ?? null;
411
1025
  } catch (err) {
412
- console.warn(`[hub] npcLine failed: ${err?.stack ?? err}`);
1026
+ console.warn(text !== undefined || npc.owner ? '[hub] npcLine failed' : `[hub] npcLine failed: ${err?.stack ?? err}`);
413
1027
  }
414
1028
  if (said === null || said === undefined) {
415
- said = DEFAULT_LINES[why]?.(npc.name, h.ctx.username(playerId)) ?? null;
1029
+ said = DEFAULT_LINES[fallback]?.(npc.name, h.ctx.username(playerId)) ?? null;
416
1030
  }
417
- if (said) {
418
- // The line may name the player (the kit's hello does): nobody a block
419
- // hides them from is ever sent it, a player who arrives later included.
420
- say(h, npc, said, { about: playerId });
421
- // `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 });
1031
+ const emit = () => {
1032
+ if (said) {
1033
+ // The line may name the player (the kit's hello does): nobody a block
1034
+ // hides them from is ever sent it, a player who arrives later included.
1035
+ say(h, npc, said, { about: playerId, ...(npc.speakers && text !== undefined ? { to: [playerId] } : {}) });
1036
+ // `why` lets the speaker's panel say an answer was scripted, not the mind's.
1037
+ h.ctx.send(playerId, { k: 'hub-npc-line', npc: npc.id, text: String(said).slice(0, SPEECH_MAX), why, ...(op ? { op } : {}), ...(rid ? { rid } : {}) });
1038
+ }
1039
+ };
1040
+ if (h.place.talkLog === true && (said || text !== undefined)) {
1041
+ const entry = { operationId: op ? `${op}:script:${why}` : rid ? `authored:${playerId}:${rid}` : logOperation(why, conversation),
1042
+ ...(conversation !== undefined ? { conversationId: String(conversation) } : {}),
1043
+ ...(text !== undefined ? { input: text } : {}),
1044
+ ...(said ? { reply: String(said).slice(0, SPEECH_MAX) } : {}),
1045
+ };
1046
+ return Promise.resolve().then(() => archiveTalk(h, npc, playerId, entry)).then(() => {
1047
+ if (h.sim.players.has(playerId) && (conversation === undefined || talkingOf(npc, playerId)?.conversation === conversation)) {
1048
+ emit();
1049
+ }
1050
+ }).catch(() => logRefused(h, n, npc, playerId));
423
1051
  }
1052
+ emit();
424
1053
  }
425
1054
 
426
1055
  const DEFAULT_LINES = {
@@ -428,22 +1057,44 @@ const DEFAULT_LINES = {
428
1057
  busy: (name) => `${name} is talking with someone else.`,
429
1058
  budget: (name) => `${name} has a crowd to answer. Try again in a moment.`,
430
1059
  unavailable: (name) => `${name} doesn't catch that. Try again in a moment.`,
1060
+ // The kit's unavailable line when ghost refused this turn's characters
1061
+ // outright: it promises no retry. The hook still hears `unavailable`.
1062
+ refused: (name) => `${name} smiles and nods.`,
431
1063
  };
432
1064
 
433
1065
  // Words to a body with no mind here (the dev serve, a session the host brokers
434
1066
  // 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') {
1067
+ function authoredSay(h, n, playerId, npcId, text, rid) {
1068
+ const npc = recordOf(n, npcId);
1069
+ if (!npc || typeof text !== 'string') {
1070
+ return;
1071
+ }
1072
+ const talking = conversationOf(h, npc, playerId);
1073
+ if (!talking) {
438
1074
  return;
439
1075
  }
440
1076
  const now = h.sim.timeMs;
441
- if (now - (n.saidAt.get(playerId) ?? -Infinity) < SAY_GAP_MS || hasMind(h, npc)) {
1077
+ // v1.148: a mind hears here only its under-13 speaker's authored taps.
1078
+ const taps = hasMind(h, npc) ? speakerState(npc, playerId)?.taps : null;
1079
+ if (now - (n.saidAt.get(playerId) ?? -Infinity) < SAY_GAP_MS || (hasMind(h, npc) && !taps?.includes(text.trim()))) {
442
1080
  return;
443
1081
  }
1082
+ if (taps) {
1083
+ text = text.trim();
1084
+ }
1085
+ if (choicesOnly(h, playerId)) {
1086
+ text = text.trim();
1087
+ if (!CHILD_ASKS.includes(text)) {
1088
+ return;
1089
+ }
1090
+ }
444
1091
  n.saidAt.set(playerId, now);
445
- npc.talking.at = now;
446
- line(h, npc, playerId, 'authored', text.slice(0, INPUT_MAX));
1092
+ talking.said = true;
1093
+ talking.at = now;
1094
+ metNow(h, n, npc, playerId);
1095
+ // v1.46: echo only this send's short request id, when its client gave one.
1096
+ const requestId = typeof rid === 'string' && rid.length <= 64 ? rid : null;
1097
+ line(h, n, npc, playerId, 'authored', text.slice(0, INPUT_MAX), undefined, requestId, talking.conversation);
447
1098
  }
448
1099
 
449
1100
  // A turn the host granted: the kit admits it only for the player this body is
@@ -452,20 +1103,33 @@ function authoredSay(h, n, playerId, npcId, text) {
452
1103
  // the speaker's words), inside the character's budget. Anything else is
453
1104
  // refused before a model is called.
454
1105
  async function admitTurn(h, n, turn) {
1106
+ // v1.76: greeting status reads can never name an admitted turn.
1107
+ if (typeof turn.operationId === 'string' && turn.operationId.startsWith('greeting:')) {
1108
+ turn.reject('HUB_NPC_OPERATION_RESERVED');
1109
+ return;
1110
+ }
455
1111
  const speaker = turn.speaker.playerId;
456
1112
  // Several bodies may share one character (the town's barkers): the one this
457
1113
  // 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];
1114
+ const bodies = [...talkRecords(n)].filter((b) => b.character === turn.characterId);
1115
+ const npc = bodies.find((b) => talkingOf(b, speaker)) ?? bodies[0];
460
1116
  const npcs = h.place.npcs;
461
1117
  if (!npc || !npcs || !hasMind(h, npc)) {
462
1118
  turn.reject('HUB_NPC_UNKNOWN');
463
1119
  return;
464
1120
  }
465
- if (npc.talking?.playerId !== speaker || distanceTo(h, npc, speaker) > npc.talkRange + 1) {
1121
+ if (npc.speakers && fullFor(npc, speaker)) {
1122
+ turn.reject('HUB_NPC_BUSY');
1123
+ line(h, n, npc, speaker, 'busy', undefined, turn.operationId);
1124
+ return;
1125
+ }
1126
+ const talking = conversationOf(h, npc, speaker);
1127
+ if (!talking || distanceTo(h, npc, speaker) > npc.talkRange + 1) {
466
1128
  turn.reject('HUB_NPC_NOT_TALKING');
467
1129
  return;
468
1130
  }
1131
+ const state = speakerState(npc, speaker);
1132
+ const conversation = talking.conversation;
469
1133
  const audience = turn.audience;
470
1134
  if (audience.disclosure !== 'participants' || audience.characterIds.length || audience.players.length) {
471
1135
  turn.reject('HUB_NPC_AUDIENCE');
@@ -475,49 +1139,97 @@ async function admitTurn(h, n, turn) {
475
1139
  // turn already admitted: ghost replays it, so it neither waits behind
476
1140
  // itself nor spends the budget twice.
477
1141
  const key = `${speaker}:${turn.operationId}`;
478
- const existing = n.turns.get(key) ?? (npc.pending?.key === key ? npc.pending : null);
1142
+ let existing = n.turns.get(key) ?? (state.pending?.key === key ? state.pending : null);
1143
+ // v1.47: a sent turn fixes the opening, even if its notes need a retry.
1144
+ if (typeof turn.input === 'string' && turn.input.trim()) {
1145
+ talking.said = true;
1146
+ }
1147
+ // v1.148: authored taps are answered by the place, never a mind turn.
1148
+ if (state?.taps) {
1149
+ turn.reject('HUB_NPC_CHOICE_REQUIRED');
1150
+ return;
1151
+ }
1152
+ const child = childAsks(h, npc, speaker);
1153
+ // Check raw bytes even on replay: no notes, whitespace or extra text.
1154
+ if (child && !child.some(({ id }) => turn.input === `choice:${id}`)) {
1155
+ turn.reject('HUB_NPC_CHOICE_REQUIRED');
1156
+ return;
1157
+ }
479
1158
  // A replay was checked when it was first admitted; its notes may be gone.
480
- const words = existing ? null : wordsOf(h, npc, speaker, turn.input);
1159
+ const words = existing ? null : child ? turn.input : wordsOf(h, npc, speaker, turn.input);
481
1160
  if (!existing && words === null) {
482
1161
  turn.reject('HUB_NPC_NOTES');
483
1162
  // The client may have missed the newest: send them again for its retry.
484
1163
  issueNotes(h, npc, speaker, { force: true });
485
1164
  return;
486
1165
  }
1166
+ if (!child && !existing && choicesOnly(h, speaker) && !CHILD_ASKS.includes(words)) {
1167
+ turn.reject('HUB_NPC_CHOICE_REQUIRED');
1168
+ return;
1169
+ }
1170
+ const archive = child || under13(h, speaker) ? undefined : existing?.archive ?? (h.place.talkLog === true && !existing
1171
+ ? { npcId: npc.id, conversationId: String(conversation), input: words } : undefined);
1172
+ if (archive && !existing) {
1173
+ try {
1174
+ await archiveTalk(h, npc, speaker, { operationId: turn.operationId, conversationId: archive.conversationId, input: words });
1175
+ } catch {
1176
+ turn.reject('HUB_NPC_LOG_UNAVAILABLE');
1177
+ return;
1178
+ }
1179
+ // This await may outlive a departure, replacement or conversation switch.
1180
+ if (!conversationOf(h, npc, speaker, talking)) {
1181
+ turn.reject('HUB_NPC_NOT_TALKING');
1182
+ return;
1183
+ }
1184
+ }
1185
+ if (!existing && state.pending?.key === key) {
1186
+ existing = state.pending;
1187
+ }
487
1188
  if (!existing) {
488
- if (npc.pending && !npc.pending.delivered && h.sim.timeMs - npc.pending.at < PENDING_MS) {
1189
+ if (state.pending && !state.pending.delivered && h.sim.timeMs - state.pending.at < PENDING_MS) {
489
1190
  turn.reject('HUB_NPC_BUSY');
1191
+ line(h, n, npc, speaker, 'busy', undefined, turn.operationId);
490
1192
  return;
491
1193
  }
492
1194
  const now = Date.now();
493
1195
  npc.recent = npc.recent.filter((at) => now - at < 60_000);
494
1196
  if (npc.recent.length >= npcs.turnsPerMinute) {
495
1197
  turn.reject('HUB_NPC_BUDGET');
496
- line(h, npc, speaker, 'budget');
1198
+ line(h, n, npc, speaker, 'budget', undefined, turn.operationId);
497
1199
  return;
498
1200
  }
499
1201
  npc.recent.push(now);
500
1202
  }
501
- npc.talking.at = h.sim.timeMs;
1203
+ talking.at = h.sim.timeMs;
502
1204
  const record = existing ?? {
503
1205
  key,
504
1206
  npc: npc.id,
505
1207
  speaker,
506
1208
  at: h.sim.timeMs,
507
1209
  delivered: false,
1210
+ ...(archive ? { archive } : {}),
508
1211
  };
509
1212
  // Only a new turn takes the body; a replay leaves whatever holds it.
510
1213
  if (!existing) {
511
- npc.pending = record;
1214
+ state.pending = record;
1215
+ }
1216
+ // v1.66: the place's tools ride with a new turn; a replay keeps the first
1217
+ // admission's. Without `npcTools` this is the send as it always was.
1218
+ if (!child && !existing && typeof h.hooks.npcTools === 'function') {
1219
+ record.tools = placeTools(h, npc, speaker);
512
1220
  }
513
1221
  try {
514
- await turn.send();
1222
+ if (!child && (record.tools || record.archive)) {
1223
+ await turn.send({ ...(record.tools ? { tools: record.tools.list } : {}), ...(record.archive ? { hubTextArchive: record.archive } : {}) });
1224
+ } else {
1225
+ await turn.send();
1226
+ }
515
1227
  } catch (err) {
516
- if (npc.pending === record && !existing) {
517
- npc.pending = null;
1228
+ if (state.pending === record && !existing) {
1229
+ state.pending = null;
518
1230
  }
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.
1231
+ // Ghost's place-mind capacity for this character is full: the place's
1232
+ // busy line, not its unavailable one.
521
1233
  // Ghost's town-wide budget for this character is spent this minute: the
522
1234
  // place's budget line, as for its own per-character budget.
523
1235
  const why =
@@ -526,22 +1238,135 @@ async function admitTurn(h, n, turn) {
526
1238
  : err?.code === 'CAULDRON_SHARED_CHARACTER_BUDGET'
527
1239
  ? 'budget'
528
1240
  : 'unavailable';
529
- line(h, npc, speaker, why);
1241
+ if (!npc.owner || recordOf(n, npc.id) === npc) {
1242
+ const refused = why === 'unavailable' && /characters are unavailable/i.test(typeof err?.message === 'string' ? err.message : '');
1243
+ line(h, n, npc, speaker, why, undefined, turn.operationId, undefined, undefined, refused ? 'refused' : why);
1244
+ }
530
1245
  throw err;
531
1246
  }
532
1247
  // A replayed admission keeps the first record, so a reply is shown once.
533
1248
  if (!existing) {
1249
+ if (npc.owner && recordOf(n, npc.id) !== npc) {
1250
+ return;
1251
+ }
534
1252
  n.turns.set(key, record);
535
1253
  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}`);
1254
+ // The words belong to the opening and identity that admitted them,
1255
+ // even when the same player id opens another conversation mid-send.
1256
+ if (talkingOf(npc, speaker)?.conversation === conversation && conversationOf(h, npc, speaker, talking)) {
1257
+ metNow(h, n, npc, speaker);
1258
+ try {
1259
+ syncHookResult(h, 'npcHeard', h.hooks.npcHeard?.(h.ctx, h.ctx.npc(npc.id), speaker, { text: words, conversation }));
1260
+ } catch {
1261
+ console.warn('[hub] npcHeard failed');
1262
+ }
541
1263
  }
542
1264
  }
543
1265
  }
544
1266
 
1267
+ // The place's declarations for this turn, kept only when every cap holds;
1268
+ // a bad entry is dropped, so a place's mistake costs a lookup, never a turn.
1269
+ function placeTools(h, npc, speaker) {
1270
+ let declared;
1271
+ try {
1272
+ // Read at admission and answered at once: a promise is no declarations.
1273
+ declared = syncHookResult(h, 'npcTools', h.hooks.npcTools(h.ctx, h.ctx.npc(npc.id), speaker));
1274
+ } catch {
1275
+ console.warn('[hub] npcTools failed');
1276
+ return null;
1277
+ }
1278
+ if (!Array.isArray(declared)) {
1279
+ return null;
1280
+ }
1281
+ try {
1282
+ return toolList(declared);
1283
+ } catch {
1284
+ console.warn('[hub] npcTools declarations unusable');
1285
+ return null;
1286
+ }
1287
+ }
1288
+
1289
+ function toolList(declared) {
1290
+ const list = [];
1291
+ const names = new Set();
1292
+ for (const tool of declared) {
1293
+ if (list.length >= TOOLS_MAX) {
1294
+ break;
1295
+ }
1296
+ const entry = toolEntry(tool);
1297
+ if (!entry || names.has(entry.name)) {
1298
+ continue;
1299
+ }
1300
+ if (Buffer.byteLength(JSON.stringify([...list, entry]), 'utf8') > TOOLS_BYTES) {
1301
+ break;
1302
+ }
1303
+ names.add(entry.name);
1304
+ list.push(entry);
1305
+ }
1306
+ return list.length ? { list, names, used: false } : null;
1307
+ }
1308
+
1309
+ function toolEntry(tool) {
1310
+ if (!tool || typeof tool !== 'object') {
1311
+ return null;
1312
+ }
1313
+ const { name, description, input_schema: schema } = tool;
1314
+ if (typeof name !== 'string' || !TOOL_NAME.test(name) || TOOL_RESERVED.has(name)) {
1315
+ return null;
1316
+ }
1317
+ if (typeof description !== 'string' || !description.trim() || description.length > TOOL_DESCRIPTION_MAX) {
1318
+ return null;
1319
+ }
1320
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) {
1321
+ return null;
1322
+ }
1323
+ let text;
1324
+ try {
1325
+ text = JSON.stringify(schema);
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ // A toJSON can make an object serialize as anything, or nothing.
1330
+ if (typeof text !== 'string' || !text.startsWith('{') || Buffer.byteLength(text, 'utf8') > TOOL_SCHEMA_BYTES) {
1331
+ return null;
1332
+ }
1333
+ return { name, description, input_schema: JSON.parse(text) };
1334
+ }
1335
+
1336
+ // One lookup: only for a turn this place admitted for that speaker and
1337
+ // character, only a tool it declared for that turn, and once. Anything else
1338
+ // answers an error and runs no hook. The place's answer goes to the mind
1339
+ // alone; the SDK caps and sends it.
1340
+ async function answerTool(h, n, request) {
1341
+ const { operationId, characterId, playerId, name, input } = request ?? {};
1342
+ const key = `${playerId}:${operationId}`;
1343
+ const record = n.turns.get(key) ?? [...talkRecords(n)].map((b) => pendingTurn(b, key)).find(Boolean) ?? null;
1344
+ const npc = record ? recordOf(n, record.npc) : null;
1345
+ if (
1346
+ !record?.tools ||
1347
+ record.speaker !== playerId ||
1348
+ !npc ||
1349
+ childAsks(h, npc, playerId) ||
1350
+ npc.character !== characterId ||
1351
+ !record.tools.names.has(name) ||
1352
+ record.tools.used ||
1353
+ !h.sim?.players.has(playerId) ||
1354
+ typeof h.hooks.npcTool !== 'function'
1355
+ ) {
1356
+ return { error: 'not available' };
1357
+ }
1358
+ record.tools.used = true;
1359
+ const started = Date.now();
1360
+ try {
1361
+ const answer = await h.hooks.npcTool(h.ctx, h.ctx.npc(npc.id), playerId, name, input ?? {});
1362
+ console.log(`[hub] npc tool ${name} ${Date.now() - started}ms`);
1363
+ return answer ?? { error: 'no answer' };
1364
+ } catch {
1365
+ console.warn(`[hub] npc tool ${name} failed`);
1366
+ return { error: 'tool failed' };
1367
+ }
1368
+ }
1369
+
545
1370
  function trimTurns(h, n) {
546
1371
  const now = h.sim?.timeMs ?? 0;
547
1372
  for (const [key, turn] of n.turns) {
@@ -561,15 +1386,87 @@ async function routeRead(h, n, request) {
561
1386
  request.reject('HUB_NPC_READ_NOT_ALLOWED');
562
1387
  return;
563
1388
  }
564
- const result = await request.read();
565
1389
  const speaker = request.speaker.playerId;
566
- if (type === 'inspect' && typeof result?.participantId === 'string') {
567
- n.participants.set(speaker, result.participantId);
1390
+ const body = h.sim?.players.get(speaker);
1391
+ const userId = userIdOf(h, speaker);
1392
+ const operationId = request.query.operationId;
1393
+ const read = {};
1394
+ if (type === 'inspect') {
1395
+ n.inspectReads.set(speaker, read);
1396
+ }
1397
+ let result;
1398
+ try {
1399
+ result = await request.read();
1400
+ } catch (err) {
1401
+ if (n.inspectReads.get(speaker) === read) {
1402
+ n.inspectReads.delete(speaker);
1403
+ }
1404
+ throw err;
1405
+ }
1406
+ if (type === 'inspect') {
1407
+ // v1.47: a read finishing after departure cannot restore private data.
1408
+ if (n.inspectReads.get(speaker) !== read) {
1409
+ return;
1410
+ }
1411
+ n.inspectReads.delete(speaker);
1412
+ if (!body || h.sim?.players.get(speaker) !== body || userIdOf(h, speaker) !== userId) {
1413
+ return;
1414
+ }
1415
+ if (typeof result?.participantId === 'string') {
1416
+ n.participants.set(speaker, result.participantId);
1417
+ }
1418
+ if (!userId) {
1419
+ n.greetings.delete(speaker);
1420
+ return;
1421
+ }
1422
+ const greetings = new Map();
1423
+ for (const character of Array.isArray(result?.characters) ? result.characters : []) {
1424
+ const text = cleanLine(character?.privateState?.nextGreeting?.text, SPEECH_MAX);
1425
+ if (typeof character?.characterId === 'string' && text) {
1426
+ greetings.set(character.characterId, text);
1427
+ }
1428
+ }
1429
+ n.greetings.set(speaker, { userId, body, characters: greetings });
1430
+ const hooks = [];
1431
+ for (const npc of n.bodies.values()) {
1432
+ refreshOpening(h, n, npc, speaker);
1433
+ if (!npc.owner && hasMind(h, npc) && h.sim.bodies.get(npc.id) === npc.body && greetings.has(npc.character)) {
1434
+ hooks.push({ npc: npc.id, character: npc.character });
1435
+ }
1436
+ }
1437
+ if (hooks.length && h.sim?.players.get(speaker) === body && userIdOf(h, speaker) === userId) {
1438
+ h.ctx.send(speaker, { k: 'hub-npc-hooks', hooks });
1439
+ }
568
1440
  return;
569
1441
  }
570
1442
  if (type !== 'status') {
571
1443
  return;
572
1444
  }
1445
+ // v1.76: ghost consumes this hook once, separately from turn status.
1446
+ if (typeof operationId === 'string' && operationId.startsWith('greeting:')) {
1447
+ const character = operationId.slice('greeting:'.length);
1448
+ const text = cleanLine(result?.greeting?.text, SPEECH_MAX);
1449
+ if (!userId || !body || h.sim?.players.get(speaker) !== body || userIdOf(h, speaker) !== userId || !character || result?.characterId !== character || !text) {
1450
+ return;
1451
+ }
1452
+ const nearby = [...n.bodies.values()]
1453
+ .filter((npc) => !childAsks(h, npc, speaker) && !npc.owner && npc.character === character && hasMind(h, npc) && h.sim.bodies.get(npc.id) === npc.body && !fullFor(npc, speaker))
1454
+ .map((npc) => ({ npc, d: distanceTo(h, npc, speaker) }))
1455
+ // The Chat prompt's range plus 2 m allows for movement during the read.
1456
+ .filter(({ npc, d }) => d <= npc.talkRange + 2)
1457
+ .sort((a, b) => a.d - b.d || a.npc.id.localeCompare(b.npc.id));
1458
+ if (nearby.length) {
1459
+ const npc = nearby[0].npc;
1460
+ if (h.place.talkLog === true) {
1461
+ await archiveTalk(h, npc, speaker, { operationId: logOperation('walk-greeting'), reply: text });
1462
+ if (h.sim?.players.get(speaker) !== body || userIdOf(h, speaker) !== userId) {
1463
+ return;
1464
+ }
1465
+ }
1466
+ say(h, npc, npcDisplayText(text), { to: [speaker], about: speaker });
1467
+ }
1468
+ return;
1469
+ }
573
1470
  const turn = n.turns.get(`${speaker}:${request.query.operationId}`);
574
1471
  const done = result?.status === 'completed' || result?.status === 'interrupted';
575
1472
  if (!turn || turn.delivered || !done) {
@@ -578,15 +1475,19 @@ async function routeRead(h, n, request) {
578
1475
  // Finished, with words or without (an interrupted turn may have none):
579
1476
  // either way the body is free for its next turn.
580
1477
  turn.delivered = true;
581
- const npc = n.bodies.get(turn.npc);
1478
+ const npc = recordOf(n, turn.npc);
582
1479
  if (!npc) {
583
1480
  return;
584
1481
  }
585
- if (npc.pending === turn) {
586
- npc.pending = null;
1482
+ const state = speakerState(npc, speaker);
1483
+ if (state?.pending === turn) {
1484
+ state.pending = null;
587
1485
  }
588
1486
  if (typeof result.response === 'string' && result.response.trim() && h.sim?.players.has(turn.speaker)) {
589
- say(h, npc, unquote(result.response), { to: [turn.speaker], about: turn.speaker });
1487
+ say(h, npc, npcDisplayText(result.response), { to: [turn.speaker], about: turn.speaker });
1488
+ }
1489
+ if (npc.owner) {
1490
+ return; // The owner reads the reply in the panel; no follow or public read.
590
1491
  }
591
1492
  // The reply may have come with the character's follow action.
592
1493
  n.watchUntil = h.sim.timeMs + FOLLOW_WATCH_MS;
@@ -599,7 +1500,7 @@ function pollFollow(h, n) {
599
1500
  const world = sessionCharacters(h);
600
1501
  const now = h.sim?.timeMs ?? 0;
601
1502
  const following = [...n.bodies.values()].some((npc) => npc.following && npc.followByToken);
602
- const gap = Math.min(FOLLOW_POLL_MS * 2 ** n.inspectFailures, 60_000);
1503
+ const gap = Math.min(FOLLOW_POLL_MS * 2 ** n.inspectFailures, FOLLOW_POLL_MAX_MS);
603
1504
  if (!world || n.polling || (now > n.watchUntil && !following) || now - n.polledAt < gap) {
604
1505
  return;
605
1506
  }
@@ -617,8 +1518,11 @@ function pollFollow(h, n) {
617
1518
  .catch((err) => {
618
1519
  // Backed off, not given up: a transient failure must not stop a later
619
1520
  // follow from being seen.
620
- n.inspectFailures = Math.min(n.inspectFailures + 1, 5);
621
- console.warn(`[hub] NPC follow could not read the world's public projection: ${err?.message ?? err}`);
1521
+ // Logged once per run of failures.
1522
+ if (!n.inspectFailures) {
1523
+ console.warn(`[hub] NPC follow could not read the world's public projection: ${err?.message ?? err}`);
1524
+ }
1525
+ n.inspectFailures = Math.min(n.inspectFailures + 1, Math.ceil(Math.log2(FOLLOW_POLL_MAX_MS / FOLLOW_POLL_MS)));
622
1526
  })
623
1527
  .finally(() => {
624
1528
  n.polling = false;
@@ -628,7 +1532,7 @@ function pollFollow(h, n) {
628
1532
  function applyFollow(h, n, view) {
629
1533
  const objects = view?.gameplay?.objects ?? {};
630
1534
  for (const npc of n.bodies.values()) {
631
- if (!npc.followObject) {
1535
+ if (!npc.followObject || npc.movementHeld) {
632
1536
  continue;
633
1537
  }
634
1538
  const holder = objects[npc.followObject]?.holderId ?? null;
@@ -645,18 +1549,29 @@ function applyFollow(h, n, view) {
645
1549
  }
646
1550
  }
647
1551
 
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.
1552
+ // One body's tick: a conversation holds it facing its speaker; a reaction
1553
+ // holds it until expiry, then queued place movement and idle facing resume.
650
1554
  function moveBody(h, n, npc, dt) {
651
1555
  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;
1556
+ for (const talking of conversations(npc)) {
1557
+ const gone = !h.sim.players.has(talking.playerId);
1558
+ const idle = now - talking.at > IDLE_END_MS;
1559
+ const far = distanceTo(h, npc, talking.playerId) > LEAVE_RANGE_M;
656
1560
  if (gone || idle || far) {
657
- endTalk(h, n, npc.id, npc.talking.playerId, gone ? 'left' : idle ? 'idle' : 'far');
1561
+ endTalk(h, n, npc.id, talking.playerId, gone ? 'left' : idle ? 'idle' : 'far');
1562
+ }
1563
+ }
1564
+ // A closed speaker retains its turn until delivered or timed out, just as
1565
+ // the legacy body does, without retaining notes or occupying a slot.
1566
+ for (const [playerId, state] of npc.speakers ?? []) {
1567
+ if (!state.talking && (!state.pending || state.pending.delivered || now - state.pending.at >= PENDING_MS)) {
1568
+ npc.speakers.delete(playerId);
658
1569
  }
659
1570
  }
1571
+ if (npc.movementHeld) {
1572
+ npc.body.setNextKinematicTranslation(npc.body.translation());
1573
+ return;
1574
+ }
660
1575
  const followLimit = (h.place.npcs?.followSec ?? 120) * 1000;
661
1576
  if (npc.following && (!h.sim.players.has(npc.following) || now - npc.followSince > followLimit)) {
662
1577
  const participant = n.participants.get(npc.following);
@@ -668,8 +1583,12 @@ function moveBody(h, n, npc, dt) {
668
1583
  }
669
1584
 
670
1585
  let next = null;
671
- if (npc.talking) {
672
- faceToward(npc, h.sim.players.get(npc.talking.playerId)?.at);
1586
+ const talking = conversations(npc)[0];
1587
+ if (talking && (!npc.speakers || (!npc.walk && !npc.following))) {
1588
+ faceToward(npc, h.sim.players.get(talking.playerId)?.at);
1589
+ } else if (npc.reaction && now < npc.reaction.until) {
1590
+ // A place may queue a station return while this reaction is under way.
1591
+ faceToward(npc, npc.reaction.at);
673
1592
  } else if (npc.walk) {
674
1593
  const w = npc.walk;
675
1594
  const step = stepToward(npc, w.x, w.z, w.stopAt, dt);
@@ -724,10 +1643,3 @@ function stepToward(npc, x, z, stopAt, dt) {
724
1643
  const stride = Math.min(d - stopAt, WALK_MPS * dt);
725
1644
  return { arrived: false, next: { x: p.x + (dx / d) * stride, y: p.y, z: p.z + (dz / d) * stride } };
726
1645
  }
727
-
728
- // A model sometimes wraps its whole line in quotes; a speech bubble is quotes
729
- // enough.
730
- function unquote(text) {
731
- const t = text.trim();
732
- return t.length > 1 && /^["“]/.test(t) && /["”]$/.test(t) ? t.slice(1, -1).trim() : t;
733
- }