briyah 2.0.2 → 2.0.4
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.
- package/LICENSE +216 -0
- package/README.md +43 -7
- package/data/common/config/LICENSE-model-prices.md +65 -0
- package/data/common/config/markup +1 -1
- package/data/common/config/model_prices.json +47443 -46295
- package/data/common/prompts/narrator/create_story.prompt +2 -0
- package/data/packs/dnd5e/agents/player.json +11 -11
- package/data/packs/dnd5e/prompts/character_creator/defaults_config.json +21 -20
- package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +19 -12
- package/data/packs/dnd5e/prompts/dnd_player/perceive.prompt +10 -6
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +173 -2
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +172 -3
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +241 -5
- package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
- package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
- package/dist-sdk/server/src/ai/LLM/deepseek.service.js +102 -3
- package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/LLM/fal.service.js +55 -1
- package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
- package/dist-sdk/server/src/ai/LLM/googleai.service.js +42 -1
- package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
- package/dist-sdk/server/src/ai/LLM/grok.service.js +54 -2
- package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
- package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/openai.service.js +80 -2
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +44 -2
- package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/together.service.js +60 -2
- package/dist-sdk/server/src/ai/agent-config.d.ts +15 -0
- package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
- package/dist-sdk/server/src/ai/agent-factory.js +20 -0
- package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
- package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +166 -5
- package/dist-sdk/server/src/ai/agent.d.ts +196 -0
- package/dist-sdk/server/src/ai/agent.js +224 -11
- package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
- package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
- package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
- package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
- package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
- package/dist-sdk/server/src/ai/artifact.service.js +148 -3
- package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
- package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
- package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
- package/dist-sdk/server/src/ai/model_prices.js +91 -5
- package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
- package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
- package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
- package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
- package/dist-sdk/server/src/app/balance-message.service.js +24 -0
- package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
- package/dist-sdk/server/src/app/balance.module.js +4 -0
- package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
- package/dist-sdk/server/src/app/balance.service.js +54 -0
- package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
- package/dist-sdk/server/src/app/stripe.controller.js +35 -0
- package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
- package/dist-sdk/server/src/app/stripe.service.js +62 -0
- package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
- package/dist-sdk/server/src/app/transaction.service.js +36 -0
- package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
- package/dist-sdk/server/src/app/user-service-factory.js +38 -1
- package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
- package/dist-sdk/server/src/app/user-service-manager.js +43 -0
- package/dist-sdk/server/src/app.controller.d.ts +87 -0
- package/dist-sdk/server/src/app.controller.js +272 -12
- package/dist-sdk/server/src/app.module.js +28 -6
- package/dist-sdk/server/src/app.service.d.ts +1662 -0
- package/dist-sdk/server/src/app.service.js +1862 -6
- package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
- package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
- package/dist-sdk/server/src/auth/auth.controller.js +46 -0
- package/dist-sdk/server/src/auth/auth.module.js +3 -2
- package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
- package/dist-sdk/server/src/auth/auth.service.js +39 -3
- package/dist-sdk/server/src/auth/jwt-auth.guard.js +18 -0
- package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
- package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
- package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
- package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
- package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
- package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
- package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
- package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
- package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
- package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
- package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
- package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
- package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
- package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
- package/dist-sdk/server/src/auth/session.guard.js +8 -0
- package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
- package/dist-sdk/server/src/auth/twilio.service.js +30 -4
- package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
- package/dist-sdk/server/src/auth/users.service.js +42 -0
- package/dist-sdk/server/src/common/errors.d.ts +20 -0
- package/dist-sdk/server/src/common/errors.js +21 -0
- package/dist-sdk/server/src/config/env-config.d.ts +7 -0
- package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
- package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
- package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
- package/dist-sdk/server/src/config/user-config.service.js +57 -0
- package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
- package/dist-sdk/server/src/config/user-paths.service.js +67 -0
- package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
- package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.js +99 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +100 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +58 -0
- package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
- package/dist-sdk/server/src/packs/pack.service.js +98 -1
- package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
- package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
- package/dist-sdk/server/src/room/artifact.d.ts +18 -0
- package/dist-sdk/server/src/room/message.d.ts +64 -0
- package/dist-sdk/server/src/room/message.js +77 -2
- package/dist-sdk/server/src/room/nickname.d.ts +27 -0
- package/dist-sdk/server/src/room/nickname.js +41 -0
- package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
- package/dist-sdk/server/src/room/room-config.d.ts +26 -0
- package/dist-sdk/server/src/room/room-factory.d.ts +12 -0
- package/dist-sdk/server/src/room/room-factory.js +14 -0
- package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
- package/dist-sdk/server/src/room/room-message.service.js +28 -0
- package/dist-sdk/server/src/room/room-store.service.d.ts +177 -0
- package/dist-sdk/server/src/room/room-store.service.js +242 -5
- package/dist-sdk/server/src/room/room.d.ts +906 -1
- package/dist-sdk/server/src/room/room.js +1525 -34
- package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
- package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +38 -3
- package/dist-sdk/server/src/rpg/rpg-roster.js +49 -49
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
- package/dist-sdk/server/src/rpg/rpg.service.js +108 -5
- package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
- package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
- package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
- package/dist-sdk/server/src/sdk/briyah.js +285 -7
- package/dist-sdk/server/src/sdk/index.d.ts +0 -1
- package/dist-sdk/server/src/sdk/index.js +24 -3
- package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
- package/dist-sdk/server/src/shared/shared.module.js +13 -5
- package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
- package/dist-sdk/server/src/story/story-message.service.js +43 -0
- package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
- package/dist-sdk/server/src/story/story-progress.service.js +23 -0
- package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
- package/dist-sdk/server/src/story/story-store.service.js +136 -1
- package/dist-sdk/server/src/story/story.service.d.ts +398 -0
- package/dist-sdk/server/src/story/story.service.js +829 -25
- package/dist-sdk/server/src/tools/core/index.d.ts +25 -0
- package/dist-sdk/server/src/tools/core/index.js +31 -0
- package/dist-sdk/server/src/tools/core/rename.tool.d.ts +10 -0
- package/dist-sdk/server/src/tools/core/rename.tool.js +72 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +186 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +192 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +144 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +164 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +188 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +125 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
- package/dist-sdk/server/src/tools/packs/index.d.ts +52 -2
- package/dist-sdk/server/src/tools/packs/index.js +83 -9
- package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
- package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +73 -0
- package/dist-sdk/server/src/tools/tool-execution.service.js +74 -0
- package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
- package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
- package/dist-sdk/shared/types/app.types.d.ts +285 -14
- package/dist-sdk/shared/types/app.types.js +3 -0
- package/package.json +167 -139
- package/data/common/config/random_words.txt +0 -2241
- package/data/common/story_ideas/biblical.json +0 -122
- package/data/common/story_ideas/fantasy.json +0 -82
- package/data/common/story_ideas/historical_fiction.json +0 -82
- package/data/common/story_ideas/science_fiction.json +0 -82
- package/data/packs/acts/agents/character-guide.json +0 -6
- package/data/packs/acts/agents/discipleship-mentor.json +0 -6
- package/data/packs/acts/agents/mentor-coach.json +0 -6
- package/data/packs/acts/agents/student.json +0 -13
- package/data/packs/acts/agents/table-moderator.json +0 -6
- package/data/packs/acts/artifacts/chapter-01-acts-1.md +0 -405
- package/data/packs/acts/artifacts/chapter-02-acts-2.md +0 -443
- package/data/packs/acts/artifacts/chapter-03-acts-3.md +0 -409
- package/data/packs/acts/artifacts/chapter-04-acts-4.md +0 -438
- package/data/packs/acts/artifacts/chapter-05-acts-5.md +0 -434
- package/data/packs/acts/artifacts/chapter-06-acts-6.md +0 -441
- package/data/packs/acts/artifacts/chapter-07-acts-7.md +0 -472
- package/data/packs/acts/artifacts/chapter-08-acts-8.md +0 -512
- package/data/packs/acts/artifacts/chapter-09-acts-9.md +0 -346
- package/data/packs/acts/artifacts/chapter-10-acts-10.md +0 -367
- package/data/packs/acts/artifacts/chapter-11-acts-11.md +0 -391
- package/data/packs/acts/artifacts/chapter-12-acts-12.md +0 -390
- package/data/packs/acts/artifacts/chapter-13-acts-13.md +0 -388
- package/data/packs/acts/artifacts/chapter-14-acts-14.md +0 -466
- package/data/packs/acts/artifacts/chapter-15-acts-15.md +0 -413
- package/data/packs/acts/artifacts/chapter-16-acts-16.md +0 -585
- package/data/packs/acts/artifacts/chapter-17-acts-17.md +0 -428
- package/data/packs/acts/artifacts/chapter-18-acts-18.md +0 -486
- package/data/packs/acts/artifacts/chapter-19-acts-19.md +0 -461
- package/data/packs/acts/artifacts/chapter-20-acts-20.md +0 -389
- package/data/packs/acts/artifacts/chapter-21-acts-21.md +0 -452
- package/data/packs/acts/artifacts/chapter-22-acts-22.md +0 -424
- package/data/packs/acts/artifacts/chapter-23-acts-23.md +0 -395
- package/data/packs/acts/artifacts/chapter-24-acts-24.md +0 -446
- package/data/packs/acts/artifacts/chapter-25-acts-25.md +0 -391
- package/data/packs/acts/artifacts/chapter-26-acts-26.md +0 -431
- package/data/packs/acts/artifacts/chapter-27-acts-27.md +0 -530
- package/data/packs/acts/artifacts/chapter-28-acts-28.md +0 -1871
- package/data/packs/acts/artifacts/chapters.manifest.json +0 -170
- package/data/packs/acts/artifacts/character_guide-creation.md +0 -112
- package/data/packs/acts/artifacts/discipleship_mentor-procedure.md +0 -154
- package/data/packs/acts/artifacts/discipleship_mentor-systems.md +0 -72
- package/data/packs/acts/artifacts/manifest.json +0 -197
- package/data/packs/acts/artifacts/stage-guide.md +0 -94
- package/data/packs/acts/pack.json +0 -6
- package/data/packs/acts/prompts/acts_player/defaults_config.json +0 -5
- package/data/packs/acts/prompts/acts_player/perceive.json +0 -29
- package/data/packs/acts/prompts/acts_player/perceive.prompt +0 -87
- package/data/packs/acts/prompts/acts_player/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/acts_room_moderator/defaults_config.json +0 -9
- package/data/packs/acts/prompts/acts_room_moderator/moderate.json +0 -34
- package/data/packs/acts/prompts/acts_room_moderator/moderate.prompt +0 -70
- package/data/packs/acts/prompts/acts_room_moderator/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/character_guide/defaults_config.json +0 -18
- package/data/packs/acts/prompts/character_guide/perceive.json +0 -29
- package/data/packs/acts/prompts/character_guide/perceive.prompt +0 -140
- package/data/packs/acts/prompts/character_guide/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/discipleship_mentor/defaults_config.json +0 -23
- package/data/packs/acts/prompts/discipleship_mentor/perceive.json +0 -33
- package/data/packs/acts/prompts/discipleship_mentor/perceive.prompt +0 -245
- package/data/packs/acts/prompts/discipleship_mentor/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/mentor_coach/defaults_config.json +0 -13
- package/data/packs/acts/prompts/mentor_coach/perceive.json +0 -29
- package/data/packs/acts/prompts/mentor_coach/perceive.prompt +0 -87
- package/data/packs/acts/prompts/mentor_coach/system_instruction.prompt +0 -0
- package/data/packs/acts/rooms/session.json +0 -14
- package/data/packs/acts/rooms/training.json +0 -58
- package/dist-sdk/server/src/tools/packs/acts/data/cards.d.ts +0 -53
- package/dist-sdk/server/src/tools/packs/acts/data/cards.js +0 -54
- package/dist-sdk/server/src/tools/packs/acts/data/character-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/character-cards.generated.js +0 -185
- package/dist-sdk/server/src/tools/packs/acts/data/encounters.d.ts +0 -12
- package/dist-sdk/server/src/tools/packs/acts/data/encounters.js +0 -102
- package/dist-sdk/server/src/tools/packs/acts/data/event-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/event-cards.generated.js +0 -196
- package/dist-sdk/server/src/tools/packs/acts/data/item-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/item-cards.generated.js +0 -1311
- package/dist-sdk/server/src/tools/packs/acts/engine/cards.d.ts +0 -5
- package/dist-sdk/server/src/tools/packs/acts/engine/cards.js +0 -27
- package/dist-sdk/server/src/tools/packs/acts/engine/challenge.d.ts +0 -37
- package/dist-sdk/server/src/tools/packs/acts/engine/challenge.js +0 -120
- package/dist-sdk/server/src/tools/packs/acts/engine/dice.d.ts +0 -20
- package/dist-sdk/server/src/tools/packs/acts/engine/dice.js +0 -41
- package/dist-sdk/server/src/tools/packs/acts/engine/sheet.d.ts +0 -54
- package/dist-sdk/server/src/tools/packs/acts/engine/sheet.js +0 -200
- package/dist-sdk/server/src/tools/packs/acts/index.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/index.js +0 -24
- package/dist-sdk/server/src/tools/packs/acts/tools/award.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/award.tool.js +0 -184
- package/dist-sdk/server/src/tools/packs/acts/tools/challenge.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/challenge.tool.js +0 -107
- package/dist-sdk/server/src/tools/packs/acts/tools/chapter.tool.d.ts +0 -3
- package/dist-sdk/server/src/tools/packs/acts/tools/chapter.tool.js +0 -146
- package/dist-sdk/server/src/tools/packs/acts/tools/check.tool.d.ts +0 -4
- package/dist-sdk/server/src/tools/packs/acts/tools/check.tool.js +0 -241
- package/dist-sdk/server/src/tools/packs/acts/tools/encounter.tool.d.ts +0 -3
- package/dist-sdk/server/src/tools/packs/acts/tools/encounter.tool.js +0 -72
- package/dist-sdk/server/src/tools/packs/acts/tools/faith.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/faith.tool.js +0 -75
- package/dist-sdk/server/src/tools/packs/acts/tools/shared.d.ts +0 -20
- package/dist-sdk/server/src/tools/packs/acts/tools/shared.js +0 -70
- package/dist-sdk/server/src/tools/packs/acts/tools/sheet.tools.d.ts +0 -4
- package/dist-sdk/server/src/tools/packs/acts/tools/sheet.tools.js +0 -215
- package/docs/.nojekyll +0 -1
- package/docs/assets/hierarchy.js +0 -1
- package/docs/assets/highlight.css +0 -113
- package/docs/assets/icons.js +0 -18
- package/docs/assets/icons.svg +0 -1
- package/docs/assets/main.js +0 -60
- package/docs/assets/navigation.js +0 -1
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1648
- package/docs/classes/Agent.html +0 -801
- package/docs/classes/Briyah.html +0 -296
- package/docs/classes/BriyahConfigService.html +0 -119
- package/docs/classes/NativeToolRegistry.html +0 -166
- package/docs/classes/PackInstantiationService.html +0 -157
- package/docs/classes/PackService.html +0 -247
- package/docs/classes/Room.html +0 -1338
- package/docs/classes/RoomMessage.html +0 -290
- package/docs/enums/MessageAction.html +0 -136
- package/docs/functions/actsTools.html +0 -44
- package/docs/functions/availableToolPacks.html +0 -41
- package/docs/functions/buildMarkdown.html +0 -54
- package/docs/functions/dnd5eTools.html +0 -44
- package/docs/functions/installToolPacks.html +0 -48
- package/docs/functions/pageMarker.html +0 -45
- package/docs/functions/registerToolPacks.html +0 -54
- package/docs/functions/splitMarkdownIntoPages.html +0 -51
- package/docs/functions/stripWrappingFence.html +0 -52
- package/docs/hierarchy.html +0 -46
- package/docs/index.html +0 -595
- package/docs/interfaces/AgentCreationOptions.html +0 -125
- package/docs/interfaces/AgentInfo.html +0 -218
- package/docs/interfaces/AgentMessagesResponse.html +0 -74
- package/docs/interfaces/AppService.html +0 -3337
- package/docs/interfaces/Artifact.html +0 -95
- package/docs/interfaces/ArtifactMetadata.html +0 -112
- package/docs/interfaces/ArtifactWriteOptions.html +0 -90
- package/docs/interfaces/AttachDocumentResponse.html +0 -62
- package/docs/interfaces/BriyahConfigOptions.html +0 -124
- package/docs/interfaces/ChapterInfo.html +0 -62
- package/docs/interfaces/Character.html +0 -86
- package/docs/interfaces/ConversionAgent.html +0 -78
- package/docs/interfaces/CreateAgentResponse.html +0 -56
- package/docs/interfaces/CreateRoomResponse.html +0 -62
- package/docs/interfaces/CreateStoryResponse.html +0 -56
- package/docs/interfaces/FileList.html +0 -56
- package/docs/interfaces/FileMetadata.html +0 -89
- package/docs/interfaces/IConfigService.html +0 -79
- package/docs/interfaces/InstantiateModels.html +0 -64
- package/docs/interfaces/InstantiateRoomResult.html +0 -70
- package/docs/interfaces/LoadedPack.html +0 -131
- package/docs/interfaces/LoggingOptions.html +0 -92
- package/docs/interfaces/Message.html +0 -84
- package/docs/interfaces/ModelChoice.html +0 -73
- package/docs/interfaces/ModelInfo.html +0 -74
- package/docs/interfaces/NativeToolDefinition.html +0 -107
- package/docs/interfaces/PackAgentTemplate.html +0 -101
- package/docs/interfaces/PackRoomTemplate.html +0 -108
- package/docs/interfaces/PackView.html +0 -172
- package/docs/interfaces/PdfConversionOptions.html +0 -102
- package/docs/interfaces/PdfConversionResult.html +0 -97
- package/docs/interfaces/PdfMarkdownOptions.html +0 -198
- package/docs/interfaces/PdfMarkdownResult.html +0 -106
- package/docs/interfaces/PdfPageMarkdown.html +0 -94
- package/docs/interfaces/PreparedPromptResponse.html +0 -62
- package/docs/interfaces/ProcessTextResponse.html +0 -86
- package/docs/interfaces/PromptFile.html +0 -70
- package/docs/interfaces/PromptFileContent.html +0 -76
- package/docs/interfaces/PromptFilesResponse.html +0 -56
- package/docs/interfaces/PromptFolder.html +0 -80
- package/docs/interfaces/PromptFolderDefaults.html +0 -155
- package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
- package/docs/interfaces/PromptFoldersResponse.html +0 -56
- package/docs/interfaces/RoomDetails.html +0 -151
- package/docs/interfaces/RoomErrorUpdate.html +0 -82
- package/docs/interfaces/RoomInfo.html +0 -88
- package/docs/interfaces/RoomMessageUpdate.html +0 -113
- package/docs/interfaces/RoomMessagesResponse.html +0 -62
- package/docs/interfaces/SendMessageResult.html +0 -62
- package/docs/interfaces/StoryErrorEvent.html +0 -84
- package/docs/interfaces/StoryIdea.html +0 -74
- package/docs/interfaces/StoryInfo.html +0 -198
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
- package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
- package/docs/interfaces/StoryState.html +0 -108
- package/docs/interfaces/StoryStateEvent.html +0 -76
- package/docs/interfaces/ToolArtifact.html +0 -85
- package/docs/interfaces/ToolCaller.html +0 -77
- package/docs/interfaces/ToolDefinition.html +0 -80
- package/docs/interfaces/ToolHelpers.html +0 -105
- package/docs/interfaces/ToolPackDocuments.html +0 -100
- package/docs/interfaces/ToolParameter.html +0 -74
- package/docs/interfaces/ToolRoomAccess.html +0 -227
- package/docs/interfaces/ToolSummary.html +0 -74
- package/docs/interfaces/ToolsResponse.html +0 -68
- package/docs/interfaces/Transaction.html +0 -104
- package/docs/interfaces/TransactionHistoryResponse.html +0 -62
- package/docs/modules.html +0 -53
- package/docs/types/PackOrigin.html +0 -34
- package/docs/types/PromptScope.html +0 -34
- package/docs/types/RoomTurnMode.html +0 -42
- package/docs/types/RoomUpdate.html +0 -36
- package/docs/types/RosterOverrides.html +0 -42
- package/docs/types/ToolContext.html +0 -40
- package/docs/types/ToolRunResult.html +0 -34
- package/src/tools/packs/dnd5e/README.md +0 -867
|
@@ -1,22 +1,131 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Room = void 0;
|
|
4
|
+
const agent_1 = require("../ai/agent");
|
|
4
5
|
const app_types_1 = require("../../../shared/types/app.types");
|
|
5
6
|
const message_1 = require("./message");
|
|
7
|
+
const nickname_1 = require("./nickname");
|
|
6
8
|
const crypto_1 = require("crypto");
|
|
7
9
|
const errors_1 = require("../common/errors");
|
|
8
10
|
const logger_1 = require("../common/logger");
|
|
11
|
+
/**
|
|
12
|
+
* A Room that contains agents
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* Cap on a description written through {@link ToolRoomAccess.setDescription}. Every
|
|
16
|
+
* agent's description sits in every other agent's cached prompt, so this is a
|
|
17
|
+
* guard against one tool call inflating the whole room's per-turn cost.
|
|
18
|
+
*/
|
|
9
19
|
const MAX_DESCRIPTION_CHARS = 500;
|
|
20
|
+
/**
|
|
21
|
+
* Cap on a nickname set through {@link ToolRoomAccess.renameAgent}. Long enough for
|
|
22
|
+
* "Thorin Oakenshield" and short enough that it cannot be used to smuggle prose
|
|
23
|
+
* into the roster, which every agent carries.
|
|
24
|
+
*/
|
|
25
|
+
const MAX_NICKNAME_CHARS = 40;
|
|
10
26
|
class Room {
|
|
27
|
+
/**
|
|
28
|
+
* Maximum EXECUTE/PUBLISH chain length within a single agent turn.
|
|
29
|
+
*
|
|
30
|
+
* A backstop against an agent looping on its tools forever, not a budget. Five
|
|
31
|
+
* was too tight for anything with real bookkeeping: a single round of combat runs
|
|
32
|
+
* a spell lookup, a resource spend, the attack and damage rolls, the hit point
|
|
33
|
+
* change and then the narration, and a character build runs create, read and
|
|
34
|
+
* patch before the hand-back. Half of one campaign's Dungeon Master turns hit the
|
|
35
|
+
* limit, and hitting it is expensive in its own right — the turn is re-prompted,
|
|
36
|
+
* the work is often redone, and a person has to notice and say "carry on".
|
|
37
|
+
*
|
|
38
|
+
* Raise it with `ROOM_MAX_TOOL_ITERATIONS`. Read per turn so it can be retuned on
|
|
39
|
+
* a running server, and floored at 1 so a nonsense value cannot stop every agent
|
|
40
|
+
* from acting.
|
|
41
|
+
*
|
|
42
|
+
* @returns The number of tool calls an agent may chain in one turn
|
|
43
|
+
*/
|
|
11
44
|
static maxToolIterations() {
|
|
12
45
|
const configured = Number(process.env.ROOM_MAX_TOOL_ITERATIONS);
|
|
13
46
|
return Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : 30;
|
|
14
47
|
}
|
|
48
|
+
/** What an agent is told when it is prompted again because it still holds the floor. */
|
|
15
49
|
static CONTINUE_NOTE = 'From system: You still have the floor. Carry on from where you stopped, and address whoever should act next when you are ready to hand it on.';
|
|
50
|
+
/**
|
|
51
|
+
* How many times in a row an agent may be handed the floor back to itself.
|
|
52
|
+
*
|
|
53
|
+
* A self-loop normally means a stuck room, which is why both routing paths broke
|
|
54
|
+
* one unconditionally. But an agent sometimes genuinely still holds the floor: a
|
|
55
|
+
* Battle Master running consecutive monster turns has nobody to address — a
|
|
56
|
+
* monster's turn has no addressee — and when every player character is unconscious
|
|
57
|
+
* there is no player to hand to either. That is exactly where one campaign stalled,
|
|
58
|
+
* needing a person to type "Marshal, continue" seven times in one fight.
|
|
59
|
+
*
|
|
60
|
+
* So the loop is allowed, and bounded. Three is enough for a few rounds of a fight
|
|
61
|
+
* nobody is awake for, and short enough that a genuinely stuck agent is stopped
|
|
62
|
+
* before it costs much. Raise it with `ROOM_MAX_SELF_CONTINUES`.
|
|
63
|
+
*
|
|
64
|
+
* @returns The number of consecutive self-addressed turns permitted
|
|
65
|
+
*/
|
|
16
66
|
static maxSelfContinues() {
|
|
17
67
|
const configured = Number(process.env.ROOM_MAX_SELF_CONTINUES);
|
|
18
68
|
return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : 3;
|
|
19
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* How many stalled turns in a row the room may re-route before it gives up.
|
|
72
|
+
*
|
|
73
|
+
* Counted since the last word actually said, not since the room opened: any
|
|
74
|
+
* audible message resets it, so a table that stalls once an hour never runs out.
|
|
75
|
+
* The cap exists for the case where re-routing cannot help — every agent in turn
|
|
76
|
+
* declining the same message — and the room would otherwise pay a moderator call
|
|
77
|
+
* per attempt forever with nobody at the keyboard to stop it.
|
|
78
|
+
*
|
|
79
|
+
* Raise it with `ROOM_MAX_STALL_RECOVERIES`; zero switches recovery off.
|
|
80
|
+
*
|
|
81
|
+
* @returns The number of consecutive recoveries permitted
|
|
82
|
+
*/
|
|
83
|
+
static maxStallRecoveries() {
|
|
84
|
+
const configured = Number(process.env.ROOM_MAX_STALL_RECOVERIES);
|
|
85
|
+
return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : 3;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* What the moderator is told when it is asked to re-route a stalled message.
|
|
89
|
+
* @param sender Who sent the message nobody answered
|
|
90
|
+
* @param declined Everyone that has already been asked to answer it
|
|
91
|
+
* @returns A note for the moderator's transient prompt
|
|
92
|
+
*/
|
|
93
|
+
static rerouteNote(sender, declined) {
|
|
94
|
+
const names = Room.listNames(declined);
|
|
95
|
+
return [
|
|
96
|
+
`IMPORTANT: this message was given to ${names} to answer, and it was not answered.`,
|
|
97
|
+
`Nothing was said in the room and nobody is speaking, so the table is now waiting.`,
|
|
98
|
+
`Name in "name" the one agent who should answer it instead, and put that same`,
|
|
99
|
+
`agent in "targets" — an answer with no targets is discarded.`,
|
|
100
|
+
`Do not name ${sender}, and do not name ${names} again.`,
|
|
101
|
+
].join(' ');
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* What the re-routed agent is told, so it can tell this from being handed a
|
|
105
|
+
* message it has already seen answered.
|
|
106
|
+
* @param sender Who sent the message
|
|
107
|
+
* @param declined Everyone that was asked before it
|
|
108
|
+
* @returns A system note for the agent's history
|
|
109
|
+
*/
|
|
110
|
+
static rerouteHandoffNote(sender, declined) {
|
|
111
|
+
return (`From system: ${sender}'s message above was given to ${Room.listNames(declined)}, ` +
|
|
112
|
+
`who did not answer it. It is meant for you. Answer it now.`);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* What the sender is told when its own unanswered message comes back to it.
|
|
116
|
+
*
|
|
117
|
+
* The last resort, and at a game table not a rare one: the leader is usually the
|
|
118
|
+
* one who addressed the wrong agent, so it is both the sender and the fallback.
|
|
119
|
+
* Being told to try again is a real recovery — it is the only agent that knows
|
|
120
|
+
* who the message was meant for.
|
|
121
|
+
* @param declined Everyone that was asked and did not answer
|
|
122
|
+
* @returns A system note for the sender's history
|
|
123
|
+
*/
|
|
124
|
+
static retryHandoffNote(declined) {
|
|
125
|
+
return (`From system: your message above was given to ${Room.listNames(declined)}, who did ` +
|
|
126
|
+
`not answer it, and nobody else here can take it. Carry on, and address whoever ` +
|
|
127
|
+
`should act next.`);
|
|
128
|
+
}
|
|
20
129
|
id;
|
|
21
130
|
name;
|
|
22
131
|
goal;
|
|
@@ -25,6 +134,16 @@ class Room {
|
|
|
25
134
|
roomLeader;
|
|
26
135
|
turnMode = 'broadcast';
|
|
27
136
|
moderator = '';
|
|
137
|
+
/**
|
|
138
|
+
* Who heard the message the moderator routed last, told to the moderator on its
|
|
139
|
+
* next turn.
|
|
140
|
+
*
|
|
141
|
+
* What makes a conversation with a sub-group hold together: speak to three of six
|
|
142
|
+
* agents, and the follow-up should reach the same three rather than whoever the
|
|
143
|
+
* moderator reconstructs from a 16-message history. Kept in memory only — losing
|
|
144
|
+
* it across a restart costs one turn of continuity, which is not worth persisting
|
|
145
|
+
* for.
|
|
146
|
+
*/
|
|
28
147
|
lastModeratedAudience = [];
|
|
29
148
|
roomMessages = [];
|
|
30
149
|
pendingMessages;
|
|
@@ -34,24 +153,40 @@ class Room {
|
|
|
34
153
|
isAdjourned = false;
|
|
35
154
|
processingInProgress = true;
|
|
36
155
|
isPaused = false;
|
|
37
|
-
currentSpeaker = null;
|
|
156
|
+
currentSpeaker = null; // Track whose turn it is to speak
|
|
157
|
+
/** The agent currently keeping the floor by addressing itself, if any. */
|
|
38
158
|
selfContinuingAgent = null;
|
|
159
|
+
/** How many turns in a row {@link selfContinuingAgent} has held it. */
|
|
39
160
|
consecutiveSelfContinues = 0;
|
|
161
|
+
/**
|
|
162
|
+
* The last audible message this room asked somebody to answer, and who was
|
|
163
|
+
* asked. Read only by {@link recoverStalledFloor}. In memory only: a restart
|
|
164
|
+
* ends any turn that was in flight, so there is nothing left to re-route.
|
|
165
|
+
*/
|
|
166
|
+
lastDispatch = null;
|
|
167
|
+
/** Consecutive stalls re-routed since the last word said. See {@link maxStallRecoveries}. */
|
|
168
|
+
stallRecoveries = 0;
|
|
40
169
|
isPublished = false;
|
|
41
170
|
isLoading = false;
|
|
42
171
|
onStateChangeCallbacks = new Map();
|
|
43
172
|
onErrorCallbacks = new Map();
|
|
44
|
-
currentSituation = '';
|
|
45
|
-
currentSituationTime = '';
|
|
46
|
-
onSituationUpdate;
|
|
173
|
+
currentSituation = ''; // Current story situation (for story rooms with moderator)
|
|
174
|
+
currentSituationTime = ''; // Current in-story time (24-hour "HH:MM"), kept separate from the situation text
|
|
175
|
+
onSituationUpdate; // Callback for situation changes
|
|
47
176
|
onModeratorResponseCallback;
|
|
48
|
-
templateRoomId;
|
|
177
|
+
templateRoomId; // NEW: Links published instance to template
|
|
178
|
+
/** The pack this room is filed under. See {@link RoomConfig.pack}. */
|
|
49
179
|
pack;
|
|
180
|
+
/** The pack template's key, when this room came from one. */
|
|
50
181
|
packRoomKey;
|
|
182
|
+
// Persistence
|
|
51
183
|
storageDir;
|
|
52
|
-
roomStoreService;
|
|
184
|
+
roomStoreService; // Reference to RoomStoreService for self-persistence
|
|
185
|
+
// User-defined tools (set via setToolServices; absent in tests that construct Room directly)
|
|
53
186
|
toolStoreService;
|
|
54
187
|
toolExecutionService;
|
|
188
|
+
// Opaque, host-supplied context for the current interaction, threaded to any
|
|
189
|
+
// tool an agent invokes. In-memory only — never serialized to disk.
|
|
55
190
|
currentToolContext = undefined;
|
|
56
191
|
constructor(id, name, goal, baseRoomDir = '', storageDir = '', roomStoreService = null) {
|
|
57
192
|
this.name = name;
|
|
@@ -60,7 +195,7 @@ class Room {
|
|
|
60
195
|
this.storageDir = storageDir;
|
|
61
196
|
this.roomStoreService = roomStoreService;
|
|
62
197
|
this.createdAt = new Date();
|
|
63
|
-
this.processingInProgress = true;
|
|
198
|
+
this.processingInProgress = true; // Call ready() when room is ready to use
|
|
64
199
|
this.id = id ? id : (0, crypto_1.randomUUID)();
|
|
65
200
|
this.isLoading = false;
|
|
66
201
|
}
|
|
@@ -104,12 +239,18 @@ class Room {
|
|
|
104
239
|
setTemplateRoomId(templateId) {
|
|
105
240
|
this.templateRoomId = templateId;
|
|
106
241
|
}
|
|
242
|
+
/** @returns The pack this room is filed under, or undefined when it is not filed */
|
|
107
243
|
getPack() {
|
|
108
244
|
return this.pack;
|
|
109
245
|
}
|
|
246
|
+
/**
|
|
247
|
+
* Files this room under a pack, or clears it.
|
|
248
|
+
* @param pack The pack name; empty or undefined clears it
|
|
249
|
+
*/
|
|
110
250
|
setPack(pack) {
|
|
111
251
|
this.pack = pack || undefined;
|
|
112
252
|
}
|
|
253
|
+
/** @returns The pack template's key, when this room came from one */
|
|
113
254
|
getPackRoomKey() {
|
|
114
255
|
return this.packRoomKey;
|
|
115
256
|
}
|
|
@@ -120,16 +261,27 @@ class Room {
|
|
|
120
261
|
this.roomMessages = [];
|
|
121
262
|
this.roomStoreService.clearRoomMessages(this.id, this.storageDir);
|
|
122
263
|
}
|
|
264
|
+
/**
|
|
265
|
+
* Adds an agent to the room
|
|
266
|
+
* @param agent The agent to add
|
|
267
|
+
* @returns True if the agent was added, false if it was already in the room
|
|
268
|
+
*/
|
|
123
269
|
arrive(agent) {
|
|
270
|
+
// Check if an agent with the same nickname is already in the room
|
|
124
271
|
if (this.agents.some((a) => a.agentNickname === agent.agentNickname)) {
|
|
125
272
|
return false;
|
|
126
273
|
}
|
|
274
|
+
// Add the agent to the room
|
|
127
275
|
this.agents.push(agent);
|
|
128
276
|
return true;
|
|
129
277
|
}
|
|
130
278
|
getAgents() {
|
|
131
279
|
return [...this.agents];
|
|
132
280
|
}
|
|
281
|
+
/**
|
|
282
|
+
* Replaces all agents in the room with new agents
|
|
283
|
+
* @param newAgents Array of agents to set
|
|
284
|
+
*/
|
|
133
285
|
setAgents(newAgents) {
|
|
134
286
|
this.agents = [];
|
|
135
287
|
for (const agent of newAgents) {
|
|
@@ -145,6 +297,7 @@ class Room {
|
|
|
145
297
|
getRoomLeader() {
|
|
146
298
|
if (this.roomLeader)
|
|
147
299
|
return this.roomLeader;
|
|
300
|
+
// Return empty string if no agents
|
|
148
301
|
if (this.agents.length > 0 && this.agents[0]) {
|
|
149
302
|
return this.agents[0].agentNickname || '';
|
|
150
303
|
}
|
|
@@ -153,34 +306,74 @@ class Room {
|
|
|
153
306
|
getTurnMode() {
|
|
154
307
|
return this.turnMode;
|
|
155
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Sets how the room chooses who responds to a message. See {@link RoomTurnMode}.
|
|
311
|
+
* @param mode The turn mode; anything unrecognized falls back to 'broadcast'
|
|
312
|
+
*/
|
|
156
313
|
setTurnMode(mode) {
|
|
157
314
|
this.turnMode = mode === 'directed' ? 'directed' : 'broadcast';
|
|
158
315
|
}
|
|
316
|
+
/** @returns The configured moderator nickname, or '' when none is set */
|
|
159
317
|
getModerator() {
|
|
160
318
|
return this.moderator || '';
|
|
161
319
|
}
|
|
320
|
+
/**
|
|
321
|
+
* Names the agent that places messages the room cannot route mechanically.
|
|
322
|
+
* @param agentNickname The moderator's nickname; empty clears it
|
|
323
|
+
*/
|
|
162
324
|
setModerator(agentNickname) {
|
|
163
325
|
this.moderator = agentNickname || '';
|
|
164
326
|
}
|
|
165
327
|
getAgentCount() {
|
|
166
328
|
return this.agents.length;
|
|
167
329
|
}
|
|
330
|
+
// Allow messages processing in the room after creation or adjournment
|
|
168
331
|
ready() {
|
|
169
332
|
if (this.isAdjourned || this.processingInProgress) {
|
|
170
333
|
this.isAdjourned = false;
|
|
334
|
+
// The human opens the conversation, so they start with the floor. With
|
|
335
|
+
// no human — including a room that has no agents yet — the floor is
|
|
336
|
+
// nobody's: an empty nickname is not null, and would be read as someone
|
|
337
|
+
// else holding it, refusing the first player to arrive.
|
|
171
338
|
this.endTurn({ to: this.getHumanAgentName() || null });
|
|
172
339
|
}
|
|
173
340
|
}
|
|
341
|
+
// Get current speaker (whose turn it is)
|
|
174
342
|
getCurrentSpeaker() {
|
|
175
343
|
return this.currentSpeaker;
|
|
176
344
|
}
|
|
345
|
+
// Set current speaker (called by moderator when routing messages)
|
|
177
346
|
setCurrentSpeaker(agentNickname) {
|
|
178
347
|
this.currentSpeaker = agentNickname;
|
|
179
348
|
this.notifyStateChange();
|
|
180
349
|
}
|
|
350
|
+
// Check if it's a specific agent's turn
|
|
181
351
|
isAgentsTurn(agentNickname) {
|
|
182
352
|
return this.currentSpeaker === agentNickname;
|
|
183
353
|
}
|
|
354
|
+
/**
|
|
355
|
+
* Ends the room's turn: drops the processing lock, settles who holds the floor,
|
|
356
|
+
* and optionally keeps draining the queue.
|
|
357
|
+
*
|
|
358
|
+
* Every path that finishes a turn goes through here. It used to be open-coded
|
|
359
|
+
* at fifteen sites, and the omissions were the bug: the main responder loop
|
|
360
|
+
* released the lock without giving up the floor, so any turn that ended without
|
|
361
|
+
* producing a message pinned the floor to an agent forever and the human could
|
|
362
|
+
* never speak again. Two more sites had the same gap.
|
|
363
|
+
*
|
|
364
|
+
* The invariant it exists to hold: **once no turn is in flight, the floor is
|
|
365
|
+
* either nobody's or the human's.** An AI agent holding it with nothing running
|
|
366
|
+
* is a dead room.
|
|
367
|
+
*
|
|
368
|
+
* In a directed room that invariant is only half of it. The floor being nobody's
|
|
369
|
+
* with nothing queued is a dead room too, because in directed mode the floor is a
|
|
370
|
+
* baton: one agent is prompted, and the room only moves on if that agent's turn
|
|
371
|
+
* produces an audible message. {@link recoverStalledFloor} closes that half, and
|
|
372
|
+
* runs here so that every path ending a turn is covered rather than the handful
|
|
373
|
+
* anyone thought to guard.
|
|
374
|
+
* @param floor Who holds the floor now — see {@link FloorHandover}
|
|
375
|
+
* @param opts.drain True to keep processing anything queued
|
|
376
|
+
*/
|
|
184
377
|
endTurn(floor, opts = {}) {
|
|
185
378
|
if (floor === 'release') {
|
|
186
379
|
this.currentSpeaker = null;
|
|
@@ -189,10 +382,209 @@ class Room {
|
|
|
189
382
|
this.currentSpeaker = floor.to ?? null;
|
|
190
383
|
}
|
|
191
384
|
this.processingInProgress = false;
|
|
385
|
+
// One notification, after both fields settle. The old code released the
|
|
386
|
+
// lock, notified, then set the speaker and notified again, which briefly
|
|
387
|
+
// published "no turn running" alongside a speaker that had already moved on.
|
|
192
388
|
this.notifyStateChange();
|
|
193
389
|
if (opts.drain && this.pendingMessages && this.pendingMessages.length > 0) {
|
|
194
390
|
this.processPendingMessages();
|
|
195
391
|
}
|
|
392
|
+
// After the drain, so a queue with anything left in it is not mistaken for a
|
|
393
|
+
// room with nothing to do.
|
|
394
|
+
this.recoverStalledFloor();
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Puts the floor back in somebody's hands when a directed turn ended without a
|
|
398
|
+
* word said.
|
|
399
|
+
*
|
|
400
|
+
* The stall this exists for: a message is addressed to the wrong agent, that
|
|
401
|
+
* agent answers with a `think` — reasonably, since the message was not for it —
|
|
402
|
+
* and a thought prompts nobody. The turn ends, the floor is released, the queue
|
|
403
|
+
* is empty and the room sits there. A `think` is only the commonest way in; a
|
|
404
|
+
* turn that fails, returns nothing, or spends itself on tool calls leaves the
|
|
405
|
+
* room in exactly the same state, which is why this guards the state rather than
|
|
406
|
+
* the action that produced it.
|
|
407
|
+
*
|
|
408
|
+
* **In a directed room, an empty queue with the floor held by nobody is always a
|
|
409
|
+
* stall.** A message meant for a person hands them the floor by name, so a
|
|
410
|
+
* released floor is never "waiting for the human" — it is nobody's turn at all.
|
|
411
|
+
*
|
|
412
|
+
* Recovery is the moderator's existing job: it is handed the unanswered message
|
|
413
|
+
* and asked who should have answered it. Nothing about the stall reaches the
|
|
414
|
+
* transcript — the message has already been logged and heard once, and a second
|
|
415
|
+
* copy of it, or a note about the plumbing, is not part of the story.
|
|
416
|
+
*
|
|
417
|
+
* Needs a moderator that was actually configured. {@link getModeratorAgent} falls
|
|
418
|
+
* back to the first non-player agent, which at a game table is the Dungeon Master
|
|
419
|
+
* — asking it to route its own unanswered message is the confusion this is
|
|
420
|
+
* supposed to end, so a room without a moderator keeps the old behaviour and
|
|
421
|
+
* waits for a person.
|
|
422
|
+
*/
|
|
423
|
+
recoverStalledFloor() {
|
|
424
|
+
if (this.turnMode !== 'directed')
|
|
425
|
+
return;
|
|
426
|
+
if (this.isPaused || this.isAdjourned || this.isLoading)
|
|
427
|
+
return;
|
|
428
|
+
if (this.processingInProgress)
|
|
429
|
+
return;
|
|
430
|
+
if (this.currentSpeaker !== null)
|
|
431
|
+
return;
|
|
432
|
+
if (this.pendingMessages && this.pendingMessages.length > 0)
|
|
433
|
+
return;
|
|
434
|
+
const dispatch = this.lastDispatch;
|
|
435
|
+
if (!dispatch)
|
|
436
|
+
return;
|
|
437
|
+
const moderator = this.configuredModerator();
|
|
438
|
+
if (!moderator)
|
|
439
|
+
return;
|
|
440
|
+
if (this.stallRecoveries >= Room.maxStallRecoveries()) {
|
|
441
|
+
logger_1.logger.warn(`Room ${this.name}: ${this.stallRecoveries} stalled turn(s) re-routed in a row with nothing said; leaving the floor free`);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
this.stallRecoveries += 1;
|
|
445
|
+
logger_1.logger.warn(`Room ${this.name}: nobody answered ${dispatch.message.getSender()} and the room has gone quiet; asking ${moderator.agentNickname} to re-route (attempt ${this.stallRecoveries} of ${Room.maxStallRecoveries()})`);
|
|
446
|
+
// Held for the whole re-route, so a human message arriving mid-flight queues
|
|
447
|
+
// behind it instead of racing the moderator call.
|
|
448
|
+
this.processingInProgress = true;
|
|
449
|
+
this.notifyStateChange();
|
|
450
|
+
void this.rerouteStalledTurn(dispatch, moderator).catch((error) => {
|
|
451
|
+
logger_1.logger.error(`Room ${this.name}: re-routing a stalled turn failed:`, error);
|
|
452
|
+
this.endTurn('release', { drain: true });
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* The moderator this room was configured with, and only that one.
|
|
457
|
+
*
|
|
458
|
+
* Unlike {@link getModeratorAgent} there is no fallback: a caller that needs a
|
|
459
|
+
* genuine moderator would rather have none than the room leader.
|
|
460
|
+
* @returns The configured moderator agent, or undefined
|
|
461
|
+
*/
|
|
462
|
+
configuredModerator() {
|
|
463
|
+
if (!this.moderator)
|
|
464
|
+
return undefined;
|
|
465
|
+
return this.agents.find((a) => !a.isControlledByHuman &&
|
|
466
|
+
this.checkAgentNicknameMatch(a.agentNickname, this.moderator));
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Asks the moderator who should have answered a message nobody did, then gives
|
|
470
|
+
* that agent the floor.
|
|
471
|
+
*
|
|
472
|
+
* The message itself is not re-logged and not re-delivered: everyone who could
|
|
473
|
+
* hear it already did, on its first pass. Only the chosen agent is touched, with
|
|
474
|
+
* a note saying why it is being asked — without one it cannot tell this from
|
|
475
|
+
* being handed something it has already watched somebody else answer.
|
|
476
|
+
* @param dispatch The unanswered message and everyone already asked
|
|
477
|
+
* @param moderator The room's configured moderator
|
|
478
|
+
*/
|
|
479
|
+
async rerouteStalledTurn(dispatch, moderator) {
|
|
480
|
+
const stalled = dispatch.message;
|
|
481
|
+
let named;
|
|
482
|
+
await this.moderate(moderator, stalled, (answer) => {
|
|
483
|
+
named = answer?.name;
|
|
484
|
+
}, { note: Room.rerouteNote(stalled.getSender(), dispatch.responders) });
|
|
485
|
+
if (this.isPaused || this.isAdjourned) {
|
|
486
|
+
this.endTurn('keep');
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const responder = this.resolveRerouteResponder(named, dispatch, moderator);
|
|
490
|
+
if (!responder) {
|
|
491
|
+
logger_1.logger.warn(`Room ${this.name}: nobody left to answer ${stalled.getSender()}'s message; leaving the floor free`);
|
|
492
|
+
this.endTurn('release', { drain: true });
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
// Only when it could not have heard the message the first time — a whisper it
|
|
496
|
+
// was not part of. Delivering one it already has would double it in history.
|
|
497
|
+
if (!stalled.canHear(responder.agentNickname)) {
|
|
498
|
+
this.deliverModerated(responder, stalled, stalled.getContent());
|
|
499
|
+
}
|
|
500
|
+
// Remembered before the turn runs, so a responder that also declines is not
|
|
501
|
+
// asked again on the next recovery.
|
|
502
|
+
this.lastDispatch = {
|
|
503
|
+
message: stalled,
|
|
504
|
+
responders: [...dispatch.responders, responder.agentNickname],
|
|
505
|
+
};
|
|
506
|
+
if (responder.isControlledByHuman) {
|
|
507
|
+
logger_1.logger.log(`Re-routed ${stalled.getSender()}'s message to ${responder.agentNickname}`);
|
|
508
|
+
this.endTurn({ to: responder.agentNickname });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
const isAuthor = this.checkAgentNicknameMatch(responder.agentNickname, stalled.getSender());
|
|
512
|
+
responder.addToConversationHistory(isAuthor
|
|
513
|
+
? Room.retryHandoffNote(dispatch.responders)
|
|
514
|
+
: Room.rerouteHandoffNote(stalled.getSender(), dispatch.responders), false);
|
|
515
|
+
responder.save();
|
|
516
|
+
this.setCurrentSpeaker(responder.agentNickname);
|
|
517
|
+
// Prompted directly rather than through `perceive`, which would record the
|
|
518
|
+
// message in its history a second time.
|
|
519
|
+
this.getAgentAiResponse(responder, stalled, (message) => {
|
|
520
|
+
if (this.isPaused) {
|
|
521
|
+
this.endTurn('keep');
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
this.queueAgentResponse(message);
|
|
525
|
+
this.endTurn('release', { drain: true });
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Picks the agent a re-routed message goes to.
|
|
530
|
+
*
|
|
531
|
+
* Three candidates, in order: whoever the moderator named, the room leader — the
|
|
532
|
+
* same contract {@link handleModeratorResponse} works to — and finally the sender
|
|
533
|
+
* itself, told to try again. Everyone that has already declined the message is
|
|
534
|
+
* skipped at each step, and so is the moderator, which never answers.
|
|
535
|
+
*
|
|
536
|
+
* The sender is last rather than excluded because at a game table it is usually
|
|
537
|
+
* also the leader: the Dungeon Master addresses the wrong player far more often
|
|
538
|
+
* than anyone else does, so excluding it would leave the commonest stall with
|
|
539
|
+
* nowhere to go.
|
|
540
|
+
* @param named The nickname the moderator answered with, if any
|
|
541
|
+
* @param dispatch The unanswered message and everyone already asked
|
|
542
|
+
* @param moderator The moderator that was consulted
|
|
543
|
+
* @returns The agent to give the floor to, or undefined if there is nobody left
|
|
544
|
+
*/
|
|
545
|
+
resolveRerouteResponder(named, dispatch, moderator) {
|
|
546
|
+
const excluded = [moderator.agentNickname, ...dispatch.responders];
|
|
547
|
+
const eligible = (agent) => !excluded.some((name) => this.checkAgentNicknameMatch(agent.agentNickname, name));
|
|
548
|
+
const sender = dispatch.message.getSender();
|
|
549
|
+
const chosen = named
|
|
550
|
+
? this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, named))
|
|
551
|
+
: undefined;
|
|
552
|
+
if (chosen) {
|
|
553
|
+
if (eligible(chosen) && !this.checkAgentNicknameMatch(chosen.agentNickname, sender)) {
|
|
554
|
+
return chosen;
|
|
555
|
+
}
|
|
556
|
+
logger_1.logger.warn(`Room ${this.name}: moderator re-routed to ${chosen.agentNickname}, who sent the message or has already declined it; falling back`);
|
|
557
|
+
}
|
|
558
|
+
const leader = this.agents.find((a) => a.agentNickname === this.getRoomLeader());
|
|
559
|
+
if (leader && eligible(leader) && !this.checkAgentNicknameMatch(leader.agentNickname, sender)) {
|
|
560
|
+
return leader;
|
|
561
|
+
}
|
|
562
|
+
const author = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, sender));
|
|
563
|
+
return author && eligible(author) && !author.isControlledByHuman ? author : undefined;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Files an agent's response from a turn that has just ended.
|
|
567
|
+
*
|
|
568
|
+
* A thought is nobody's message but its own, so it is logged and goes no further.
|
|
569
|
+
* A shout jumps the queue. Anything else joins the back of it — and, being an
|
|
570
|
+
* audible message, is the room making progress, which is what ends a run of
|
|
571
|
+
* stall recoveries.
|
|
572
|
+
* @param message The response, or null if the turn produced nothing
|
|
573
|
+
*/
|
|
574
|
+
queueAgentResponse(message) {
|
|
575
|
+
if (message === null)
|
|
576
|
+
return;
|
|
577
|
+
if (message.action === app_types_1.MessageAction.THINK) {
|
|
578
|
+
this.addRoomMessage(message);
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
this.stallRecoveries = 0;
|
|
582
|
+
if (message.action === app_types_1.MessageAction.SHOUT) {
|
|
583
|
+
this.pendingMessages = [message, ...(this.pendingMessages || [])];
|
|
584
|
+
}
|
|
585
|
+
else {
|
|
586
|
+
this.pendingMessages = [...(this.pendingMessages || []), message];
|
|
587
|
+
}
|
|
196
588
|
}
|
|
197
589
|
getRoomMessageStats() {
|
|
198
590
|
let numMessages = this.roomMessages.length;
|
|
@@ -200,23 +592,31 @@ class Room {
|
|
|
200
592
|
return { numMessages, numChars };
|
|
201
593
|
}
|
|
202
594
|
getLatestRoomMessages(fromIndex = 0, includeThoughts = false) {
|
|
595
|
+
// Filter messages based on fromIndex
|
|
203
596
|
const messages = this.roomMessages.filter((msg) => msg.index >= fromIndex);
|
|
204
597
|
if (!includeThoughts) {
|
|
598
|
+
// Hide internal activity: thoughts and tool-execution notices
|
|
205
599
|
return messages.filter((msg) => msg.action !== app_types_1.MessageAction.THINK && msg.action !== app_types_1.MessageAction.TOOL);
|
|
206
600
|
}
|
|
207
601
|
return messages;
|
|
208
602
|
}
|
|
209
603
|
setRoomMessages(messages) {
|
|
604
|
+
// Convert string messages to indexed messages
|
|
210
605
|
this.roomMessages = messages.map((m, idx) => {
|
|
211
606
|
m.index = idx;
|
|
212
607
|
return m;
|
|
213
608
|
});
|
|
609
|
+
// Update the next message index
|
|
214
610
|
this.nextMessageIndex = this.roomMessages.length;
|
|
215
611
|
}
|
|
216
612
|
addRoomMessage(message, options) {
|
|
217
613
|
message.index = this.nextMessageIndex++;
|
|
218
614
|
this.roomMessages.push(message);
|
|
615
|
+
// Save new messages to disk incrementally
|
|
219
616
|
this.saveMessages([message]);
|
|
617
|
+
// Skip the situation callback when the caller has already processed this
|
|
618
|
+
// situation (e.g. the moderator-routing path processes the narrator's
|
|
619
|
+
// situation before moderation, then relays the same message here).
|
|
220
620
|
if (message.situation && !options?.suppressSituationUpdate) {
|
|
221
621
|
void this.handleSituationUpdate(message.situation);
|
|
222
622
|
}
|
|
@@ -230,7 +630,9 @@ class Room {
|
|
|
230
630
|
return m;
|
|
231
631
|
});
|
|
232
632
|
this.roomMessages = this.roomMessages.concat(indexedMessages);
|
|
633
|
+
// Save new messages to disk incrementally
|
|
233
634
|
this.saveMessages(indexedMessages);
|
|
635
|
+
// Notify that state has changed
|
|
234
636
|
this.notifyStateChange();
|
|
235
637
|
}
|
|
236
638
|
getCreatedAt() {
|
|
@@ -239,15 +641,203 @@ class Room {
|
|
|
239
641
|
setCreatedAt(date) {
|
|
240
642
|
this.createdAt = date;
|
|
241
643
|
}
|
|
644
|
+
/**
|
|
645
|
+
* Gets all artifacts in the room
|
|
646
|
+
* @returns Array of artifacts
|
|
647
|
+
*/
|
|
242
648
|
getArtifacts() {
|
|
243
649
|
return [...this.artifacts];
|
|
244
650
|
}
|
|
651
|
+
/**
|
|
652
|
+
* Renames an agent, and everything in this room that named it.
|
|
653
|
+
*
|
|
654
|
+
* A room routes by nickname and nothing else, so an agent whose character is
|
|
655
|
+
* called something different gives every other agent two names for one person.
|
|
656
|
+
* The Dungeon Master addresses the character, the room has never heard of them,
|
|
657
|
+
* and the message falls through to the moderator — see
|
|
658
|
+
* {@link namesNobodyInADirectedRoom}, which exists to catch exactly that and
|
|
659
|
+
* once absorbed about a quarter of a campaign's calls. This is the fix that
|
|
660
|
+
* makes the workaround unnecessary: give the agent the character's name.
|
|
661
|
+
*
|
|
662
|
+
* Expensive in the same way {@link ToolRoomAccess.setDescription} is, and for
|
|
663
|
+
* the same reason: the roster sits in every agent's *cached* prompt prefix, so
|
|
664
|
+
* a rename throws away the whole room's cache. Character creation is the moment
|
|
665
|
+
* for it, because play has not started; mid-scene it is a real cost.
|
|
666
|
+
*
|
|
667
|
+
* **History is deliberately not rewritten.** Past messages are a record of what
|
|
668
|
+
* was said, and rewriting them would mean parsing and re-serializing every
|
|
669
|
+
* entry, with compaction summaries reachable only by regex. Instead every agent
|
|
670
|
+
* is told, once, that the name changed — which is what lets them reconcile a
|
|
671
|
+
* roster that says `Leah` with a history that says `StudentOne`.
|
|
672
|
+
*
|
|
673
|
+
* @param from The agent to rename, matched the way messages are routed
|
|
674
|
+
* @param to The new name — a character name, which may be longer than a nickname
|
|
675
|
+
* @returns What happened, including the reason when nothing did
|
|
676
|
+
*/
|
|
677
|
+
renameAgent(from, to) {
|
|
678
|
+
const agent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, from));
|
|
679
|
+
if (!agent)
|
|
680
|
+
return { renamed: false, reason: 'not_found' };
|
|
681
|
+
const fullName = (to || '').trim().slice(0, MAX_NICKNAME_CHARS);
|
|
682
|
+
if (!fullName)
|
|
683
|
+
return { renamed: false, reason: 'invalid' };
|
|
684
|
+
// The room routes on the nickname, so derive it the same way agent creation
|
|
685
|
+
// does: "Leah bat Yosef" seats as `Leah` and keeps the whole thing as its
|
|
686
|
+
// name. Deriving rather than storing the character name whole is what keeps
|
|
687
|
+
// `targets` short enough for a model to spell reliably.
|
|
688
|
+
const nickname = agent_1.Agent.generateNickname(fullName);
|
|
689
|
+
const previous = agent.agentNickname;
|
|
690
|
+
if (previous === nickname && agent.agentName === fullName) {
|
|
691
|
+
return { renamed: false, reason: 'unchanged', from: previous, to: nickname };
|
|
692
|
+
}
|
|
693
|
+
// Ambiguity rather than equality: routing matches a first word too, so
|
|
694
|
+
// `Thorin` would reach both "Thorin Oakenshield" and a second Thorin. A
|
|
695
|
+
// clash has to be refused rather than suffixed — a character name is what
|
|
696
|
+
// the player hears out loud, so seating them as "Leah 2" is worse than
|
|
697
|
+
// asking for another name.
|
|
698
|
+
const clash = this.conflictingNickname(agent, nickname);
|
|
699
|
+
if (clash) {
|
|
700
|
+
return {
|
|
701
|
+
renamed: false,
|
|
702
|
+
reason: 'ambiguous',
|
|
703
|
+
from: previous,
|
|
704
|
+
to: nickname,
|
|
705
|
+
conflictsWith: clash,
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
agent.agentNickname = nickname;
|
|
709
|
+
agent.agentName = fullName;
|
|
710
|
+
agent.save(); // Persists and pushes the new roster to the client
|
|
711
|
+
const artifactsUpdated = this.repointNickname(previous, nickname);
|
|
712
|
+
return {
|
|
713
|
+
renamed: true,
|
|
714
|
+
from: previous,
|
|
715
|
+
to: nickname,
|
|
716
|
+
fullName,
|
|
717
|
+
artifactsUpdated,
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* The agent this room would refuse to rename to `nickname`, if any.
|
|
722
|
+
*
|
|
723
|
+
* Separate from {@link renameAgent} so a caller renaming an agent that sits in
|
|
724
|
+
* more than one room can check them all before changing anything — a rename
|
|
725
|
+
* applied to two rooms and refused by a third would leave the agent named one
|
|
726
|
+
* thing and half the rooms pointing at another.
|
|
727
|
+
*
|
|
728
|
+
* @param agent The agent being renamed, excluded from its own check
|
|
729
|
+
* @param nickname The nickname it would take
|
|
730
|
+
* @returns The conflicting agent's nickname, or undefined
|
|
731
|
+
*/
|
|
732
|
+
conflictingNickname(agent, nickname) {
|
|
733
|
+
const clash = this.agents.find((a) => a !== agent && (0, nickname_1.nicknamesAreAmbiguous)(a.agentNickname, nickname));
|
|
734
|
+
return clash?.agentNickname;
|
|
735
|
+
}
|
|
736
|
+
/**
|
|
737
|
+
* Repoints everything in *this room* that named an agent, and tells the room.
|
|
738
|
+
*
|
|
739
|
+
* The room-side half of a rename, split out because an agent may sit in more
|
|
740
|
+
* than one room while its own record is only mutated once. {@link renameAgent}
|
|
741
|
+
* is this plus the agent itself.
|
|
742
|
+
*
|
|
743
|
+
* @param previous The nickname being replaced
|
|
744
|
+
* @param nickname The nickname replacing it
|
|
745
|
+
* @returns How many artifacts changed
|
|
746
|
+
*/
|
|
747
|
+
repointNickname(previous, nickname) {
|
|
748
|
+
if (!previous || previous === nickname)
|
|
749
|
+
return 0;
|
|
750
|
+
const artifactsUpdated = this.renameInArtifacts(previous, nickname);
|
|
751
|
+
if (this.roomLeader === previous)
|
|
752
|
+
this.roomLeader = nickname;
|
|
753
|
+
if (this.moderator === previous)
|
|
754
|
+
this.moderator = nickname;
|
|
755
|
+
this.saveMetadata();
|
|
756
|
+
this.announceRename(previous, nickname);
|
|
757
|
+
return artifactsUpdated;
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Repoints every artifact that named the old nickname.
|
|
761
|
+
*
|
|
762
|
+
* `viewers` is the one that fails silently: an artifact keeps working, the agent
|
|
763
|
+
* simply stops being able to see it, so a player loses their own character sheet
|
|
764
|
+
* with nothing logged. `creator` decides attribution and counts as a viewer.
|
|
765
|
+
*
|
|
766
|
+
* @param previous The nickname being replaced
|
|
767
|
+
* @param nickname The nickname replacing it
|
|
768
|
+
* @returns How many artifacts changed
|
|
769
|
+
*/
|
|
770
|
+
renameInArtifacts(previous, nickname) {
|
|
771
|
+
let changed = 0;
|
|
772
|
+
for (const artifact of this.artifacts) {
|
|
773
|
+
let touched = false;
|
|
774
|
+
if (artifact.creator === previous) {
|
|
775
|
+
artifact.creator = nickname;
|
|
776
|
+
touched = true;
|
|
777
|
+
}
|
|
778
|
+
if (artifact.viewers?.some((viewer) => viewer === previous)) {
|
|
779
|
+
artifact.viewers = artifact.viewers.map((viewer) => viewer === previous ? nickname : viewer);
|
|
780
|
+
touched = true;
|
|
781
|
+
}
|
|
782
|
+
if (!touched)
|
|
783
|
+
continue;
|
|
784
|
+
changed++;
|
|
785
|
+
if (this.roomStoreService && this.storageDir) {
|
|
786
|
+
this.roomStoreService.saveArtifactFile(this.id, this.storageDir, artifact);
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
return changed;
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Tells every agent in the room that a name changed.
|
|
793
|
+
*
|
|
794
|
+
* One line each, and the reason the history can be left alone: without it an
|
|
795
|
+
* agent reads `Leah` in the roster and `StudentOne` in its own history with
|
|
796
|
+
* nothing joining the two, which is the confusion the rename exists to remove.
|
|
797
|
+
* The renamed agent is told as well — it is the one most likely to be unsure
|
|
798
|
+
* what it is called.
|
|
799
|
+
*/
|
|
800
|
+
announceRename(previous, nickname) {
|
|
801
|
+
const note = `[Room] "${previous}" is now known as "${nickname}". Earlier messages use the old name.`;
|
|
802
|
+
for (const agent of this.agents) {
|
|
803
|
+
agent.addToConversationHistory(note, false);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Checks if the room is currently adjourned
|
|
808
|
+
* @returns True if the room is adjourned, false otherwise
|
|
809
|
+
*/
|
|
245
810
|
isRoomAdjourned() {
|
|
246
811
|
return this.isAdjourned;
|
|
247
812
|
}
|
|
813
|
+
/**
|
|
814
|
+
* Sets the room's artifacts (used when loading from storage)
|
|
815
|
+
* @param artifacts Array of artifacts to set
|
|
816
|
+
*/
|
|
248
817
|
setArtifacts(artifacts) {
|
|
249
818
|
this.artifacts = [...artifacts];
|
|
250
819
|
}
|
|
820
|
+
/**
|
|
821
|
+
* Whether a message names recipients but none of them is in this room.
|
|
822
|
+
*
|
|
823
|
+
* Only asked of a directed room, where a message is answered by the one agent it
|
|
824
|
+
* names. `selectResponders` cannot place such a message: no target matches, and
|
|
825
|
+
* the leader is skipped when it is the sender — which it is whenever the leader
|
|
826
|
+
* is the one who misnamed someone. What is left is a fallback that widens to
|
|
827
|
+
* *every* other agent, and a directed room exists precisely to avoid that. One
|
|
828
|
+
* campaign spent about a quarter of its calls there, because the Dungeon Master
|
|
829
|
+
* addressed a player by their character's name rather than the nickname the room
|
|
830
|
+
* knows them by.
|
|
831
|
+
*
|
|
832
|
+
* Moderating instead costs one cheap call and is the moderator's documented job:
|
|
833
|
+
* a message that "did not name a recipient the room could use" is routed from its
|
|
834
|
+
* content. A misnamed target is usually a non-player character anyway, and the
|
|
835
|
+
* moderator already knows to hand those to the room leader.
|
|
836
|
+
*
|
|
837
|
+
* @param action The message's normalized action
|
|
838
|
+
* @param targets The names the message was addressed to
|
|
839
|
+
* @returns True when the room should moderate rather than guess
|
|
840
|
+
*/
|
|
251
841
|
namesNobodyInADirectedRoom(action, targets) {
|
|
252
842
|
if (this.turnMode !== 'directed')
|
|
253
843
|
return false;
|
|
@@ -257,6 +847,12 @@ class Room {
|
|
|
257
847
|
return false;
|
|
258
848
|
return !targets.some((name) => this.agents.some((a) => this.checkAgentNicknameMatch(a.agentNickname, name)));
|
|
259
849
|
}
|
|
850
|
+
/**
|
|
851
|
+
* Parses AI response into RoomMessage object (private helper moved from Agent)
|
|
852
|
+
* @param agent The agent that made the response
|
|
853
|
+
* @param response Raw AI response object
|
|
854
|
+
* @returns Parsed RoomMessage object
|
|
855
|
+
*/
|
|
260
856
|
parseAgentResponse(agent, response) {
|
|
261
857
|
let needsModeration = false;
|
|
262
858
|
let targets = [];
|
|
@@ -281,12 +877,19 @@ class Room {
|
|
|
281
877
|
needsModeration = true;
|
|
282
878
|
}
|
|
283
879
|
else {
|
|
880
|
+
// Normalize action case. LLMs occasionally emit "THINK" / "Speak" etc.
|
|
881
|
+
// despite the schema specifying lowercase enum values; tolerate that
|
|
882
|
+
// rather than dropping the message through the downstream filters.
|
|
284
883
|
normalizedAction = Room.coerceMessageAction(response.action);
|
|
285
884
|
if (!normalizedAction) {
|
|
286
885
|
logger_1.logger.error(`Agent ${agent.agentNickname} produced message with invalid action "${response.action}"; routing through moderator`);
|
|
287
886
|
needsModeration = true;
|
|
288
887
|
}
|
|
289
888
|
else if (response.targets) {
|
|
889
|
+
// A model asked for a list of names sometimes hands back one bare
|
|
890
|
+
// name instead. Everything downstream — the directed-room check,
|
|
891
|
+
// responder selection, `targets.join` in a log line — assumes an
|
|
892
|
+
// array, so coerce here rather than at each of those.
|
|
290
893
|
targets = Array.isArray(response.targets)
|
|
291
894
|
? response.targets
|
|
292
895
|
: [response.targets];
|
|
@@ -299,9 +902,11 @@ class Room {
|
|
|
299
902
|
}
|
|
300
903
|
}
|
|
301
904
|
}
|
|
905
|
+
// EXECUTE must name the tool to run
|
|
302
906
|
if (normalizedAction === app_types_1.MessageAction.EXECUTE && (!response.name || !response.name.trim())) {
|
|
303
907
|
needsModeration = true;
|
|
304
908
|
}
|
|
909
|
+
// COMMISSION must name at least one target agent
|
|
305
910
|
if (normalizedAction === app_types_1.MessageAction.COMMISSION && targets.length === 0) {
|
|
306
911
|
needsModeration = true;
|
|
307
912
|
}
|
|
@@ -311,16 +916,27 @@ class Room {
|
|
|
311
916
|
}
|
|
312
917
|
}
|
|
313
918
|
if (needsModeration) {
|
|
919
|
+
// A message routed to the moderator has to carry text, because a moderator
|
|
920
|
+
// is going to read it. `content` is initialised from the response itself,
|
|
921
|
+
// which is the response *object* whenever the reason for moderating was a
|
|
922
|
+
// failed check on an otherwise well-formed object — and an object reaching
|
|
923
|
+
// the moderator's string handling throws, which the caller's catch turns
|
|
924
|
+
// into silence rather than an error.
|
|
314
925
|
const moderatedContent = response && typeof response === 'object'
|
|
315
926
|
? (response.content ?? JSON.stringify(response))
|
|
316
927
|
: content;
|
|
317
928
|
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.MODERATE, moderatedContent, [], null, situation);
|
|
318
929
|
}
|
|
930
|
+
// Capture situation if provided (usually from narrator)
|
|
319
931
|
situation = response.situation || undefined;
|
|
320
932
|
const msg = new message_1.RoomMessage(agent.agentNickname, normalizedAction, response.content, targets, response.name, situation);
|
|
321
933
|
if (response.changes && typeof response.changes === 'object') {
|
|
322
934
|
msg.changes = response.changes;
|
|
323
935
|
}
|
|
936
|
+
// A moderator may name the action its relayed message should carry. Only
|
|
937
|
+
// the audible actions are accepted: `think` is nobody's message but the
|
|
938
|
+
// sender's, and the relay actions would just be the moderator's own answer
|
|
939
|
+
// again. Anything else is ignored, which leaves the original behaviour.
|
|
324
940
|
if (response.relayAs) {
|
|
325
941
|
const relayAs = Room.coerceMessageAction(response.relayAs);
|
|
326
942
|
const relayable = [
|
|
@@ -337,11 +953,29 @@ class Room {
|
|
|
337
953
|
}
|
|
338
954
|
return msg;
|
|
339
955
|
}
|
|
956
|
+
/**
|
|
957
|
+
* Extracts an opaque "preamble" block from the top of an agent response.
|
|
958
|
+
*
|
|
959
|
+
* A preamble is one or more consecutive `<tag>value</tag>` lines at the
|
|
960
|
+
* very start of the response, terminated by a blank line or non-tag
|
|
961
|
+
* content. The captured preamble is the verbatim text of those tag
|
|
962
|
+
* lines, suitable for downstream parsing by whoever owns the semantic
|
|
963
|
+
* interpretation (e.g. the story service for narrator responses).
|
|
964
|
+
*
|
|
965
|
+
* The Room itself never parses the preamble's contents. It just hands
|
|
966
|
+
* the text to the situation callback so callers (story, debate, etc.)
|
|
967
|
+
* can interpret it however they want.
|
|
968
|
+
*/
|
|
340
969
|
static extractPreamble(response) {
|
|
341
970
|
const lines = response.split('\n');
|
|
971
|
+
// Skip leading blank lines without consuming them from the output.
|
|
342
972
|
let i = 0;
|
|
343
973
|
while (i < lines.length && lines[i].trim() === '')
|
|
344
974
|
i++;
|
|
975
|
+
// Some providers (e.g. DeepSeek) wrap the whole response in a
|
|
976
|
+
// ```...``` code fence. Skip a leading fence line so the preamble
|
|
977
|
+
// detection still finds the tags on the next line. The matching
|
|
978
|
+
// trailing fence is stripped from the content at the end.
|
|
345
979
|
const fenceRe = /^\s*```\w*\s*$/;
|
|
346
980
|
const hadLeadingFence = i < lines.length && fenceRe.test(lines[i]);
|
|
347
981
|
if (hadLeadingFence)
|
|
@@ -356,9 +990,11 @@ class Room {
|
|
|
356
990
|
j++;
|
|
357
991
|
}
|
|
358
992
|
const preamble = preambleLines.join('\n');
|
|
993
|
+
// Skip a single trailing blank line between preamble and content.
|
|
359
994
|
if (j < lines.length && lines[j].trim() === '')
|
|
360
995
|
j++;
|
|
361
996
|
let contentLines = lines.slice(j);
|
|
997
|
+
// Drop a matching trailing code fence (and any trailing blanks after it).
|
|
362
998
|
if (hadLeadingFence) {
|
|
363
999
|
let k = contentLines.length - 1;
|
|
364
1000
|
while (k >= 0 && contentLines[k].trim() === '')
|
|
@@ -370,6 +1006,11 @@ class Room {
|
|
|
370
1006
|
const content = contentLines.join('\n').trimStart();
|
|
371
1007
|
return { preamble, content };
|
|
372
1008
|
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Maps an arbitrary action string to a MessageAction enum value,
|
|
1011
|
+
* accepting any casing. Returns undefined if the value doesn't correspond
|
|
1012
|
+
* to a known action.
|
|
1013
|
+
*/
|
|
373
1014
|
static coerceMessageAction(raw) {
|
|
374
1015
|
if (typeof raw !== 'string')
|
|
375
1016
|
return undefined;
|
|
@@ -377,6 +1018,22 @@ class Room {
|
|
|
377
1018
|
const values = Object.values(app_types_1.MessageAction);
|
|
378
1019
|
return values.includes(lowered) ? lowered : undefined;
|
|
379
1020
|
}
|
|
1021
|
+
/**
|
|
1022
|
+
* Determines which character agents are part of a message's audience, so a
|
|
1023
|
+
* perceiving agent can be shown (in the transient situation message) the
|
|
1024
|
+
* descriptions of only the characters it is currently interacting with.
|
|
1025
|
+
*
|
|
1026
|
+
* The audience is taken from the message's `targets` (the moderator fills these
|
|
1027
|
+
* with every agent who can hear the message) plus the message sender. Only
|
|
1028
|
+
* character agents (promptFolder === 'character') are returned; the narrator,
|
|
1029
|
+
* moderator and other support agents are excluded. The perceiving agent is never
|
|
1030
|
+
* included in its own list. When a message has no explicit targets (e.g. a plain
|
|
1031
|
+
* SPEAK broadcast in a non-story room) every character who can hear it is included.
|
|
1032
|
+
*
|
|
1033
|
+
* @param perceivingAgent The agent that will receive these descriptions
|
|
1034
|
+
* @param message The message being perceived
|
|
1035
|
+
* @returns Character agents in the message's audience, excluding the perceiver
|
|
1036
|
+
*/
|
|
380
1037
|
getPresentCharacters(perceivingAgent, message) {
|
|
381
1038
|
const audienceNames = message.getTargets();
|
|
382
1039
|
const senderName = message.getSender();
|
|
@@ -389,11 +1046,22 @@ class Room {
|
|
|
389
1046
|
return true;
|
|
390
1047
|
if (audienceNames.some((name) => this.checkAgentNicknameMatch(a.agentNickname, name)))
|
|
391
1048
|
return true;
|
|
1049
|
+
// No explicit targets: fall back to anyone who can hear the message.
|
|
392
1050
|
if (audienceNames.length === 0 && message.canHear(a.agentNickname))
|
|
393
1051
|
return true;
|
|
394
1052
|
return false;
|
|
395
1053
|
});
|
|
396
1054
|
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Builds a digest of the other agents' private context (in stories, their
|
|
1057
|
+
* inventory and conditions), for the oversight agents — the moderator and the room
|
|
1058
|
+
* leader (the Narrator in stories) — who need to keep the world consistent. Other
|
|
1059
|
+
* agents never see this; each only sees its own private context. The leader's own
|
|
1060
|
+
* context is left out, since it already receives that directly. Returns an
|
|
1061
|
+
* empty string when nobody else has any private context.
|
|
1062
|
+
*
|
|
1063
|
+
* @returns A markdown block of per-agent private context, or '' if none
|
|
1064
|
+
*/
|
|
397
1065
|
buildCharacterPrivateContextDigest() {
|
|
398
1066
|
const leader = this.getRoomLeader();
|
|
399
1067
|
return this.agents
|
|
@@ -401,10 +1069,21 @@ class Room {
|
|
|
401
1069
|
.map((a) => `### ${a.agentNickname}\n${a.privateContext}`)
|
|
402
1070
|
.join('\n\n');
|
|
403
1071
|
}
|
|
1072
|
+
/**
|
|
1073
|
+
* Builds the descriptors of the tools granted to an agent, for rendering into
|
|
1074
|
+
* its perceive prompt. Tool code is never exposed — only name, description and
|
|
1075
|
+
* parameters. Tools that were deleted after being granted are silently dropped.
|
|
1076
|
+
* @param agent The agent whose granted tools to describe
|
|
1077
|
+
* @returns Array of tool descriptors (empty when the agent has no usable tools)
|
|
1078
|
+
*/
|
|
404
1079
|
async buildAvailableTools(agent) {
|
|
405
1080
|
if (!agent.toolNames || agent.toolNames.length === 0) {
|
|
406
1081
|
return [];
|
|
407
1082
|
}
|
|
1083
|
+
// Resolve each granted name native-first (native tools are always available),
|
|
1084
|
+
// then fall back to the user-authored store. Descriptors expose only
|
|
1085
|
+
// name/description/parameters — never handler or code. Names that resolve
|
|
1086
|
+
// to nothing (deleted tool, or authored tools while gated off) are dropped.
|
|
408
1087
|
const nativeByName = new Map((this.toolExecutionService?.listNativeTools() || []).map((t) => [t.name, t]));
|
|
409
1088
|
const tools = [];
|
|
410
1089
|
for (const name of agent.toolNames) {
|
|
@@ -417,6 +1096,7 @@ class Room {
|
|
|
417
1096
|
});
|
|
418
1097
|
continue;
|
|
419
1098
|
}
|
|
1099
|
+
// Only surface authored tools when this deployment allows running them.
|
|
420
1100
|
if (!this.toolStoreService || !this.toolExecutionService?.userAuthoredToolsEnabled) {
|
|
421
1101
|
continue;
|
|
422
1102
|
}
|
|
@@ -431,6 +1111,22 @@ class Room {
|
|
|
431
1111
|
}
|
|
432
1112
|
return tools;
|
|
433
1113
|
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Renders an artifact for a prompt, dropping any ```briyah-state fenced
|
|
1116
|
+
* block.
|
|
1117
|
+
*
|
|
1118
|
+
* That fence is the convention for machine state an artifact carries for the
|
|
1119
|
+
* tools that maintain it — a character sheet keeps its whole state object
|
|
1120
|
+
* there, below the human-readable summary. Tools read the artifact directly
|
|
1121
|
+
* and are unaffected; a model never needs it, and pasting a page of raw JSON
|
|
1122
|
+
* into a prompt full of JSON is how a small model loses track of which JSON
|
|
1123
|
+
* it is supposed to be producing.
|
|
1124
|
+
*
|
|
1125
|
+
* An unterminated fence drops everything after it, which is the right
|
|
1126
|
+
* reading: whatever follows an opening state fence is state too.
|
|
1127
|
+
* @param artifact The artifact to render
|
|
1128
|
+
* @returns The prompt-facing text
|
|
1129
|
+
*/
|
|
434
1130
|
static renderArtifactForPrompt(artifact) {
|
|
435
1131
|
const kept = [];
|
|
436
1132
|
let inState = false;
|
|
@@ -448,10 +1144,20 @@ class Room {
|
|
|
448
1144
|
}
|
|
449
1145
|
return kept.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
450
1146
|
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Builds the Handlebars variables for an agent's perceive prompt,
|
|
1149
|
+
* including artifacts and the agent's granted tools.
|
|
1150
|
+
* @param agent The agent generating a response
|
|
1151
|
+
* @returns The prompt variables
|
|
1152
|
+
*/
|
|
451
1153
|
async buildPerceiveVariables(agent) {
|
|
1154
|
+
// Prepare variables for the prompt, including artifacts
|
|
452
1155
|
const visibleArtifacts = this.getVisibleArtifacts(agent.agentNickname)
|
|
453
1156
|
.map((a) => `${a.name} (by ${a.creator}): ${Room.renderArtifactForPrompt(a)}`)
|
|
454
1157
|
.join('\n\n');
|
|
1158
|
+
// Name the human-controlled characters. A room can have several players, so
|
|
1159
|
+
// the singular variable names the first for the prompts that assume one, and
|
|
1160
|
+
// the list names them all.
|
|
455
1161
|
const humanCharacterNames = this.getHumanAgents().map((a) => a.agentNickname);
|
|
456
1162
|
const humanCharacterName = humanCharacterNames[0] ?? 'Player';
|
|
457
1163
|
const humanCharacterList = Room.listNames(humanCharacterNames);
|
|
@@ -463,18 +1169,36 @@ class Room {
|
|
|
463
1169
|
otherAgents: this.agents.filter((a) => a.agentNickname !== agent.agentNickname),
|
|
464
1170
|
roomLeader: this.getRoomLeader(),
|
|
465
1171
|
roomGoal: this.getGoal(),
|
|
466
|
-
scenario: this.getGoal(),
|
|
1172
|
+
scenario: this.getGoal(), // Alias for story rooms
|
|
467
1173
|
situation: this.getSituation() || 'Story beginning',
|
|
468
1174
|
visibleArtifacts: visibleArtifacts,
|
|
469
1175
|
humanCharacterName: humanCharacterName,
|
|
470
|
-
humanAgentName: humanCharacterName,
|
|
1176
|
+
humanAgentName: humanCharacterName, // Alias for moderator
|
|
471
1177
|
humanCharacterNames: humanCharacterNames,
|
|
472
1178
|
humanCharacterList: humanCharacterList,
|
|
473
|
-
humanAgentList: humanCharacterList,
|
|
1179
|
+
humanAgentList: humanCharacterList, // Alias, as above
|
|
474
1180
|
maxOutputChars: maxOutputChars,
|
|
475
1181
|
availableTools: await this.buildAvailableTools(agent),
|
|
476
1182
|
};
|
|
477
1183
|
}
|
|
1184
|
+
/**
|
|
1185
|
+
* The names of the artifacts an agent cannot read.
|
|
1186
|
+
*
|
|
1187
|
+
* Volatile by nature: it changes whenever *any* artifact anywhere in the room is
|
|
1188
|
+
* created or deleted, for every agent that cannot read the new one. That put it in
|
|
1189
|
+
* the wrong half of the prompt for a long time. `transient` protects an artifact's
|
|
1190
|
+
* contents and nothing protected the roster, so placing four monsters at the start
|
|
1191
|
+
* of a fight rewrote this string for eight of nine agents and invalidated all eight
|
|
1192
|
+
* cached prefixes. Measured across one session it was 41.7% of the entire
|
|
1193
|
+
* cache-creation spend — and the Battle Master, the one agent that *could* read the
|
|
1194
|
+
* new artifacts, was the only one the fight cost nothing.
|
|
1195
|
+
*
|
|
1196
|
+
* Measured against what the agent can *read*, not against the cached block: a
|
|
1197
|
+
* transient artifact arrives in the per-turn prompt, so naming it here as one the
|
|
1198
|
+
* agent cannot see would be a lie.
|
|
1199
|
+
* @param nickname The agent the list is for
|
|
1200
|
+
* @returns A comma-separated list, or '' when the agent can read everything
|
|
1201
|
+
*/
|
|
478
1202
|
invisibleArtifactNames(nickname) {
|
|
479
1203
|
const readable = this.getReadableArtifacts(nickname);
|
|
480
1204
|
return this.getArtifacts()
|
|
@@ -482,6 +1206,24 @@ class Room {
|
|
|
482
1206
|
.map((a) => a.name)
|
|
483
1207
|
.join(', ');
|
|
484
1208
|
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Builds the transient (uncached) prompt message for an agent. It is sent
|
|
1211
|
+
* uncached and is not saved to the agent's history, which makes it the right
|
|
1212
|
+
* place to inject context that changes frequently, so a change never
|
|
1213
|
+
* invalidates the cached prompt instructions:
|
|
1214
|
+
* - the descriptions of the characters present in this message's audience
|
|
1215
|
+
* (each character sees how the others currently look without leaking
|
|
1216
|
+
* details about characters who are elsewhere), and
|
|
1217
|
+
* - the perceiving agent's own private context (e.g. its story inventory
|
|
1218
|
+
* and conditions), which only that agent may see.
|
|
1219
|
+
* The in-story time and situation text lead the transient prompt; the time
|
|
1220
|
+
* is on its own labeled line (see buildSituationHeader).
|
|
1221
|
+
* @param agent The agent that will receive this prompt
|
|
1222
|
+
* @param message The message being perceived, or null for follow-up prompts
|
|
1223
|
+
* within the same turn (e.g. after a tool result), where there is no new
|
|
1224
|
+
* message audience to describe
|
|
1225
|
+
* @returns The transient prompt, or null if there is nothing to inject
|
|
1226
|
+
*/
|
|
485
1227
|
buildTransientPrompt(agent, message) {
|
|
486
1228
|
let prompt = this.buildSituationHeader() || null;
|
|
487
1229
|
if (message) {
|
|
@@ -494,6 +1236,12 @@ class Room {
|
|
|
494
1236
|
prompt = prompt ? `${prompt}\n\n${charactersPresent}` : charactersPresent;
|
|
495
1237
|
}
|
|
496
1238
|
}
|
|
1239
|
+
// Artifacts marked transient. They are re-sent whole on every turn and
|
|
1240
|
+
// never cached, which is why they are the right home for small state that
|
|
1241
|
+
// moves constantly — a character sheet whose hit points change each round
|
|
1242
|
+
// would otherwise throw away this agent's cached rule documents on every
|
|
1243
|
+
// write. Placed before the private context so the agent reads its own
|
|
1244
|
+
// state before whatever it privately knows.
|
|
497
1245
|
const transientArtifacts = this.getTransientArtifacts(agent.agentNickname);
|
|
498
1246
|
if (transientArtifacts.length > 0) {
|
|
499
1247
|
const rendered = transientArtifacts
|
|
@@ -506,11 +1254,16 @@ class Room {
|
|
|
506
1254
|
const privateBlock = `Your private context (known only to you):\n${agent.privateContext}`;
|
|
507
1255
|
prompt = prompt ? `${prompt}\n\n${privateBlock}` : privateBlock;
|
|
508
1256
|
}
|
|
1257
|
+
// Here rather than in the cached instructions — see invisibleArtifactNames.
|
|
509
1258
|
const invisible = this.invisibleArtifactNames(agent.agentNickname);
|
|
510
1259
|
if (invisible) {
|
|
511
1260
|
const block = `Other documents in this room, which you cannot read:\n${invisible}`;
|
|
512
1261
|
prompt = prompt ? `${prompt}\n\n${block}` : block;
|
|
513
1262
|
}
|
|
1263
|
+
// The room leader (the Narrator in stories) has oversight of the world, so
|
|
1264
|
+
// it also receives every character's private context (inventory/conditions).
|
|
1265
|
+
// Like the moderator, this goes in the transient prompt rather than the
|
|
1266
|
+
// cached instructions so frequent inventory changes don't bust the cache.
|
|
514
1267
|
if (agent.agentNickname === this.getRoomLeader()) {
|
|
515
1268
|
const digest = this.buildCharacterPrivateContextDigest();
|
|
516
1269
|
if (digest) {
|
|
@@ -520,13 +1273,39 @@ class Room {
|
|
|
520
1273
|
}
|
|
521
1274
|
return prompt;
|
|
522
1275
|
}
|
|
1276
|
+
/**
|
|
1277
|
+
* Sends a single perceive prompt to an agent and parses the response.
|
|
1278
|
+
* The raw response is added to the agent's history. InsufficientBalanceError
|
|
1279
|
+
* (and any other error) propagates to the caller.
|
|
1280
|
+
* @param agent The agent generating a response
|
|
1281
|
+
* @param transientPrompt The uncached prompt message (see buildTransientPrompt)
|
|
1282
|
+
* @param variables The Handlebars variables (see buildPerceiveVariables)
|
|
1283
|
+
* @returns The agent's parsed response
|
|
1284
|
+
*/
|
|
523
1285
|
async promptAgentOnce(agent, transientPrompt, variables) {
|
|
524
|
-
const response = await agent.instructedPrompt(transientPrompt,
|
|
1286
|
+
const response = await agent.instructedPrompt(transientPrompt, // uncached prompt message stored in the situation
|
|
1287
|
+
'perceive', variables, false, true, variables.maxOutputChars);
|
|
525
1288
|
const answer = this.parseAgentResponse(agent, response);
|
|
526
1289
|
agent.addToConversationHistory(response, true);
|
|
527
1290
|
agent.save();
|
|
528
1291
|
return answer;
|
|
529
1292
|
}
|
|
1293
|
+
/**
|
|
1294
|
+
* Runs an agent's full turn: an initial response to the heard message,
|
|
1295
|
+
* followed by a private research loop. EXECUTE and PUBLISH responses are
|
|
1296
|
+
* handled here — the tool result (or publish confirmation) is fed back into
|
|
1297
|
+
* the agent's history and the agent is re-prompted — until the agent emits
|
|
1298
|
+
* an audible action or the iteration cap is hit. The room's processing lock
|
|
1299
|
+
* is held by the caller for the duration, so other agents wait.
|
|
1300
|
+
* @param agent The agent taking its turn
|
|
1301
|
+
* @param heardMessage The message that triggered this turn (already in the
|
|
1302
|
+
* agent's history), or null when the trigger was fed to the history
|
|
1303
|
+
* directly (e.g. commission deliverables)
|
|
1304
|
+
* @param opts inCommission: the agent is a commission target; nested
|
|
1305
|
+
* commissions are rejected and DELIVER is the expected terminal action
|
|
1306
|
+
* @returns The agent's final audible message, or null if the room was
|
|
1307
|
+
* paused/adjourned mid-turn
|
|
1308
|
+
*/
|
|
530
1309
|
async runAgentTurn(agent, heardMessage, opts = {}) {
|
|
531
1310
|
const variables = await this.buildPerceiveVariables(agent);
|
|
532
1311
|
let response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, heardMessage), variables);
|
|
@@ -548,19 +1327,33 @@ class Room {
|
|
|
548
1327
|
}
|
|
549
1328
|
else {
|
|
550
1329
|
if (!opts.inCommission && response.action === app_types_1.MessageAction.DELIVER) {
|
|
1330
|
+
// Stray DELIVER outside a commission: degrade to a normal SPEAK
|
|
551
1331
|
response.action = app_types_1.MessageAction.SPEAK;
|
|
552
1332
|
}
|
|
553
|
-
return response;
|
|
1333
|
+
return response; // Audible action — the turn is complete
|
|
554
1334
|
}
|
|
555
1335
|
agent.addToConversationHistory(feedback, false);
|
|
556
1336
|
agent.save();
|
|
557
1337
|
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
558
1338
|
}
|
|
1339
|
+
// Iteration cap hit: one corrective prompt, then coerce
|
|
559
1340
|
if (this.isPaused || this.isAdjourned)
|
|
560
1341
|
return null;
|
|
561
1342
|
agent.addToConversationHistory(`From system: You have reached the tool-call limit for this turn. Respond now with an audible action (speak, whisper, think, ...).`, false);
|
|
562
1343
|
agent.save();
|
|
563
1344
|
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
1345
|
+
// Still reaching for a tool after being told to stop. The turn has to end, but
|
|
1346
|
+
// what the agent produced must not be thrown away silently, which is what
|
|
1347
|
+
// coercing it to a thought used to do:
|
|
1348
|
+
//
|
|
1349
|
+
// - A **PUBLISH** is a finished document. A campaign designer spent its whole
|
|
1350
|
+
// chain on research, published the campaign it had just written, and the
|
|
1351
|
+
// coercion turned four thousand characters of it into an inaudible thought.
|
|
1352
|
+
// Nobody noticed until the person at the table asked where the artifact was.
|
|
1353
|
+
// Publish it, then end the turn.
|
|
1354
|
+
// - An **EXECUTE** cannot be run — that is the limit doing its job — but say so
|
|
1355
|
+
// where a person can see it. Damage that was never applied and death saves
|
|
1356
|
+
// that were never rolled read exactly like a quiet turn otherwise.
|
|
564
1357
|
if (response.action === app_types_1.MessageAction.PUBLISH && response.name) {
|
|
565
1358
|
this.publishArtifact(response.name, agent.agentNickname, response.content, response.targets);
|
|
566
1359
|
logger_1.logger.warn(`Room ${this.name}: ${agent.agentNickname} published "${response.name}" on its final tool call; publishing it and ending the turn`);
|
|
@@ -574,6 +1367,14 @@ class Room {
|
|
|
574
1367
|
}
|
|
575
1368
|
return response;
|
|
576
1369
|
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Runs a tool for an agent's EXECUTE message and returns the feedback string
|
|
1372
|
+
* to add to the agent's history. Also logs a TOOL notice to the room so
|
|
1373
|
+
* humans watching (with thoughts visible) can see the activity.
|
|
1374
|
+
* @param agent The agent that issued the EXECUTE
|
|
1375
|
+
* @param message The EXECUTE message (name = tool name, content = JSON args)
|
|
1376
|
+
* @returns The feedback string for the agent's history
|
|
1377
|
+
*/
|
|
577
1378
|
async executeToolForAgent(agent, message) {
|
|
578
1379
|
const toolName = message.name;
|
|
579
1380
|
const result = this.toolExecutionService
|
|
@@ -584,11 +1385,54 @@ class Room {
|
|
|
584
1385
|
this.addRoomMessage(new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.TOOL, `${toolName}(${argsPreview}) → ${statusText}`));
|
|
585
1386
|
return `From system: Result of tool "${toolName}":\n${JSON.stringify(result)}`;
|
|
586
1387
|
}
|
|
1388
|
+
/**
|
|
1389
|
+
* How much of a result a TOOL notice shows.
|
|
1390
|
+
*
|
|
1391
|
+
* Generous because the result is the half a person needs when something has gone
|
|
1392
|
+
* wrong, and a clipped one hides whether a call that reported success actually
|
|
1393
|
+
* changed anything.
|
|
1394
|
+
*
|
|
1395
|
+
* Most results never reach this: {@link describeToolResult} prefers a result's own
|
|
1396
|
+
* `detail` or `summary` one-liner, and the 5e tools all write one. It binds on the
|
|
1397
|
+
* results that have neither, which are the raw ones worth reading in full.
|
|
1398
|
+
*/
|
|
587
1399
|
static TOOL_LOG_PREVIEW = 2000;
|
|
1400
|
+
/**
|
|
1401
|
+
* How much of an EXECUTE's arguments the room's TOOL notice keeps.
|
|
1402
|
+
*
|
|
1403
|
+
* Far longer than the result's allowance because the arguments are the half a
|
|
1404
|
+
* person actually reads — what the agent asked the tool to do — and at 200
|
|
1405
|
+
* characters a `create_sheet` call was cut off inside its own spec, showing the
|
|
1406
|
+
* character's race and nothing after it. The bound is a sanity limit rather than
|
|
1407
|
+
* a budget: arguments are written by a model, so they are already short.
|
|
1408
|
+
*
|
|
1409
|
+
* A TOOL notice is heard by nobody and never enters an agent's history
|
|
1410
|
+
* (`RoomMessage.canHear` refuses TOOL), so none of this costs a token. It costs
|
|
1411
|
+
* bytes in the room log and on the update stream, which is the right trade for
|
|
1412
|
+
* being able to see what was run.
|
|
1413
|
+
*/
|
|
588
1414
|
static TOOL_LOG_ARGS_PREVIEW = 4000;
|
|
1415
|
+
/** Clips a preview so one tool call cannot fill the transcript. */
|
|
589
1416
|
static previewForToolLog(text, limit = Room.TOOL_LOG_PREVIEW) {
|
|
590
1417
|
return text.length > limit ? `${text.slice(0, limit)}...` : text;
|
|
591
1418
|
}
|
|
1419
|
+
/**
|
|
1420
|
+
* Summarizes a successful tool result for the room log.
|
|
1421
|
+
*
|
|
1422
|
+
* `ok` on its own hid the only part anyone watching wanted: a check that
|
|
1423
|
+
* rolled 11 against DC 13 and failed was logged exactly like one that passed.
|
|
1424
|
+
* A result carrying its own one-line summary — `detail` or `summary`, the two
|
|
1425
|
+
* the 5e tools already write — is quoted; anything else is shown as a clipped
|
|
1426
|
+
* JSON preview, which at least says what came back.
|
|
1427
|
+
*
|
|
1428
|
+
* Deliberately no knowledge of any particular tool: these are conventional
|
|
1429
|
+
* field names, and a tool that uses neither still reads better than 'ok'.
|
|
1430
|
+
*
|
|
1431
|
+
* A TOOL notice is heard by nobody and never enters an agent's history, so
|
|
1432
|
+
* none of this costs a token — it is purely for the person reading the room.
|
|
1433
|
+
* @param value The `result` of a successful run
|
|
1434
|
+
* @returns A single line for the notice
|
|
1435
|
+
*/
|
|
592
1436
|
static describeToolResult(value) {
|
|
593
1437
|
if (value === undefined || value === null)
|
|
594
1438
|
return 'ok';
|
|
@@ -603,6 +1447,20 @@ class Room {
|
|
|
603
1447
|
const rendered = typeof value === 'string' ? value : JSON.stringify(value);
|
|
604
1448
|
return rendered ? Room.previewForToolLog(rendered) : 'ok';
|
|
605
1449
|
}
|
|
1450
|
+
/**
|
|
1451
|
+
* Builds the room access a tool receives as `helpers.room`, scoped to the
|
|
1452
|
+
* agent that invoked it. Deliberately a closure rather than a class holding
|
|
1453
|
+
* a Room reference: {@link ToolRoomAccess} is part of the tool-facing
|
|
1454
|
+
* contract, and importing Room into it would pull the whole room graph into
|
|
1455
|
+
* the SDK's public types.
|
|
1456
|
+
*
|
|
1457
|
+
* The wrapper is not a pass-through to publishArtifact — it corrects three
|
|
1458
|
+
* behaviors that are right for an agent's PUBLISH but wrong for a tool:
|
|
1459
|
+
* publishArtifact credits the artifact to whoever wrote last, treats an
|
|
1460
|
+
* empty viewers list as creator-only, and deletes on an empty body.
|
|
1461
|
+
* @param agent The agent whose EXECUTE triggered the tool call
|
|
1462
|
+
* @returns The room accessor handed to the tool
|
|
1463
|
+
*/
|
|
606
1464
|
buildToolRoomAccess(agent) {
|
|
607
1465
|
const toToolArtifact = (a) => a
|
|
608
1466
|
? {
|
|
@@ -618,6 +1476,11 @@ class Room {
|
|
|
618
1476
|
throw new Error(`Refusing to write an empty body to artifact "${name}"; that would delete it`);
|
|
619
1477
|
}
|
|
620
1478
|
const existing = this.findArtifact(name);
|
|
1479
|
+
// Keep the original author so a tool call by another agent (e.g. the
|
|
1480
|
+
// room leader updating a document a player owns) doesn't reassign it.
|
|
1481
|
+
// On creation the tool may name the agent the artifact belongs to,
|
|
1482
|
+
// but only if that agent is actually here — crediting someone absent
|
|
1483
|
+
// would make the artifact unreadable to everyone.
|
|
621
1484
|
let creator = agent.agentNickname;
|
|
622
1485
|
if (existing) {
|
|
623
1486
|
creator = existing.creator;
|
|
@@ -631,6 +1494,8 @@ class Room {
|
|
|
631
1494
|
(existing && existing.viewers && existing.viewers.length > 0
|
|
632
1495
|
? existing.viewers
|
|
633
1496
|
: this.agents.map((a) => a.agentNickname));
|
|
1497
|
+
// Like viewers and creator: undefined means "leave it as it is", so a
|
|
1498
|
+
// tool that updates a body does not have to restate how it is delivered.
|
|
634
1499
|
return toToolArtifact(this.publishArtifact(name, creator, body, finalViewers, options?.transient));
|
|
635
1500
|
};
|
|
636
1501
|
return {
|
|
@@ -639,6 +1504,7 @@ class Room {
|
|
|
639
1504
|
isHuman: !!agent.isControlledByHuman,
|
|
640
1505
|
isLeader: agent.agentNickname === this.getRoomLeader(),
|
|
641
1506
|
},
|
|
1507
|
+
// Snapshotted: the roster cannot change during a single tool call.
|
|
642
1508
|
agentNicknames: this.agents.map((a) => a.agentNickname),
|
|
643
1509
|
roomId: this.getId(),
|
|
644
1510
|
roomName: this.getName(),
|
|
@@ -662,11 +1528,21 @@ class Room {
|
|
|
662
1528
|
if (!target)
|
|
663
1529
|
return false;
|
|
664
1530
|
target.description = trimmed.slice(0, MAX_DESCRIPTION_CHARS);
|
|
665
|
-
target.save();
|
|
1531
|
+
target.save(); // Persists and notifies the client
|
|
666
1532
|
return true;
|
|
667
1533
|
},
|
|
1534
|
+
renameAgent: (nickname, newName) => this.renameAgent(nickname, newName),
|
|
668
1535
|
};
|
|
669
1536
|
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Gets AI response for an agent (private helper moved from Agent).
|
|
1539
|
+
* Thin callback adapter around runAgentTurn: the callback does not fire
|
|
1540
|
+
* until the agent's whole turn (including any tool research loop) is done,
|
|
1541
|
+
* which is what holds the room's processing lock for the duration.
|
|
1542
|
+
* @param agent The agent generating response
|
|
1543
|
+
* @param message The message the agent is responding to
|
|
1544
|
+
* @param onResponse Callback with AI response
|
|
1545
|
+
*/
|
|
670
1546
|
getAgentAiResponse(agent, message, onResponse) {
|
|
671
1547
|
this.runAgentTurn(agent, message)
|
|
672
1548
|
.then(async (answer) => {
|
|
@@ -678,12 +1554,32 @@ class Room {
|
|
|
678
1554
|
this.handleInsufficientBalance(e);
|
|
679
1555
|
}
|
|
680
1556
|
else {
|
|
1557
|
+
// Other errors remain internalized (existing behavior)
|
|
681
1558
|
let internalizedError = `${agent.agentNickname} thinks: No one heard me because ${e.message}`;
|
|
682
1559
|
agent.addToConversationHistory(internalizedError, true);
|
|
683
1560
|
}
|
|
684
1561
|
onResponse(null);
|
|
685
1562
|
});
|
|
686
1563
|
}
|
|
1564
|
+
/**
|
|
1565
|
+
* Summarises an agent's history when it has outgrown the compaction threshold.
|
|
1566
|
+
*
|
|
1567
|
+
* Called at the end of a turn rather than the start of one, which is the only
|
|
1568
|
+
* safe point: the turn's tool chain feeds results back into history and
|
|
1569
|
+
* re-prompts, so compacting part-way through would summarise away the tool call
|
|
1570
|
+
* whose result the agent is waiting on. By the time the turn returns, its own
|
|
1571
|
+
* response is already in history and the summary can cover it.
|
|
1572
|
+
*
|
|
1573
|
+
* It also runs *before* `onResponse`, which is what releases the room to process
|
|
1574
|
+
* the next message. Compacting afterwards would rewrite this agent's history
|
|
1575
|
+
* while the following turn was reading it.
|
|
1576
|
+
*
|
|
1577
|
+
* A failed summary is logged and swallowed. The agent keeps a too-long history
|
|
1578
|
+
* and the campaign carries on, which is strictly better than ending a turn that
|
|
1579
|
+
* already produced a good answer because a bookkeeping call failed.
|
|
1580
|
+
*
|
|
1581
|
+
* @param agent The agent whose turn has just finished
|
|
1582
|
+
*/
|
|
687
1583
|
async compactIfOversized(agent) {
|
|
688
1584
|
if (!agent.needsCompaction())
|
|
689
1585
|
return;
|
|
@@ -694,6 +1590,16 @@ class Room {
|
|
|
694
1590
|
logger_1.logger.warn(`Could not compact ${agent.agentName}, continuing with full history: ${e.message}`);
|
|
695
1591
|
}
|
|
696
1592
|
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Delivers a message into an agent's history without asking it to respond.
|
|
1595
|
+
* Split out of {@link perceive} so agents that are not responding this turn
|
|
1596
|
+
* still stay in sync with the conversation at no LLM cost. Callers that are
|
|
1597
|
+
* not counting this agent in their outstanding-response tally must use this
|
|
1598
|
+
* rather than `perceive`, which always invokes its callback.
|
|
1599
|
+
* @param agent The agent receiving the message
|
|
1600
|
+
* @param message The message being delivered
|
|
1601
|
+
* @returns True if the agent could hear the message and it was recorded
|
|
1602
|
+
*/
|
|
697
1603
|
hear(agent, message) {
|
|
698
1604
|
if (!message.canHear(agent.agentNickname)) {
|
|
699
1605
|
return false;
|
|
@@ -702,31 +1608,58 @@ class Room {
|
|
|
702
1608
|
agent.save();
|
|
703
1609
|
return true;
|
|
704
1610
|
}
|
|
1611
|
+
/**
|
|
1612
|
+
* Allows an agent to perceive messages and generate a response (moved from Agent)
|
|
1613
|
+
* @param agent The agent that is perceiving
|
|
1614
|
+
* @param message
|
|
1615
|
+
* @param onResponse Callback with agent's response or null
|
|
1616
|
+
*/
|
|
705
1617
|
perceive(agent, message, onResponse, opts = {}) {
|
|
1618
|
+
// An agent keeping the floor is answering its own message, which is already in
|
|
1619
|
+
// its history because it wrote it — and `canHear` is false for your own
|
|
1620
|
+
// message, so the delivery gate below would drop the prompt and leave the room
|
|
1621
|
+
// with nobody acting at all. Prompt it directly, with a note saying why it is
|
|
1622
|
+
// being asked again: without one it cannot tell a continuation from being
|
|
1623
|
+
// handed back something it has already answered.
|
|
706
1624
|
if (opts.continuing) {
|
|
707
1625
|
agent.addToConversationHistory(Room.CONTINUE_NOTE, false);
|
|
708
1626
|
agent.save();
|
|
709
1627
|
this.getAgentAiResponse(agent, message, onResponse);
|
|
710
1628
|
return;
|
|
711
1629
|
}
|
|
1630
|
+
// Check if this agent can hear the message, and record it if so
|
|
712
1631
|
if (!this.hear(agent, message)) {
|
|
713
1632
|
onResponse(null);
|
|
714
1633
|
return;
|
|
715
1634
|
}
|
|
1635
|
+
// Check if should respond
|
|
716
1636
|
if (!agent.canRespond(message)) {
|
|
717
1637
|
onResponse(null);
|
|
718
1638
|
return;
|
|
719
1639
|
}
|
|
720
1640
|
if (agent.isControlledByHuman) {
|
|
1641
|
+
// onResponse is not called. This prevents the agentsRemaining count from hitting zero and stops message processing
|
|
721
1642
|
return;
|
|
722
1643
|
}
|
|
1644
|
+
// AI-CONTROLLED AGENT: Query AI service and call callback with response
|
|
723
1645
|
this.getAgentAiResponse(agent, message, onResponse);
|
|
724
1646
|
}
|
|
725
|
-
|
|
1647
|
+
/**
|
|
1648
|
+
* Moderator agent evaluates and routes a message (moved from Agent)
|
|
1649
|
+
* @param moderatorAgent The moderator agent
|
|
1650
|
+
* @param message RoomMessage to moderate
|
|
1651
|
+
* @param onResponse Callback with routing decision
|
|
1652
|
+
* @param opts.note Extra instruction for this one routing decision, put in the
|
|
1653
|
+
* transient prompt so it never enters the moderator's cached prefix
|
|
1654
|
+
*/
|
|
1655
|
+
async moderate(moderatorAgent, message, onResponse, opts = {}) {
|
|
1656
|
+
// Name the human-controlled characters. The moderator routes to one of them
|
|
1657
|
+
// by name, so it needs the whole list, not just the first.
|
|
726
1658
|
const humanAgents = this.getHumanAgents();
|
|
727
1659
|
const humanAgent = humanAgents[0];
|
|
728
1660
|
const humanAgentNames = humanAgents.map((a) => a.agentNickname);
|
|
729
1661
|
const humanAgentName = humanAgentNames[0] ?? 'Player';
|
|
1662
|
+
// Build base variables
|
|
730
1663
|
const visibleArtifacts = this.getVisibleArtifacts(moderatorAgent.agentNickname)
|
|
731
1664
|
.map((a) => `${a.name} (by ${a.creator}): ${Room.renderArtifactForPrompt(a)}`)
|
|
732
1665
|
.join('\n\n');
|
|
@@ -738,7 +1671,7 @@ class Room {
|
|
|
738
1671
|
agents: this.getAgents(),
|
|
739
1672
|
roomLeader: this.getRoomLeader(),
|
|
740
1673
|
roomGoal: this.getGoal(),
|
|
741
|
-
scenario: this.getGoal(),
|
|
1674
|
+
scenario: this.getGoal(), // Alias for story rooms
|
|
742
1675
|
humanAgent: humanAgent,
|
|
743
1676
|
humanAgentName: humanAgentName,
|
|
744
1677
|
humanAgentNames: humanAgentNames,
|
|
@@ -750,13 +1683,31 @@ ${this.buildSituationHeader()}
|
|
|
750
1683
|
Sender: ${message.getSender()}
|
|
751
1684
|
Recent Message: ${message.getContent()}
|
|
752
1685
|
`;
|
|
1686
|
+
// Adjacent to the message it changes the meaning of, rather than appended at
|
|
1687
|
+
// the end behind the inventories.
|
|
1688
|
+
if (opts.note) {
|
|
1689
|
+
prompt += `\n${opts.note}\n`;
|
|
1690
|
+
}
|
|
1691
|
+
// Who heard the last routed message, so a conversation with a sub-group stays
|
|
1692
|
+
// with that sub-group. In the transient prompt rather than the instructions:
|
|
1693
|
+
// it changes every turn, and in the cached prefix it would invalidate the
|
|
1694
|
+
// moderator's cache on each one.
|
|
753
1695
|
if (this.lastModeratedAudience.length > 0) {
|
|
754
1696
|
prompt += `\nAudience of the previous message: ${this.lastModeratedAudience.join(', ')}\n`;
|
|
755
1697
|
}
|
|
1698
|
+
// The document names tell the moderator what stage the table is at, which is
|
|
1699
|
+
// what it routes on. Transient for the same reason as the audience above: the
|
|
1700
|
+
// list changes whenever any artifact is created anywhere in the room, and
|
|
1701
|
+
// cached it invalidated the moderator's prefix every time one was.
|
|
756
1702
|
const invisible = this.invisibleArtifactNames(moderatorAgent.agentNickname);
|
|
757
1703
|
if (invisible) {
|
|
758
1704
|
prompt += `\nDocuments at this table you cannot read: ${invisible}\n`;
|
|
759
1705
|
}
|
|
1706
|
+
// The moderator needs every character's current inventory and conditions to
|
|
1707
|
+
// keep the story consistent and to emit update_inventory. Each character keeps
|
|
1708
|
+
// these in its private context. Inject them into the transient (uncached)
|
|
1709
|
+
// moderator prompt rather than the cached instructions, so a frequently-changing
|
|
1710
|
+
// inventory never invalidates the moderator's prompt cache.
|
|
760
1711
|
const characterContexts = this.buildCharacterPrivateContextDigest();
|
|
761
1712
|
if (characterContexts) {
|
|
762
1713
|
prompt += `\nCharacter Inventories and Conditions:\n${characterContexts}\n`;
|
|
@@ -774,75 +1725,137 @@ Recent Message: ${message.getContent()}
|
|
|
774
1725
|
this.handleInsufficientBalance(e, onResponse);
|
|
775
1726
|
}
|
|
776
1727
|
else {
|
|
1728
|
+
// Other errors - rethrow
|
|
777
1729
|
throw e;
|
|
778
1730
|
}
|
|
779
1731
|
}
|
|
780
1732
|
}
|
|
1733
|
+
/**
|
|
1734
|
+
* Handles insufficient balance errors by pausing the conversation
|
|
1735
|
+
* @param error The insufficient balance error
|
|
1736
|
+
* @param onResponse Optional callback to call with null
|
|
1737
|
+
*/
|
|
781
1738
|
handleInsufficientBalance(error, onResponse) {
|
|
1739
|
+
// Notify error callback (propagates to SSE clients)
|
|
782
1740
|
this.notifyError(error);
|
|
1741
|
+
// Add visible system message
|
|
783
1742
|
const balanceMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, `Conversation paused: ${error.message}`, [], null, null);
|
|
784
1743
|
this.addRoomMessage(balanceMessage);
|
|
1744
|
+
// Stop processing. 'keep' rather than 'release' so a pause that is already
|
|
1745
|
+
// holding the floor for the human keeps it; the caller's own callback
|
|
1746
|
+
// releases it on the paths where that is right.
|
|
785
1747
|
this.endTurn('keep');
|
|
1748
|
+
// Call callback with null if provided
|
|
786
1749
|
if (onResponse) {
|
|
787
1750
|
onResponse(null);
|
|
788
1751
|
}
|
|
789
1752
|
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Gets an artifact by name
|
|
1755
|
+
* @param name The name of the artifact
|
|
1756
|
+
* @returns The artifact or undefined if not found
|
|
1757
|
+
*/
|
|
790
1758
|
findArtifact(name) {
|
|
791
1759
|
return this.artifacts.find((a) => a.name === name);
|
|
792
1760
|
}
|
|
1761
|
+
/**
|
|
1762
|
+
* Creates or updates an artifact with PUBLISH action
|
|
1763
|
+
* If body is empty, deletes the artifact instead
|
|
1764
|
+
* @param name The name of the artifact
|
|
1765
|
+
* @param creator The name of the agent who created it
|
|
1766
|
+
* @param body The content of the artifact (empty body will delete the artifact)
|
|
1767
|
+
* @param viewers Array of agent names who can view the artifact
|
|
1768
|
+
* @returns The created or updated artifact, or null if deleted
|
|
1769
|
+
*/
|
|
793
1770
|
publishArtifact(name, creator, body, viewers = [], transient) {
|
|
1771
|
+
// Empty body means delete the artifact
|
|
794
1772
|
if (!body || body.trim().length === 0) {
|
|
795
1773
|
this.deleteArtifact(name);
|
|
796
1774
|
return null;
|
|
797
1775
|
}
|
|
1776
|
+
// Check if an artifact with this name already exists
|
|
798
1777
|
const existingIndex = this.artifacts.findIndex((a) => a.name === name);
|
|
799
1778
|
let returnedArtifact;
|
|
800
1779
|
if (existingIndex >= 0) {
|
|
1780
|
+
// Update existing artifact
|
|
801
1781
|
this.artifacts[existingIndex].body = body;
|
|
802
1782
|
this.artifacts[existingIndex].creator = creator;
|
|
803
1783
|
this.artifacts[existingIndex].viewers = viewers.length > 0 ? viewers : [creator];
|
|
1784
|
+
// Undefined leaves it as it was, so an agent's PUBLISH over a
|
|
1785
|
+
// transient artifact cannot silently promote it into the cached block.
|
|
804
1786
|
if (transient !== undefined) {
|
|
805
1787
|
this.artifacts[existingIndex].transient = transient;
|
|
806
1788
|
}
|
|
807
1789
|
returnedArtifact = this.artifacts[existingIndex];
|
|
808
1790
|
}
|
|
809
1791
|
else {
|
|
1792
|
+
// Create new artifact
|
|
810
1793
|
const newArtifact = {
|
|
811
1794
|
name,
|
|
812
1795
|
creator,
|
|
813
1796
|
body,
|
|
814
|
-
viewers: viewers.length > 0 ? viewers : [creator],
|
|
1797
|
+
viewers: viewers.length > 0 ? viewers : [creator], // If no viewers specified, only creator can see
|
|
815
1798
|
...(transient !== undefined && { transient }),
|
|
816
1799
|
};
|
|
817
1800
|
this.artifacts.push(newArtifact);
|
|
818
1801
|
returnedArtifact = newArtifact;
|
|
819
1802
|
}
|
|
1803
|
+
// Save individual artifact file
|
|
820
1804
|
if (this.roomStoreService && this.storageDir) {
|
|
821
1805
|
this.roomStoreService.saveArtifactFile(this.id, this.storageDir, returnedArtifact);
|
|
822
1806
|
}
|
|
823
|
-
this.saveMetadata();
|
|
1807
|
+
this.saveMetadata(); // Still save metadata for other room fields
|
|
1808
|
+
// Tools can write artifacts outside the message flow, so the client has
|
|
1809
|
+
// no other signal to refresh its artifact list.
|
|
824
1810
|
this.notifyStateChange();
|
|
825
1811
|
return returnedArtifact;
|
|
826
1812
|
}
|
|
1813
|
+
/**
|
|
1814
|
+
* Deletes an artifact from the room
|
|
1815
|
+
* @param name The name of the artifact to delete
|
|
1816
|
+
* @returns True if the artifact was found and deleted, false otherwise
|
|
1817
|
+
*/
|
|
827
1818
|
deleteArtifact(name) {
|
|
828
1819
|
const index = this.artifacts.findIndex((a) => a.name === name);
|
|
829
1820
|
if (index === -1) {
|
|
830
1821
|
return false;
|
|
831
1822
|
}
|
|
1823
|
+
// Remove from in-memory array
|
|
832
1824
|
this.artifacts.splice(index, 1);
|
|
1825
|
+
// Delete artifact file
|
|
833
1826
|
if (this.roomStoreService && this.storageDir) {
|
|
834
1827
|
this.roomStoreService.deleteArtifactFile(this.id, this.storageDir, name);
|
|
835
1828
|
}
|
|
836
1829
|
return true;
|
|
837
1830
|
}
|
|
1831
|
+
/**
|
|
1832
|
+
* Gets the artifacts an agent may read, transient ones included.
|
|
1833
|
+
* @param agentNickname The name of the agent
|
|
1834
|
+
* @returns Array of artifacts readable by the agent
|
|
1835
|
+
*/
|
|
838
1836
|
getReadableArtifacts(agentNickname) {
|
|
839
1837
|
return this.artifacts.filter((a) => a.creator === agentNickname ||
|
|
840
1838
|
(a.viewers && a.viewers.includes(agentNickname)) ||
|
|
841
1839
|
!a.viewers);
|
|
842
1840
|
}
|
|
1841
|
+
/**
|
|
1842
|
+
* Gets the artifacts rendered into an agent's **cached** prompt block.
|
|
1843
|
+
*
|
|
1844
|
+
* Transient artifacts are deliberately excluded: they go in the per-turn
|
|
1845
|
+
* prompt instead (see `buildTransientPrompt`), which is the whole point of
|
|
1846
|
+
* marking one transient. They are still readable — `getTransientArtifacts`
|
|
1847
|
+
* returns them, and a tool reads any artifact regardless.
|
|
1848
|
+
* @param agentNickname The name of the agent
|
|
1849
|
+
* @returns Array of artifacts visible to the agent
|
|
1850
|
+
*/
|
|
843
1851
|
getVisibleArtifacts(agentNickname) {
|
|
844
1852
|
return this.getReadableArtifacts(agentNickname).filter((a) => !a.transient);
|
|
845
1853
|
}
|
|
1854
|
+
/**
|
|
1855
|
+
* Gets the artifacts delivered to an agent in the uncached per-turn prompt.
|
|
1856
|
+
* @param agentNickname The name of the agent
|
|
1857
|
+
* @returns Array of transient artifacts readable by the agent
|
|
1858
|
+
*/
|
|
846
1859
|
getTransientArtifacts(agentNickname) {
|
|
847
1860
|
return this.getReadableArtifacts(agentNickname).filter((a) => a.transient);
|
|
848
1861
|
}
|
|
@@ -864,22 +1877,38 @@ Recent Message: ${message.getContent()}
|
|
|
864
1877
|
setRoomStoreService(service) {
|
|
865
1878
|
this.roomStoreService = service;
|
|
866
1879
|
}
|
|
1880
|
+
/**
|
|
1881
|
+
* @internal Injects the user-scoped tool services so agents in this room can
|
|
1882
|
+
* EXECUTE user-defined tools. Called by RoomStoreService and RoomFactory at
|
|
1883
|
+
* every Room construction site; SDK consumers never call this directly.
|
|
1884
|
+
* @param toolStore The user's tool store
|
|
1885
|
+
* @param toolExecution The user's tool execution service
|
|
1886
|
+
*/
|
|
867
1887
|
setToolServices(toolStore, toolExecution) {
|
|
868
1888
|
this.toolStoreService = toolStore;
|
|
869
1889
|
this.toolExecutionService = toolExecution;
|
|
870
1890
|
}
|
|
1891
|
+
/**
|
|
1892
|
+
* Saves messages incrementally to disk
|
|
1893
|
+
* @param messages The new messages to append
|
|
1894
|
+
*/
|
|
871
1895
|
saveMessages(messages) {
|
|
872
1896
|
if (!this.roomStoreService || !this.storageDir || !this.id) {
|
|
873
|
-
return;
|
|
1897
|
+
return; // Can't save if persistence not configured
|
|
874
1898
|
}
|
|
1899
|
+
// Append each new message to the messages file
|
|
875
1900
|
for (const message of messages) {
|
|
876
1901
|
this.roomStoreService.appendMessageToFile(this.id, message, this.storageDir);
|
|
877
1902
|
}
|
|
878
1903
|
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Saves the room metadata to disk
|
|
1906
|
+
*/
|
|
879
1907
|
saveMetadata() {
|
|
880
1908
|
if (!this.roomStoreService || !this.storageDir) {
|
|
881
|
-
return;
|
|
1909
|
+
return; // Can't save if persistence not configured
|
|
882
1910
|
}
|
|
1911
|
+
// Prevent saving during room loading to avoid saving incomplete state
|
|
883
1912
|
if (this.isLoading) {
|
|
884
1913
|
return;
|
|
885
1914
|
}
|
|
@@ -887,9 +1916,21 @@ Recent Message: ${message.getContent()}
|
|
|
887
1916
|
this.notifyStateChange();
|
|
888
1917
|
return id;
|
|
889
1918
|
}
|
|
1919
|
+
/**
|
|
1920
|
+
* Registers a state-change listener under a stable key. Each key holds at most
|
|
1921
|
+
* one listener — re-registering with the same key replaces its callback.
|
|
1922
|
+
* Different keys can coexist so multiple subsystems (e.g. the rooms SSE endpoint
|
|
1923
|
+
* and the story service) both receive notifications without clobbering each other.
|
|
1924
|
+
* @param key Stable identifier for the subsystem (e.g. 'app-service', 'story')
|
|
1925
|
+
* @param callback Function to call on state changes
|
|
1926
|
+
*/
|
|
890
1927
|
setOnStateChange(key, callback) {
|
|
891
1928
|
this.onStateChangeCallbacks.set(key, callback);
|
|
892
1929
|
}
|
|
1930
|
+
/**
|
|
1931
|
+
* Removes a previously-registered state-change listener.
|
|
1932
|
+
* @param key The key passed to {@link setOnStateChange}
|
|
1933
|
+
*/
|
|
893
1934
|
removeOnStateChange(key) {
|
|
894
1935
|
this.onStateChangeCallbacks.delete(key);
|
|
895
1936
|
}
|
|
@@ -898,9 +1939,25 @@ Recent Message: ${message.getContent()}
|
|
|
898
1939
|
callback();
|
|
899
1940
|
}
|
|
900
1941
|
}
|
|
1942
|
+
/**
|
|
1943
|
+
* Subscribes to errors raised while running a turn.
|
|
1944
|
+
*
|
|
1945
|
+
* Keyed like {@link setOnStateChange}, and for the same reason: more than one
|
|
1946
|
+
* thing wants to hear about a failed turn. A single-callback setter meant the
|
|
1947
|
+
* last caller silently replaced the first — the SDK's bridge onto the room's
|
|
1948
|
+
* update stream and a story's own handler could not both exist, and whichever
|
|
1949
|
+
* registered second won without any sign that it had taken the other's place.
|
|
1950
|
+
*
|
|
1951
|
+
* @param key Identifies the subscriber; registering the same key twice replaces it
|
|
1952
|
+
* @param callback Function to call on errors
|
|
1953
|
+
*/
|
|
901
1954
|
setOnError(key, callback) {
|
|
902
1955
|
this.onErrorCallbacks.set(key, callback);
|
|
903
1956
|
}
|
|
1957
|
+
/**
|
|
1958
|
+
* Stops delivering errors to a subscriber.
|
|
1959
|
+
* @param key The key it registered with
|
|
1960
|
+
*/
|
|
904
1961
|
clearOnError(key) {
|
|
905
1962
|
this.onErrorCallbacks.delete(key);
|
|
906
1963
|
}
|
|
@@ -909,9 +1966,28 @@ Recent Message: ${message.getContent()}
|
|
|
909
1966
|
callback(error);
|
|
910
1967
|
}
|
|
911
1968
|
}
|
|
1969
|
+
/**
|
|
1970
|
+
* Every human-controlled agent in the room, in arrival order.
|
|
1971
|
+
*
|
|
1972
|
+
* A room may have more than one: several people can share a browser, and one
|
|
1973
|
+
* person can play several characters. Code that genuinely needs a single human
|
|
1974
|
+
* uses {@link getDefaultHumanAgent} — but anything reacting to a *message* must
|
|
1975
|
+
* resolve the human from its sender, because the sender is rarely the default.
|
|
1976
|
+
*/
|
|
912
1977
|
getHumanAgents() {
|
|
913
1978
|
return this.agents.filter((agent) => agent.isControlledByHuman);
|
|
914
1979
|
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Names as a prompt reads them aloud: `Rhys`, `Rhys and Mira`, `Rhys, Mira and Tor`.
|
|
1982
|
+
*
|
|
1983
|
+
* Handlebars has no `join`, and this codebase registers no helpers, so a template
|
|
1984
|
+
* wanting a list inline has to either be handed one or spell out an `{{#each}}`
|
|
1985
|
+
* with `{{#unless @last}}`. Handing it over is the difference between a prompt
|
|
1986
|
+
* that reads like a sentence and one every author gets subtly wrong — which is
|
|
1987
|
+
* how a table with two players came to have prompts that only ever named one.
|
|
1988
|
+
* @param names The names to list, in order
|
|
1989
|
+
* @returns The joined phrase, or an empty string for no names
|
|
1990
|
+
*/
|
|
915
1991
|
static listNames(names) {
|
|
916
1992
|
if (names.length === 0)
|
|
917
1993
|
return '';
|
|
@@ -919,17 +1995,38 @@ Recent Message: ${message.getContent()}
|
|
|
919
1995
|
return names[0];
|
|
920
1996
|
return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
921
1997
|
}
|
|
1998
|
+
/**
|
|
1999
|
+
* The human the room falls back to when it has to pick one, which is whoever
|
|
2000
|
+
* arrived first. Used to open the conversation and to attribute a message that
|
|
2001
|
+
* arrives with no sender. Which one it is carries no meaning.
|
|
2002
|
+
*/
|
|
922
2003
|
getDefaultHumanAgent() {
|
|
923
2004
|
return this.agents.find((agent) => agent.isControlledByHuman);
|
|
924
2005
|
}
|
|
2006
|
+
/**
|
|
2007
|
+
* The human-controlled agent a sender name refers to, matched the same way
|
|
2008
|
+
* message targets are, or undefined when no human answers to that name.
|
|
2009
|
+
*/
|
|
925
2010
|
getHumanAgentByName(sender) {
|
|
926
2011
|
if (!sender)
|
|
927
2012
|
return undefined;
|
|
928
2013
|
return this.getHumanAgents().find((agent) => this.checkAgentNicknameMatch(agent.agentNickname, sender));
|
|
929
2014
|
}
|
|
2015
|
+
/** True when `nickname` names a human-controlled agent in this room. */
|
|
930
2016
|
isHumanNickname(nickname) {
|
|
931
2017
|
return !!nickname && !!this.getHumanAgentByName(nickname);
|
|
932
2018
|
}
|
|
2019
|
+
/**
|
|
2020
|
+
* True when a message is the players talking among themselves: a whisper whose
|
|
2021
|
+
* every target is a human-controlled agent.
|
|
2022
|
+
*
|
|
2023
|
+
* Such a message cannot reach the game. `canHear` restricts a whisper to its
|
|
2024
|
+
* targets, so no AI agent hears it; every target is human, so no agent is
|
|
2025
|
+
* prompted and nothing is spent. That is what lets the room take one **out of
|
|
2026
|
+
* turn** and leave the floor untouched — the players get to chat across the
|
|
2027
|
+
* table while an agent is mid-turn, and it still shows up in the transcript for
|
|
2028
|
+
* everyone at the table to read.
|
|
2029
|
+
*/
|
|
933
2030
|
isPlayerAside(message) {
|
|
934
2031
|
if (message.getAction() !== app_types_1.MessageAction.WHISPER)
|
|
935
2032
|
return false;
|
|
@@ -938,9 +2035,29 @@ Recent Message: ${message.getContent()}
|
|
|
938
2035
|
return false;
|
|
939
2036
|
return targets.every((target) => this.isHumanNickname(target));
|
|
940
2037
|
}
|
|
2038
|
+
/**
|
|
2039
|
+
* Gets the name of the default human-controlled agent
|
|
2040
|
+
* @returns The human agent's name or empty string if not found
|
|
2041
|
+
*/
|
|
941
2042
|
getHumanAgentName() {
|
|
942
2043
|
return this.getDefaultHumanAgent()?.agentNickname ?? '';
|
|
943
2044
|
}
|
|
2045
|
+
/**
|
|
2046
|
+
* Gets the agent that places messages the room cannot route mechanically.
|
|
2047
|
+
*
|
|
2048
|
+
* Prefers the configured {@link setModerator} nickname. The fallback to the
|
|
2049
|
+
* first agent is how story rooms have always chosen theirs — the narrator is
|
|
2050
|
+
* added first — and is kept so they keep working, but it is a guess: in any
|
|
2051
|
+
* other room the first agent is whoever happened to be added first and has no
|
|
2052
|
+
* `moderate.prompt` at all. Name one explicitly.
|
|
2053
|
+
*
|
|
2054
|
+
* The fallback prefers an agent that actually has a `moderate.prompt`, because
|
|
2055
|
+
* one that does not fails in the worst way available: the prompt lookup throws,
|
|
2056
|
+
* the throw is swallowed, and the message disappears. Arrival order is only
|
|
2057
|
+
* consulted when nobody in the room can moderate, which keeps a room that was
|
|
2058
|
+
* working before this preference existed working now.
|
|
2059
|
+
* @returns The moderator agent or undefined if the room is empty
|
|
2060
|
+
*/
|
|
944
2061
|
getModeratorAgent() {
|
|
945
2062
|
if (this.moderator) {
|
|
946
2063
|
const named = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, this.moderator));
|
|
@@ -948,18 +2065,43 @@ Recent Message: ${message.getContent()}
|
|
|
948
2065
|
return named;
|
|
949
2066
|
logger_1.logger.warn(`Room ${this.name}: configured moderator "${this.moderator}" is not in the room; falling back to the first agent`);
|
|
950
2067
|
}
|
|
2068
|
+
// Skip the players. Moderating means answering a prompt, which a human agent
|
|
2069
|
+
// never does — it would take the floor and hold it. With one player at the
|
|
2070
|
+
// table this was unlikely to bite; with several, the odds that the first
|
|
2071
|
+
// agent is one of them are much better.
|
|
951
2072
|
const candidates = this.agents.filter((a) => !a.isControlledByHuman);
|
|
952
2073
|
return candidates.find((a) => a.hasPrompt('moderate')) ?? candidates[0];
|
|
953
2074
|
}
|
|
2075
|
+
/**
|
|
2076
|
+
* Gets the current story situation
|
|
2077
|
+
* @returns The current situation string
|
|
2078
|
+
*/
|
|
954
2079
|
getSituation() {
|
|
955
2080
|
return this.currentSituation;
|
|
956
2081
|
}
|
|
2082
|
+
/**
|
|
2083
|
+
* Gets the current in-story time (24-hour "HH:MM"), stored separately from the
|
|
2084
|
+
* situation text.
|
|
2085
|
+
* @returns The current time string, or '' if none is set
|
|
2086
|
+
*/
|
|
957
2087
|
getSituationTime() {
|
|
958
2088
|
return this.currentSituationTime;
|
|
959
2089
|
}
|
|
2090
|
+
/**
|
|
2091
|
+
* Sets the current in-story time (24-hour "HH:MM").
|
|
2092
|
+
* @param time The time string to set
|
|
2093
|
+
*/
|
|
960
2094
|
setSituationTime(time) {
|
|
961
2095
|
this.currentSituationTime = time || '';
|
|
962
2096
|
}
|
|
2097
|
+
/**
|
|
2098
|
+
* Builds the situation header shared by every agent's transient prompt: the
|
|
2099
|
+
* in-story time on its own labeled line (flagged as a 24-hour clock so a character
|
|
2100
|
+
* doesn't misread "10:30" as 10:30 PM), followed by the situation text. Either
|
|
2101
|
+
* line is omitted when its value is empty.
|
|
2102
|
+
*
|
|
2103
|
+
* @returns The time and situation lines, or '' if both are empty
|
|
2104
|
+
*/
|
|
963
2105
|
buildSituationHeader() {
|
|
964
2106
|
const lines = [];
|
|
965
2107
|
if (this.currentSituationTime) {
|
|
@@ -970,18 +2112,36 @@ Recent Message: ${message.getContent()}
|
|
|
970
2112
|
}
|
|
971
2113
|
return lines.join('\n');
|
|
972
2114
|
}
|
|
2115
|
+
/**
|
|
2116
|
+
* Sets the current story situation
|
|
2117
|
+
* @param situation The situation string to set
|
|
2118
|
+
*/
|
|
973
2119
|
setSituation(situation) {
|
|
974
2120
|
this.currentSituation = situation;
|
|
975
2121
|
}
|
|
2122
|
+
/**
|
|
2123
|
+
* Sets a callback to be invoked whenever situation changes
|
|
2124
|
+
* @param callback Function to call with new situation
|
|
2125
|
+
*/
|
|
976
2126
|
setOnSituationUpdate(callback) {
|
|
977
2127
|
this.onSituationUpdate = callback;
|
|
978
2128
|
}
|
|
979
2129
|
setOnModeratorResponse(callback) {
|
|
980
2130
|
this.onModeratorResponseCallback = callback;
|
|
981
2131
|
}
|
|
2132
|
+
/**
|
|
2133
|
+
* Handles situation update from an agent message
|
|
2134
|
+
* Updates internal state and notifies callback
|
|
2135
|
+
* @param situation The new situation string
|
|
2136
|
+
* @param messageBody Body of the message that produced this situation, for
|
|
2137
|
+
* consumers that need the triggering message but can't read it from the
|
|
2138
|
+
* room yet (it may not be logged at the time the callback fires).
|
|
2139
|
+
*/
|
|
982
2140
|
async handleSituationUpdate(situation, messageBody) {
|
|
983
2141
|
logger_1.logger.log(`Situation updated: ${situation}`);
|
|
984
2142
|
this.currentSituation = situation;
|
|
2143
|
+
// Notify callback if registered. Awaited so callers that need the
|
|
2144
|
+
// situation fully processed before continuing can rely on it being done.
|
|
985
2145
|
if (this.onSituationUpdate) {
|
|
986
2146
|
await this.onSituationUpdate(situation, messageBody);
|
|
987
2147
|
}
|
|
@@ -992,21 +2152,27 @@ Recent Message: ${message.getContent()}
|
|
|
992
2152
|
const artifactName = message.name;
|
|
993
2153
|
const creator = message.sender;
|
|
994
2154
|
const body = message.content;
|
|
995
|
-
const viewers = message.targets;
|
|
2155
|
+
const viewers = message.targets; // targets are now viewers
|
|
996
2156
|
this.publishArtifact(artifactName, creator, body, viewers);
|
|
997
2157
|
}
|
|
998
2158
|
}
|
|
999
2159
|
}
|
|
1000
2160
|
handleAdjournMessages(messages) {
|
|
2161
|
+
// If there are no adjourn messages, nothing to do
|
|
1001
2162
|
if (messages.length === 0) {
|
|
1002
2163
|
return;
|
|
1003
2164
|
}
|
|
2165
|
+
// Get the names of agents who have sent adjourn messages
|
|
1004
2166
|
const adjournedAgents = messages.map((m) => m.sender);
|
|
2167
|
+
// Get all agent names in the room
|
|
1005
2168
|
const allAgentNames = this.agents.map((a) => a.agentNickname);
|
|
2169
|
+
// Check if all agents have adjourned
|
|
1006
2170
|
const allAdjourned = allAgentNames.every((name) => adjournedAgents.includes(name));
|
|
1007
2171
|
if (allAdjourned) {
|
|
2172
|
+
// All agents have adjourned, mark the room as adjourned
|
|
1008
2173
|
this.isAdjourned = true;
|
|
1009
2174
|
this.notifyStateChange();
|
|
2175
|
+
// Add a moderator message indicating the room has been adjourned
|
|
1010
2176
|
this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, 'All agents have agreed to adjourn. The conversation has ended.'));
|
|
1011
2177
|
this.pendingMessages = null;
|
|
1012
2178
|
}
|
|
@@ -1021,9 +2187,14 @@ Recent Message: ${message.getContent()}
|
|
|
1021
2187
|
}
|
|
1022
2188
|
}
|
|
1023
2189
|
addPendingMessage(message, clearQueue = false, context) {
|
|
2190
|
+
// Adopt the host's opaque tool context for the interaction this message
|
|
2191
|
+
// starts. Held in memory only (never persisted); because the room is
|
|
2192
|
+
// single-flight, it applies to the whole resulting cascade — including
|
|
2193
|
+
// agents reacting to each other and commissioned sub-agents.
|
|
1024
2194
|
if (context !== undefined) {
|
|
1025
2195
|
this.currentToolContext = context;
|
|
1026
2196
|
}
|
|
2197
|
+
// Initialize pendingMessages if this is the first message (e.g., after reconnection)
|
|
1027
2198
|
if (!this.pendingMessages) {
|
|
1028
2199
|
this.pendingMessages = [];
|
|
1029
2200
|
}
|
|
@@ -1033,13 +2204,32 @@ Recent Message: ${message.getContent()}
|
|
|
1033
2204
|
if (!message.sender) {
|
|
1034
2205
|
message.sender = 'system';
|
|
1035
2206
|
}
|
|
2207
|
+
// Resolved from the sender, not from the room's default human: with several
|
|
2208
|
+
// players in the room, only one of them is the default, and matching against
|
|
2209
|
+
// it would leave every other player's message treated as a system message —
|
|
2210
|
+
// never added to their own agent's history, never clearing the floor.
|
|
1036
2211
|
const humanAgent = this.getHumanAgentByName(message.sender);
|
|
1037
2212
|
const isHumanMessage = !!humanAgent;
|
|
2213
|
+
// Somebody is at the keyboard, so the room is not stuck whatever came before.
|
|
2214
|
+
if (isHumanMessage)
|
|
2215
|
+
this.stallRecoveries = 0;
|
|
2216
|
+
// A player who uses the moderator is moderated whatever the message claimed.
|
|
2217
|
+
// Their composer stops offering an action at all, but this endpoint stays
|
|
2218
|
+
// reachable — from the published room page, from the API, from a bot — and
|
|
2219
|
+
// honouring a speak or a whisper there would route around the moderator the
|
|
2220
|
+
// room's prompts are written to expect.
|
|
2221
|
+
//
|
|
2222
|
+
// Players only. On an AI agent the flag is a declaration that it will emit
|
|
2223
|
+
// MODERATE itself, not an instruction to override what it chose to send.
|
|
1038
2224
|
if (isHumanMessage && humanAgent.useModerator && message.action !== app_types_1.MessageAction.MODERATE) {
|
|
1039
2225
|
logger_1.logger.log(`${humanAgent.agentNickname} uses the moderator; sending as moderate rather than ${message.action}`);
|
|
1040
2226
|
message.action = app_types_1.MessageAction.MODERATE;
|
|
1041
2227
|
message.targets = [];
|
|
1042
2228
|
}
|
|
2229
|
+
// Players talking among themselves never enters the queue. Logging it and
|
|
2230
|
+
// delivering it to the other players is the whole job: nobody is prompted,
|
|
2231
|
+
// the turn order is not consulted, and the floor stays where it was. This is
|
|
2232
|
+
// the one message a player may send while an agent holds the floor.
|
|
1043
2233
|
if (isHumanMessage && this.isPlayerAside(message)) {
|
|
1044
2234
|
for (const target of message.getTargets()) {
|
|
1045
2235
|
const player = this.getHumanAgentByName(target);
|
|
@@ -1051,16 +2241,29 @@ Recent Message: ${message.getContent()}
|
|
|
1051
2241
|
this.addRoomMessage(message);
|
|
1052
2242
|
return { accepted: true };
|
|
1053
2243
|
}
|
|
2244
|
+
// Special handling for human messages when paused
|
|
1054
2245
|
if (isHumanMessage && this.isPaused) {
|
|
1055
2246
|
if (clearQueue) {
|
|
2247
|
+
// Clear all pending messages - human is interjecting
|
|
1056
2248
|
this.pendingMessages = [];
|
|
1057
2249
|
}
|
|
2250
|
+
// Add human's message to conversation history
|
|
1058
2251
|
humanAgent.addToConversationHistory(message, true);
|
|
1059
2252
|
humanAgent.save();
|
|
1060
2253
|
this.pendingMessages.push(message);
|
|
2254
|
+
// Auto-resume processing
|
|
1061
2255
|
this.resume();
|
|
1062
2256
|
return { accepted: true };
|
|
1063
2257
|
}
|
|
2258
|
+
// Validate a human can only send when the floor is a human's (non-paused state).
|
|
2259
|
+
//
|
|
2260
|
+
// The test is "any human", not "this human". The floor lands on a specific
|
|
2261
|
+
// player for two different reasons — an agent addressed that character, or
|
|
2262
|
+
// ready()/pause() handed it to the arbitrary default — and the room cannot
|
|
2263
|
+
// tell them apart. Enforcing it per-player would therefore lock every other
|
|
2264
|
+
// player out of a freshly opened or just-resumed room. So the players share
|
|
2265
|
+
// the floor between them and settle turn order at the table; what still gets
|
|
2266
|
+
// refused is speaking over an AI agent that is mid-turn.
|
|
1064
2267
|
if (isHumanMessage) {
|
|
1065
2268
|
if (this.currentSpeaker !== null && !this.isHumanNickname(this.currentSpeaker)) {
|
|
1066
2269
|
logger_1.logger.warn(`Human agent ${humanAgent.agentNickname} tried to speak out of turn. Current speaker: ${this.currentSpeaker}`);
|
|
@@ -1071,9 +2274,11 @@ Recent Message: ${message.getContent()}
|
|
|
1071
2274
|
}
|
|
1072
2275
|
humanAgent.addToConversationHistory(message, true);
|
|
1073
2276
|
humanAgent.save();
|
|
2277
|
+
// Clear current speaker when human responds
|
|
1074
2278
|
this.setCurrentSpeaker(null);
|
|
1075
2279
|
}
|
|
1076
2280
|
this.pendingMessages.push(message);
|
|
2281
|
+
// Trigger processing if not already processing
|
|
1077
2282
|
if (!this.processingInProgress) {
|
|
1078
2283
|
this.processPendingMessages();
|
|
1079
2284
|
}
|
|
@@ -1082,19 +2287,33 @@ Recent Message: ${message.getContent()}
|
|
|
1082
2287
|
isProcessingInProgress() {
|
|
1083
2288
|
return this.processingInProgress;
|
|
1084
2289
|
}
|
|
2290
|
+
/**
|
|
2291
|
+
* True when the room is idle pending input from the human-controlled agent.
|
|
2292
|
+
*
|
|
2293
|
+
* This is distinct from `isProcessingInProgress()`: after an agent addresses
|
|
2294
|
+
* the human, the room intentionally leaves processing "in progress" while it
|
|
2295
|
+
* waits for the human's reply (the human's perceive never fires a response
|
|
2296
|
+
* callback). Hosts should use this flag — not `processingInProgress` — to
|
|
2297
|
+
* decide whether to show a typing indicator.
|
|
2298
|
+
*/
|
|
1085
2299
|
isWaitingForHuman() {
|
|
1086
2300
|
if (this.getHumanAgents().length === 0) {
|
|
1087
2301
|
return false;
|
|
1088
2302
|
}
|
|
2303
|
+
// A human holds the floor (an agent addressed them, or the room is paused)
|
|
1089
2304
|
if (this.isHumanNickname(this.currentSpeaker)) {
|
|
1090
2305
|
return true;
|
|
1091
2306
|
}
|
|
2307
|
+
// Idle room: nothing queued, nothing in flight, no speaker — the host's
|
|
2308
|
+
// next human message is what starts the conversation
|
|
1092
2309
|
return (this.currentSpeaker === null &&
|
|
1093
2310
|
!this.processingInProgress &&
|
|
1094
2311
|
(!this.pendingMessages || this.pendingMessages.length === 0));
|
|
1095
2312
|
}
|
|
1096
2313
|
pause() {
|
|
1097
2314
|
this.isPaused = true;
|
|
2315
|
+
// Give the floor to a human so they can send messages. Naming the default
|
|
2316
|
+
// is enough: a floor held by any human is open to all of them.
|
|
1098
2317
|
const humanAgent = this.getDefaultHumanAgent();
|
|
1099
2318
|
if (humanAgent) {
|
|
1100
2319
|
this.currentSpeaker = humanAgent.agentNickname;
|
|
@@ -1104,6 +2323,7 @@ Recent Message: ${message.getContent()}
|
|
|
1104
2323
|
resume() {
|
|
1105
2324
|
this.isPaused = false;
|
|
1106
2325
|
this.notifyStateChange();
|
|
2326
|
+
// Trigger processing if there are pending messages
|
|
1107
2327
|
if (this.pendingMessages && this.pendingMessages.length > 0) {
|
|
1108
2328
|
this.processPendingMessages();
|
|
1109
2329
|
}
|
|
@@ -1113,15 +2333,37 @@ Recent Message: ${message.getContent()}
|
|
|
1113
2333
|
this.pause();
|
|
1114
2334
|
}
|
|
1115
2335
|
checkAgentNicknameMatch(existingNickname, targetNickname) {
|
|
2336
|
+
// Nobody answers to no name. A moderator that cannot tell who should respond
|
|
2337
|
+
// is told to leave `name` empty, and a moderator answer that gets coerced back
|
|
2338
|
+
// to MODERATE arrives with a null name — so this is reached on the ordinary
|
|
2339
|
+
// path, not just a malformed one. Throwing here meant the caller's catch
|
|
2340
|
+
// swallowed the message and the room went quiet with one log line.
|
|
1116
2341
|
if (!existingNickname || !targetNickname)
|
|
1117
2342
|
return false;
|
|
2343
|
+
// Full nickname match (case-insensitive)
|
|
1118
2344
|
if (existingNickname.toLowerCase() === targetNickname.toLowerCase())
|
|
1119
2345
|
return true;
|
|
2346
|
+
// First word match (e.g., "Alex" matches "Alex Smith")
|
|
1120
2347
|
const nicknameFirstWord = existingNickname.split(/\s+/)[0];
|
|
1121
2348
|
if (nicknameFirstWord.toLowerCase() === targetNickname.toLowerCase())
|
|
1122
2349
|
return true;
|
|
1123
2350
|
return false;
|
|
1124
2351
|
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Hands a moderated message to one recipient in the shape that recipient needs.
|
|
2354
|
+
*
|
|
2355
|
+
* An AI agent gets the message itself, so a room whose agents answer in the JSON
|
|
2356
|
+
* protocol sees moderated messages in the same shape as every other one — half a
|
|
2357
|
+
* history in plain prose models the wrong output format, and a prose reply is
|
|
2358
|
+
* silently absorbed by parseAgentResponse rather than corrected, so the drift has
|
|
2359
|
+
* no back pressure.
|
|
2360
|
+
*
|
|
2361
|
+
* A human gets the readable form. Nothing prompts a human agent, so its history
|
|
2362
|
+
* is a record rather than a set of examples, and JSON is the wrong thing to keep.
|
|
2363
|
+
*
|
|
2364
|
+
* With no `relayAs` the two branches produce identical text, which is why story
|
|
2365
|
+
* rooms are unaffected by this distinction.
|
|
2366
|
+
*/
|
|
1125
2367
|
deliverModerated(recipient, message, content) {
|
|
1126
2368
|
if (recipient.isControlledByHuman) {
|
|
1127
2369
|
recipient.addToConversationHistory(`From: ${message.sender}\n${content}`, false);
|
|
@@ -1131,10 +2373,22 @@ Recent Message: ${message.getContent()}
|
|
|
1131
2373
|
}
|
|
1132
2374
|
recipient.save();
|
|
1133
2375
|
}
|
|
2376
|
+
/**
|
|
2377
|
+
* Handles the moderator's routing response for a single message
|
|
2378
|
+
* @param moderatorMessage The routing response from the moderator
|
|
2379
|
+
* @param originalMessage The original message that needed routing
|
|
2380
|
+
*/
|
|
1134
2381
|
handleModeratorResponse(moderatorMessage, originalMessage) {
|
|
1135
2382
|
try {
|
|
1136
2383
|
let responderNickname = moderatorMessage.name;
|
|
1137
2384
|
const roomLeaderName = this.getRoomLeader();
|
|
2385
|
+
// The moderator's audience, and nobody else. The room leader used to be
|
|
2386
|
+
// added to every moderated message here, which was a workaround for
|
|
2387
|
+
// weak models dropping the "always include the narrator" instruction —
|
|
2388
|
+
// the prompts now carry that rule where it belongs. Adding it in code
|
|
2389
|
+
// made a private exchange impossible: at a game table the party cannot
|
|
2390
|
+
// plan out of the leader's earshot, and an agent cannot convincingly
|
|
2391
|
+
// pretend not to know what is in its own history.
|
|
1138
2392
|
const targets = [...(moderatorMessage.targets || [])];
|
|
1139
2393
|
if (this.onModeratorResponseCallback) {
|
|
1140
2394
|
this.onModeratorResponseCallback(moderatorMessage);
|
|
@@ -1144,9 +2398,19 @@ Recent Message: ${message.getContent()}
|
|
|
1144
2398
|
content = originalMessage.getContent();
|
|
1145
2399
|
if (originalMessage.content != content) {
|
|
1146
2400
|
logger_1.logger.warn(`Moderator changed content:\n${originalMessage.content}\nto\n${content}`);
|
|
1147
|
-
originalMessage.content = content;
|
|
2401
|
+
originalMessage.content = content; // In case the moderator changed the content
|
|
1148
2402
|
}
|
|
1149
2403
|
if (this.checkAgentNicknameMatch(originalMessage.sender, responderNickname)) {
|
|
2404
|
+
// The moderator named the sender as the next responder. Usually that is
|
|
2405
|
+
// a stall — the agent would talk to itself and the UI would wait forever
|
|
2406
|
+
// ("Waiting for Story") — but not always: an agent running consecutive
|
|
2407
|
+
// turns nobody else is part of has no one else to name, and this branch
|
|
2408
|
+
// used to overrule the moderator every time. In a played fight it did
|
|
2409
|
+
// exactly that, taking the floor off the Battle Master mid-round and
|
|
2410
|
+
// waking the Dungeon Master, whose own prompt tells it to stay out of
|
|
2411
|
+
// combat, so it said nothing and the room idled until a person stepped in.
|
|
2412
|
+
//
|
|
2413
|
+
// So the loop is allowed a bounded number of turns, and only then broken.
|
|
1150
2414
|
if (this.mayContinueAlone(originalMessage.sender)) {
|
|
1151
2415
|
logger_1.logger.log(`Moderator kept the floor with ${originalMessage.sender} (turn ${this.consecutiveSelfContinues} of ${Room.maxSelfContinues()})`);
|
|
1152
2416
|
}
|
|
@@ -1160,6 +2424,12 @@ Recent Message: ${message.getContent()}
|
|
|
1160
2424
|
else {
|
|
1161
2425
|
this.clearSelfContinue();
|
|
1162
2426
|
}
|
|
2427
|
+
// 1. Resolve the responder, before delivering to the audience, so the
|
|
2428
|
+
// agent that is about to be prompted is not also handed the message as
|
|
2429
|
+
// history. Falling back to the room leader is the established contract
|
|
2430
|
+
// for a moderator that names nobody — room_moderator's own prompt tells
|
|
2431
|
+
// it to leave `name` empty when it cannot tell, and something has to
|
|
2432
|
+
// take the floor or the room stalls.
|
|
1163
2433
|
let responderAgent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, responderNickname));
|
|
1164
2434
|
if (!responderAgent) {
|
|
1165
2435
|
let roomLeaderAgent = this.agents.find((a) => a.agentNickname === roomLeaderName);
|
|
@@ -1169,42 +2439,83 @@ Recent Message: ${message.getContent()}
|
|
|
1169
2439
|
responderAgent = roomLeaderAgent;
|
|
1170
2440
|
responderNickname = roomLeaderAgent.agentNickname;
|
|
1171
2441
|
}
|
|
2442
|
+
// An agent asked to answer a message it never heard is incoherent, so the
|
|
2443
|
+
// responder is always part of the audience. This narrow guarantee is what
|
|
2444
|
+
// replaced adding the room leader to every message: when the moderator
|
|
2445
|
+
// named nobody, the responder resolved above *is* the leader, so the
|
|
2446
|
+
// leader still hears what it is being asked to answer.
|
|
1172
2447
|
if (!targets.some((target) => this.checkAgentNicknameMatch(responderAgent.agentNickname, target))) {
|
|
1173
2448
|
targets.push(responderAgent.agentNickname);
|
|
1174
2449
|
}
|
|
1175
2450
|
logger_1.logger.log(`Moderator routing: sender=${originalMessage.sender} action=${moderatorMessage.action}${moderatorMessage.relayAs ? ` as ${moderatorMessage.relayAs}` : ''}, name=${responderNickname}, targets=${targets.join(', ')}`);
|
|
2451
|
+
// The message the room actually carries. `relayAs` turns it into an
|
|
2452
|
+
// ordinary room message — stored in the same shape as any other and
|
|
2453
|
+
// rendered with the right badge in the transcript. Without it the message
|
|
2454
|
+
// stays a MODERATE, which is the plain-prose form stories are built on.
|
|
1176
2455
|
const relayed = new message_1.RoomMessage(originalMessage.sender, moderatorMessage.relayAs ?? originalMessage.action, content, targets, originalMessage.name, originalMessage.situation);
|
|
2456
|
+
// 2. Add the message to the room log ONLY if action is RELAY (not
|
|
2457
|
+
// RELAY_SILENT). RELAY_SILENT is internal processing that should not
|
|
2458
|
+
// appear in the room log.
|
|
1177
2459
|
if (moderatorMessage.action === app_types_1.MessageAction.RELAY) {
|
|
1178
2460
|
this.addRoomMessage(relayed, {
|
|
2461
|
+
// The situation was already processed before moderation
|
|
2462
|
+
// (see processPendingMessages); don't run it again here.
|
|
1179
2463
|
suppressSituationUpdate: true,
|
|
1180
2464
|
});
|
|
1181
2465
|
}
|
|
2466
|
+
// 3. Give the message to the rest of the audience for awareness.
|
|
2467
|
+
//
|
|
2468
|
+
// The moderator's targets are authoritative rather than canHear(): a
|
|
2469
|
+
// `speak` is audible to the whole room, so delivering this through
|
|
2470
|
+
// hear() would broadcast a message the moderator deliberately addressed
|
|
2471
|
+
// to three of six agents, and sub-group conversation would be impossible.
|
|
1182
2472
|
for (const recipientName of targets) {
|
|
2473
|
+
// The responder is prompted with it below rather than told about it.
|
|
1183
2474
|
if (this.checkAgentNicknameMatch(responderAgent.agentNickname, recipientName)) {
|
|
1184
2475
|
continue;
|
|
1185
2476
|
}
|
|
2477
|
+
// The original sender already logged the message to their own history
|
|
1186
2478
|
if (recipientName === originalMessage.sender)
|
|
1187
2479
|
continue;
|
|
1188
2480
|
const recipient = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, recipientName));
|
|
1189
2481
|
if (recipient)
|
|
1190
2482
|
this.deliverModerated(recipient, relayed, content);
|
|
1191
2483
|
}
|
|
2484
|
+
// Remembered for the next moderation prompt so a conversation with a
|
|
2485
|
+
// sub-group stays with that sub-group, instead of the moderator having to
|
|
2486
|
+
// reconstruct who was in it from its own short history.
|
|
1192
2487
|
this.lastModeratedAudience = [...targets];
|
|
2488
|
+
// 4. If responder is human, just wait for their response via addPendingMessage
|
|
1193
2489
|
if (responderAgent.isControlledByHuman) {
|
|
1194
2490
|
logger_1.logger.log(`Waiting for human agent ${responderNickname} to respond`);
|
|
1195
2491
|
this.deliverModerated(responderAgent, relayed, content);
|
|
2492
|
+
// Processing continues, but human has the turn. They will send their
|
|
2493
|
+
// message via addPendingMessage, which triggers processing again.
|
|
1196
2494
|
this.endTurn({ to: responderNickname });
|
|
1197
2495
|
return;
|
|
1198
2496
|
}
|
|
2497
|
+
// 5. For AI agents, call perceive to get their response
|
|
2498
|
+
// Set current speaker to AI agent
|
|
1199
2499
|
this.setCurrentSpeaker(responderNickname);
|
|
2500
|
+
// `relayed` carries the moderator's audience, so the responder sees the
|
|
2501
|
+
// descriptions of only the characters present for this message (see
|
|
2502
|
+
// getPresentCharacters).
|
|
1200
2503
|
const continuing = this.checkAgentNicknameMatch(originalMessage.sender, responderAgent.agentNickname);
|
|
2504
|
+
// See the matching assignment in processPendingMessages: a moderated turn
|
|
2505
|
+
// that ends without a word said stalls the room the same way.
|
|
2506
|
+
this.lastDispatch = { message: relayed, responders: [responderAgent.agentNickname] };
|
|
1201
2507
|
this.perceive(responderAgent, relayed, (response) => {
|
|
1202
2508
|
if (this.isPaused) {
|
|
2509
|
+
// User interrupted while this perceive was in flight; drop the
|
|
2510
|
+
// response and leave currentSpeaker on the human (set by pause()).
|
|
1203
2511
|
this.endTurn('keep');
|
|
1204
2512
|
return;
|
|
1205
2513
|
}
|
|
1206
2514
|
if (response !== null) {
|
|
2515
|
+
// Add response to pending queue for next round of processing
|
|
1207
2516
|
this.pendingMessages = [response, ...this.pendingMessages];
|
|
2517
|
+
if (response.action !== app_types_1.MessageAction.THINK)
|
|
2518
|
+
this.stallRecoveries = 0;
|
|
1208
2519
|
}
|
|
1209
2520
|
this.endTurn('release', { drain: true });
|
|
1210
2521
|
}, { continuing });
|
|
@@ -1212,14 +2523,26 @@ Recent Message: ${message.getContent()}
|
|
|
1212
2523
|
catch (error) {
|
|
1213
2524
|
logger_1.logger.error('Error parsing moderator response:', error);
|
|
1214
2525
|
logger_1.logger.error('Moderator message content:', moderatorMessage.content);
|
|
2526
|
+
// Continue processing despite error. The floor is released because the
|
|
2527
|
+
// speaker was named just above, before the routing that threw — leaving
|
|
2528
|
+
// it set would pin the room on an agent whose turn never happened.
|
|
1215
2529
|
this.endTurn('release', { drain: true });
|
|
1216
2530
|
}
|
|
1217
2531
|
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Runs one commissioned agent's research turn and normalizes the result into
|
|
2534
|
+
* a DELIVER message. If the agent's terminal action isn't DELIVER it gets one
|
|
2535
|
+
* corrective re-prompt; a still-wrong action is coerced into a DELIVER so the
|
|
2536
|
+
* commissioner is never starved. Errors become a synthetic error DELIVER.
|
|
2537
|
+
* @param agent The commissioned agent
|
|
2538
|
+
* @param commission The COMMISSION message (already in the agent's history)
|
|
2539
|
+
* @returns The DELIVER message, or null if the room was paused/adjourned
|
|
2540
|
+
*/
|
|
1218
2541
|
async runDeliverTurn(agent, commission) {
|
|
1219
2542
|
try {
|
|
1220
2543
|
let response = await this.runAgentTurn(agent, commission, { inCommission: true });
|
|
1221
2544
|
if (response === null)
|
|
1222
|
-
return null;
|
|
2545
|
+
return null; // paused/adjourned mid-turn
|
|
1223
2546
|
if (response.action !== app_types_1.MessageAction.DELIVER) {
|
|
1224
2547
|
agent.addToConversationHistory(`From system: You were commissioned by ${commission.sender}. Respond now with action "deliver" targeting ${commission.sender}, containing your complete result.`, false);
|
|
1225
2548
|
agent.save();
|
|
@@ -1227,6 +2550,7 @@ Recent Message: ${message.getContent()}
|
|
|
1227
2550
|
response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, null), variables);
|
|
1228
2551
|
}
|
|
1229
2552
|
if (response.action !== app_types_1.MessageAction.DELIVER) {
|
|
2553
|
+
// Coerce: wrap whatever the agent produced into a DELIVER
|
|
1230
2554
|
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, response.content, [commission.sender]);
|
|
1231
2555
|
}
|
|
1232
2556
|
response.sender = agent.agentNickname;
|
|
@@ -1242,8 +2566,25 @@ Recent Message: ${message.getContent()}
|
|
|
1242
2566
|
return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${agent.agentNickname} encountered an error: ${e.message})`, [commission.sender]);
|
|
1243
2567
|
}
|
|
1244
2568
|
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Orchestrates a COMMISSION message. Called from processPendingMessages with
|
|
2571
|
+
* the processing lock held; the lock stays held until the commissioner has
|
|
2572
|
+
* responded to the aggregated deliverables (or the room pauses/adjourns).
|
|
2573
|
+
*
|
|
2574
|
+
* Flow: every agent hears the commission (it is public, like SPEAK) → each AI
|
|
2575
|
+
* target concurrently runs its own research turn ending in a DELIVER → the
|
|
2576
|
+
* DELIVERs are logged and heard by the room → the commissioner receives the
|
|
2577
|
+
* concatenated deliverables and responds, re-entering normal processing.
|
|
2578
|
+
*
|
|
2579
|
+
* Human-controlled targets are skipped (waiting on a human while the lock is
|
|
2580
|
+
* held would deadlock the room) and noted in the aggregate. Nothing about an
|
|
2581
|
+
* in-flight commission is persisted: a server restart kills it, leaving only
|
|
2582
|
+
* the already-logged messages.
|
|
2583
|
+
* @param msg The COMMISSION message (already added to the room log)
|
|
2584
|
+
*/
|
|
1245
2585
|
async handleCommissionMessage(msg) {
|
|
1246
2586
|
try {
|
|
2587
|
+
// 1. Resolve targets: dedupe, drop the sender, partition by kind
|
|
1247
2588
|
const aiTargets = [];
|
|
1248
2589
|
const humanTargetNames = [];
|
|
1249
2590
|
const unknownNames = [];
|
|
@@ -1253,6 +2594,7 @@ Recent Message: ${message.getContent()}
|
|
|
1253
2594
|
unknownNames.push(name);
|
|
1254
2595
|
}
|
|
1255
2596
|
else if (agent.agentNickname === msg.sender) {
|
|
2597
|
+
// Ignore self-targeting
|
|
1256
2598
|
}
|
|
1257
2599
|
else if (agent.isControlledByHuman) {
|
|
1258
2600
|
humanTargetNames.push(agent.agentNickname);
|
|
@@ -1261,6 +2603,7 @@ Recent Message: ${message.getContent()}
|
|
|
1261
2603
|
aiTargets.push(agent);
|
|
1262
2604
|
}
|
|
1263
2605
|
}
|
|
2606
|
+
// 2. Everyone but the sender hears the commission (public, like SPEAK)
|
|
1264
2607
|
for (const agent of this.agents) {
|
|
1265
2608
|
if (agent.agentNickname === msg.sender)
|
|
1266
2609
|
continue;
|
|
@@ -1268,6 +2611,7 @@ Recent Message: ${message.getContent()}
|
|
|
1268
2611
|
agent.save();
|
|
1269
2612
|
}
|
|
1270
2613
|
const commissioner = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, msg.sender));
|
|
2614
|
+
// 3. No one to commission: tell the commissioner and let it respond
|
|
1271
2615
|
if (aiTargets.length === 0) {
|
|
1272
2616
|
const reasons = [];
|
|
1273
2617
|
if (unknownNames.length > 0)
|
|
@@ -1278,8 +2622,13 @@ Recent Message: ${message.getContent()}
|
|
|
1278
2622
|
await this.respondToCommissioner(commissioner, note);
|
|
1279
2623
|
return;
|
|
1280
2624
|
}
|
|
2625
|
+
// 4. All AI targets research concurrently, each ending in a DELIVER
|
|
1281
2626
|
const settled = await Promise.allSettled(aiTargets.map((t) => this.runDeliverTurn(t, msg)));
|
|
2627
|
+
// 5. Bail if the room paused/adjourned mid-commission, or a balance
|
|
2628
|
+
// error already released the lock (see handleInsufficientBalance)
|
|
1282
2629
|
if (this.isPaused || this.isAdjourned || !this.processingInProgress) {
|
|
2630
|
+
// 'keep' rather than 'release': if a pause got here first it owns the
|
|
2631
|
+
// floor, and if the lock is already down a balance error released it.
|
|
1283
2632
|
if (this.processingInProgress)
|
|
1284
2633
|
this.endTurn('keep');
|
|
1285
2634
|
return;
|
|
@@ -1289,6 +2638,8 @@ Recent Message: ${message.getContent()}
|
|
|
1289
2638
|
return result.value;
|
|
1290
2639
|
return new message_1.RoomMessage(aiTargets[i].agentNickname, app_types_1.MessageAction.DELIVER, `(No deliverable: ${aiTargets[i].agentNickname} did not complete the commission)`, [msg.sender]);
|
|
1291
2640
|
});
|
|
2641
|
+
// 6. Log each DELIVER; everyone but the commissioner (who gets the
|
|
2642
|
+
// aggregate next) and the deliverer hears it
|
|
1292
2643
|
for (const deliver of delivers) {
|
|
1293
2644
|
this.addRoomMessage(deliver);
|
|
1294
2645
|
for (const agent of this.agents) {
|
|
@@ -1300,6 +2651,7 @@ Recent Message: ${message.getContent()}
|
|
|
1300
2651
|
agent.save();
|
|
1301
2652
|
}
|
|
1302
2653
|
}
|
|
2654
|
+
// 7. Feed the aggregated deliverables to the commissioner
|
|
1303
2655
|
const sections = delivers.map((d) => `## From ${d.sender}\n${d.content}`);
|
|
1304
2656
|
if (humanTargetNames.length > 0) {
|
|
1305
2657
|
sections.push(`(Skipped: ${humanTargetNames.join(', ')} — human-controlled agents cannot be commissioned)`);
|
|
@@ -1315,6 +2667,14 @@ Recent Message: ${message.getContent()}
|
|
|
1315
2667
|
this.endTurn('release', { drain: true });
|
|
1316
2668
|
}
|
|
1317
2669
|
}
|
|
2670
|
+
/**
|
|
2671
|
+
* Delivers a system note (commission results or failure) to the commissioner,
|
|
2672
|
+
* lets it respond, queues that response, and releases the processing lock.
|
|
2673
|
+
* A human or missing commissioner just gets the note; the room then waits
|
|
2674
|
+
* for their next message as usual.
|
|
2675
|
+
* @param commissioner The commissioning agent, if found
|
|
2676
|
+
* @param note The system note to add to the commissioner's history
|
|
2677
|
+
*/
|
|
1318
2678
|
async respondToCommissioner(commissioner, note) {
|
|
1319
2679
|
if (!commissioner) {
|
|
1320
2680
|
logger_1.logger.warn('Commissioner not found in room; dropping commission results');
|
|
@@ -1323,6 +2683,7 @@ Recent Message: ${message.getContent()}
|
|
|
1323
2683
|
commissioner.addToConversationHistory(note, false);
|
|
1324
2684
|
commissioner.save();
|
|
1325
2685
|
if (commissioner.isControlledByHuman) {
|
|
2686
|
+
// Surface the results in the room log and hand the turn to the human
|
|
1326
2687
|
this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, note, [
|
|
1327
2688
|
commissioner.agentNickname,
|
|
1328
2689
|
]));
|
|
@@ -1347,6 +2708,7 @@ Recent Message: ${message.getContent()}
|
|
|
1347
2708
|
this.endTurn(this.isPaused ? 'keep' : 'release', { drain: true });
|
|
1348
2709
|
}
|
|
1349
2710
|
processPendingMessages() {
|
|
2711
|
+
// If paused, already processing, or no messages, skip
|
|
1350
2712
|
if (this.isPaused ||
|
|
1351
2713
|
this.processingInProgress ||
|
|
1352
2714
|
!this.pendingMessages ||
|
|
@@ -1355,25 +2717,34 @@ Recent Message: ${message.getContent()}
|
|
|
1355
2717
|
}
|
|
1356
2718
|
this.processingInProgress = true;
|
|
1357
2719
|
this.notifyStateChange();
|
|
2720
|
+
// Take current batch of messages to process
|
|
1358
2721
|
const messages = [...this.pendingMessages];
|
|
1359
2722
|
this.pendingMessages = [];
|
|
2723
|
+
// Handle special actions that bypass moderator
|
|
1360
2724
|
this.handlePublishMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.PUBLISH));
|
|
2725
|
+
// AI-issued EXECUTE messages are consumed inside the sender's turn
|
|
2726
|
+
// (see runAgentTurn); one arriving through the queue has no turn to
|
|
2727
|
+
// return its result to, so it is dropped.
|
|
1361
2728
|
const strayExecuteMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.EXECUTE);
|
|
1362
2729
|
if (strayExecuteMessages.length > 0) {
|
|
1363
2730
|
logger_1.logger.warn(`Dropping ${strayExecuteMessages.length} queued EXECUTE message(s); tool calls are handled within the sender's turn`);
|
|
1364
2731
|
}
|
|
1365
2732
|
this.handleAdjournMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.ADJOURN));
|
|
2733
|
+
// If the room is adjourned, don't continue processing messages
|
|
1366
2734
|
if (this.isAdjourned) {
|
|
1367
2735
|
logger_1.logger.log(`Room ${this.name} has been adjourned. Message processing stopped.`);
|
|
1368
2736
|
this.pendingMessages = null;
|
|
1369
2737
|
this.endTurn('release');
|
|
1370
2738
|
return;
|
|
1371
2739
|
}
|
|
2740
|
+
// Separate MODERATE from regular messages
|
|
1372
2741
|
const moderateMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.MODERATE);
|
|
1373
2742
|
let regularMessages = messages.filter((m) => m.getAction() !== app_types_1.MessageAction.MODERATE &&
|
|
1374
2743
|
m.getAction() !== app_types_1.MessageAction.PUBLISH &&
|
|
1375
2744
|
m.getAction() !== app_types_1.MessageAction.EXECUTE &&
|
|
1376
2745
|
m.getAction() !== app_types_1.MessageAction.ADJOURN);
|
|
2746
|
+
// Process MODERATE messages through moderator
|
|
2747
|
+
// Process ONE message at a time so moderator can make routing decisions per message
|
|
1377
2748
|
if (moderateMessages.length > 0) {
|
|
1378
2749
|
const moderator = this.getModeratorAgent();
|
|
1379
2750
|
if (!moderator) {
|
|
@@ -1381,16 +2752,26 @@ Recent Message: ${message.getContent()}
|
|
|
1381
2752
|
this.endTurn('release');
|
|
1382
2753
|
return;
|
|
1383
2754
|
}
|
|
2755
|
+
// Take the first moderate message
|
|
1384
2756
|
const originalMessage = moderateMessages[0];
|
|
2757
|
+
// Put any remaining moderate messages back in the queue
|
|
1385
2758
|
if (moderateMessages.length > 1) {
|
|
1386
2759
|
this.pendingMessages = [...moderateMessages.slice(1), ...this.pendingMessages];
|
|
1387
2760
|
}
|
|
2761
|
+
// Process the sender's situation (if any) BEFORE moderation, and
|
|
2762
|
+
// wait for it to finish, so the moderator routes against the updated
|
|
2763
|
+
// situation and any roster changes the situation handler made. (In
|
|
2764
|
+
// stories, the situation handler can add a new agent to the room;
|
|
2765
|
+
// doing it first means the moderator won't route to an agent that
|
|
2766
|
+
// doesn't exist yet and bounce the message back to the room leader.)
|
|
1388
2767
|
const dispatchToModerator = async () => {
|
|
1389
2768
|
if (originalMessage.situation) {
|
|
1390
2769
|
await this.handleSituationUpdate(originalMessage.situation, originalMessage.getContent());
|
|
1391
2770
|
}
|
|
1392
2771
|
await this.moderate(moderator, originalMessage, (response) => {
|
|
1393
2772
|
if (this.isPaused) {
|
|
2773
|
+
// User interrupted while this moderate call was in flight;
|
|
2774
|
+
// drop the routing response and leave the room paused.
|
|
1394
2775
|
this.endTurn('keep');
|
|
1395
2776
|
return;
|
|
1396
2777
|
}
|
|
@@ -1398,6 +2779,7 @@ Recent Message: ${message.getContent()}
|
|
|
1398
2779
|
this.handleModeratorResponse(response, originalMessage);
|
|
1399
2780
|
}
|
|
1400
2781
|
else {
|
|
2782
|
+
// No response from moderator, continue processing
|
|
1401
2783
|
this.endTurn('release', { drain: true });
|
|
1402
2784
|
}
|
|
1403
2785
|
});
|
|
@@ -1408,6 +2790,7 @@ Recent Message: ${message.getContent()}
|
|
|
1408
2790
|
});
|
|
1409
2791
|
return;
|
|
1410
2792
|
}
|
|
2793
|
+
// Process regular messages (for non-story rooms or non-MODERATE messages)
|
|
1411
2794
|
if (regularMessages.length === 0)
|
|
1412
2795
|
return;
|
|
1413
2796
|
let nextMessage;
|
|
@@ -1425,16 +2808,32 @@ Recent Message: ${message.getContent()}
|
|
|
1425
2808
|
nextMessage = filteredMessage;
|
|
1426
2809
|
}
|
|
1427
2810
|
this.addRoomMessage(nextMessage);
|
|
2811
|
+
// COMMISSION messages get dedicated orchestration instead of the broadcast:
|
|
2812
|
+
// the targets run concurrent research turns ending in DELIVERs, then the
|
|
2813
|
+
// commissioner responds to the aggregated deliverables. The processing lock
|
|
2814
|
+
// stays held for the whole exchange.
|
|
1428
2815
|
if (nextMessage.getAction() === app_types_1.MessageAction.COMMISSION) {
|
|
1429
2816
|
void this.handleCommissionMessage(nextMessage);
|
|
1430
2817
|
return;
|
|
1431
2818
|
}
|
|
2819
|
+
// In 'directed' mode this is a single agent; in 'broadcast' it is everyone.
|
|
1432
2820
|
const responders = this.selectResponders(nextMessage);
|
|
2821
|
+
// Everyone else still hears the message, at no LLM cost. This must use
|
|
2822
|
+
// hear() rather than perceive(): these agents are not counted in
|
|
2823
|
+
// agentsInProgress, and perceive() would fire a callback that decrements it.
|
|
1433
2824
|
for (const agent of this.agents) {
|
|
1434
2825
|
if (responders.includes(agent))
|
|
1435
2826
|
continue;
|
|
1436
2827
|
this.hear(agent, nextMessage);
|
|
1437
2828
|
}
|
|
2829
|
+
// A human responder has no callback to release the lock (perceive returns
|
|
2830
|
+
// early for human agents), so a responder set with no AI agent in it would
|
|
2831
|
+
// hold the lock with nothing running. Hand the floor to a human instead —
|
|
2832
|
+
// the same thing handleModeratorResponse does when it routes to a human.
|
|
2833
|
+
//
|
|
2834
|
+
// With one human this is the single-responder case it has always handled.
|
|
2835
|
+
// With several it also covers the directed-mode widening fallback resolving
|
|
2836
|
+
// to two players, and a table where every agent is a player.
|
|
1438
2837
|
const humanResponders = responders.filter((a) => a.isControlledByHuman);
|
|
1439
2838
|
if (humanResponders.length > 0 && humanResponders.length === responders.length) {
|
|
1440
2839
|
for (const human of humanResponders) {
|
|
@@ -1443,36 +2842,85 @@ Recent Message: ${message.getContent()}
|
|
|
1443
2842
|
this.endTurn({ to: humanResponders[0].agentNickname });
|
|
1444
2843
|
return;
|
|
1445
2844
|
}
|
|
2845
|
+
// Name the agent that will actually answer. In broadcast mode that is
|
|
2846
|
+
// whoever the message targeted; in directed mode it is the resolved
|
|
2847
|
+
// responder, which also covers a message that named no target at all.
|
|
1446
2848
|
this.setCurrentSpeaker(this.turnMode === 'directed' && responders.length > 0
|
|
1447
2849
|
? responders[0].agentNickname
|
|
1448
2850
|
: nextMessage.targets[0]);
|
|
2851
|
+
// Counter to track how many agents have responded
|
|
1449
2852
|
let agentsInProgress = responders.length;
|
|
2853
|
+
// Edge case: nobody to dispatch to (an empty room, or a directed message
|
|
2854
|
+
// that selected no responder). Release the lock here since no callback
|
|
2855
|
+
// will ever fire to do it, and keep draining the queue.
|
|
1450
2856
|
if (agentsInProgress === 0) {
|
|
2857
|
+
// The floor was named just above and nobody is going to use it, so give
|
|
2858
|
+
// it up. A THINK or TOOL message selects no responder in directed mode,
|
|
2859
|
+
// and leaving the floor on its target — a name that need not even be an
|
|
2860
|
+
// agent — pinned the room exactly as a failed turn used to.
|
|
1451
2861
|
this.endTurn('release', { drain: true });
|
|
1452
2862
|
return;
|
|
1453
2863
|
}
|
|
2864
|
+
// Call perceive on the responding agents with callback.
|
|
2865
|
+
// The lock is held until every one has responded (or declined to respond).
|
|
2866
|
+
// It is released inside the callback when agentsRemaining hits zero — do NOT
|
|
2867
|
+
// release it after this loop, since `perceive` is async and the loop returns
|
|
2868
|
+
// before agents have finished generating responses.
|
|
2869
|
+
// Remembered so a turn that ends without a word said can be re-routed rather
|
|
2870
|
+
// than leaving the room idle. Only audible messages reach here — a THINK or a
|
|
2871
|
+
// TOOL selects no responder — so this is always something worth answering.
|
|
2872
|
+
this.lastDispatch = {
|
|
2873
|
+
message: nextMessage,
|
|
2874
|
+
responders: responders.map((a) => a.agentNickname),
|
|
2875
|
+
};
|
|
1454
2876
|
for (const agent of responders) {
|
|
1455
2877
|
this.pinHistoryOnHandoff(agent, nextMessage);
|
|
1456
2878
|
const continuing = agent.agentNickname === nextMessage.getSender();
|
|
1457
2879
|
this.perceive(agent, nextMessage, (message) => {
|
|
1458
2880
|
agentsInProgress--;
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
2881
|
+
// Process the response immediately
|
|
2882
|
+
this.queueAgentResponse(message);
|
|
2883
|
+
// When all agents have responded, continue processing.
|
|
2884
|
+
//
|
|
2885
|
+
// Releasing the floor here is what stops a failed turn killing the
|
|
2886
|
+
// room: a turn that ends with no message queues nothing, so without
|
|
2887
|
+
// this no later round ever overwrites the speaker and every human
|
|
2888
|
+
// message is refused with "It is <Agent>'s turn to speak" forever.
|
|
2889
|
+
// 'keep' while paused, because pause() has already handed the floor
|
|
2890
|
+
// to the human and this callback must not take it back.
|
|
1470
2891
|
if (agentsInProgress === 0) {
|
|
1471
2892
|
this.endTurn(this.isPaused ? 'keep' : 'release', { drain: true });
|
|
1472
2893
|
}
|
|
1473
2894
|
}, { continuing });
|
|
1474
2895
|
}
|
|
1475
2896
|
}
|
|
2897
|
+
/**
|
|
2898
|
+
* Protects a specialist's history when the room leader hands it a task.
|
|
2899
|
+
*
|
|
2900
|
+
* A specialist runs on a short rolling window so it does not carry the last job
|
|
2901
|
+
* into the next one. That window is wrong *within* a job: a whole encounter or a
|
|
2902
|
+
* whole character interview can run longer than the window is wide. Pinning at
|
|
2903
|
+
* the handoff keeps everything from that message on, while the window still
|
|
2904
|
+
* drops what came before — so the second job forgets the first, and neither
|
|
2905
|
+
* forgets itself.
|
|
2906
|
+
*
|
|
2907
|
+
* Three conditions, all needed:
|
|
2908
|
+
*
|
|
2909
|
+
* - **the sender is the room leader**, because a handoff is the leader delegating;
|
|
2910
|
+
* - **the message names this agent**, so a general announcement is not a new task
|
|
2911
|
+
* and cannot re-pin one already running;
|
|
2912
|
+
* - **the agent has a window**, which makes this a no-op for everyone else. The
|
|
2913
|
+
* Dungeon Master keeps its whole campaign whether or not this runs.
|
|
2914
|
+
*
|
|
2915
|
+
* Called *before* {@link perceive}, so the handoff instruction itself is inside
|
|
2916
|
+
* the pin rather than the first casualty of the next trim.
|
|
2917
|
+
*
|
|
2918
|
+
* There is no unpin. Re-pinning ends the previous pin, so an abandoned task is
|
|
2919
|
+
* reclaimed by the next one and the worst a stale pin does is keep more history
|
|
2920
|
+
* than intended.
|
|
2921
|
+
* @param agent The agent about to be prompted
|
|
2922
|
+
* @param message The message being dispatched to it
|
|
2923
|
+
*/
|
|
1476
2924
|
pinHistoryOnHandoff(agent, message) {
|
|
1477
2925
|
const leader = this.getRoomLeader();
|
|
1478
2926
|
if (!leader || !this.checkAgentNicknameMatch(leader, message.getSender()))
|
|
@@ -1486,6 +2934,32 @@ Recent Message: ${message.getContent()}
|
|
|
1486
2934
|
return;
|
|
1487
2935
|
agent.pinHistory();
|
|
1488
2936
|
}
|
|
2937
|
+
/**
|
|
2938
|
+
* Decides which agents are asked to respond to a message.
|
|
2939
|
+
*
|
|
2940
|
+
* In 'broadcast' mode every agent responds and {@link filterConcurrentMessages}
|
|
2941
|
+
* later keeps one reply, discarding the rest. In 'directed' mode exactly one
|
|
2942
|
+
* agent responds — the first target that resolves to an agent, or the room
|
|
2943
|
+
* leader when no target does — so a leader agent controls the order of play
|
|
2944
|
+
* and no work is paid for and thrown away. Agents that are not selected still
|
|
2945
|
+
* receive the message through {@link hear}.
|
|
2946
|
+
*
|
|
2947
|
+
* The sender is never selected: a self-loop would have the agent answer
|
|
2948
|
+
* itself and stall the room. If neither a target nor the leader resolves to
|
|
2949
|
+
* someone other than the sender, this widens to everyone else who can hear
|
|
2950
|
+
* the message, so a misaddressed message still gets a reply from somebody.
|
|
2951
|
+
* @param message The message being processed
|
|
2952
|
+
* @returns The agents to prompt, in the order they should be dispatched
|
|
2953
|
+
*/
|
|
2954
|
+
/**
|
|
2955
|
+
* Whether an agent that has addressed itself may keep the floor.
|
|
2956
|
+
*
|
|
2957
|
+
* Counts consecutive turns rather than total ones: a run ends the moment anyone
|
|
2958
|
+
* else takes the floor, so an agent that legitimately keeps it twice during one
|
|
2959
|
+
* fight and twice more during the next is never penalised for the first pair.
|
|
2960
|
+
* @param sender The agent asking to answer itself
|
|
2961
|
+
* @returns True when it keeps the floor, false when the run has gone on too long
|
|
2962
|
+
*/
|
|
1489
2963
|
mayContinueAlone(sender) {
|
|
1490
2964
|
if (this.selfContinuingAgent !== sender) {
|
|
1491
2965
|
this.selfContinuingAgent = sender;
|
|
@@ -1499,6 +2973,7 @@ Recent Message: ${message.getContent()}
|
|
|
1499
2973
|
this.consecutiveSelfContinues += 1;
|
|
1500
2974
|
return true;
|
|
1501
2975
|
}
|
|
2976
|
+
/** Ends a self-continue run, because the floor has gone to somebody else. */
|
|
1502
2977
|
clearSelfContinue() {
|
|
1503
2978
|
this.selfContinuingAgent = null;
|
|
1504
2979
|
this.consecutiveSelfContinues = 0;
|
|
@@ -1507,6 +2982,7 @@ Recent Message: ${message.getContent()}
|
|
|
1507
2982
|
if (this.turnMode !== 'directed') {
|
|
1508
2983
|
return [...this.agents];
|
|
1509
2984
|
}
|
|
2985
|
+
// Inaudible messages never prompt anyone.
|
|
1510
2986
|
const action = message.getAction();
|
|
1511
2987
|
if (action === app_types_1.MessageAction.THINK || action === app_types_1.MessageAction.TOOL) {
|
|
1512
2988
|
return [];
|
|
@@ -1514,8 +2990,10 @@ Recent Message: ${message.getContent()}
|
|
|
1514
2990
|
for (const name of message.getTargets() || []) {
|
|
1515
2991
|
const target = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, name));
|
|
1516
2992
|
if (!target)
|
|
1517
|
-
continue;
|
|
2993
|
+
continue; // Unknown name: try the next target
|
|
1518
2994
|
if (target.agentNickname === message.getSender()) {
|
|
2995
|
+
// Addressing itself. Normally a stall, but it is also the only way an
|
|
2996
|
+
// agent can say "I am not finished" when there is nobody to hand to.
|
|
1519
2997
|
if (!this.mayContinueAlone(message.getSender()))
|
|
1520
2998
|
continue;
|
|
1521
2999
|
return [target];
|
|
@@ -1532,6 +3010,12 @@ Recent Message: ${message.getContent()}
|
|
|
1532
3010
|
logger_1.logger.warn(`Directed room ${this.name}: neither a target nor the leader could answer ${message.getSender()}; widening to ${others.length} other agent(s)`);
|
|
1533
3011
|
return others;
|
|
1534
3012
|
}
|
|
3013
|
+
/**
|
|
3014
|
+
* Filters concurrent messages to ensure only one message is processed
|
|
3015
|
+
* Priority: SHOUT > SPEAK > WHISPER, then by agent order in room
|
|
3016
|
+
* @param messages Array of messages to filter
|
|
3017
|
+
* @returns Single message (or original if <= 1)
|
|
3018
|
+
*/
|
|
1535
3019
|
filterConcurrentMessages(messages) {
|
|
1536
3020
|
if (messages.length == 0)
|
|
1537
3021
|
return null;
|
|
@@ -1543,27 +3027,33 @@ Recent Message: ${message.getContent()}
|
|
|
1543
3027
|
if (systemMessages.length > 0) {
|
|
1544
3028
|
return systemMessages[0];
|
|
1545
3029
|
}
|
|
3030
|
+
// Step 1: Check for SHOUT - highest priority
|
|
1546
3031
|
const shoutMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SHOUT);
|
|
1547
3032
|
if (shoutMessages.length > 0) {
|
|
1548
3033
|
filtered = shoutMessages;
|
|
1549
3034
|
}
|
|
3035
|
+
// Step 2: If still multiple, apply SPEAK/WHISPER rules
|
|
3036
|
+
// (COMMISSION competes at SPEAK priority)
|
|
1550
3037
|
if (filtered.length > 1) {
|
|
1551
3038
|
const speakMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SPEAK ||
|
|
1552
3039
|
m.getAction() === app_types_1.MessageAction.COMMISSION);
|
|
1553
3040
|
const whisperMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.WHISPER);
|
|
1554
3041
|
if (speakMessages.length > 0) {
|
|
3042
|
+
// If anyone speaks, remove all whispers
|
|
1555
3043
|
filtered = speakMessages;
|
|
1556
3044
|
}
|
|
1557
3045
|
else {
|
|
1558
3046
|
filtered = whisperMessages;
|
|
1559
3047
|
}
|
|
1560
3048
|
}
|
|
3049
|
+
// Step 3: If still multiple, check to see if one of them was targeted to speak next by the previous message
|
|
1561
3050
|
if (filtered.length > 1) {
|
|
1562
3051
|
const targetedMessages = filtered.filter((m) => m.getSender() === this.currentSpeaker);
|
|
1563
3052
|
if (targetedMessages.length === 1) {
|
|
1564
3053
|
filtered = targetedMessages;
|
|
1565
3054
|
}
|
|
1566
3055
|
}
|
|
3056
|
+
// Step 4: If still multiple, pick the first one in the room order
|
|
1567
3057
|
if (filtered.length > 1) {
|
|
1568
3058
|
let earliestMessage = null;
|
|
1569
3059
|
let earliestIndex = Infinity;
|
|
@@ -1578,6 +3068,7 @@ Recent Message: ${message.getContent()}
|
|
|
1578
3068
|
filtered = [earliestMessage];
|
|
1579
3069
|
}
|
|
1580
3070
|
else if (filtered.length > 0) {
|
|
3071
|
+
// Fallback: keep first message if no agent match found
|
|
1581
3072
|
filtered = [filtered[0]];
|
|
1582
3073
|
}
|
|
1583
3074
|
}
|