briyah 2.0.3 → 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/README.md +43 -7
- package/data/common/config/LICENSE-model-prices.md +65 -0
- package/data/common/config/model_prices.json +47443 -46295
- package/data/common/prompts/narrator/create_story.prompt +2 -0
- 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 +1661 -0
- package/dist-sdk/server/src/app.service.js +1837 -4
- 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 +26 -0
- package/dist-sdk/server/src/room/nickname.js +26 -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 +176 -0
- package/dist-sdk/server/src/room/room-store.service.js +238 -5
- package/dist-sdk/server/src/room/room.d.ts +878 -0
- package/dist-sdk/server/src/room/room.js +1291 -23
- 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 +37 -0
- package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
- package/dist-sdk/server/src/rpg/rpg.service.js +103 -0
- 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.js +23 -0
- 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 +22 -0
- package/dist-sdk/server/src/tools/core/index.js +22 -0
- package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
- package/dist-sdk/server/src/tools/core/rename.tool.js +11 -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 +176 -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 +116 -0
- 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 +49 -0
- package/dist-sdk/server/src/tools/packs/index.js +66 -0
- 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 -13
- package/dist-sdk/shared/types/app.types.js +3 -0
- package/package.json +167 -168
- 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/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 -1434
- package/docs/classes/RoomMessage.html +0 -290
- package/docs/enums/MessageAction.html +0 -136
- 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 -51
- 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 -3340
- 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 -260
- 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
|
@@ -65,6 +65,10 @@ const yauzl = __importStar(require("yauzl"));
|
|
|
65
65
|
const message_1 = require("../room/message");
|
|
66
66
|
const errors_1 = require("../common/errors");
|
|
67
67
|
const logger_1 = require("../common/logger");
|
|
68
|
+
/**
|
|
69
|
+
* Service handling business logic for stories
|
|
70
|
+
* Works alongside StoryStoreService which handles persistence
|
|
71
|
+
*/
|
|
68
72
|
let StoryService = class StoryService {
|
|
69
73
|
storyStore;
|
|
70
74
|
agentStore;
|
|
@@ -74,7 +78,11 @@ let StoryService = class StoryService {
|
|
|
74
78
|
userPaths;
|
|
75
79
|
agentFactory;
|
|
76
80
|
roomFactory;
|
|
81
|
+
// Map to store story-specific artifact services
|
|
77
82
|
storyArtifactServices = new Map();
|
|
83
|
+
// Tracks stories with an in-flight chapter progression so we can reject
|
|
84
|
+
// concurrent calls. The UI disables the Next Chapter button, but that
|
|
85
|
+
// protection is best-effort (double-click race, HTTP retry, multiple tabs).
|
|
78
86
|
chaptersInProgress = new Set();
|
|
79
87
|
constructor(storyStore, agentStore, roomStore, progressService, messageService, userPaths, agentFactory, roomFactory) {
|
|
80
88
|
this.storyStore = storyStore;
|
|
@@ -86,27 +94,57 @@ let StoryService = class StoryService {
|
|
|
86
94
|
this.agentFactory = agentFactory;
|
|
87
95
|
this.roomFactory = roomFactory;
|
|
88
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* Gets the progress emitter for a story
|
|
99
|
+
* @param storyId The story ID
|
|
100
|
+
* @returns The event emitter or undefined
|
|
101
|
+
*/
|
|
89
102
|
getProgressEmitter(storyId) {
|
|
90
103
|
return this.progressService.getProgressEmitter(storyId);
|
|
91
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Gets or creates the message emitter for a story
|
|
107
|
+
* @param storyId The story ID
|
|
108
|
+
* @returns The event emitter
|
|
109
|
+
*/
|
|
92
110
|
getMessageEmitter(storyId) {
|
|
93
111
|
return this.messageService.getOrCreateEmitter(storyId);
|
|
94
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* Cleans up the progress emitter for a story
|
|
115
|
+
* @param storyId The story ID
|
|
116
|
+
*/
|
|
95
117
|
cleanupProgressEmitter(storyId) {
|
|
96
118
|
this.progressService.cleanup(storyId);
|
|
97
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Cleans up the message emitter for a story
|
|
122
|
+
* @param storyId The story ID
|
|
123
|
+
*/
|
|
98
124
|
cleanupMessageEmitter(storyId) {
|
|
99
125
|
this.messageService.cleanup(storyId);
|
|
100
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* Gets or creates the artifact service for a story
|
|
129
|
+
* @param storyId The story ID
|
|
130
|
+
* @returns The story-specific artifact service
|
|
131
|
+
*/
|
|
101
132
|
getStoryArtifactService(storyId) {
|
|
133
|
+
// Check if we already have an artifact service for this story
|
|
102
134
|
let artifactService = this.storyArtifactServices.get(storyId);
|
|
103
135
|
if (!artifactService) {
|
|
136
|
+
// Create new story-specific artifact service
|
|
104
137
|
const { artifactsDir } = this.getStoryStorageDirs(storyId);
|
|
105
138
|
artifactService = new artifact_service_1.ArtifactService(this.userPaths, artifactsDir);
|
|
106
139
|
this.storyArtifactServices.set(storyId, artifactService);
|
|
107
140
|
}
|
|
108
141
|
return artifactService;
|
|
109
142
|
}
|
|
143
|
+
/**
|
|
144
|
+
* Emits a story state update to connected SSE clients
|
|
145
|
+
* Called by room's onStateChange callback
|
|
146
|
+
* @param storyId The story ID
|
|
147
|
+
*/
|
|
110
148
|
async emitStoryStateUpdate(storyId) {
|
|
111
149
|
try {
|
|
112
150
|
let story = await this.ensureStoryLoaded(storyId);
|
|
@@ -119,17 +157,20 @@ let StoryService = class StoryService {
|
|
|
119
157
|
logger_1.logger.error(`Room ${story.roomId} not found for story ${storyId}`);
|
|
120
158
|
return;
|
|
121
159
|
}
|
|
160
|
+
// Update story cost whenever state changes (after AI responses)
|
|
122
161
|
await this.updateStoryCost(storyId);
|
|
123
|
-
story = await this.getStoryInfo(storyId);
|
|
162
|
+
story = await this.getStoryInfo(storyId); // refresh storyInfo after updating cost
|
|
124
163
|
const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
|
|
125
164
|
if (!humanAgent) {
|
|
126
165
|
logger_1.logger.error(`No human agent found for story ${storyId}`);
|
|
127
166
|
return;
|
|
128
167
|
}
|
|
168
|
+
// Get latest room message
|
|
129
169
|
const roomMessages = room.getLatestRoomMessages(0, true);
|
|
130
170
|
const latestMessage = roomMessages[roomMessages.length - 1];
|
|
131
171
|
const currentSpeaker = room.getCurrentSpeaker();
|
|
132
172
|
const humanPrompt = this.getHumanPrompt(room);
|
|
173
|
+
// Create incremental update with latest message only
|
|
133
174
|
const stateUpdate = {
|
|
134
175
|
storyId: story.id,
|
|
135
176
|
latestRoomMessage: latestMessage,
|
|
@@ -140,41 +181,81 @@ let StoryService = class StoryService {
|
|
|
140
181
|
totalInputTokens: story.totalInputTokens || 0,
|
|
141
182
|
totalOutputTokens: story.totalOutputTokens || 0,
|
|
142
183
|
};
|
|
184
|
+
// Emit SSE update (this service maintains the emitters)
|
|
143
185
|
this.messageService.emitStoryState(storyId, stateUpdate);
|
|
144
186
|
}
|
|
145
187
|
catch (error) {
|
|
146
188
|
logger_1.logger.error(`Error emitting story state update for ${storyId}:`, error);
|
|
147
189
|
}
|
|
148
190
|
}
|
|
191
|
+
// Get human prompt based on current speaker
|
|
149
192
|
getHumanPrompt(room) {
|
|
150
193
|
const humanAgent = room.getAgents().find((a) => a.isControlledByHuman);
|
|
151
194
|
if (!humanAgent) {
|
|
152
195
|
return '';
|
|
153
196
|
}
|
|
154
197
|
if (room.getCurrentSpeaker() === humanAgent.agentNickname) {
|
|
198
|
+
// It's the human's turn
|
|
155
199
|
return `What does ${humanAgent.agentNickname} do or say next?`;
|
|
156
200
|
}
|
|
157
201
|
else if (room.getCurrentSpeaker() !== null) {
|
|
202
|
+
// It's another agent's turn
|
|
158
203
|
return `Waiting for ${room.getCurrentSpeaker()}...`;
|
|
159
204
|
}
|
|
160
205
|
else if (room.isProcessingInProgress()) {
|
|
206
|
+
// System is processing
|
|
161
207
|
return 'Processing...';
|
|
162
208
|
}
|
|
163
209
|
else {
|
|
210
|
+
// No current speaker and not processing
|
|
164
211
|
return '';
|
|
165
212
|
}
|
|
166
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Handles errors from room operations and emits them through SSE
|
|
216
|
+
* @param storyId The story ID
|
|
217
|
+
* @param error The error that occurred
|
|
218
|
+
*/
|
|
167
219
|
handleRoomError(storyId, error) {
|
|
168
220
|
logger_1.logger.log(`Room error for story ${storyId}: ${error.name} - ${error.message}`);
|
|
169
221
|
this.messageService.emitError(storyId, error);
|
|
170
222
|
}
|
|
223
|
+
/**
|
|
224
|
+
* Picks a random word from the random words file, if there is one.
|
|
225
|
+
*
|
|
226
|
+
* The list is optional and is not published with the package, so an SDK host
|
|
227
|
+
* has no file to read. `create_story.prompt` offers the word as an aid rather
|
|
228
|
+
* than requiring it — "if you need random numbers or words, use these" — so a
|
|
229
|
+
* story created without one is a story the narrator had one fewer prompt from.
|
|
230
|
+
*
|
|
231
|
+
* Absent has to be handled here rather than left to throw: this runs inside
|
|
232
|
+
* {@link createStory}, so a missing file would fail every story creation
|
|
233
|
+
* outright rather than costing the narrator an idea.
|
|
234
|
+
* @returns A random word, or '' when no list is installed
|
|
235
|
+
*/
|
|
171
236
|
getRandomWord() {
|
|
172
237
|
const randomWordsPath = path.join(this.userPaths.getCommonConfigDir(), 'random_words.txt');
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
238
|
+
try {
|
|
239
|
+
if (!fs.existsSync(randomWordsPath))
|
|
240
|
+
return '';
|
|
241
|
+
const content = fs.readFileSync(randomWordsPath, 'utf-8');
|
|
242
|
+
const words = content.split('\n').filter((word) => word.trim().length > 0);
|
|
243
|
+
// An empty list used to index [0] of nothing and render the word
|
|
244
|
+
// "undefined" into the prompt.
|
|
245
|
+
if (words.length === 0)
|
|
246
|
+
return '';
|
|
247
|
+
return words[Math.floor(Math.random() * words.length)];
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
logger_1.logger.warn(`Could not read ${randomWordsPath}: ${error.message}`);
|
|
251
|
+
return '';
|
|
252
|
+
}
|
|
177
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Gets the storage directories for a story
|
|
256
|
+
* @param storyId The story ID
|
|
257
|
+
* @returns Object with agentsDir, roomsDir, and artifactsDir paths
|
|
258
|
+
*/
|
|
178
259
|
getStoryStorageDirs(storyId) {
|
|
179
260
|
const userStoriesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
|
|
180
261
|
return {
|
|
@@ -183,6 +264,11 @@ let StoryService = class StoryService {
|
|
|
183
264
|
artifactsDir: path.join(userStoriesDir, storyId, 'artifacts'),
|
|
184
265
|
};
|
|
185
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Looks up AI service and model from story_models.json using the model identifier
|
|
269
|
+
* @param storyModel The model identifier (e.g., "claude-sonnet-4-5")
|
|
270
|
+
* @returns Object with service and model, or null if not found
|
|
271
|
+
*/
|
|
186
272
|
getStoryModelConfig(storyModel) {
|
|
187
273
|
const storyModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'story_models.json');
|
|
188
274
|
try {
|
|
@@ -193,6 +279,8 @@ let StoryService = class StoryService {
|
|
|
193
279
|
service: modelConfig.service,
|
|
194
280
|
model: modelConfig.model,
|
|
195
281
|
smallModel: modelConfig.small_model,
|
|
282
|
+
// Moderator/illustrator service+model, falling back to the
|
|
283
|
+
// main story service+model when not specified in the entry.
|
|
196
284
|
moderatorService: modelConfig.moderator_service || modelConfig.service,
|
|
197
285
|
moderatorModel: modelConfig.moderator_model || modelConfig.model,
|
|
198
286
|
};
|
|
@@ -206,42 +294,60 @@ let StoryService = class StoryService {
|
|
|
206
294
|
}
|
|
207
295
|
}
|
|
208
296
|
async getStoryRoom(storyId) {
|
|
297
|
+
// Get the story metadata
|
|
209
298
|
const story = await this.ensureStoryLoaded(storyId);
|
|
210
299
|
if (!story) {
|
|
211
300
|
throw new Error('Story not found');
|
|
212
301
|
}
|
|
302
|
+
// Get the room
|
|
213
303
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
214
304
|
if (!room) {
|
|
215
305
|
throw new Error('Story room not found');
|
|
216
306
|
}
|
|
217
307
|
return room;
|
|
218
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Ensures a story's room and agents are loaded into memory
|
|
311
|
+
* Sets up the state change callback for event-driven updates
|
|
312
|
+
* @param storyId The story ID
|
|
313
|
+
*/
|
|
219
314
|
async ensureStoryLoaded(storyId) {
|
|
315
|
+
// Get the story metadata to check if it has a room
|
|
220
316
|
const story = this.storyStore.getStory(storyId);
|
|
221
317
|
if (!story)
|
|
222
|
-
return null;
|
|
318
|
+
return null; // No room configured yet
|
|
223
319
|
if (!story.roomId) {
|
|
224
320
|
logger_1.logger.error(`Story ${storyId} has no roomId. Deleting story from storage...`);
|
|
225
321
|
this.storyStore.removeStory(storyId);
|
|
226
322
|
return null;
|
|
227
323
|
}
|
|
324
|
+
// Check if the room is already loaded in memory
|
|
228
325
|
let room = await this.roomStore.getRoom(story.roomId);
|
|
229
326
|
if (room) {
|
|
230
|
-
return story;
|
|
327
|
+
return story; // Room is already loaded, no need to reload
|
|
231
328
|
}
|
|
329
|
+
// Room not loaded yet, load from directory
|
|
330
|
+
// Room not loaded yet, load from directory
|
|
232
331
|
const { agentsDir, roomsDir } = this.getStoryStorageDirs(storyId);
|
|
233
332
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
234
333
|
await this.agentStore.loadAgentsFromDirectory(agentsDir, storyArtifactService);
|
|
235
334
|
await this.roomStore.loadRoomsFromDirectory(roomsDir);
|
|
335
|
+
// Get the loaded room and set up callbacks
|
|
236
336
|
room = await this.roomStore.getRoom(story.roomId);
|
|
237
337
|
if (room) {
|
|
238
338
|
room.setOnStateChange('story', () => {
|
|
239
339
|
this.emitStoryStateUpdate(storyId);
|
|
240
340
|
});
|
|
341
|
+
// Set up error callback
|
|
241
342
|
room.setOnError('story', (error) => {
|
|
242
343
|
this.handleRoomError(storyId, error);
|
|
243
344
|
});
|
|
345
|
+
// Set up situation update callback (awaited by the room before it
|
|
346
|
+
// routes a narrator message, so an introduced character is created
|
|
347
|
+
// before moderation). latestMessage is the narration that triggered
|
|
348
|
+
// the update, passed through because it isn't logged to the room yet.
|
|
244
349
|
room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyId, situation, latestMessage));
|
|
350
|
+
// Handle moderator-triggered portrait updates
|
|
245
351
|
room.setOnModeratorResponse((message) => {
|
|
246
352
|
const portraitsToUpdate = message.changes?.update_portrait ?? [];
|
|
247
353
|
if (portraitsToUpdate.length) {
|
|
@@ -250,6 +356,9 @@ let StoryService = class StoryService {
|
|
|
250
356
|
.getAgents()
|
|
251
357
|
.find((a) => a.agentNickname === nickname);
|
|
252
358
|
if (characterAgent) {
|
|
359
|
+
// updateDescription=true: the moderator flagged an
|
|
360
|
+
// appearance change, so refresh agent.description too
|
|
361
|
+
// (works even when images are disabled).
|
|
253
362
|
this.updateCharacterPortrait(room, characterAgent, storyId, true).catch((e) => logger_1.logger.error(`Error updating appearance for ${nickname}:`, e));
|
|
254
363
|
}
|
|
255
364
|
else {
|
|
@@ -259,6 +368,7 @@ let StoryService = class StoryService {
|
|
|
259
368
|
}
|
|
260
369
|
this.applyInventoryUpdates(room, message);
|
|
261
370
|
});
|
|
371
|
+
// Initialize room's situation from story metadata
|
|
262
372
|
if (story.situation) {
|
|
263
373
|
room.setSituation(story.situation);
|
|
264
374
|
}
|
|
@@ -271,22 +381,41 @@ let StoryService = class StoryService {
|
|
|
271
381
|
async getStoryInfo(storyId) {
|
|
272
382
|
return this.storyStore.getStory(storyId);
|
|
273
383
|
}
|
|
384
|
+
/**
|
|
385
|
+
* Creates a new story with business logic
|
|
386
|
+
* @param name The story name
|
|
387
|
+
* @param idea The story idea or existing story text (if isImport is true)
|
|
388
|
+
* @param userCharacterDesc Description of the character the user will play
|
|
389
|
+
* @param otherCharactersDesc Description of other prominent characters
|
|
390
|
+
* @param illustrateStory True if the story will be illustrated
|
|
391
|
+
* @param storyModel The model identifier (e.g., "claude-sonnet-4-5") from story_models.json
|
|
392
|
+
* @param isImport Flag indicating this is an imported existing story
|
|
393
|
+
* @param imageModelName Name of the image model in data/common/config/image_models.json. Each entry supplies both a generation model (portraits/scene references) and an editing model (story images with reference images).
|
|
394
|
+
* @param skipDetailedPlot When true, generate a simple plot scenario instead of a detailed plot plan with secrets, twists, and events
|
|
395
|
+
* @returns The story information including the generated ID
|
|
396
|
+
*/
|
|
274
397
|
async createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport = false, imageModelName, skipDetailedPlot = false) {
|
|
398
|
+
// Validate input
|
|
275
399
|
if (!name || name.trim().length === 0) {
|
|
276
400
|
throw new Error('Story name is required');
|
|
277
401
|
}
|
|
402
|
+
// Create story directory structure and get ID
|
|
278
403
|
const storyInfo = this.storyStore.createStory(name);
|
|
279
404
|
storyInfo.turnNumber = 0;
|
|
280
405
|
let storyTitle = name;
|
|
281
406
|
try {
|
|
407
|
+
// Create progress emitter for this story
|
|
282
408
|
this.progressService.createProgressEmitter(storyInfo.id);
|
|
283
409
|
this.progressService.emitProgress(storyInfo.id, 'start', 'Starting story creation...');
|
|
410
|
+
// Get story-specific storage directories
|
|
284
411
|
const { agentsDir: storyAgentsDir, roomsDir: storyRoomsDir } = this.getStoryStorageDirs(storyInfo.id);
|
|
412
|
+
// Get story-specific artifact service
|
|
285
413
|
const storyArtifactService = this.getStoryArtifactService(storyInfo.id);
|
|
286
414
|
let aiServiceName;
|
|
287
415
|
let aiModelName;
|
|
288
416
|
if (!storyModel || storyModel.trim().length === 0)
|
|
289
417
|
storyModel = process.env.DEFAULT_STORY_MODEL;
|
|
418
|
+
// Look up service and model from story_models.json
|
|
290
419
|
const modelConfig = this.getStoryModelConfig(storyModel);
|
|
291
420
|
if (modelConfig) {
|
|
292
421
|
aiServiceName = modelConfig.service;
|
|
@@ -294,14 +423,20 @@ let StoryService = class StoryService {
|
|
|
294
423
|
}
|
|
295
424
|
if (!aiServiceName || !aiModelName)
|
|
296
425
|
throw new Error(`Failed to find model config for "${storyModel}"`);
|
|
297
|
-
|
|
426
|
+
// PHASE 1: Create moderator agent (BEFORE narrator)
|
|
427
|
+
let moderator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Moderator`, // Agent name = "[story title] - [nickname]"
|
|
428
|
+
'Moderator', 'Story moderator responsible for message routing and conversation flow', 'story_moderator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
|
|
429
|
+
// Set rolling window for moderator (keep only last 16 messages)
|
|
298
430
|
moderator.maxHistoryMessages = 16;
|
|
299
431
|
moderator.reasoningEffort = 'low';
|
|
300
|
-
moderator.promptCacheTTL = 60;
|
|
432
|
+
moderator.promptCacheTTL = 60; // Cache prompts but don't auto refresh
|
|
301
433
|
moderator.ownerRoomId = storyInfo.id;
|
|
302
|
-
moderator.markupRate = 0;
|
|
434
|
+
moderator.markupRate = 0; // Don't markup the moderator
|
|
303
435
|
moderator.save();
|
|
304
436
|
logger_1.logger.log(`Created moderator agent: ${moderator.agentName}`);
|
|
437
|
+
// Resolve the image model - fall back to the env default when illustrateStory
|
|
438
|
+
// is set. A single consolidated entry supplies both the generation and
|
|
439
|
+
// editing models (see image_models.json).
|
|
305
440
|
if (illustrateStory) {
|
|
306
441
|
if (!imageModelName)
|
|
307
442
|
imageModelName = process.env.DEFAULT_IMAGE_MODEL;
|
|
@@ -309,11 +444,17 @@ let StoryService = class StoryService {
|
|
|
309
444
|
else {
|
|
310
445
|
imageModelName = undefined;
|
|
311
446
|
}
|
|
447
|
+
// Create artist agent (text-to-image: portraits and scene references) from
|
|
448
|
+
// the entry's generation model.
|
|
312
449
|
const artist = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist', 'generation');
|
|
450
|
+
// Create artist edit agent (image-to-image: story images with reference
|
|
451
|
+
// images) from the same entry's editing model.
|
|
313
452
|
const artistEdit = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist (Edit)', 'editing');
|
|
453
|
+
// Create illustrator agent (only if artist exists)
|
|
314
454
|
let illustrator = null;
|
|
315
455
|
if (artist) {
|
|
316
|
-
illustrator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Illustrator`,
|
|
456
|
+
illustrator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Illustrator`, // Agent name = "[story title] - [nickname]"
|
|
457
|
+
'Illustrator', 'Visual artist for generating scene illustrations', 'illustrator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
|
|
317
458
|
illustrator.reasoningEffort = 'low';
|
|
318
459
|
illustrator.maxHistoryMessages = 10;
|
|
319
460
|
illustrator.promptCacheTTL = 60;
|
|
@@ -321,7 +462,10 @@ let StoryService = class StoryService {
|
|
|
321
462
|
illustrator.save();
|
|
322
463
|
logger_1.logger.log(`Created illustrator agent: ${illustrator.agentName}`);
|
|
323
464
|
}
|
|
324
|
-
|
|
465
|
+
// PHASE 2: Create narrator agent
|
|
466
|
+
let narrator = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - Narrator`, // Agent name = "[story title] - [nickname]"
|
|
467
|
+
'Narrator', // Agent nickname
|
|
468
|
+
'Story narrator. Should receive all messages where a character wants to perform an action or PASS or INTRODUCE a new character. Responds to all dialog with characters not listed in Available Agents.', 'narrator', aiModelName, storyAgentsDir, storyArtifactService);
|
|
325
469
|
narrator.reasoningEffort = 'low';
|
|
326
470
|
narrator.allowSearch = true;
|
|
327
471
|
narrator.promptCacheTTL = 60;
|
|
@@ -329,9 +473,12 @@ let StoryService = class StoryService {
|
|
|
329
473
|
narrator.smallModelName = modelConfig.smallModel;
|
|
330
474
|
narrator.save();
|
|
331
475
|
logger_1.logger.log(`Created narrator agent: ${narrator.agentName}`);
|
|
476
|
+
// Enable story creation flags (will be disabled after plot/profiles complete)
|
|
332
477
|
narrator.disableMarkup = true;
|
|
333
478
|
narrator.disableBalanceCheck = true;
|
|
334
479
|
narrator.save();
|
|
480
|
+
// PHASE 2: Extract initial story framework (scenario and character names/descriptions)
|
|
481
|
+
// Generate ONLY the opening scene (quick LLM call)
|
|
335
482
|
this.progressService.emitProgress(storyInfo.id, 'opening-scene', 'Generating opening scene...');
|
|
336
483
|
const storyFrameworkPromptName = isImport ? 'import_story' : 'create_story';
|
|
337
484
|
const storyFrameworkResponse = await narrator.preparedPrompt(storyFrameworkPromptName, {
|
|
@@ -352,13 +499,16 @@ let StoryService = class StoryService {
|
|
|
352
499
|
importedStoryText = idea;
|
|
353
500
|
}
|
|
354
501
|
logger_1.logger.log(`Story framework extracted: ${otherCharactersInfo.length} other characters`);
|
|
502
|
+
// Build complete characters array including human character
|
|
355
503
|
const characters = [
|
|
504
|
+
// Human character first
|
|
356
505
|
{
|
|
357
506
|
name: userCharacterInfo.name,
|
|
358
507
|
sex: userCharacterInfo.sex,
|
|
359
508
|
description: userCharacterInfo.description,
|
|
360
509
|
isControlledByHuman: true,
|
|
361
510
|
},
|
|
511
|
+
// Then AI characters
|
|
362
512
|
...otherCharactersInfo.map((char) => ({
|
|
363
513
|
name: char.name,
|
|
364
514
|
sex: char.sex,
|
|
@@ -366,24 +516,32 @@ let StoryService = class StoryService {
|
|
|
366
516
|
isControlledByHuman: false,
|
|
367
517
|
})),
|
|
368
518
|
];
|
|
519
|
+
// Update story metadata with extracted information
|
|
369
520
|
storyInfo.scenario = scenario;
|
|
370
521
|
storyInfo.characters = characters;
|
|
371
522
|
storyInfo.aiService = aiServiceName;
|
|
372
523
|
storyInfo.aiModel = aiModelName;
|
|
373
524
|
storyInfo.isImport = isImport;
|
|
374
525
|
storyInfo.skipDetailedPlot = skipDetailedPlot;
|
|
526
|
+
// Save the updated metadata
|
|
375
527
|
this.storyStore.updateStoryMetadata(storyInfo.id, storyInfo);
|
|
528
|
+
// Save the initial creation parameters to a separate file for historical purposes
|
|
376
529
|
this.storyStore.saveStoryCreationParameters(storyInfo.id, idea, userCharacterDesc, otherCharactersDesc);
|
|
530
|
+
// Create user character agent
|
|
377
531
|
const userCharacterName = userCharacterInfo.name || 'Player';
|
|
532
|
+
// Generate nickname (first word of character name)
|
|
378
533
|
const userNickname = userCharacterName.trim().split(/\s+/)[0];
|
|
379
534
|
let userAgent = null;
|
|
380
535
|
try {
|
|
381
|
-
userAgent = this.agentFactory.createAgent(aiServiceName, `${name} - ${userNickname}`,
|
|
536
|
+
userAgent = this.agentFactory.createAgent(aiServiceName, `${name} - ${userNickname}`, // Agent name = "[story title] - [nickname]"
|
|
537
|
+
userNickname, // Agent nickname = character nickname
|
|
538
|
+
userCharacterInfo.description || userCharacterDesc, 'character', aiModelName, storyAgentsDir, storyArtifactService);
|
|
382
539
|
userAgent.isControlledByHuman = true;
|
|
383
540
|
userAgent.ownerRoomId = storyInfo.id;
|
|
384
541
|
userAgent.smallModelName = modelConfig.smallModel;
|
|
385
542
|
userAgent.save();
|
|
386
543
|
logger_1.logger.log(`Created human-controlled character agent: ${userCharacterName}`);
|
|
544
|
+
// Enable story creation flags (will be disabled after character profile completes)
|
|
387
545
|
userAgent.disableMarkup = true;
|
|
388
546
|
userAgent.disableBalanceCheck = true;
|
|
389
547
|
userAgent.save();
|
|
@@ -392,17 +550,23 @@ let StoryService = class StoryService {
|
|
|
392
550
|
logger_1.logger.error('Error creating user character:', error);
|
|
393
551
|
throw error;
|
|
394
552
|
}
|
|
553
|
+
// Create other character agents sequentially
|
|
395
554
|
const characterAgents = [];
|
|
396
555
|
for (let i = 0; i < otherCharactersInfo.length; i++) {
|
|
397
556
|
const charInfo = otherCharactersInfo[i];
|
|
557
|
+
// Generate nickname (first word of character name)
|
|
398
558
|
const characterNickname = charInfo.name.trim().split(/\s+/)[0];
|
|
399
559
|
try {
|
|
400
|
-
const agent = this.agentFactory.createAgent(aiServiceName, `${name} - ${characterNickname}`,
|
|
560
|
+
const agent = this.agentFactory.createAgent(aiServiceName, `${name} - ${characterNickname}`, // Agent name = "[story title] - [nickname]"
|
|
561
|
+
characterNickname, // Agent nickname = character nickname
|
|
562
|
+
charInfo.description, 'character', aiModelName, storyAgentsDir, storyArtifactService);
|
|
401
563
|
agent.promptCacheTTL = 60;
|
|
564
|
+
//agent.maxOutputTokens = 1000; // To limit responses to 4096 chars for Discord
|
|
402
565
|
agent.ownerRoomId = storyInfo.id;
|
|
403
566
|
agent.smallModelName = modelConfig.smallModel;
|
|
404
567
|
agent.save();
|
|
405
568
|
logger_1.logger.log(`Created character agent: ${charInfo.name}`);
|
|
569
|
+
// Enable story creation flags (will be disabled after character profile completes)
|
|
406
570
|
agent.disableMarkup = true;
|
|
407
571
|
agent.disableBalanceCheck = true;
|
|
408
572
|
agent.save();
|
|
@@ -410,21 +574,29 @@ let StoryService = class StoryService {
|
|
|
410
574
|
}
|
|
411
575
|
catch (error) {
|
|
412
576
|
logger_1.logger.error(`Error creating character ${charInfo.name}:`, error);
|
|
577
|
+
// Continue with other characters
|
|
413
578
|
}
|
|
414
579
|
}
|
|
415
580
|
logger_1.logger.log(`Created ${characterAgents.length + (userAgent ? 1 : 0)} character agents`);
|
|
416
|
-
const room = this.roomFactory.createRoom(`Story: ${name}`, scenario, '',
|
|
581
|
+
const room = this.roomFactory.createRoom(`Story: ${name}`, scenario, '', // baseRoomDir
|
|
582
|
+
storyRoomsDir);
|
|
583
|
+
// Add moderator agent FIRST (makes it the first agent in room)
|
|
417
584
|
room.arrive(moderator);
|
|
418
585
|
room.arrive(narrator);
|
|
586
|
+
// Add user's character agent (human-controlled)
|
|
419
587
|
if (userAgent) {
|
|
420
588
|
room.arrive(userAgent);
|
|
421
589
|
}
|
|
590
|
+
// Add all AI character agents to the room
|
|
422
591
|
for (const characterAgent of characterAgents) {
|
|
423
592
|
room.arrive(characterAgent);
|
|
424
593
|
}
|
|
425
594
|
room.setRoomLeader(narrator.agentNickname);
|
|
595
|
+
// Set Narrator as current speaker before generating opening scene
|
|
426
596
|
room.setCurrentSpeaker(narrator.agentNickname);
|
|
597
|
+
// Initialize situation
|
|
427
598
|
room.setSituation(scenario || 'Story beginning');
|
|
599
|
+
// Store the room in story-specific directory
|
|
428
600
|
const roomId = room.saveMetadata();
|
|
429
601
|
room.addRoomMessages([
|
|
430
602
|
new message_1.RoomMessage(`${userCharacterName}'s Backstory`, app_types_1.MessageAction.SYSTEM, userCharacterBackstory),
|
|
@@ -432,16 +604,24 @@ let StoryService = class StoryService {
|
|
|
432
604
|
this.populateStoryHistory(room, openingScene);
|
|
433
605
|
const totalCharacters = (userAgent ? 1 : 0) + characterAgents.length;
|
|
434
606
|
logger_1.logger.log(`Created story room: ${roomId} with moderator, narrator, and ${totalCharacters} character agents`);
|
|
607
|
+
// Set human agent as current speaker - story is ready for their response
|
|
435
608
|
if (userAgent) {
|
|
436
609
|
room.setCurrentSpeaker(userAgent.agentNickname);
|
|
437
610
|
}
|
|
611
|
+
// Set up callbacks for event-driven updates
|
|
438
612
|
room.setOnStateChange('story', () => {
|
|
439
613
|
this.emitStoryStateUpdate(storyInfo.id);
|
|
440
614
|
});
|
|
615
|
+
// Set up error callback
|
|
441
616
|
room.setOnError('story', (error) => {
|
|
442
617
|
this.handleRoomError(storyInfo.id, error);
|
|
443
618
|
});
|
|
619
|
+
// Set up situation update callback (awaited by the room before it
|
|
620
|
+
// routes a narrator message, so an introduced character is created
|
|
621
|
+
// before moderation). latestMessage is the narration that triggered
|
|
622
|
+
// the update, passed through because it isn't logged to the room yet.
|
|
444
623
|
room.setOnSituationUpdate((situation, latestMessage) => this.updateStorySituation(storyInfo.id, situation, latestMessage));
|
|
624
|
+
// Handle moderator-triggered portrait updates
|
|
445
625
|
room.setOnModeratorResponse((message) => {
|
|
446
626
|
const portraitsToUpdate = message.changes?.update_portrait ?? [];
|
|
447
627
|
if (portraitsToUpdate.length) {
|
|
@@ -459,6 +639,7 @@ let StoryService = class StoryService {
|
|
|
459
639
|
}
|
|
460
640
|
this.applyInventoryUpdates(room, message);
|
|
461
641
|
});
|
|
642
|
+
// Update story metadata
|
|
462
643
|
storyInfo.roomId = roomId;
|
|
463
644
|
storyInfo.moderatorAgentId = moderator.id;
|
|
464
645
|
storyInfo.illustratorAgentId = illustrator?.id;
|
|
@@ -471,11 +652,14 @@ let StoryService = class StoryService {
|
|
|
471
652
|
this.storyStore.updateStoryMetadata(storyInfo.id, storyInfo);
|
|
472
653
|
await this.updateStoryCost(storyInfo.id);
|
|
473
654
|
room.ready();
|
|
655
|
+
// Return the story ID immediately and do the heavy work in the background
|
|
656
|
+
// This allows the client to subscribe to SSE before progress events are emitted
|
|
474
657
|
setImmediate(() => {
|
|
475
658
|
this.createStoryAsync(storyInfo.id, name, importedStoryText, isImport, skipDetailedPlot).catch((error) => {
|
|
476
659
|
logger_1.logger.error('Error in async story creation:', error);
|
|
477
660
|
this.progressService.emitProgress(storyInfo.id, 'error', `Error: ${error.message}`);
|
|
478
661
|
this.progressService.cleanup(storyInfo.id);
|
|
662
|
+
// Clean up partial story directory on async error
|
|
479
663
|
this.deleteStory(storyInfo.id).catch((cleanupError) => {
|
|
480
664
|
logger_1.logger.error('Error cleaning up story after async failure:', cleanupError);
|
|
481
665
|
});
|
|
@@ -484,17 +668,26 @@ let StoryService = class StoryService {
|
|
|
484
668
|
return storyInfo;
|
|
485
669
|
}
|
|
486
670
|
catch (error) {
|
|
671
|
+
// Clean up partially created story on error
|
|
487
672
|
logger_1.logger.error('Error creating story:', error);
|
|
488
673
|
this.progressService.emitProgress(storyInfo.id, 'error', `Error: ${error.message}`);
|
|
489
674
|
this.progressService.cleanup(storyInfo.id);
|
|
675
|
+
// Delete the story directory and all its contents
|
|
490
676
|
await this.deleteStory(storyInfo.id);
|
|
677
|
+
// Re-throw the error so the caller knows creation failed
|
|
491
678
|
throw error;
|
|
492
679
|
}
|
|
493
680
|
}
|
|
681
|
+
/**
|
|
682
|
+
* Performs the actual story creation work asynchronously
|
|
683
|
+
* This runs in the background after returning the storyId to the client
|
|
684
|
+
*/
|
|
494
685
|
async createStoryAsync(storyId, name, importedStoryText, isImport, skipDetailedPlot = false) {
|
|
495
686
|
try {
|
|
496
687
|
const room = await this.getStoryRoom(storyId);
|
|
497
688
|
const storyInfo = this.storyStore.getStory(storyId);
|
|
689
|
+
// The story creation dialog is closed and the opening scene is shown while we finish the profiles
|
|
690
|
+
// PHASE 5: Generate detailed profiles and plot in parallel, publishing each immediately
|
|
498
691
|
const plotPromptName = isImport
|
|
499
692
|
? 'import_plot'
|
|
500
693
|
: skipDetailedPlot
|
|
@@ -503,6 +696,7 @@ let StoryService = class StoryService {
|
|
|
503
696
|
const userCharPromptName = isImport ? 'import_user_character' : 'create_user_character';
|
|
504
697
|
const characterPromptName = isImport ? 'import_character' : 'create_character';
|
|
505
698
|
this.progressService.emitProgress(storyInfo.id, 'profiles', 'Generating detailed profiles and plot...');
|
|
699
|
+
// Create all profile generation promises - each agent creates its own profile and publishes immediately
|
|
506
700
|
const narrator = room.getAgents().find((a) => a.agentNickname === 'Narrator');
|
|
507
701
|
const userAgent = room.getAgents().find((a) => a.isControlledByHuman === true);
|
|
508
702
|
const userCharacter = storyInfo.characters.find((c) => c.isControlledByHuman === true);
|
|
@@ -510,6 +704,7 @@ let StoryService = class StoryService {
|
|
|
510
704
|
.filter((c) => c.isControlledByHuman === false)
|
|
511
705
|
.map((c) => `${c.name}: ${c.description}.`)
|
|
512
706
|
.join('\n');
|
|
707
|
+
// Phase 1: plot plan only (opening scene image needs character profiles, generated in Phase 2)
|
|
513
708
|
let plotPlan = '';
|
|
514
709
|
const phase1Results = await Promise.all([
|
|
515
710
|
narrator
|
|
@@ -522,7 +717,7 @@ let StoryService = class StoryService {
|
|
|
522
717
|
.then((response) => {
|
|
523
718
|
if (response) {
|
|
524
719
|
const cleanedPlotPlan = this.extractMarkdownContent(response);
|
|
525
|
-
plotPlan = cleanedPlotPlan;
|
|
720
|
+
plotPlan = cleanedPlotPlan; // Capture for use in Phase 2
|
|
526
721
|
room.publishArtifact('Plot Plan', narrator.agentNickname, cleanedPlotPlan, [
|
|
527
722
|
narrator.agentNickname,
|
|
528
723
|
]);
|
|
@@ -536,7 +731,9 @@ let StoryService = class StoryService {
|
|
|
536
731
|
return { type: 'plot', success: false, error };
|
|
537
732
|
}),
|
|
538
733
|
]);
|
|
734
|
+
// Phase 2: character profiles - run in parallel now that plotPlan is available
|
|
539
735
|
const phase2Promises = [];
|
|
736
|
+
// 1. User character agent generates its own profile and publishes it
|
|
540
737
|
if (userAgent) {
|
|
541
738
|
phase2Promises.push(userAgent
|
|
542
739
|
.preparedPrompt(userCharPromptName, {
|
|
@@ -566,6 +763,7 @@ let StoryService = class StoryService {
|
|
|
566
763
|
return { type: 'userCharacter', success: false, error };
|
|
567
764
|
}));
|
|
568
765
|
}
|
|
766
|
+
// 2. Each AI character agent generates its own profile and publishes it
|
|
569
767
|
for (let i = 0; i < storyInfo.characters.length; i++) {
|
|
570
768
|
const charInfo = storyInfo.characters[i];
|
|
571
769
|
if (charInfo.isControlledByHuman)
|
|
@@ -611,14 +809,18 @@ let StoryService = class StoryService {
|
|
|
611
809
|
}));
|
|
612
810
|
}
|
|
613
811
|
const phase2Results = await Promise.all(phase2Promises);
|
|
812
|
+
// Phase 3: opening scene image - needs character profile artifacts created in Phase 2
|
|
614
813
|
const openingSceneResult = await this.generateOpeningSceneImage(storyInfo, room);
|
|
615
814
|
const profileResults = [...phase1Results, ...phase2Results, openingSceneResult];
|
|
815
|
+
// Check if any profiles failed
|
|
616
816
|
const failedProfiles = profileResults.filter((r) => !r.success);
|
|
617
817
|
if (failedProfiles.length > 0) {
|
|
618
818
|
logger_1.logger.warn(`${failedProfiles.length} profile(s) failed to generate`);
|
|
619
819
|
}
|
|
620
820
|
narrator.allowSearch = false;
|
|
621
|
-
narrator.
|
|
821
|
+
// narrator.maxOutputTokens = 1000; // To limit responses to 4096 chars for Discord (from here on out)
|
|
822
|
+
narrator.save(); // turn off search after creating the plot plan
|
|
823
|
+
// Disable story creation flags now that plot and profiles are complete
|
|
622
824
|
const allAgents = room.getAgents();
|
|
623
825
|
for (const agent of allAgents) {
|
|
624
826
|
if (agent.disableMarkup || agent.disableBalanceCheck) {
|
|
@@ -637,6 +839,7 @@ let StoryService = class StoryService {
|
|
|
637
839
|
this.progressService.emitProgress(storyId, 'error', `Error: ${error.message}`);
|
|
638
840
|
}
|
|
639
841
|
finally {
|
|
842
|
+
// CRITICAL: Always re-enable markup and balance checks, even on error
|
|
640
843
|
try {
|
|
641
844
|
const room = await this.getStoryRoom(storyId);
|
|
642
845
|
if (room) {
|
|
@@ -650,6 +853,7 @@ let StoryService = class StoryService {
|
|
|
650
853
|
}
|
|
651
854
|
}
|
|
652
855
|
generateCharacterPortraits(storyInfo, room) {
|
|
856
|
+
// Generate portraits for all characters (if artist exists)
|
|
653
857
|
if (!storyInfo.artistAgentId) {
|
|
654
858
|
logger_1.logger.log('Skipping character portrait generation: no artist agent');
|
|
655
859
|
return [];
|
|
@@ -680,21 +884,30 @@ let StoryService = class StoryService {
|
|
|
680
884
|
this.progressService.emitProgress(storyInfo.id, 'opening-scene', 'Generating opening scene image...');
|
|
681
885
|
return { type: 'opening-scene', success: true };
|
|
682
886
|
})
|
|
887
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
683
888
|
.catch((_error) => {
|
|
684
889
|
return Promise.resolve({ type: 'opening-scene', success: false });
|
|
685
890
|
});
|
|
686
891
|
}
|
|
892
|
+
/**
|
|
893
|
+
* Validates the structure of an imported story directory
|
|
894
|
+
* @param importDir The directory containing the extracted story files
|
|
895
|
+
* @returns Validation result with errors and metadata if valid
|
|
896
|
+
*/
|
|
687
897
|
async validateImportStructure(importDir) {
|
|
688
898
|
const errors = [];
|
|
899
|
+
// Check metadata.json exists at root
|
|
689
900
|
const metadataPath = path.join(importDir, 'metadata.json');
|
|
690
901
|
if (!fs.existsSync(metadataPath)) {
|
|
691
902
|
errors.push('metadata.json not found at root level');
|
|
692
903
|
return { valid: false, errors };
|
|
693
904
|
}
|
|
905
|
+
// Parse and validate metadata
|
|
694
906
|
let metadata;
|
|
695
907
|
try {
|
|
696
908
|
const metadataContent = fs.readFileSync(metadataPath, 'utf-8');
|
|
697
909
|
metadata = JSON.parse(metadataContent);
|
|
910
|
+
// Validate required fields
|
|
698
911
|
if (!metadata.id || typeof metadata.id !== 'string') {
|
|
699
912
|
errors.push("metadata.json missing or invalid 'id' field");
|
|
700
913
|
}
|
|
@@ -717,11 +930,13 @@ let StoryService = class StoryService {
|
|
|
717
930
|
errors.push(`Failed to parse metadata.json: ${error.message}`);
|
|
718
931
|
return { valid: false, errors };
|
|
719
932
|
}
|
|
933
|
+
// Check agents/ folder exists
|
|
720
934
|
const agentsDir = path.join(importDir, 'agents');
|
|
721
935
|
if (!fs.existsSync(agentsDir)) {
|
|
722
936
|
errors.push('agents/ folder not found');
|
|
723
937
|
}
|
|
724
938
|
else {
|
|
939
|
+
// Collect referenced agent IDs
|
|
725
940
|
const referencedAgentIds = new Set();
|
|
726
941
|
if (metadata.moderatorAgentId)
|
|
727
942
|
referencedAgentIds.add(metadata.moderatorAgentId);
|
|
@@ -731,6 +946,7 @@ let StoryService = class StoryService {
|
|
|
731
946
|
referencedAgentIds.add(metadata.artistAgentId);
|
|
732
947
|
if (metadata.userAgentId)
|
|
733
948
|
referencedAgentIds.add(metadata.userAgentId);
|
|
949
|
+
// Validate agent files exist
|
|
734
950
|
for (const agentId of referencedAgentIds) {
|
|
735
951
|
const agentFile = path.join(agentsDir, `${agentId}.json`);
|
|
736
952
|
if (!fs.existsSync(agentFile)) {
|
|
@@ -738,11 +954,13 @@ let StoryService = class StoryService {
|
|
|
738
954
|
}
|
|
739
955
|
}
|
|
740
956
|
}
|
|
957
|
+
// Check rooms/ folder exists
|
|
741
958
|
const roomsDir = path.join(importDir, 'rooms');
|
|
742
959
|
if (!fs.existsSync(roomsDir)) {
|
|
743
960
|
errors.push('rooms/ folder not found');
|
|
744
961
|
}
|
|
745
962
|
else {
|
|
963
|
+
// Validate exactly 1 room folder
|
|
746
964
|
const roomFolders = fs
|
|
747
965
|
.readdirSync(roomsDir)
|
|
748
966
|
.filter((f) => fs.statSync(path.join(roomsDir, f)).isDirectory());
|
|
@@ -750,16 +968,19 @@ let StoryService = class StoryService {
|
|
|
750
968
|
errors.push(`Expected exactly 1 room folder, found ${roomFolders.length}`);
|
|
751
969
|
}
|
|
752
970
|
else {
|
|
971
|
+
// Validate room folder name matches roomId
|
|
753
972
|
const roomFolderName = roomFolders[0];
|
|
754
973
|
if (roomFolderName !== metadata.roomId) {
|
|
755
974
|
errors.push(`Room folder name '${roomFolderName}' doesn't match roomId '${metadata.roomId}' in metadata`);
|
|
756
975
|
}
|
|
976
|
+
// Check room metadata.json exists
|
|
757
977
|
const roomMetadataPath = path.join(roomsDir, roomFolderName, 'metadata.json');
|
|
758
978
|
if (!fs.existsSync(roomMetadataPath)) {
|
|
759
979
|
errors.push(`Room metadata.json not found at rooms/${roomFolderName}/metadata.json`);
|
|
760
980
|
}
|
|
761
981
|
}
|
|
762
982
|
}
|
|
983
|
+
// Check story_creation.json exists (warn if missing, non-fatal)
|
|
763
984
|
const storyCreationPath = path.join(importDir, 'story_creation.json');
|
|
764
985
|
if (!fs.existsSync(storyCreationPath)) {
|
|
765
986
|
logger_1.logger.warn('story_creation.json not found (non-fatal)');
|
|
@@ -770,32 +991,41 @@ let StoryService = class StoryService {
|
|
|
770
991
|
metadata: errors.length === 0 ? metadata : undefined,
|
|
771
992
|
};
|
|
772
993
|
}
|
|
994
|
+
/**
|
|
995
|
+
* Extracts a zip file to a target directory with security checks
|
|
996
|
+
* @param zipBuffer The zip file buffer
|
|
997
|
+
* @param targetDir The directory to extract to
|
|
998
|
+
*/
|
|
773
999
|
async extractZip(zipBuffer, targetDir) {
|
|
774
1000
|
return new Promise((resolve, reject) => {
|
|
775
1001
|
let totalSize = 0;
|
|
776
|
-
const maxSize = 100 * 1024 * 1024;
|
|
1002
|
+
const maxSize = 100 * 1024 * 1024; // 100MB limit
|
|
777
1003
|
yauzl.fromBuffer(zipBuffer, { lazyEntries: true }, (err, zipfile) => {
|
|
778
1004
|
if (err) {
|
|
779
1005
|
return reject(new Error(`Failed to read zip file: ${err.message}`));
|
|
780
1006
|
}
|
|
781
1007
|
zipfile.readEntry();
|
|
782
1008
|
zipfile.on('entry', (entry) => {
|
|
1009
|
+
// Security: Check for path traversal
|
|
783
1010
|
const entryPath = entry.fileName;
|
|
784
1011
|
if (entryPath.includes('..') || path.isAbsolute(entryPath)) {
|
|
785
1012
|
zipfile.close();
|
|
786
1013
|
return reject(new Error(`Security: Invalid path in zip: ${entryPath}`));
|
|
787
1014
|
}
|
|
788
1015
|
const fullPath = path.join(targetDir, entryPath);
|
|
1016
|
+
// Directory entry
|
|
789
1017
|
if (/\/$/.test(entryPath)) {
|
|
790
1018
|
fs.mkdirSync(fullPath, { recursive: true });
|
|
791
1019
|
zipfile.readEntry();
|
|
792
1020
|
}
|
|
793
1021
|
else {
|
|
1022
|
+
// File entry
|
|
794
1023
|
zipfile.openReadStream(entry, (err, readStream) => {
|
|
795
1024
|
if (err) {
|
|
796
1025
|
zipfile.close();
|
|
797
1026
|
return reject(new Error(`Failed to read entry ${entryPath}: ${err.message}`));
|
|
798
1027
|
}
|
|
1028
|
+
// Ensure parent directory exists
|
|
799
1029
|
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
800
1030
|
const writeStream = fs.createWriteStream(fullPath);
|
|
801
1031
|
readStream.on('data', (chunk) => {
|
|
@@ -826,35 +1056,59 @@ let StoryService = class StoryService {
|
|
|
826
1056
|
});
|
|
827
1057
|
});
|
|
828
1058
|
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Imports a story from a zip file buffer
|
|
1061
|
+
* @param zipBuffer The zip file buffer to import
|
|
1062
|
+
* @returns The imported story metadata
|
|
1063
|
+
*/
|
|
829
1064
|
async importStoryFromZip(zipBuffer) {
|
|
830
1065
|
const storiesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
|
|
831
1066
|
const importDir = path.join(storiesDir, 'import');
|
|
832
1067
|
try {
|
|
1068
|
+
// 1. Clean import directory
|
|
833
1069
|
if (fs.existsSync(importDir)) {
|
|
834
1070
|
fs.rmSync(importDir, { recursive: true, force: true });
|
|
835
1071
|
}
|
|
836
1072
|
fs.mkdirSync(importDir, { recursive: true });
|
|
1073
|
+
// 2. Extract zip to import directory
|
|
837
1074
|
await this.extractZip(zipBuffer, importDir);
|
|
1075
|
+
// 3. Validate structure
|
|
838
1076
|
const validationResult = await this.validateImportStructure(importDir);
|
|
839
1077
|
if (!validationResult.valid) {
|
|
840
1078
|
throw new Error(`Invalid story structure:\n${validationResult.errors.join('\n')}`);
|
|
841
1079
|
}
|
|
842
1080
|
const metadata = validationResult.metadata;
|
|
1081
|
+
// 4. Check ID collision
|
|
843
1082
|
const finalStoryPath = path.join(storiesDir, metadata.id);
|
|
844
1083
|
if (fs.existsSync(finalStoryPath)) {
|
|
845
1084
|
throw new Error(`Story with ID ${metadata.id} already exists (name: '${metadata.name}')`);
|
|
846
1085
|
}
|
|
1086
|
+
// 5. Move to final location
|
|
847
1087
|
fs.renameSync(importDir, finalStoryPath);
|
|
848
1088
|
logger_1.logger.log(`Successfully imported story: ${metadata.name} (${metadata.id})`);
|
|
849
1089
|
return metadata;
|
|
850
1090
|
}
|
|
851
1091
|
catch (error) {
|
|
1092
|
+
// Cleanup on failure
|
|
852
1093
|
if (fs.existsSync(importDir)) {
|
|
853
1094
|
fs.rmSync(importDir, { recursive: true, force: true });
|
|
854
1095
|
}
|
|
855
1096
|
throw error;
|
|
856
1097
|
}
|
|
857
1098
|
}
|
|
1099
|
+
/**
|
|
1100
|
+
* Populates agent conversation histories and room messages with imported story text
|
|
1101
|
+
*
|
|
1102
|
+
* @param room The story room
|
|
1103
|
+
* @param storyText The imported story text
|
|
1104
|
+
* @param audience Nicknames of the characters present for `storyText`. Characters
|
|
1105
|
+
* outside it do not hear it, which is how a chapter can open on a scene only some
|
|
1106
|
+
* of the cast are in. Non-character agents (narrator, moderator, illustrator,
|
|
1107
|
+
* artist) are always seeded - they work on the whole story, not a scene of it -
|
|
1108
|
+
* as is the player's own character, who is reading the text on screen either way.
|
|
1109
|
+
* Omit to seed everyone, which is right when the text opens the story and the
|
|
1110
|
+
* whole cast is new to it.
|
|
1111
|
+
*/
|
|
858
1112
|
populateStoryHistory(room, storyText, audience) {
|
|
859
1113
|
try {
|
|
860
1114
|
const storyMessage = {
|
|
@@ -880,19 +1134,34 @@ let StoryService = class StoryService {
|
|
|
880
1134
|
throw error;
|
|
881
1135
|
}
|
|
882
1136
|
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Sends a message to the story dialog and gets an AI response
|
|
1139
|
+
* @param storyId The story ID
|
|
1140
|
+
* @param message The user's message
|
|
1141
|
+
* @param action The action type ('say' or 'do')
|
|
1142
|
+
* @returns The AI assistant's response
|
|
1143
|
+
*/
|
|
1144
|
+
/**
|
|
1145
|
+
* Gets the current state of a story including room messages and pending status
|
|
1146
|
+
* @param storyId The story ID
|
|
1147
|
+
* @returns Story state with room messages and pending status
|
|
1148
|
+
*/
|
|
883
1149
|
async getStoryState(storyId) {
|
|
884
1150
|
const story = await this.ensureStoryLoaded(storyId);
|
|
885
1151
|
if (!story) {
|
|
886
1152
|
throw new Error('Story not found');
|
|
887
1153
|
}
|
|
1154
|
+
// Get the room
|
|
888
1155
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
889
1156
|
if (!room) {
|
|
890
1157
|
throw new Error('Story room not found');
|
|
891
1158
|
}
|
|
1159
|
+
// Find the human-controlled agent
|
|
892
1160
|
const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
|
|
893
1161
|
if (!humanAgent) {
|
|
894
1162
|
throw new Error('No human-controlled agent found in story');
|
|
895
1163
|
}
|
|
1164
|
+
// Get room messages to determine the latest index
|
|
896
1165
|
const roomMessages = room.getLatestRoomMessages(0, true);
|
|
897
1166
|
const latestMessageIndex = roomMessages.length > 0 ? roomMessages[roomMessages.length - 1].index : -1;
|
|
898
1167
|
let latestRoomMessage = null;
|
|
@@ -912,9 +1181,15 @@ let StoryService = class StoryService {
|
|
|
912
1181
|
};
|
|
913
1182
|
return storyState;
|
|
914
1183
|
}
|
|
1184
|
+
/**
|
|
1185
|
+
* Lists all characters in the story (excluding narrator)
|
|
1186
|
+
* @param storyId The story ID
|
|
1187
|
+
* @returns Array of character info
|
|
1188
|
+
*/
|
|
915
1189
|
async listCharacters(storyId) {
|
|
916
1190
|
try {
|
|
917
1191
|
const room = await this.getStoryRoom(storyId);
|
|
1192
|
+
// Get all character agents
|
|
918
1193
|
const characters = room
|
|
919
1194
|
.getAgents()
|
|
920
1195
|
.filter((agent) => agent.promptFolder === 'character');
|
|
@@ -929,9 +1204,16 @@ let StoryService = class StoryService {
|
|
|
929
1204
|
return [];
|
|
930
1205
|
}
|
|
931
1206
|
}
|
|
1207
|
+
/**
|
|
1208
|
+
* Gets a character profile artifact content
|
|
1209
|
+
* @param storyId The story ID
|
|
1210
|
+
* @param characterName The character name
|
|
1211
|
+
* @returns The character profile markdown content
|
|
1212
|
+
*/
|
|
932
1213
|
async getCharacter(storyId, characterName) {
|
|
933
1214
|
try {
|
|
934
1215
|
const room = await this.getStoryRoom(storyId);
|
|
1216
|
+
// Find the character profile artifact
|
|
935
1217
|
const artifactName = `Character Profile - ${characterName}`;
|
|
936
1218
|
const artifacts = room.getArtifacts();
|
|
937
1219
|
const profileArtifact = artifacts.find((a) => a.name === artifactName);
|
|
@@ -939,11 +1221,13 @@ let StoryService = class StoryService {
|
|
|
939
1221
|
return null;
|
|
940
1222
|
}
|
|
941
1223
|
let content = profileArtifact.body;
|
|
1224
|
+
// Find the character portrait artifact and prepend image markdown
|
|
942
1225
|
const portraitName = `Portrait - ${characterName}`;
|
|
943
1226
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
944
1227
|
const allArtifacts = storyArtifactService.listArtifacts();
|
|
945
1228
|
const portraitArtifact = allArtifacts.find((a) => a.name === portraitName);
|
|
946
1229
|
if (portraitArtifact) {
|
|
1230
|
+
// Prepend image markdown to profile content
|
|
947
1231
|
const imgUrl = `/api/stories/${storyId}/artifacts/${portraitArtifact.artifactId}`;
|
|
948
1232
|
const imageMarkdown = `\n\n`;
|
|
949
1233
|
content = imageMarkdown + content;
|
|
@@ -955,10 +1239,23 @@ let StoryService = class StoryService {
|
|
|
955
1239
|
throw new Error(`Error getting character: ${error.message}`);
|
|
956
1240
|
}
|
|
957
1241
|
}
|
|
1242
|
+
/**
|
|
1243
|
+
* Saves a character profile (convenience wrapper for PUBLISH action)
|
|
1244
|
+
* @param storyId The story ID
|
|
1245
|
+
* @param characterName The character name
|
|
1246
|
+
* @param content The updated character profile markdown
|
|
1247
|
+
* @returns Success status
|
|
1248
|
+
*/
|
|
958
1249
|
saveCharacter(storyId, characterName, content) {
|
|
959
1250
|
const artifactName = `Character Profile - ${characterName}`;
|
|
960
1251
|
this.publishArtifact(storyId, artifactName, characterName, content, []);
|
|
961
1252
|
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Gets a character's inventory, stored in the owning agent's private context.
|
|
1255
|
+
* @param storyId The story ID
|
|
1256
|
+
* @param characterName The character name
|
|
1257
|
+
* @returns The inventory markdown content, or null if no inventory exists yet
|
|
1258
|
+
*/
|
|
962
1259
|
async getCharacterInventory(storyId, characterName) {
|
|
963
1260
|
try {
|
|
964
1261
|
const room = await this.getStoryRoom(storyId);
|
|
@@ -970,12 +1267,25 @@ let StoryService = class StoryService {
|
|
|
970
1267
|
throw new Error(`Error getting character inventory: ${error.message}`);
|
|
971
1268
|
}
|
|
972
1269
|
}
|
|
1270
|
+
/**
|
|
1271
|
+
* Saves a character's inventory to the owning agent's private context. The
|
|
1272
|
+
* inventory stays visible only to the owning character and the Moderator.
|
|
1273
|
+
* @param storyId The story ID
|
|
1274
|
+
* @param characterName The character name
|
|
1275
|
+
* @param content The updated inventory markdown
|
|
1276
|
+
*/
|
|
973
1277
|
async saveCharacterInventory(storyId, characterName, content) {
|
|
974
1278
|
const room = await this.getStoryRoom(storyId);
|
|
975
1279
|
this.storeCharacterInventory(room, characterName, content);
|
|
976
1280
|
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Gets the plot plan artifact content
|
|
1283
|
+
* @param storyId The story ID
|
|
1284
|
+
* @returns The plot plan markdown content
|
|
1285
|
+
*/
|
|
977
1286
|
async getPlotPlan(storyId) {
|
|
978
1287
|
const room = await this.getStoryRoom(storyId);
|
|
1288
|
+
// Find the plot plan artifact
|
|
979
1289
|
const artifacts = room.getArtifacts();
|
|
980
1290
|
const artifact = artifacts.find((a) => a.name === 'Plot Plan');
|
|
981
1291
|
if (!artifact) {
|
|
@@ -983,52 +1293,82 @@ let StoryService = class StoryService {
|
|
|
983
1293
|
}
|
|
984
1294
|
return artifact.body;
|
|
985
1295
|
}
|
|
1296
|
+
/**
|
|
1297
|
+
* Gets the formatted conversation history for an agent in the story
|
|
1298
|
+
* @param storyId The story ID
|
|
1299
|
+
* @param agentId The agent ID
|
|
1300
|
+
* @returns JSON string of the agent's conversation history
|
|
1301
|
+
*/
|
|
986
1302
|
async getAgentHistory(storyId, agentId) {
|
|
987
1303
|
const room = await this.getStoryRoom(storyId);
|
|
1304
|
+
// Find the agent by ID
|
|
988
1305
|
const agent = room.getAgents().find((a) => a.id === agentId);
|
|
989
1306
|
if (!agent) {
|
|
990
1307
|
throw new Error(`Agent not found: ${agentId}`);
|
|
991
1308
|
}
|
|
1309
|
+
// Return the agent's history as JSON string
|
|
1310
|
+
// History is already in the format [{role, content}, ...]
|
|
992
1311
|
return JSON.stringify(agent.history || []);
|
|
993
1312
|
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Saves the plot plan (convenience wrapper for PUBLISH action)
|
|
1315
|
+
* @param storyId The story ID
|
|
1316
|
+
* @param content The updated plot plan markdown
|
|
1317
|
+
* @returns Success status
|
|
1318
|
+
*/
|
|
994
1319
|
async savePlotPlan(storyId, content) {
|
|
995
1320
|
const room = await this.getStoryRoom(storyId);
|
|
996
1321
|
room.publishArtifact('Plot Plan', 'Narrator', content, []);
|
|
997
1322
|
}
|
|
998
1323
|
async publishArtifact(storyId, name, creator, body, viewers) {
|
|
1324
|
+
// Get the story metadata
|
|
999
1325
|
const room = await this.getStoryRoom(storyId);
|
|
1000
1326
|
room.publishArtifact(name, creator, body, viewers);
|
|
1001
1327
|
}
|
|
1002
1328
|
async respondToStory(storyId, content) {
|
|
1329
|
+
// Get the story metadata
|
|
1003
1330
|
const room = await this.getStoryRoom(storyId);
|
|
1004
1331
|
const trimmedContent = content?.trim();
|
|
1005
1332
|
const isPassing = trimmedContent?.toUpperCase() === 'PASS';
|
|
1006
1333
|
if (!trimmedContent && !isPassing) {
|
|
1007
1334
|
throw new Error('No message content provided');
|
|
1008
1335
|
}
|
|
1336
|
+
// Increment turn number
|
|
1009
1337
|
const story = this.storyStore.getStory(storyId);
|
|
1010
1338
|
if (story) {
|
|
1011
1339
|
story.turnNumber = (story.turnNumber || 0) + 1;
|
|
1012
1340
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1013
1341
|
}
|
|
1342
|
+
// Find the human-controlled agent
|
|
1014
1343
|
const humanAgent = room.getAgents().find((agent) => agent.isControlledByHuman);
|
|
1015
1344
|
if (!humanAgent) {
|
|
1016
1345
|
throw new Error('No human-controlled agent found in story');
|
|
1017
1346
|
}
|
|
1018
1347
|
const responseMessage = new message_1.RoomMessage(humanAgent.agentNickname, app_types_1.MessageAction.MODERATE, content, [], null);
|
|
1348
|
+
// Add the message to the room's pending queue
|
|
1349
|
+
// This triggers processing whether there was an active callback or not
|
|
1019
1350
|
room.addPendingMessage(responseMessage);
|
|
1020
1351
|
}
|
|
1021
1352
|
async interruptStory(storyId) {
|
|
1022
1353
|
const room = await this.getStoryRoom(storyId);
|
|
1023
1354
|
room.interrupt();
|
|
1024
1355
|
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Introduces a new character into an existing story
|
|
1358
|
+
* Creates character agent, updates profile, and notifies narrator
|
|
1359
|
+
* @param latestNarration When introduced by the narrator, the narration
|
|
1360
|
+
* prose that introduced this character. It isn't logged to the room yet,
|
|
1361
|
+
* so it's threaded in to seed the new character's first profile.
|
|
1362
|
+
*/
|
|
1025
1363
|
async introduceCharacter(storyId, characterName, characterDescription, storyModel, fromNarratorSuggestion, latestNarration) {
|
|
1364
|
+
// Load story and room
|
|
1026
1365
|
const room = await this.getStoryRoom(storyId);
|
|
1027
1366
|
if (!characterName)
|
|
1028
1367
|
throw new Error('No character name provided');
|
|
1029
1368
|
if (characterName === 'Narrator' || characterName === 'Moderator') {
|
|
1030
1369
|
throw new Error('Cannot introduce a character named Narrator or Moderator');
|
|
1031
1370
|
}
|
|
1371
|
+
// Check for duplicate name (use nickname for comparison)
|
|
1032
1372
|
const existingAgent = room.getAgents().find((agent) => {
|
|
1033
1373
|
const agentFirstNickname = agent.agentNickname.split(/\s+/)[0];
|
|
1034
1374
|
return agent.agentNickname === characterName || agentFirstNickname === characterName;
|
|
@@ -1043,11 +1383,17 @@ let StoryService = class StoryService {
|
|
|
1043
1383
|
? this.getStoryModelConfig(storyModel)
|
|
1044
1384
|
: null;
|
|
1045
1385
|
if (explicitConfig) {
|
|
1386
|
+
// An explicit model was requested for this introduction.
|
|
1046
1387
|
aiServiceName = explicitConfig.service;
|
|
1047
1388
|
aiModelName = explicitConfig.model;
|
|
1048
1389
|
aiSmallModelName = explicitConfig.smallModel;
|
|
1049
1390
|
}
|
|
1050
1391
|
else {
|
|
1392
|
+
// No explicit model: inherit the story's model from an existing cast member
|
|
1393
|
+
// (a character, or the narrator) so a mid-story introduction matches the
|
|
1394
|
+
// rest of the cast. Falling back to DEFAULT_STORY_MODEL here was wrong — it
|
|
1395
|
+
// is usually a smaller/cheaper model than the one the story was created with,
|
|
1396
|
+
// so narrator-introduced characters ended up running on the wrong model.
|
|
1051
1397
|
const template = room.getAgents().find((a) => a.promptFolder === 'character') ??
|
|
1052
1398
|
room.getAgents().find((a) => a.promptFolder === 'narrator');
|
|
1053
1399
|
if (template) {
|
|
@@ -1056,6 +1402,7 @@ let StoryService = class StoryService {
|
|
|
1056
1402
|
aiSmallModelName = template.smallModelName;
|
|
1057
1403
|
}
|
|
1058
1404
|
else {
|
|
1405
|
+
// Last resort (e.g., no cast loaded): use the default story model.
|
|
1059
1406
|
const fallback = this.getStoryModelConfig(process.env.DEFAULT_STORY_MODEL);
|
|
1060
1407
|
if (fallback) {
|
|
1061
1408
|
aiServiceName = fallback.service;
|
|
@@ -1067,21 +1414,35 @@ let StoryService = class StoryService {
|
|
|
1067
1414
|
if (!aiServiceName || !aiModelName) {
|
|
1068
1415
|
throw new Error('Invalid story model provided');
|
|
1069
1416
|
}
|
|
1417
|
+
// Nullify current speaker while introducing the character
|
|
1070
1418
|
room.setCurrentSpeaker(null);
|
|
1419
|
+
// Create character agent
|
|
1071
1420
|
const { agentsDir: storyAgentsDir } = this.getStoryStorageDirs(storyId);
|
|
1072
1421
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1422
|
+
// Get story title
|
|
1073
1423
|
const story = this.storyStore.getStory(storyId);
|
|
1074
1424
|
const storyTitle = story.name;
|
|
1425
|
+
// Generate nickname (first word of character name)
|
|
1075
1426
|
const characterNickname = characterName.trim().split(/\s+/)[0];
|
|
1076
|
-
const characterAgent = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - ${characterNickname}`,
|
|
1427
|
+
const characterAgent = this.agentFactory.createAgent(aiServiceName, `${storyTitle} - ${characterNickname}`, // Agent name = "[story title] - [nickname]"
|
|
1428
|
+
characterNickname, // Agent nickname = character nickname
|
|
1429
|
+
characterDescription, 'character', // promptFolder for character agents
|
|
1430
|
+
aiModelName, storyAgentsDir, storyArtifactService);
|
|
1077
1431
|
characterAgent.promptCacheTTL = 60;
|
|
1078
1432
|
characterAgent.smallModelName = aiSmallModelName;
|
|
1079
1433
|
characterAgent.save();
|
|
1434
|
+
// Add agent to room
|
|
1080
1435
|
room.arrive(characterAgent);
|
|
1436
|
+
// Retrieve plot plan so the new character's profile is informed by it
|
|
1081
1437
|
const introducedCharArtifacts = room.getArtifacts();
|
|
1082
1438
|
const introducedCharPlotPlanArtifact = introducedCharArtifacts.find((a) => a.name === 'Plot Plan');
|
|
1083
1439
|
const introducedCharPlotPlan = introducedCharPlotPlanArtifact?.body || '';
|
|
1440
|
+
// Update character profile - this sets characterAgent.description from
|
|
1441
|
+
// the AI-generated profile, which is what we want to persist below.
|
|
1084
1442
|
await this.updateCharacterProfiles(room, [characterAgent], introducedCharPlotPlan, latestNarration);
|
|
1443
|
+
// Persist the new character in story metadata now that the profile has
|
|
1444
|
+
// been generated (the runtime source of truth is the room's agents, but
|
|
1445
|
+
// metadata is used for markdown export, plot-plan prompts, etc.).
|
|
1085
1446
|
if (!story.characters) {
|
|
1086
1447
|
story.characters = [];
|
|
1087
1448
|
}
|
|
@@ -1092,11 +1453,19 @@ let StoryService = class StoryService {
|
|
|
1092
1453
|
isControlledByHuman: false,
|
|
1093
1454
|
});
|
|
1094
1455
|
}
|
|
1456
|
+
// Clear any pending narrator suggestion for this character
|
|
1095
1457
|
if (story.pendingSuggestion?.type === 'suggest-introduce-character' &&
|
|
1096
1458
|
story.pendingSuggestion.characterName === characterName) {
|
|
1097
1459
|
story.pendingSuggestion = undefined;
|
|
1098
1460
|
}
|
|
1099
1461
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1462
|
+
// Generate portrait for newly introduced character — but only as a
|
|
1463
|
+
// fallback. updateCharacterProfiles above already regenerates portraits
|
|
1464
|
+
// for characters whose profile changed, and a brand-new character's
|
|
1465
|
+
// profile always changes, so it normally produces the portrait here.
|
|
1466
|
+
// Generating again would create a second image (and double the cost).
|
|
1467
|
+
// Only generate from scratch if that path didn't leave a portrait
|
|
1468
|
+
// (e.g. the profile came back empty and the agent was filtered out).
|
|
1100
1469
|
const portraitName = `Portrait - ${characterAgent.agentNickname}`;
|
|
1101
1470
|
const portraitAlreadyExists = this.getStoryArtifactService(storyId)
|
|
1102
1471
|
.listArtifacts()
|
|
@@ -1110,16 +1479,27 @@ let StoryService = class StoryService {
|
|
|
1110
1479
|
}
|
|
1111
1480
|
catch (error) {
|
|
1112
1481
|
logger_1.logger.error(`Error generating portrait for introduced character ${characterName}:`, error);
|
|
1482
|
+
// Continue even if portrait generation fails
|
|
1113
1483
|
}
|
|
1114
1484
|
}
|
|
1485
|
+
// Only send INTRODUCE message if NOT from narrator suggestion
|
|
1115
1486
|
if (!fromNarratorSuggestion) {
|
|
1487
|
+
// Send instruction to narrator - processing will happen naturally
|
|
1488
|
+
// The moderator will route to narrator, narrator will respond, then it's the human's turn
|
|
1116
1489
|
room.addPendingMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.MODERATE, `INTRODUCE ${characterName}`));
|
|
1117
1490
|
}
|
|
1118
1491
|
else {
|
|
1119
1492
|
logger_1.logger.log(`Skipping INTRODUCE message for ${characterName} (already introduced by narrator)`);
|
|
1493
|
+
// The narrator already introduced this character, so no MODERATE message is sent.
|
|
1494
|
+
// We must restore currentSpeaker (nullified above) so the human can respond.
|
|
1120
1495
|
room.setCurrentSpeaker(room.getHumanAgentName());
|
|
1121
1496
|
}
|
|
1122
1497
|
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Records that user declined to introduce a character
|
|
1500
|
+
* @param storyId The story ID
|
|
1501
|
+
* @param characterName The character name that was declined
|
|
1502
|
+
*/
|
|
1123
1503
|
async declineCharacter(storyId, characterName) {
|
|
1124
1504
|
const story = this.storyStore.getStory(storyId);
|
|
1125
1505
|
if (!story) {
|
|
@@ -1138,10 +1518,17 @@ let StoryService = class StoryService {
|
|
|
1138
1518
|
}
|
|
1139
1519
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1140
1520
|
}
|
|
1521
|
+
/**
|
|
1522
|
+
* Deletes a character agent from a story but preserves the character profile artifact
|
|
1523
|
+
* @param storyId The story ID
|
|
1524
|
+
* @param characterName The character name to delete
|
|
1525
|
+
* @returns Success status and message
|
|
1526
|
+
*/
|
|
1141
1527
|
async deleteCharacter(storyId, characterName) {
|
|
1142
1528
|
let room;
|
|
1143
1529
|
try {
|
|
1144
1530
|
room = await this.getStoryRoom(storyId);
|
|
1531
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
1145
1532
|
}
|
|
1146
1533
|
catch (_error) {
|
|
1147
1534
|
throw new errors_1.NotFoundError(`Story not found: ${storyId}`);
|
|
@@ -1149,20 +1536,27 @@ let StoryService = class StoryService {
|
|
|
1149
1536
|
if (!room) {
|
|
1150
1537
|
throw new errors_1.NotFoundError(`Story not found: ${storyId}`);
|
|
1151
1538
|
}
|
|
1539
|
+
// Find the agent
|
|
1152
1540
|
const agent = room.getAgents().find((a) => a.agentNickname === characterName);
|
|
1153
1541
|
if (!agent) {
|
|
1154
1542
|
throw new errors_1.NotFoundError(`Character agent not found: ${characterName}`);
|
|
1155
1543
|
}
|
|
1544
|
+
// Prevent deletion of system agents
|
|
1156
1545
|
if (characterName === 'Narrator' ||
|
|
1157
1546
|
characterName === 'Moderator' ||
|
|
1158
1547
|
agent.isControlledByHuman) {
|
|
1159
1548
|
throw new errors_1.OperationFailedError(`Cannot delete ${characterName} - system agents and human-controlled characters cannot be removed`);
|
|
1160
1549
|
}
|
|
1550
|
+
// Remove agent from room
|
|
1161
1551
|
const agents = room.getAgents();
|
|
1162
1552
|
const filteredAgents = agents.filter((a) => a.agentNickname !== characterName);
|
|
1163
1553
|
room.setAgents(filteredAgents);
|
|
1164
1554
|
room.saveMetadata();
|
|
1555
|
+
// Delete the agent file (removeAgent deletes from store and file)
|
|
1165
1556
|
this.agentStore.removeAgent(agent.id);
|
|
1557
|
+
// Remove from story metadata characters array. Match on both full name
|
|
1558
|
+
// and nickname since introduced characters store full name while
|
|
1559
|
+
// deletion is keyed by nickname.
|
|
1166
1560
|
const story = this.storyStore.getStory(storyId);
|
|
1167
1561
|
if (story?.characters) {
|
|
1168
1562
|
const filtered = story.characters.filter((c) => {
|
|
@@ -1174,14 +1568,19 @@ let StoryService = class StoryService {
|
|
|
1174
1568
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1175
1569
|
}
|
|
1176
1570
|
}
|
|
1571
|
+
// Note: We do NOT delete the character profile artifact - it's preserved
|
|
1572
|
+
// The character profile artifact remains in the artifacts and can be referenced
|
|
1177
1573
|
}
|
|
1178
1574
|
async deleteStory(storyId) {
|
|
1179
1575
|
logger_1.logger.log(`Deleting story ${storyId}...`);
|
|
1576
|
+
// Get story info (may not exist if story creation failed early)
|
|
1180
1577
|
const story = this.storyStore.getStory(storyId);
|
|
1578
|
+
// Try to clean up the room and its agents if they exist
|
|
1181
1579
|
if (story?.roomId) {
|
|
1182
1580
|
try {
|
|
1183
1581
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1184
1582
|
if (room) {
|
|
1583
|
+
// Delete all agents in the room
|
|
1185
1584
|
const agents = room.getAgents();
|
|
1186
1585
|
await Promise.all(agents.map(async (agent) => {
|
|
1187
1586
|
try {
|
|
@@ -1205,6 +1604,7 @@ let StoryService = class StoryService {
|
|
|
1205
1604
|
else {
|
|
1206
1605
|
logger_1.logger.warn(`Story ${storyId} has no roomId, skipping room cleanup`);
|
|
1207
1606
|
}
|
|
1607
|
+
// Try to clean up artist and illustrator agents if they exist
|
|
1208
1608
|
if (story?.artistAgentId) {
|
|
1209
1609
|
try {
|
|
1210
1610
|
this.agentStore.removeAgent(story.artistAgentId);
|
|
@@ -1223,6 +1623,7 @@ let StoryService = class StoryService {
|
|
|
1223
1623
|
logger_1.logger.warn(`Error deleting illustrator agent ${story.illustratorAgentId}:`, error);
|
|
1224
1624
|
}
|
|
1225
1625
|
}
|
|
1626
|
+
// Always clean up progress and message emitters
|
|
1226
1627
|
try {
|
|
1227
1628
|
this.cleanupProgressEmitter(storyId);
|
|
1228
1629
|
this.cleanupMessageEmitter(storyId);
|
|
@@ -1230,6 +1631,7 @@ let StoryService = class StoryService {
|
|
|
1230
1631
|
catch (error) {
|
|
1231
1632
|
logger_1.logger.warn(`Error cleaning up emitters for story ${storyId}:`, error);
|
|
1232
1633
|
}
|
|
1634
|
+
// Always try to remove the story from the store
|
|
1233
1635
|
try {
|
|
1234
1636
|
this.storyStore.removeStory(storyId);
|
|
1235
1637
|
logger_1.logger.log(`Deleted story ${storyId} from store`);
|
|
@@ -1239,6 +1641,12 @@ let StoryService = class StoryService {
|
|
|
1239
1641
|
}
|
|
1240
1642
|
logger_1.logger.log(`Story ${storyId} deletion complete`);
|
|
1241
1643
|
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Helper function to disable markup and balance checks for story agents
|
|
1646
|
+
* Used during story creation, chapter progression, and compaction
|
|
1647
|
+
* @param agents Array of agents to disable flags for
|
|
1648
|
+
* @param reason Optional reason for logging (e.g., "story creation", "chapter progression")
|
|
1649
|
+
*/
|
|
1242
1650
|
disableStoryAgentFlags(agents, reason = 'operation') {
|
|
1243
1651
|
for (const agent of agents) {
|
|
1244
1652
|
if (agent && !agent.disableMarkup && !agent.disableBalanceCheck) {
|
|
@@ -1249,6 +1657,12 @@ let StoryService = class StoryService {
|
|
|
1249
1657
|
}
|
|
1250
1658
|
}
|
|
1251
1659
|
}
|
|
1660
|
+
/**
|
|
1661
|
+
* Helper function to re-enable markup and balance checks for story agents
|
|
1662
|
+
* Used after story creation, chapter progression, and compaction complete
|
|
1663
|
+
* @param agents Array of agents to re-enable flags for
|
|
1664
|
+
* @param reason Optional reason for logging (e.g., "story creation", "chapter progression")
|
|
1665
|
+
*/
|
|
1252
1666
|
enableStoryAgentFlags(agents, reason = 'operation') {
|
|
1253
1667
|
for (const agent of agents) {
|
|
1254
1668
|
if (agent && (agent.disableMarkup || agent.disableBalanceCheck)) {
|
|
@@ -1259,17 +1673,27 @@ let StoryService = class StoryService {
|
|
|
1259
1673
|
}
|
|
1260
1674
|
}
|
|
1261
1675
|
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Compacts the conversation history for all agents in a story
|
|
1678
|
+
* Uses story-specific prompts tailored for narrator (plot events) and characters (relationships)
|
|
1679
|
+
* Processes all agents in parallel for better performance
|
|
1680
|
+
* @param storyId The story ID
|
|
1681
|
+
* @returns Success status, message, and details about compaction
|
|
1682
|
+
*/
|
|
1262
1683
|
async compactStory(storyId) {
|
|
1263
1684
|
let agents = [];
|
|
1264
1685
|
try {
|
|
1265
1686
|
const room = await this.getStoryRoom(storyId);
|
|
1687
|
+
// Get all agents in the room
|
|
1266
1688
|
agents = room.getAgents();
|
|
1267
1689
|
if (agents.length === 0) {
|
|
1268
1690
|
throw new Error('No agents in story room');
|
|
1269
1691
|
}
|
|
1270
1692
|
logger_1.logger.log(`Compacting ${agents.length} agents in parallel`);
|
|
1693
|
+
// Disable markup and balance checks during compaction
|
|
1271
1694
|
const agentsToCompact = agents.filter(agent => agent !== room.getModeratorAgent());
|
|
1272
1695
|
this.disableStoryAgentFlags(agentsToCompact, 'compaction');
|
|
1696
|
+
// Compact all agents in parallel
|
|
1273
1697
|
const compactionPromises = agents.map(async (agent) => {
|
|
1274
1698
|
if (agent === room.getModeratorAgent()) {
|
|
1275
1699
|
agent.history = [];
|
|
@@ -1283,6 +1707,7 @@ let StoryService = class StoryService {
|
|
|
1283
1707
|
logger_1.logger.error(`Error compacting ${agent.agentName}:`, error);
|
|
1284
1708
|
}
|
|
1285
1709
|
});
|
|
1710
|
+
// Execute all compactions in parallel
|
|
1286
1711
|
await Promise.all(compactionPromises);
|
|
1287
1712
|
logger_1.logger.log(`Finished compacting ${agents.length} agents in parallel`);
|
|
1288
1713
|
return { success: true };
|
|
@@ -1292,41 +1717,65 @@ let StoryService = class StoryService {
|
|
|
1292
1717
|
return { success: false, message: error.message };
|
|
1293
1718
|
}
|
|
1294
1719
|
finally {
|
|
1720
|
+
// Always re-enable flags after compaction
|
|
1295
1721
|
if (agents.length > 0) {
|
|
1296
1722
|
this.enableStoryAgentFlags(agents, 'compaction');
|
|
1297
1723
|
}
|
|
1298
1724
|
}
|
|
1299
1725
|
}
|
|
1726
|
+
/**
|
|
1727
|
+
* Progresses a story to the next chapter by:
|
|
1728
|
+
* 1. Updating the Plot Plan artifact based on recent story events
|
|
1729
|
+
* 2. Updating all Character Profile artifacts based on character development
|
|
1730
|
+
* 3. Creating a new chapter folder with the next chapter index
|
|
1731
|
+
* 4. Backing up the current room messages to the new chapter folder
|
|
1732
|
+
* 5. Compacting the story conversation history in place
|
|
1733
|
+
* 6. Clearing all room messages to start fresh for the next chapter
|
|
1734
|
+
* @param storyId The story ID
|
|
1735
|
+
* @returns Result with success status, chapter index, and compaction details
|
|
1736
|
+
*/
|
|
1300
1737
|
async progressStoryToNextChapter(storyId) {
|
|
1738
|
+
// Validate story exists
|
|
1301
1739
|
const story = await this.ensureStoryLoaded(storyId);
|
|
1302
1740
|
if (!story) {
|
|
1303
1741
|
throw new Error('Story not found');
|
|
1304
1742
|
}
|
|
1743
|
+
// Reject concurrent progression. Two calls would double-backup the chapter,
|
|
1744
|
+
// emit duplicate progress events, and call updatePlotPlan twice.
|
|
1305
1745
|
if (this.chaptersInProgress.has(storyId)) {
|
|
1306
1746
|
throw new errors_1.OperationFailedError('Chapter progression is already in progress for this story');
|
|
1307
1747
|
}
|
|
1308
1748
|
this.chaptersInProgress.add(storyId);
|
|
1309
1749
|
try {
|
|
1750
|
+
// Clear any pending progress-chapter suggestion now that the player is acting on it
|
|
1310
1751
|
if (story.pendingSuggestion?.type === 'suggest-progress-chapter') {
|
|
1311
1752
|
story.pendingSuggestion = undefined;
|
|
1312
1753
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1313
1754
|
}
|
|
1755
|
+
// Check if already progressing
|
|
1314
1756
|
const existingEmitter = this.progressService.getProgressEmitter(storyId);
|
|
1315
1757
|
if (!existingEmitter) {
|
|
1316
1758
|
this.progressService.createProgressEmitter(storyId);
|
|
1317
1759
|
}
|
|
1318
1760
|
const room = await this.getStoryRoom(storyId);
|
|
1319
1761
|
room.setCurrentSpeaker('system');
|
|
1762
|
+
// Generate opening scene and get chapter title for PREVIOUS chapter
|
|
1320
1763
|
this.progressService.emitProgress(storyId, 'opening-scene', 'Generating opening scene of chapter...');
|
|
1321
1764
|
const agents = room.getAgents();
|
|
1322
1765
|
const narrator = agents.find((agent) => agent.promptFolder === 'narrator');
|
|
1323
1766
|
const { openingScene, chapterTitle, preamble } = await this.generateOpeningScene(room, narrator);
|
|
1767
|
+
// Now save the PREVIOUS chapter with its generated title
|
|
1324
1768
|
this.progressService.emitProgress(storyId, 'chapter-backup', `Saving previous chapter: "${chapterTitle}"...`);
|
|
1325
1769
|
const chapterIndex = this.storyStore.getNextChapterIndex(storyId);
|
|
1326
1770
|
const backupSuccess = this.storyStore.createChapterBackup(storyId, chapterIndex, chapterTitle);
|
|
1327
1771
|
if (!backupSuccess) {
|
|
1328
1772
|
throw new Error('Failed to backup chapter');
|
|
1329
1773
|
}
|
|
1774
|
+
// The room's situation is still the end of the chapter just backed up. Move
|
|
1775
|
+
// it to the new chapter's before anything reads it - the moderator treats it
|
|
1776
|
+
// as authoritative about who is present, and the first thing it does with it
|
|
1777
|
+
// is decide who hears the opening scene. After the backup, so the snapshot
|
|
1778
|
+
// stays a picture of the chapter that ended.
|
|
1330
1779
|
const openingSituation = this.parseNarratorPreamble(preamble);
|
|
1331
1780
|
if (openingSituation.situation) {
|
|
1332
1781
|
room.setSituation(openingSituation.situation);
|
|
@@ -1338,8 +1787,10 @@ let StoryService = class StoryService {
|
|
|
1338
1787
|
const audience = openingSituation.situation
|
|
1339
1788
|
? await this.moderateOpeningSceneAudience(room, openingScene)
|
|
1340
1789
|
: null;
|
|
1790
|
+
// Clear room messages and populate with opening scene
|
|
1341
1791
|
room.clearRoomMessages();
|
|
1342
1792
|
this.populateStoryHistory(room, openingScene, audience ?? undefined);
|
|
1793
|
+
// Set human agent as the current speaker-chapter is ready for their response
|
|
1343
1794
|
const humanAgent = room.getAgents().find((a) => a.isControlledByHuman);
|
|
1344
1795
|
if (humanAgent) {
|
|
1345
1796
|
room.setCurrentSpeaker(humanAgent.agentNickname);
|
|
@@ -1358,10 +1809,29 @@ let StoryService = class StoryService {
|
|
|
1358
1809
|
return { chapterIndex };
|
|
1359
1810
|
}
|
|
1360
1811
|
catch (err) {
|
|
1812
|
+
// Sync phase threw - async worker never started, so clean up here.
|
|
1361
1813
|
this.chaptersInProgress.delete(storyId);
|
|
1362
1814
|
throw err;
|
|
1363
1815
|
}
|
|
1364
1816
|
}
|
|
1817
|
+
/**
|
|
1818
|
+
* Reverts the most recent chapter progression. Restores the previous
|
|
1819
|
+
* chapter's room messages, artifacts, and agent histories from the
|
|
1820
|
+
* `chapters/chapter_N/` backup, then deletes that backup so the story
|
|
1821
|
+
* is back to exactly the state it was in before the player clicked
|
|
1822
|
+
* Next Chapter.
|
|
1823
|
+
*
|
|
1824
|
+
* Only valid when the current chapter has not been played yet - i.e.
|
|
1825
|
+
* the only room message is the Opening Scene. The endpoint also requires
|
|
1826
|
+
* at least one chapter backup to exist.
|
|
1827
|
+
*
|
|
1828
|
+
* Token counts and cost totals are not rolled back (those tokens were
|
|
1829
|
+
* actually consumed), matching `resetStory` semantics.
|
|
1830
|
+
*
|
|
1831
|
+
* @throws {NotFoundError} If the story or its room does not exist
|
|
1832
|
+
* @throws {OperationFailedError} If no previous chapter exists, or the
|
|
1833
|
+
* chapter has already been played past the opening scene.
|
|
1834
|
+
*/
|
|
1365
1835
|
async revertStoryChapter(storyId) {
|
|
1366
1836
|
const story = this.storyStore.getStory(storyId);
|
|
1367
1837
|
if (!story || !story.roomId) {
|
|
@@ -1405,6 +1875,11 @@ let StoryService = class StoryService {
|
|
|
1405
1875
|
}
|
|
1406
1876
|
logger_1.logger.log(`Reverted story ${storyId} to chapter ${targetChapter} (${restoredMessages?.length ?? 0} messages, ${restoredArtifacts.length} artifacts)`);
|
|
1407
1877
|
}
|
|
1878
|
+
/**
|
|
1879
|
+
* Performs the actual chapter progression work asynchronously
|
|
1880
|
+
* Phase 1: Quick opening scene generation (user-visible, 5-10s)
|
|
1881
|
+
* Phase 2: Background processing (plot, profiles, compaction, 20-50s)
|
|
1882
|
+
*/
|
|
1408
1883
|
async progressStoryToNextChapterAsync(storyId) {
|
|
1409
1884
|
let room = null;
|
|
1410
1885
|
let agents = [];
|
|
@@ -1415,6 +1890,7 @@ let StoryService = class StoryService {
|
|
|
1415
1890
|
agents = room.getAgents();
|
|
1416
1891
|
narrator = agents.find((agent) => agent.promptFolder === 'narrator');
|
|
1417
1892
|
characterAgents = agents.filter((agent) => agent.promptFolder === 'character');
|
|
1893
|
+
// Enable chapter progression flags for narrator and characters
|
|
1418
1894
|
if (narrator) {
|
|
1419
1895
|
narrator.disableMarkup = true;
|
|
1420
1896
|
narrator.disableBalanceCheck = true;
|
|
@@ -1426,16 +1902,20 @@ let StoryService = class StoryService {
|
|
|
1426
1902
|
agent.disableBalanceCheck = true;
|
|
1427
1903
|
agent.save();
|
|
1428
1904
|
}
|
|
1905
|
+
// Update plot plan first, then character profiles (characters need the new plot plan)
|
|
1429
1906
|
this.progressService.emitProgress(storyId, 'profiles', 'Updating plot plan and character profiles...');
|
|
1430
1907
|
const skipDetailedPlot = this.storyStore.getStory(storyId)?.skipDetailedPlot ?? false;
|
|
1431
1908
|
const updatedPlotPlan = await this.updatePlotPlan(room, narrator, skipDetailedPlot);
|
|
1432
1909
|
await this.updateCharacterProfiles(room, characterAgents, updatedPlotPlan);
|
|
1910
|
+
// Update story cost
|
|
1433
1911
|
await this.updateStoryCost(storyId);
|
|
1912
|
+
// Signal opening scene is ready
|
|
1913
|
+
// Final completion event
|
|
1434
1914
|
this.progressService.emitProgress(storyId, 'complete', 'Chapter progression complete!');
|
|
1435
1915
|
}
|
|
1436
1916
|
catch (error) {
|
|
1437
1917
|
logger_1.logger.error('Error in async chapter progression:', error);
|
|
1438
|
-
throw error;
|
|
1918
|
+
throw error; // Caught by outer handler
|
|
1439
1919
|
}
|
|
1440
1920
|
finally {
|
|
1441
1921
|
if (room) {
|
|
@@ -1444,22 +1924,33 @@ let StoryService = class StoryService {
|
|
|
1444
1924
|
}
|
|
1445
1925
|
}
|
|
1446
1926
|
}
|
|
1927
|
+
/**
|
|
1928
|
+
* Generates the opening scene for a new chapter and a title for the previous chapter
|
|
1929
|
+
* Uses create_chapter prompt which returns the title on the first line (with a #
|
|
1930
|
+
* prefix), then the same `<time>`/`<situation>` preamble a narration carries, then
|
|
1931
|
+
* the opening scene.
|
|
1932
|
+
*/
|
|
1447
1933
|
async generateOpeningScene(room, narrator) {
|
|
1448
1934
|
const artifacts = room.getArtifacts();
|
|
1449
1935
|
const plotPlanArtifact = artifacts.find((a) => a.name === 'Plot Plan');
|
|
1450
1936
|
const currentPlotPlan = plotPlanArtifact?.body || 'No plot plan found.';
|
|
1451
1937
|
const formattedHistory = narrator.getRawMessages();
|
|
1938
|
+
// Call AI with create_chapter prompt
|
|
1452
1939
|
const aiResponse = await narrator.preparedPrompt('create_chapter', {
|
|
1453
1940
|
currentPlotPlan: currentPlotPlan,
|
|
1454
1941
|
formattedHistory: formattedHistory || 'No recent events...',
|
|
1455
1942
|
}, false);
|
|
1943
|
+
// Parse the response - first line should have chapter title with # prefix
|
|
1456
1944
|
const lines = aiResponse.split('\n');
|
|
1457
|
-
let chapterTitle = 'Untitled Chapter';
|
|
1945
|
+
let chapterTitle = 'Untitled Chapter'; // Default if not found
|
|
1458
1946
|
let openingScene = aiResponse;
|
|
1947
|
+
// Check if first line starts with #
|
|
1459
1948
|
if (lines.length > 0 && lines[0].trim().startsWith('#')) {
|
|
1460
|
-
chapterTitle = lines[0].trim().substring(1).trim();
|
|
1461
|
-
openingScene = lines.slice(1).join('\n').trim();
|
|
1949
|
+
chapterTitle = lines[0].trim().substring(1).trim(); // Remove # and whitespace
|
|
1950
|
+
openingScene = lines.slice(1).join('\n').trim(); // Rest is the opening scene
|
|
1462
1951
|
}
|
|
1952
|
+
// The tags sit below the title, so the title has to come off before the same
|
|
1953
|
+
// peeling a narration gets can find them.
|
|
1463
1954
|
const parsed = room_1.Room.extractPreamble(openingScene);
|
|
1464
1955
|
return {
|
|
1465
1956
|
openingScene: parsed ? parsed.content : openingScene,
|
|
@@ -1467,6 +1958,22 @@ let StoryService = class StoryService {
|
|
|
1467
1958
|
preamble: parsed ? parsed.preamble : '',
|
|
1468
1959
|
};
|
|
1469
1960
|
}
|
|
1961
|
+
/**
|
|
1962
|
+
* Asks the moderator which characters are present for the opening scene of a
|
|
1963
|
+
* new chapter.
|
|
1964
|
+
*
|
|
1965
|
+
* A chapter opening does not go through the room's message loop - it is written
|
|
1966
|
+
* before the chapter exists and seeded straight into history - so nothing has
|
|
1967
|
+
* decided its audience. Without this every character hears it, including the ones
|
|
1968
|
+
* the narrator left several days' travel away.
|
|
1969
|
+
*
|
|
1970
|
+
* Requires the room's situation to already be the new chapter's, since that is
|
|
1971
|
+
* what the moderator treats as authoritative about who is present.
|
|
1972
|
+
*
|
|
1973
|
+
* @returns The nicknames who may hear the opening scene, or null if the moderator
|
|
1974
|
+
* could not be reached or named nobody - in which case the caller should seed
|
|
1975
|
+
* every agent rather than silently narrate to an empty room.
|
|
1976
|
+
*/
|
|
1470
1977
|
async moderateOpeningSceneAudience(room, openingScene) {
|
|
1471
1978
|
const moderator = room.getModeratorAgent();
|
|
1472
1979
|
const narrator = room.getAgents().find((a) => a.promptFolder === 'narrator');
|
|
@@ -1485,6 +1992,12 @@ let StoryService = class StoryService {
|
|
|
1485
1992
|
return null;
|
|
1486
1993
|
}
|
|
1487
1994
|
}
|
|
1995
|
+
/**
|
|
1996
|
+
* Compacts every agent whose history has outgrown the threshold, in parallel.
|
|
1997
|
+
* The threshold and the exemption for windowed agents live on `Agent`, so a
|
|
1998
|
+
* story and a room agree on when a history has grown too long.
|
|
1999
|
+
* @param agents The agents to consider
|
|
2000
|
+
*/
|
|
1488
2001
|
async compactAgentHistories(agents) {
|
|
1489
2002
|
await Promise.all(agents.map(async (agent) => {
|
|
1490
2003
|
if (!agent.needsCompaction())
|
|
@@ -1499,6 +2012,7 @@ let StoryService = class StoryService {
|
|
|
1499
2012
|
}));
|
|
1500
2013
|
}
|
|
1501
2014
|
extractMarkdownContent(response) {
|
|
2015
|
+
// Strip any preamble text and pull content from inside a ```markdown ... ``` fence if present
|
|
1502
2016
|
const fenceMatch = response.match(/```(?:markdown)?\s*\n([\s\S]*?)```/);
|
|
1503
2017
|
if (fenceMatch) {
|
|
1504
2018
|
return fenceMatch[1].trim();
|
|
@@ -1506,15 +2020,23 @@ let StoryService = class StoryService {
|
|
|
1506
2020
|
return response.trim();
|
|
1507
2021
|
}
|
|
1508
2022
|
async updatePlotPlan(room, narrator, skipDetailedPlot = false) {
|
|
2023
|
+
// Get the current Plot Plan artifact
|
|
1509
2024
|
const artifacts = room.getArtifacts();
|
|
1510
2025
|
const plotPlanArtifact = artifacts.find((a) => a.name === 'Plot Plan');
|
|
1511
2026
|
const currentPlotPlan = plotPlanArtifact ? plotPlanArtifact.body : 'No plot plan found.';
|
|
2027
|
+
// Re-enable web search just for the plot-plan call. It's globally
|
|
2028
|
+
// disabled at the start of progressStoryToNextChapterAsync because the
|
|
2029
|
+
// main story model is too slow with search; the smaller model used by
|
|
2030
|
+
// withSmallModel makes search affordable here.
|
|
1512
2031
|
const previousAllowSearch = narrator.allowSearch;
|
|
1513
2032
|
narrator.allowSearch = true;
|
|
1514
2033
|
try {
|
|
2034
|
+
// Call the AI to update the plot plan. The narrator's conversation
|
|
2035
|
+
// history is already sent natively, so we don't pass formattedHistory.
|
|
1515
2036
|
const progressPlotResponse = await narrator.withSmallModel(() => narrator.preparedPrompt(skipDetailedPlot ? 'progress_simple_plot' : 'progress_plot', {
|
|
1516
2037
|
currentPlotPlan: currentPlotPlan,
|
|
1517
2038
|
}, false));
|
|
2039
|
+
// Publish the updated Plot Plan as an artifact (visible only to narrator)
|
|
1518
2040
|
if (progressPlotResponse) {
|
|
1519
2041
|
const cleanedPlotPlan = this.extractMarkdownContent(progressPlotResponse);
|
|
1520
2042
|
room.publishArtifact('Plot Plan', narrator.agentNickname, cleanedPlotPlan, [
|
|
@@ -1526,12 +2048,24 @@ let StoryService = class StoryService {
|
|
|
1526
2048
|
}
|
|
1527
2049
|
catch (error) {
|
|
1528
2050
|
logger_1.logger.error(`Error updating plot plan:`, error);
|
|
2051
|
+
// Don't throw - allow other background operations to continue
|
|
1529
2052
|
}
|
|
1530
2053
|
finally {
|
|
1531
2054
|
narrator.allowSearch = previousAllowSearch;
|
|
1532
2055
|
}
|
|
1533
2056
|
return '';
|
|
1534
2057
|
}
|
|
2058
|
+
/**
|
|
2059
|
+
* Stores a character's inventory in the owning agent's private context. The
|
|
2060
|
+
* inventory is therefore visible only to that character (injected into its own
|
|
2061
|
+
* transient prompt) and, in aggregate, to the Moderator — never to other
|
|
2062
|
+
* characters. Storing it on the agent rather than in a room artifact keeps the
|
|
2063
|
+
* frequently-changing inventory out of the cached system instructions.
|
|
2064
|
+
*
|
|
2065
|
+
* @param room The story room
|
|
2066
|
+
* @param characterNickname The owning character's nickname
|
|
2067
|
+
* @param body Markdown body of the inventory (typically '## Items' and optional '## Conditions' sections)
|
|
2068
|
+
*/
|
|
1535
2069
|
storeCharacterInventory(room, characterNickname, body) {
|
|
1536
2070
|
const agent = room
|
|
1537
2071
|
.getAgents()
|
|
@@ -1544,6 +2078,13 @@ let StoryService = class StoryService {
|
|
|
1544
2078
|
agent.save();
|
|
1545
2079
|
logger_1.logger.log(`Stored inventory for ${characterNickname}`);
|
|
1546
2080
|
}
|
|
2081
|
+
/**
|
|
2082
|
+
* Reads changes.update_inventory off a moderator response and rewrites each
|
|
2083
|
+
* named character's stored inventory. Silently no-ops if no updates.
|
|
2084
|
+
*
|
|
2085
|
+
* @param room The story room
|
|
2086
|
+
* @param moderatorMessage The moderator's RoomMessage (with .changes populated)
|
|
2087
|
+
*/
|
|
1547
2088
|
applyInventoryUpdates(room, moderatorMessage) {
|
|
1548
2089
|
const updates = moderatorMessage.changes?.update_inventory ?? [];
|
|
1549
2090
|
if (!Array.isArray(updates) || updates.length === 0)
|
|
@@ -1558,36 +2099,74 @@ let StoryService = class StoryService {
|
|
|
1558
2099
|
this.storeCharacterInventory(room, characterName, inventory);
|
|
1559
2100
|
}
|
|
1560
2101
|
}
|
|
2102
|
+
/**
|
|
2103
|
+
* Helper method to update all character profiles based on story progression
|
|
2104
|
+
* Processes all characters in parallel for better performance
|
|
2105
|
+
* @param room The story room
|
|
2106
|
+
* @param characterAgents Array of character agents (excluding narrator)
|
|
2107
|
+
* @returns Update result with details for each character
|
|
2108
|
+
*/
|
|
1561
2109
|
async updateCharacterProfiles(room, characterAgents, plotPlan = '', latestNarration) {
|
|
2110
|
+
// Get the room's artifacts once to avoid repeated access
|
|
1562
2111
|
const artifacts = room.getArtifacts();
|
|
2112
|
+
// Roster of every story character with their visible (observable)
|
|
2113
|
+
// description. Passed to introduce_character so a newly-introduced
|
|
2114
|
+
// character can be told what the characters they're interacting with
|
|
2115
|
+
// look like, even when they don't yet know names or backstories.
|
|
1563
2116
|
const characterRoster = room
|
|
1564
2117
|
.getAgents()
|
|
1565
2118
|
.filter((a) => a.promptFolder === 'character')
|
|
1566
2119
|
.map((a) => ({ name: a.agentNickname, description: a.description || '' }));
|
|
2120
|
+
// Create promises for all character profile updates. Each resolves to
|
|
2121
|
+
// the agent if its profile actually changed (so we only regenerate
|
|
2122
|
+
// portraits for those), or null if it was left unchanged / errored.
|
|
1567
2123
|
const updatePromises = characterAgents.map(async (character) => {
|
|
1568
2124
|
try {
|
|
2125
|
+
// Get the current character profile artifact
|
|
1569
2126
|
const profileArtifact = artifacts.find((a) => a.name === `Character Profile - ${character.agentNickname}`);
|
|
1570
2127
|
const currentProfile = profileArtifact ? profileArtifact.body : null;
|
|
2128
|
+
// Bootstrap case: a brand-new character with no native history
|
|
2129
|
+
// (e.g., just introduced via room.arrive) needs the existing room
|
|
2130
|
+
// messages so its first profile is consistent with what the
|
|
2131
|
+
// narrator and other characters have already said. We do NOT
|
|
2132
|
+
// write those messages into the character's own history because
|
|
2133
|
+
// that would leak knowledge the character should not yet have.
|
|
2134
|
+
// In steady state the character's native conversation history
|
|
2135
|
+
// is sent natively by textPrompt, so formattedHistory stays empty.
|
|
1571
2136
|
let formattedHistory = [];
|
|
1572
2137
|
const hasNativeHistory = (character.history?.length ?? 0) > 0;
|
|
1573
2138
|
if (!hasNativeHistory) {
|
|
1574
2139
|
formattedHistory = room
|
|
1575
2140
|
.getLatestRoomMessages(0, true)
|
|
1576
2141
|
.map((m) => `${m.sender}: ${m.content}\n`);
|
|
2142
|
+
// The narration that introduced this character is processed
|
|
2143
|
+
// before it is logged to the room, so it won't appear in the
|
|
2144
|
+
// messages above. Append it explicitly so the new character's
|
|
2145
|
+
// first profile reflects the scene they were introduced into.
|
|
1577
2146
|
if (latestNarration) {
|
|
1578
2147
|
formattedHistory.push(`${room.getRoomLeader()}: ${latestNarration}\n`);
|
|
1579
2148
|
}
|
|
1580
2149
|
}
|
|
2150
|
+
// A character with no profile yet was introduced mid-story:
|
|
2151
|
+
// use the lightweight introduce_character prompt, which only
|
|
2152
|
+
// generates a brief role/knowledge/personality profile, instead
|
|
2153
|
+
// of the full progress_character treatment.
|
|
1581
2154
|
const profilePromptName = currentProfile
|
|
1582
2155
|
? 'progress_character'
|
|
1583
2156
|
: 'introduce_character';
|
|
2157
|
+
// Call the AI to update the character profile
|
|
1584
2158
|
const progressCharacterResponse = await character.withSmallModel(() => character.preparedPrompt(profilePromptName, {
|
|
1585
2159
|
agentName: character.agentNickname,
|
|
1586
2160
|
currentProfile: currentProfile,
|
|
1587
2161
|
formattedHistory: formattedHistory,
|
|
1588
2162
|
plotPlan,
|
|
2163
|
+
// Every other story character and their visible
|
|
2164
|
+
// description (used by introduce_character).
|
|
1589
2165
|
otherCharacters: characterRoster.filter((c) => c.name !== character.agentNickname),
|
|
1590
2166
|
}, false));
|
|
2167
|
+
// progress_character returns no_changes when the character was
|
|
2168
|
+
// not significantly affected by recent events. Leave the
|
|
2169
|
+
// existing profile, inventory, and portrait untouched.
|
|
1591
2170
|
if (progressCharacterResponse.no_changes ||
|
|
1592
2171
|
!progressCharacterResponse.character_profile) {
|
|
1593
2172
|
logger_1.logger.log(`No profile changes needed for ${character.agentNickname}; leaving profile unchanged`);
|
|
@@ -1608,8 +2187,11 @@ let StoryService = class StoryService {
|
|
|
1608
2187
|
return null;
|
|
1609
2188
|
}
|
|
1610
2189
|
});
|
|
2190
|
+
// Execute all profile updates in parallel; keep only the characters
|
|
2191
|
+
// whose profiles actually changed so we don't regenerate every portrait.
|
|
1611
2192
|
const changedAgents = (await Promise.all(updatePromises)).filter((agent) => agent !== null);
|
|
1612
2193
|
logger_1.logger.log(`Updated ${changedAgents.length} of ${characterAgents.length} character profiles in parallel`);
|
|
2194
|
+
// Update portraits for all characters using the edit artist
|
|
1613
2195
|
const pathParts = room.getStorageDir().split(path.sep);
|
|
1614
2196
|
const storiesIndex = pathParts.findIndex((p) => p === 'stories');
|
|
1615
2197
|
const storyId = storiesIndex >= 0 ? pathParts[storiesIndex + 1] : null;
|
|
@@ -1617,6 +2199,7 @@ let StoryService = class StoryService {
|
|
|
1617
2199
|
logger_1.logger.error('Could not extract story ID from room path; skipping portrait updates');
|
|
1618
2200
|
}
|
|
1619
2201
|
else {
|
|
2202
|
+
// Only regenerate portraits for characters whose profiles changed.
|
|
1620
2203
|
const portraitPromises = changedAgents.map(async (characterAgent) => {
|
|
1621
2204
|
try {
|
|
1622
2205
|
const artifactId = await this.updateCharacterPortrait(room, characterAgent, storyId);
|
|
@@ -1635,18 +2218,32 @@ let StoryService = class StoryService {
|
|
|
1635
2218
|
logger_1.logger.log(`Updated portraits for ${changedAgents.length} characters`);
|
|
1636
2219
|
}
|
|
1637
2220
|
}
|
|
2221
|
+
/**
|
|
2222
|
+
* Looks up image model configuration by name for one variant. Each consolidated
|
|
2223
|
+
* entry in image_models.json carries a `generation` block (text-to-image) and an
|
|
2224
|
+
* `editing` block (image-to-image); this returns the service/model for the
|
|
2225
|
+
* requested variant.
|
|
2226
|
+
* @param modelName The name from image_models.json
|
|
2227
|
+
* @param variant Which model to resolve: 'generation' or 'editing'
|
|
2228
|
+
* @returns {service, model} or null if disabled/not found
|
|
2229
|
+
*/
|
|
1638
2230
|
getImageModelConfig(modelName, variant = 'generation') {
|
|
1639
2231
|
try {
|
|
2232
|
+
// No model name → images disabled
|
|
1640
2233
|
if (!modelName) {
|
|
1641
2234
|
return null;
|
|
1642
2235
|
}
|
|
2236
|
+
// Load image_models.json
|
|
1643
2237
|
const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
|
|
1644
2238
|
const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
|
|
2239
|
+
// Find selected entry
|
|
1645
2240
|
const entry = imageModels.find((m) => m.name === modelName);
|
|
1646
2241
|
if (!entry) {
|
|
1647
2242
|
logger_1.logger.warn(`Image model not found: ${modelName}`);
|
|
1648
2243
|
return null;
|
|
1649
2244
|
}
|
|
2245
|
+
// Resolve the requested variant. "No images" (and any entry missing the
|
|
2246
|
+
// variant) yields null, which disables that artist agent.
|
|
1650
2247
|
const variantConfig = entry[variant];
|
|
1651
2248
|
if (!variantConfig || !variantConfig.service || !variantConfig.model) {
|
|
1652
2249
|
logger_1.logger.log(`No ${variant} model for "${modelName}" (images disabled)`);
|
|
@@ -1662,10 +2259,22 @@ let StoryService = class StoryService {
|
|
|
1662
2259
|
return null;
|
|
1663
2260
|
}
|
|
1664
2261
|
}
|
|
2262
|
+
/**
|
|
2263
|
+
* Looks up the image generation properties (API params plus centsPerImage)
|
|
2264
|
+
* for an agent's model from image_models.json. This is read fresh at call
|
|
2265
|
+
* time rather than stored on the Agent — only the modelName is persisted.
|
|
2266
|
+
*
|
|
2267
|
+
* @param agent The artist or artistEdit agent
|
|
2268
|
+
* @returns The merged imageProperties to pass to generateImage/editImage,
|
|
2269
|
+
* or an empty object if the model isn't in image_models.json
|
|
2270
|
+
*/
|
|
1665
2271
|
getImagePropertiesForAgent(agent) {
|
|
1666
2272
|
try {
|
|
1667
2273
|
const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
|
|
1668
2274
|
const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
|
|
2275
|
+
// The Artist (Edit) agent uses each entry's editing block; the Artist uses
|
|
2276
|
+
// the generation block. The same model id can appear under both variants
|
|
2277
|
+
// (e.g. GPT Image edits with itself), so resolve by the agent's role first.
|
|
1669
2278
|
const isEditAgent = (agent.agentNickname ?? '').toLowerCase().includes('edit');
|
|
1670
2279
|
const preferred = isEditAgent ? 'editing' : 'generation';
|
|
1671
2280
|
const fallback = isEditAgent ? 'generation' : 'editing';
|
|
@@ -1690,9 +2299,22 @@ let StoryService = class StoryService {
|
|
|
1690
2299
|
return {};
|
|
1691
2300
|
}
|
|
1692
2301
|
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Creates the artist agent for a story
|
|
2304
|
+
* The artist agent is persistent and saved to disk for cost tracking
|
|
2305
|
+
* @param storyId The story ID
|
|
2306
|
+
* @param storyAgentsDir The story agents directory
|
|
2307
|
+
* @param storyArtifactService The story artifact service
|
|
2308
|
+
* @param imageModelName The consolidated image model name from image_models.json
|
|
2309
|
+
* @param nickname The agent nickname ('Artist' or 'Artist (Edit)')
|
|
2310
|
+
* @param variant Which model of the entry to use: 'generation' or 'editing'
|
|
2311
|
+
* @returns Artist agent
|
|
2312
|
+
*/
|
|
1693
2313
|
createArtistAgent(storyId, storyAgentsDir, storyArtifactService, imageModelName, nickname = 'Artist', variant = 'generation') {
|
|
1694
2314
|
const storyInfo = this.storyStore.getStory(storyId);
|
|
2315
|
+
// Look up image model configuration for this variant
|
|
1695
2316
|
const imageConfig = this.getImageModelConfig(imageModelName, variant);
|
|
2317
|
+
// If no valid config (or "No images"), return null
|
|
1696
2318
|
if (!imageConfig) {
|
|
1697
2319
|
logger_1.logger.log(`Artist agent creation skipped (${nickname}): images disabled`);
|
|
1698
2320
|
return null;
|
|
@@ -1704,6 +2326,13 @@ let StoryService = class StoryService {
|
|
|
1704
2326
|
logger_1.logger.log(`Created artist agent: ${artistAgent.agentName} (${imageConfig.service}/${imageConfig.model})`);
|
|
1705
2327
|
return artistAgent;
|
|
1706
2328
|
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Generates portrait image for a character
|
|
2331
|
+
* @param room The story room
|
|
2332
|
+
* @param characterAgent The character agent
|
|
2333
|
+
* @param storyId The story ID
|
|
2334
|
+
* @returns Promise resolving to the artifact ID of the generated image, or null on failure
|
|
2335
|
+
*/
|
|
1707
2336
|
async generateCharacterPortrait(room, characterAgent, storyId) {
|
|
1708
2337
|
const artifacts = room.getArtifacts();
|
|
1709
2338
|
const profileArtifact = artifacts.find((a) => a.name === `Character Profile - ${characterAgent.agentNickname}`);
|
|
@@ -1712,6 +2341,17 @@ let StoryService = class StoryService {
|
|
|
1712
2341
|
const characterProfile = profileArtifact?.body || character?.description || '';
|
|
1713
2342
|
return this.generatePortraitForName(storyId, characterAgent.agentNickname, characterProfile, characterAgent);
|
|
1714
2343
|
}
|
|
2344
|
+
/**
|
|
2345
|
+
* Generates a portrait for a character by name + profile, without requiring a character agent.
|
|
2346
|
+
* Used for both real characters (delegated from generateCharacterPortrait) and for minor
|
|
2347
|
+
* characters named by the illustrator that have no agent backing them.
|
|
2348
|
+
*
|
|
2349
|
+
* @param storyId The story ID
|
|
2350
|
+
* @param characterName The character's display name (used for the Portrait - <name> artifact)
|
|
2351
|
+
* @param characterProfile A profile or brief description used to author the visual prompt
|
|
2352
|
+
* @param promptAgent Agent used to run describe_character. Defaults to the artist when omitted.
|
|
2353
|
+
* @returns Artifact ID of the generated portrait, or null on failure
|
|
2354
|
+
*/
|
|
1715
2355
|
async generatePortraitForName(storyId, characterName, characterProfile, promptAgent) {
|
|
1716
2356
|
try {
|
|
1717
2357
|
if (!characterProfile) {
|
|
@@ -1726,6 +2366,7 @@ let StoryService = class StoryService {
|
|
|
1726
2366
|
logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
|
|
1727
2367
|
return null;
|
|
1728
2368
|
}
|
|
2369
|
+
// Ensure the artist saves images to this story's artifact service, not the default one.
|
|
1729
2370
|
artistAgent.artifactService = storyArtifactService;
|
|
1730
2371
|
const describeAgent = promptAgent || artistAgent;
|
|
1731
2372
|
const visualDescription = await describeAgent.preparedPrompt('describe_character', {
|
|
@@ -1766,6 +2407,8 @@ let StoryService = class StoryService {
|
|
|
1766
2407
|
return null;
|
|
1767
2408
|
}
|
|
1768
2409
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
2410
|
+
// Resolve the edit artist (may be absent when images are disabled
|
|
2411
|
+
// for this story).
|
|
1769
2412
|
const artistEditAgent = storyInfo.artistEditAgentId
|
|
1770
2413
|
? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
|
|
1771
2414
|
: null;
|
|
@@ -1773,6 +2416,8 @@ let StoryService = class StoryService {
|
|
|
1773
2416
|
if (artistEditAgent) {
|
|
1774
2417
|
artistEditAgent.artifactService = storyArtifactService;
|
|
1775
2418
|
}
|
|
2419
|
+
// When we don't need to refresh the description and there's no
|
|
2420
|
+
// artist, there is nothing to do — bail before spending any tokens.
|
|
1776
2421
|
if (!updateDescription && !hasArtist) {
|
|
1777
2422
|
logger_1.logger.warn(`No edit artist configured for story ${storyId}, skipping portrait update`);
|
|
1778
2423
|
return null;
|
|
@@ -1781,27 +2426,40 @@ let StoryService = class StoryService {
|
|
|
1781
2426
|
const existingPortrait = hasArtist
|
|
1782
2427
|
? storyArtifactService.listArtifacts().find((a) => a.name === portraitName)
|
|
1783
2428
|
: undefined;
|
|
2429
|
+
// Fast path: image-only update (e.g. chapter progression) where the
|
|
2430
|
+
// character has no portrait yet — generate one from scratch without
|
|
2431
|
+
// running the update_portrait prompt.
|
|
1784
2432
|
if (!updateDescription && hasArtist && !existingPortrait) {
|
|
1785
2433
|
logger_1.logger.warn(`No existing portrait for ${characterAgent.agentNickname}, generating from scratch`);
|
|
1786
2434
|
return this.generateCharacterPortrait(room, characterAgent, storyId);
|
|
1787
2435
|
}
|
|
2436
|
+
// Ask the character to describe how they look now. This yields both
|
|
2437
|
+
// the image-editing prompt and a short observable description.
|
|
1788
2438
|
const portraitResponse = await characterAgent.preparedPrompt('update_portrait', {
|
|
1789
2439
|
characterName: characterAgent.agentNickname,
|
|
1790
2440
|
characterProfile: characterDescription,
|
|
1791
2441
|
currentDescription: characterAgent.description || '',
|
|
1792
2442
|
scenario: scenario,
|
|
1793
2443
|
}, false);
|
|
2444
|
+
// Refresh the agent's short observable description so it stays in
|
|
2445
|
+
// sync with the changed appearance. Other prompts (the identity
|
|
2446
|
+
// block, the introduce_character roster, moderator routing) read
|
|
2447
|
+
// this. Done regardless of whether images are generated.
|
|
1794
2448
|
if (updateDescription &&
|
|
1795
2449
|
portraitResponse?.description &&
|
|
1796
2450
|
typeof portraitResponse.description === 'string') {
|
|
1797
2451
|
characterAgent.description = portraitResponse.description;
|
|
1798
2452
|
characterAgent.save();
|
|
2453
|
+
// Keep the story metadata copy in sync (used by markdown export
|
|
2454
|
+
// and as the portrait-generation fallback when no profile
|
|
2455
|
+
// artifact exists).
|
|
1799
2456
|
if (character) {
|
|
1800
2457
|
character.description = portraitResponse.description;
|
|
1801
2458
|
this.storyStore.updateStoryMetadata(storyId, storyInfo);
|
|
1802
2459
|
}
|
|
1803
2460
|
logger_1.logger.log(`Updated appearance description for ${characterAgent.agentNickname}`);
|
|
1804
2461
|
}
|
|
2462
|
+
// No artist → description-only update is complete.
|
|
1805
2463
|
if (!hasArtist) {
|
|
1806
2464
|
return null;
|
|
1807
2465
|
}
|
|
@@ -1810,6 +2468,8 @@ let StoryService = class StoryService {
|
|
|
1810
2468
|
logger_1.logger.warn(`Failed to generate update description for ${characterAgent.agentNickname}`);
|
|
1811
2469
|
return null;
|
|
1812
2470
|
}
|
|
2471
|
+
// Artist exists but no portrait yet (only reachable when also
|
|
2472
|
+
// updating the description) — generate from scratch.
|
|
1813
2473
|
if (!existingPortrait) {
|
|
1814
2474
|
logger_1.logger.warn(`No existing portrait for ${characterAgent.agentNickname}, generating from scratch`);
|
|
1815
2475
|
return this.generateCharacterPortrait(room, characterAgent, storyId);
|
|
@@ -1831,8 +2491,12 @@ let StoryService = class StoryService {
|
|
|
1831
2491
|
return null;
|
|
1832
2492
|
}
|
|
1833
2493
|
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Generates scene illustrations based on narrator messages
|
|
2496
|
+
*/
|
|
1834
2497
|
async generateSceneIllustration(storyId, situation, allowReference = true, latestNarration) {
|
|
1835
2498
|
try {
|
|
2499
|
+
// 1. Load story and illustrator agent
|
|
1836
2500
|
const story = this.storyStore.getStory(storyId);
|
|
1837
2501
|
if (!story?.illustratorAgentId) {
|
|
1838
2502
|
logger_1.logger.log('No illustrator configured');
|
|
@@ -1842,6 +2506,11 @@ let StoryService = class StoryService {
|
|
|
1842
2506
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1843
2507
|
if (!illustrator || !room)
|
|
1844
2508
|
return;
|
|
2509
|
+
// 2. Determine the narration to illustrate and add it to illustrator history.
|
|
2510
|
+
// When called from updateStorySituation the triggering narration is passed
|
|
2511
|
+
// in directly, because it has not been logged to the room yet (the situation
|
|
2512
|
+
// is processed before the moderator relays the message). Other callers
|
|
2513
|
+
// (opening scene, reference re-entry) illustrate the latest logged message.
|
|
1845
2514
|
let narrationText = latestNarration;
|
|
1846
2515
|
if (!narrationText) {
|
|
1847
2516
|
const allMessages = room.getLatestRoomMessages(0, true);
|
|
@@ -1852,7 +2521,11 @@ let StoryService = class StoryService {
|
|
|
1852
2521
|
}
|
|
1853
2522
|
narrationText = latestMessage.content;
|
|
1854
2523
|
}
|
|
2524
|
+
// Add narration to illustrator history BEFORE calling prompt
|
|
2525
|
+
// Agent maintains rolling window (maxHistoryMessages=10) automatically
|
|
2526
|
+
// This leverages Anthropic prompt caching
|
|
1855
2527
|
illustrator.addToConversationHistory(narrationText, false);
|
|
2528
|
+
// 3. Get existing scene artifacts
|
|
1856
2529
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1857
2530
|
const allArtifacts = storyArtifactService.listArtifacts();
|
|
1858
2531
|
const existingScenes = allArtifacts
|
|
@@ -1861,6 +2534,10 @@ let StoryService = class StoryService {
|
|
|
1861
2534
|
name: a.name.replace('Scene - ', ''),
|
|
1862
2535
|
description: a.description || '',
|
|
1863
2536
|
}));
|
|
2537
|
+
// Build the candidate character list from Portrait artifacts so minor characters
|
|
2538
|
+
// introduced by the illustrator on earlier turns are reused consistently. We don't
|
|
2539
|
+
// touch storyInfo.characters here — those represent agent-backed characters and
|
|
2540
|
+
// shouldn't include incidental NPCs named by the illustrator.
|
|
1864
2541
|
const portraitCharacters = allArtifacts
|
|
1865
2542
|
.filter((a) => a.name.startsWith('Portrait - '))
|
|
1866
2543
|
.map((a) => ({
|
|
@@ -1875,33 +2552,54 @@ let StoryService = class StoryService {
|
|
|
1875
2552
|
'No scene reference images have been created yet. (set isReference: true)';
|
|
1876
2553
|
const situationForScene = `${story.situationTime ? `${story.situationTime} - ` : ''}${story.situation}`;
|
|
1877
2554
|
let prompt = `**Current Situation**:\n ${situationForScene}\n\n**Existing Scenes**:\n ${existingScenesString}`;
|
|
2555
|
+
// 4. Call describe_scene (narrator history already in conversation)
|
|
1878
2556
|
const sceneAnalysis = await illustrator.instructedPrompt(prompt, 'describe_scene', {
|
|
1879
2557
|
characters: portraitCharacters,
|
|
1880
|
-
}, true,
|
|
2558
|
+
}, true, // Don't save this prompt to history
|
|
2559
|
+
true);
|
|
1881
2560
|
illustrator.save();
|
|
1882
2561
|
if (!sceneAnalysis || !sceneAnalysis.createImage) {
|
|
1883
2562
|
logger_1.logger.log('Illustrator decided not to create an image for this situation');
|
|
1884
2563
|
return;
|
|
1885
2564
|
}
|
|
2565
|
+
// 6. Handle response
|
|
1886
2566
|
if (sceneAnalysis.isReference) {
|
|
1887
2567
|
if (!allowReference) {
|
|
2568
|
+
// Already generated a reference on this chain - stop to avoid an infinite loop.
|
|
1888
2569
|
logger_1.logger.warn(`Illustrator requested another reference (${sceneAnalysis.sceneName}) after one was just created; skipping to avoid loop`);
|
|
1889
2570
|
return;
|
|
1890
2571
|
}
|
|
2572
|
+
// Generate scene reference, then call once more (with allowReference=false) to
|
|
2573
|
+
// produce the actual story image using the newly created reference.
|
|
1891
2574
|
const referenceCreated = await this.generateSceneReference(storyId, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription);
|
|
1892
2575
|
if (referenceCreated) {
|
|
1893
2576
|
await this.generateSceneIllustration(storyId, situation, false, latestNarration);
|
|
1894
2577
|
}
|
|
1895
2578
|
}
|
|
1896
2579
|
else {
|
|
2580
|
+
// Ensure every named character has a portrait BEFORE generating the story image,
|
|
2581
|
+
// so the Portrait lookup in generateStoryImage always finds a reference. Minor
|
|
2582
|
+
// characters introduced by the illustrator come through newCharacters with a
|
|
2583
|
+
// briefDescription we can feed into the agentless portrait path. We pass the
|
|
2584
|
+
// illustrator as the prompt agent; describe_character.prompt is shipped in the
|
|
2585
|
+
// illustrator folder for this purpose.
|
|
1897
2586
|
await this.ensureMinorCharacterPortraits(storyId, sceneAnalysis.characterNames || [], sceneAnalysis.newCharacters || [], portraitCharacters.map((c) => c.name), illustrator);
|
|
2587
|
+
// Generate story image
|
|
1898
2588
|
await this.generateStoryImage(storyId, story.turnNumber, sceneAnalysis.imageCaption, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription, sceneAnalysis.characterNames);
|
|
1899
2589
|
}
|
|
1900
2590
|
}
|
|
1901
2591
|
catch (error) {
|
|
1902
2592
|
logger_1.logger.error('Scene illustration error:', error);
|
|
2593
|
+
// Non-blocking - don't throw
|
|
1903
2594
|
}
|
|
1904
2595
|
}
|
|
2596
|
+
/**
|
|
2597
|
+
* Ensures every character named by the illustrator has a Portrait artifact before the
|
|
2598
|
+
* story image is generated. Names already present in existingPortraitNames are skipped.
|
|
2599
|
+
* Unknown names must have a matching entry in newCharacters (providing briefDescription)
|
|
2600
|
+
* — otherwise we cannot generate a portrait and the character is dropped from logging
|
|
2601
|
+
* (generateStoryImage's existing fallback will then warn and skip them).
|
|
2602
|
+
*/
|
|
1905
2603
|
async ensureMinorCharacterPortraits(storyId, characterNames, newCharacters, existingPortraitNames, promptAgent) {
|
|
1906
2604
|
const existing = new Set(existingPortraitNames);
|
|
1907
2605
|
const descriptionsByName = new Map(newCharacters.map((c) => [c.name, c.briefDescription]));
|
|
@@ -1916,9 +2614,13 @@ let StoryService = class StoryService {
|
|
|
1916
2614
|
await this.generatePortraitForName(storyId, name, briefDescription, promptAgent);
|
|
1917
2615
|
}
|
|
1918
2616
|
}
|
|
2617
|
+
/**
|
|
2618
|
+
* Generates scene reference image (environment only)
|
|
2619
|
+
*/
|
|
1919
2620
|
async generateSceneReference(storyId, sceneName, sceneDescription) {
|
|
1920
2621
|
try {
|
|
1921
2622
|
logger_1.logger.log(`Generating scene reference: ${sceneName}`);
|
|
2623
|
+
// Get artist agent by ID from story metadata
|
|
1922
2624
|
const storyInfo = this.storyStore.getStory(storyId);
|
|
1923
2625
|
if (!storyInfo || !storyInfo.artistAgentId) {
|
|
1924
2626
|
logger_1.logger.error(`Cannot generate scene reference: story ${storyId} has no artist agent`);
|
|
@@ -1952,16 +2654,21 @@ let StoryService = class StoryService {
|
|
|
1952
2654
|
return false;
|
|
1953
2655
|
}
|
|
1954
2656
|
}
|
|
2657
|
+
/**
|
|
2658
|
+
* Generates story image (scene + characters)
|
|
2659
|
+
*/
|
|
1955
2660
|
async generateStoryImage(storyId, turnNumber, imageCaption, sceneName, sceneDescription, characterNames) {
|
|
1956
2661
|
try {
|
|
1957
2662
|
logger_1.logger.log(`Generating story image for turn ${turnNumber}`);
|
|
1958
2663
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1959
2664
|
const allArtifacts = storyArtifactService.listArtifacts();
|
|
2665
|
+
// Find scene reference
|
|
1960
2666
|
const sceneArtifact = allArtifacts.find((a) => a.name === `Scene - ${sceneName}`);
|
|
1961
2667
|
if (!sceneArtifact) {
|
|
1962
2668
|
logger_1.logger.warn(`Scene not found: ${sceneName}`);
|
|
1963
2669
|
return;
|
|
1964
2670
|
}
|
|
2671
|
+
// Get artist agent by ID from story metadata
|
|
1965
2672
|
const storyInfo = this.storyStore.getStory(storyId);
|
|
1966
2673
|
if (!storyInfo || !storyInfo.artistAgentId) {
|
|
1967
2674
|
logger_1.logger.error(`Cannot generate story image: story ${storyId} has no artist agent`);
|
|
@@ -1973,9 +2680,11 @@ let StoryService = class StoryService {
|
|
|
1973
2680
|
return;
|
|
1974
2681
|
}
|
|
1975
2682
|
artistAgent.artifactService = storyArtifactService;
|
|
2683
|
+
// Find character portraits, generating any that are missing
|
|
1976
2684
|
const room = await this.getStoryRoom(storyId);
|
|
1977
2685
|
const characterPortraitIds = [];
|
|
1978
2686
|
for (const charName of characterNames) {
|
|
2687
|
+
// Re-read the artifact list each iteration so newly generated portraits are visible
|
|
1979
2688
|
const currentArtifacts = storyArtifactService.listArtifacts();
|
|
1980
2689
|
const portrait = currentArtifacts.find((a) => a.name === `Portrait - ${charName}`);
|
|
1981
2690
|
if (portrait) {
|
|
@@ -2000,6 +2709,7 @@ let StoryService = class StoryService {
|
|
|
2000
2709
|
}
|
|
2001
2710
|
}
|
|
2002
2711
|
}
|
|
2712
|
+
// Prepare reference images: scene + portraits
|
|
2003
2713
|
const referenceImageIds = [sceneArtifact.artifactId, ...characterPortraitIds];
|
|
2004
2714
|
const editAgent = storyInfo.artistEditAgentId
|
|
2005
2715
|
? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
|
|
@@ -2018,6 +2728,7 @@ let StoryService = class StoryService {
|
|
|
2018
2728
|
storyArtifactService.renameArtifact(artifactId, `Story image - ${turnNumber}`);
|
|
2019
2729
|
storyArtifactService.updateArtifactDescription(artifactId, imageCaption);
|
|
2020
2730
|
logger_1.logger.log(`Generated story image: ${imageCaption} (${artifactId})`);
|
|
2731
|
+
// Add image message to room
|
|
2021
2732
|
try {
|
|
2022
2733
|
const imgUrl = `/api/stories/${storyId}/artifacts/${artifactId}`;
|
|
2023
2734
|
const imageMarkdown = ``;
|
|
@@ -2027,12 +2738,18 @@ let StoryService = class StoryService {
|
|
|
2027
2738
|
}
|
|
2028
2739
|
catch (error) {
|
|
2029
2740
|
logger_1.logger.error('Error adding image message to room:', error);
|
|
2741
|
+
// Don't throw - image was generated successfully
|
|
2030
2742
|
}
|
|
2031
2743
|
}
|
|
2032
2744
|
catch (error) {
|
|
2033
2745
|
logger_1.logger.error('Story image generation error:', error);
|
|
2034
2746
|
}
|
|
2035
2747
|
}
|
|
2748
|
+
/**
|
|
2749
|
+
* Parses the narrator's preamble into structured fields. Extracts each
|
|
2750
|
+
* tag's inner text (first occurrence, case-insensitive); missing tags
|
|
2751
|
+
* are simply omitted from the result.
|
|
2752
|
+
*/
|
|
2036
2753
|
parseNarratorPreamble(preamble) {
|
|
2037
2754
|
const result = {};
|
|
2038
2755
|
if (!preamble)
|
|
@@ -2051,6 +2768,8 @@ let StoryService = class StoryService {
|
|
|
2051
2768
|
if (situation)
|
|
2052
2769
|
result.situation = situation;
|
|
2053
2770
|
if (introduceRaw) {
|
|
2771
|
+
// Value format: "none (reasoning)" or "CharacterName (reasoning)".
|
|
2772
|
+
// Treat the first token as the name; "none" means no introduce.
|
|
2054
2773
|
const firstToken = introduceRaw.split(/[\s(:,]/)[0];
|
|
2055
2774
|
if (firstToken && firstToken.toLowerCase() !== 'none') {
|
|
2056
2775
|
result.introduceCharacter = firstToken;
|
|
@@ -2061,18 +2780,35 @@ let StoryService = class StoryService {
|
|
|
2061
2780
|
}
|
|
2062
2781
|
return result;
|
|
2063
2782
|
}
|
|
2783
|
+
/**
|
|
2784
|
+
* Updates the story's situation in metadata. Invoked from the Room's
|
|
2785
|
+
* situation-update callback with the raw preamble text emitted by the
|
|
2786
|
+
* narrator. The Room itself stays story-agnostic and does not interpret
|
|
2787
|
+
* the preamble contents - all parsing happens here.
|
|
2788
|
+
*
|
|
2789
|
+
* @param storyId The story ID
|
|
2790
|
+
* @param preamble The raw preamble text captured by the Room
|
|
2791
|
+
*/
|
|
2064
2792
|
async updateStorySituation(storyId, preamble, latestNarration) {
|
|
2065
2793
|
const story = this.storyStore.getStory(storyId);
|
|
2066
2794
|
if (!story)
|
|
2067
2795
|
return;
|
|
2068
2796
|
const room = await this.getStoryRoom(storyId);
|
|
2069
2797
|
const parsed = this.parseNarratorPreamble(preamble);
|
|
2798
|
+
// The narrator emits the time as a separate <time> member of its preamble; keep
|
|
2799
|
+
// it separate end-to-end (rather than merging it into the situation text) so
|
|
2800
|
+
// every agent prompt can render it on its own labeled line.
|
|
2070
2801
|
const situationText = parsed.situation ?? preamble;
|
|
2071
2802
|
const situationTime = parsed.time ?? '';
|
|
2803
|
+
// Always overwrite the room's currentSituation with the readable form. The Room
|
|
2804
|
+
// defaulted it to the raw preamble (which may be XML); other agents' prompts
|
|
2805
|
+
// read getSituation() and shouldn't see tags.
|
|
2072
2806
|
room.setSituation(situationText);
|
|
2073
2807
|
room.setSituationTime(situationTime);
|
|
2074
2808
|
if (parsed.progressChapter) {
|
|
2809
|
+
// Clear declined characters on chapter progression
|
|
2075
2810
|
story.declinedCharacters = [];
|
|
2811
|
+
// Send suggestion instead of auto-executing
|
|
2076
2812
|
story.pendingSuggestion = {
|
|
2077
2813
|
type: 'suggest-progress-chapter',
|
|
2078
2814
|
timestamp: Date.now(),
|
|
@@ -2084,16 +2820,25 @@ let StoryService = class StoryService {
|
|
|
2084
2820
|
await this.compactAgentHistories(room.getAgents());
|
|
2085
2821
|
if (parsed.introduceCharacter) {
|
|
2086
2822
|
const newCharacterName = parsed.introduceCharacter;
|
|
2823
|
+
// Skip if the named character already exists in the room
|
|
2087
2824
|
const existingAgent = room.getAgents().find((a) => room.checkAgentNicknameMatch(a.agentNickname, newCharacterName));
|
|
2088
2825
|
if (existingAgent) {
|
|
2089
2826
|
logger_1.logger.log(`INTRODUCE: ${newCharacterName} ignored - character already in story`);
|
|
2090
2827
|
return;
|
|
2091
2828
|
}
|
|
2829
|
+
// Check if character was already declined
|
|
2092
2830
|
const declinedCharacters = story?.declinedCharacters || [];
|
|
2093
2831
|
if (declinedCharacters.includes(newCharacterName)) {
|
|
2094
2832
|
logger_1.logger.log(`Character ${newCharacterName} was declined, skipping prompt`);
|
|
2095
2833
|
return;
|
|
2096
2834
|
}
|
|
2835
|
+
// Auto-create the character agent now, and await it, so the agent
|
|
2836
|
+
// exists in the room before the narrator's message is routed by the
|
|
2837
|
+
// moderator. Otherwise the moderator picks the new character as the
|
|
2838
|
+
// next speaker, no matching agent is found, and the message bounces
|
|
2839
|
+
// back to the room leader (the Narrator) in a loop.
|
|
2840
|
+
// fromNarratorSuggestion=true because the narrator already wove the
|
|
2841
|
+
// character into the scene, so no INTRODUCE message is sent back.
|
|
2097
2842
|
logger_1.logger.log(`Auto-creating narrator-introduced character ${newCharacterName}`);
|
|
2098
2843
|
try {
|
|
2099
2844
|
await this.introduceCharacter(storyId, newCharacterName, '', undefined, true, latestNarration);
|
|
@@ -2107,15 +2852,27 @@ let StoryService = class StoryService {
|
|
|
2107
2852
|
story.situationTime = situationTime;
|
|
2108
2853
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
2109
2854
|
logger_1.logger.log(`Updated story ${storyId} situation: ${situationTime ? `${situationTime} - ` : ''}${situationText}`);
|
|
2855
|
+
// Generate scene illustration (fire and forget). Pass the narration that
|
|
2856
|
+
// triggered this update — it isn't in the room transcript yet (the
|
|
2857
|
+
// situation is processed before the moderator relays the message).
|
|
2110
2858
|
this.generateSceneIllustration(storyId, situationText, true, latestNarration).catch((error) => {
|
|
2111
2859
|
logger_1.logger.error('Illustration generation error:', error);
|
|
2860
|
+
// Silently continue
|
|
2112
2861
|
});
|
|
2113
2862
|
}
|
|
2863
|
+
/**
|
|
2864
|
+
* Generates a complete markdown document of the story
|
|
2865
|
+
* Includes metadata, all completed chapters, and current chapter in progress
|
|
2866
|
+
* @param storyId The story ID
|
|
2867
|
+
* @returns The complete story as markdown text
|
|
2868
|
+
*/
|
|
2114
2869
|
async generateStoryMarkdown(storyId) {
|
|
2870
|
+
// 1. Load story metadata
|
|
2115
2871
|
const story = this.storyStore.getStory(storyId);
|
|
2116
2872
|
if (!story) {
|
|
2117
2873
|
throw new Error('Story not found');
|
|
2118
2874
|
}
|
|
2875
|
+
// 2. Build markdown header with metadata
|
|
2119
2876
|
let markdown = `# ${story.name}\n\n`;
|
|
2120
2877
|
markdown += `**Scenario**: ${story.scenario}\n\n`;
|
|
2121
2878
|
markdown += `**Characters**:\n`;
|
|
@@ -2124,71 +2881,113 @@ let StoryService = class StoryService {
|
|
|
2124
2881
|
markdown += `- ${char.name} (${type}): ${char.description}\n`;
|
|
2125
2882
|
}
|
|
2126
2883
|
markdown += `\n---\n\n`;
|
|
2884
|
+
// 3. Get all chapters
|
|
2127
2885
|
const chapters = this.storyStore.listChapters(storyId);
|
|
2886
|
+
// 4. Process each completed chapter
|
|
2128
2887
|
for (const chapter of chapters) {
|
|
2129
2888
|
markdown += `## Chapter ${chapter.chapterNum}: ${chapter.chapterTitle}\n\n`;
|
|
2130
2889
|
const messages = await this.storyStore.getChapterContent(storyId, chapter.chapterNum);
|
|
2131
2890
|
markdown += this.formatMessagesToMarkdown(messages);
|
|
2132
2891
|
markdown += `\n---\n\n`;
|
|
2133
2892
|
}
|
|
2893
|
+
// 5. Add current chapter in progress
|
|
2134
2894
|
const room = await this.getStoryRoom(storyId);
|
|
2135
2895
|
if (room) {
|
|
2136
2896
|
markdown += `## Current Chapter\n\n`;
|
|
2137
2897
|
markdown += this.formatMessagesToMarkdown(room.getLatestRoomMessages(0, true));
|
|
2138
2898
|
}
|
|
2899
|
+
// 6. Process images to add sizing for better display
|
|
2139
2900
|
markdown = this.processImageMarkdown(markdown, 600);
|
|
2140
2901
|
return markdown;
|
|
2141
2902
|
}
|
|
2903
|
+
/**
|
|
2904
|
+
* Creates a zip archive of the entire story folder
|
|
2905
|
+
* @param storyId The story ID
|
|
2906
|
+
* @returns Promise resolving to a readable stream of the zip file
|
|
2907
|
+
*/
|
|
2142
2908
|
async exportStoryData(storyId) {
|
|
2909
|
+
// 1. Get story metadata for filename
|
|
2143
2910
|
const story = this.storyStore.getStory(storyId);
|
|
2144
2911
|
if (!story) {
|
|
2145
2912
|
throw new Error('Story not found');
|
|
2146
2913
|
}
|
|
2914
|
+
// 2. Get story folder path
|
|
2147
2915
|
const userStoriesDir = path.join(this.userPaths.getUserDataDir(), 'stories');
|
|
2148
2916
|
const storyFolderPath = path.join(userStoriesDir, storyId);
|
|
2917
|
+
// 3. Verify story folder exists
|
|
2149
2918
|
if (!fs.existsSync(storyFolderPath)) {
|
|
2150
2919
|
throw new Error('Story folder not found on disk');
|
|
2151
2920
|
}
|
|
2921
|
+
// 4. Create zip archive
|
|
2152
2922
|
const archive = (0, archiver_1.default)('zip', {
|
|
2153
|
-
zlib: { level: 9 },
|
|
2923
|
+
zlib: { level: 9 }, // Maximum compression
|
|
2154
2924
|
});
|
|
2925
|
+
// 5. Add entire story folder to archive
|
|
2926
|
+
// The directory() method adds all files and subdirectories recursively
|
|
2155
2927
|
archive.directory(storyFolderPath, false);
|
|
2928
|
+
// 6. Finalize the archive (important!)
|
|
2156
2929
|
archive.finalize();
|
|
2930
|
+
// 7. Generate safe filename
|
|
2157
2931
|
const sanitizedName = story.name.replace(/[^a-z0-9]/gi, '_');
|
|
2158
2932
|
const filename = `${sanitizedName}.zip`;
|
|
2933
|
+
// 8. Return stream and filename
|
|
2159
2934
|
return {
|
|
2160
2935
|
stream: archive,
|
|
2161
2936
|
filename: filename,
|
|
2162
2937
|
};
|
|
2163
2938
|
}
|
|
2939
|
+
/**
|
|
2940
|
+
* Formats room messages as markdown text
|
|
2941
|
+
* @param messages Array of room messages
|
|
2942
|
+
* @returns Formatted markdown string
|
|
2943
|
+
*/
|
|
2164
2944
|
formatMessagesToMarkdown(messages) {
|
|
2165
2945
|
let text = '';
|
|
2166
2946
|
for (const msg of messages) {
|
|
2947
|
+
// Add situation updates as section headers
|
|
2167
2948
|
if (msg.situation) {
|
|
2168
2949
|
text += `### ${msg.situation}\n\n`;
|
|
2169
2950
|
}
|
|
2951
|
+
// For stories, actions are only 'system' or 'moderate'
|
|
2952
|
+
// In both cases, output sender and content
|
|
2170
2953
|
text += `**${msg.sender}**: ${msg.content}\n\n`;
|
|
2171
2954
|
}
|
|
2172
2955
|
return text;
|
|
2173
2956
|
}
|
|
2957
|
+
/**
|
|
2958
|
+
* Process markdown to add sizing to images for better display
|
|
2959
|
+
* Converts  to <img> tags with width constraints
|
|
2960
|
+
* @param markdown The markdown string to process
|
|
2961
|
+
* @param maxWidth Maximum width for images (default: 600px)
|
|
2962
|
+
* @returns Processed markdown with HTML img tags
|
|
2963
|
+
*/
|
|
2174
2964
|
processImageMarkdown(markdown, maxWidth = 600) {
|
|
2965
|
+
// Replace markdown image syntax with HTML img tags with sizing
|
|
2966
|
+
// Pattern: 
|
|
2175
2967
|
markdown = markdown.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {
|
|
2176
2968
|
return `<img src="${url}" alt="${alt}" style="max-width: ${maxWidth}px; width: 100%; height: auto; display: block; margin: 1rem auto;" />`;
|
|
2177
2969
|
});
|
|
2178
2970
|
return markdown;
|
|
2179
2971
|
}
|
|
2972
|
+
/**
|
|
2973
|
+
* Updates the story's total cost by aggregating costs from all agents in the story's room
|
|
2974
|
+
* @param storyId The story ID
|
|
2975
|
+
*/
|
|
2180
2976
|
async updateStoryCost(storyId) {
|
|
2181
2977
|
try {
|
|
2978
|
+
// Get story metadata
|
|
2182
2979
|
const storyInfo = this.storyStore.getStory(storyId);
|
|
2183
2980
|
if (!storyInfo || !storyInfo.roomId) {
|
|
2184
2981
|
logger_1.logger.warn(`Cannot update story cost: story ${storyId} not found or has no room`);
|
|
2185
2982
|
return;
|
|
2186
2983
|
}
|
|
2984
|
+
// Get the room to access all agents
|
|
2187
2985
|
const room = await this.roomStore.getRoom(storyInfo.roomId);
|
|
2188
2986
|
if (!room) {
|
|
2189
2987
|
logger_1.logger.warn(`Cannot update story cost: room ${storyInfo.roomId} not found`);
|
|
2190
2988
|
return;
|
|
2191
2989
|
}
|
|
2990
|
+
// Aggregate costs from all agents in the room
|
|
2192
2991
|
let totalCost = 0;
|
|
2193
2992
|
let totalInputTokens = 0;
|
|
2194
2993
|
let totalOutputTokens = 0;
|
|
@@ -2198,6 +2997,7 @@ let StoryService = class StoryService {
|
|
|
2198
2997
|
totalInputTokens += agent.totalInputTokens || 0;
|
|
2199
2998
|
totalOutputTokens += agent.totalOutputTokens || 0;
|
|
2200
2999
|
}
|
|
3000
|
+
// Add illustrator agent costs
|
|
2201
3001
|
if (storyInfo.illustratorAgentId) {
|
|
2202
3002
|
const illustratorAgent = await this.agentStore.getAgent(storyInfo.illustratorAgentId);
|
|
2203
3003
|
if (illustratorAgent) {
|
|
@@ -2209,6 +3009,7 @@ let StoryService = class StoryService {
|
|
|
2209
3009
|
logger_1.logger.warn(`Illustrator agent not found: ${storyInfo.illustratorAgentId}`);
|
|
2210
3010
|
}
|
|
2211
3011
|
}
|
|
3012
|
+
// Add artist agent costs
|
|
2212
3013
|
if (storyInfo.artistAgentId) {
|
|
2213
3014
|
const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
|
|
2214
3015
|
if (artistAgent) {
|
|
@@ -2220,6 +3021,7 @@ let StoryService = class StoryService {
|
|
|
2220
3021
|
logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
|
|
2221
3022
|
}
|
|
2222
3023
|
}
|
|
3024
|
+
// Add artist edit agent costs (scene illustrations go through editImage)
|
|
2223
3025
|
if (storyInfo.artistEditAgentId) {
|
|
2224
3026
|
const artistEditAgent = await this.agentStore.getAgent(storyInfo.artistEditAgentId);
|
|
2225
3027
|
if (artistEditAgent) {
|
|
@@ -2231,9 +3033,11 @@ let StoryService = class StoryService {
|
|
|
2231
3033
|
logger_1.logger.warn(`Artist edit agent not found: ${storyInfo.artistEditAgentId}`);
|
|
2232
3034
|
}
|
|
2233
3035
|
}
|
|
3036
|
+
// Update story metadata
|
|
2234
3037
|
storyInfo.totalCost = totalCost;
|
|
2235
3038
|
storyInfo.totalInputTokens = totalInputTokens;
|
|
2236
3039
|
storyInfo.totalOutputTokens = totalOutputTokens;
|
|
3040
|
+
// Persist to disk
|
|
2237
3041
|
this.storyStore.updateStoryMetadata(storyId, storyInfo);
|
|
2238
3042
|
}
|
|
2239
3043
|
catch (error) {
|