briyah 2.0.2 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +216 -0
- package/README.md +43 -7
- package/data/common/config/LICENSE-model-prices.md +65 -0
- package/data/common/config/markup +1 -1
- package/data/common/config/model_prices.json +47443 -46295
- package/data/common/prompts/narrator/create_story.prompt +2 -0
- package/data/packs/dnd5e/agents/player.json +11 -11
- package/data/packs/dnd5e/prompts/character_creator/defaults_config.json +21 -20
- package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +19 -12
- package/data/packs/dnd5e/prompts/dnd_player/perceive.prompt +10 -6
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +173 -2
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +172 -3
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +241 -5
- package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
- package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
- package/dist-sdk/server/src/ai/LLM/deepseek.service.js +102 -3
- package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/LLM/fal.service.js +55 -1
- package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
- package/dist-sdk/server/src/ai/LLM/googleai.service.js +42 -1
- package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
- package/dist-sdk/server/src/ai/LLM/grok.service.js +54 -2
- package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
- package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/openai.service.js +80 -2
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +44 -2
- package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/together.service.js +60 -2
- package/dist-sdk/server/src/ai/agent-config.d.ts +15 -0
- package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
- package/dist-sdk/server/src/ai/agent-factory.js +20 -0
- package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
- package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +166 -5
- package/dist-sdk/server/src/ai/agent.d.ts +196 -0
- package/dist-sdk/server/src/ai/agent.js +224 -11
- package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
- package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
- package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
- package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
- package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
- package/dist-sdk/server/src/ai/artifact.service.js +148 -3
- package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
- package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
- package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
- package/dist-sdk/server/src/ai/model_prices.js +91 -5
- package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
- package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
- package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
- package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
- package/dist-sdk/server/src/app/balance-message.service.js +24 -0
- package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
- package/dist-sdk/server/src/app/balance.module.js +4 -0
- package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
- package/dist-sdk/server/src/app/balance.service.js +54 -0
- package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
- package/dist-sdk/server/src/app/stripe.controller.js +35 -0
- package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
- package/dist-sdk/server/src/app/stripe.service.js +62 -0
- package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
- package/dist-sdk/server/src/app/transaction.service.js +36 -0
- package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
- package/dist-sdk/server/src/app/user-service-factory.js +38 -1
- package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
- package/dist-sdk/server/src/app/user-service-manager.js +43 -0
- package/dist-sdk/server/src/app.controller.d.ts +87 -0
- package/dist-sdk/server/src/app.controller.js +272 -12
- package/dist-sdk/server/src/app.module.js +28 -6
- package/dist-sdk/server/src/app.service.d.ts +1662 -0
- package/dist-sdk/server/src/app.service.js +1862 -6
- package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
- package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
- package/dist-sdk/server/src/auth/auth.controller.js +46 -0
- package/dist-sdk/server/src/auth/auth.module.js +3 -2
- package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
- package/dist-sdk/server/src/auth/auth.service.js +39 -3
- package/dist-sdk/server/src/auth/jwt-auth.guard.js +18 -0
- package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
- package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
- package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
- package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
- package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
- package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
- package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
- package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
- package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
- package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
- package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
- package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
- package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
- package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
- package/dist-sdk/server/src/auth/session.guard.js +8 -0
- package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
- package/dist-sdk/server/src/auth/twilio.service.js +30 -4
- package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
- package/dist-sdk/server/src/auth/users.service.js +42 -0
- package/dist-sdk/server/src/common/errors.d.ts +20 -0
- package/dist-sdk/server/src/common/errors.js +21 -0
- package/dist-sdk/server/src/config/env-config.d.ts +7 -0
- package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
- package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
- package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
- package/dist-sdk/server/src/config/user-config.service.js +57 -0
- package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
- package/dist-sdk/server/src/config/user-paths.service.js +67 -0
- package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
- package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.js +99 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +100 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +58 -0
- package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
- package/dist-sdk/server/src/packs/pack.service.js +98 -1
- package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
- package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
- package/dist-sdk/server/src/room/artifact.d.ts +18 -0
- package/dist-sdk/server/src/room/message.d.ts +64 -0
- package/dist-sdk/server/src/room/message.js +77 -2
- package/dist-sdk/server/src/room/nickname.d.ts +27 -0
- package/dist-sdk/server/src/room/nickname.js +41 -0
- package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
- package/dist-sdk/server/src/room/room-config.d.ts +26 -0
- package/dist-sdk/server/src/room/room-factory.d.ts +12 -0
- package/dist-sdk/server/src/room/room-factory.js +14 -0
- package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
- package/dist-sdk/server/src/room/room-message.service.js +28 -0
- package/dist-sdk/server/src/room/room-store.service.d.ts +177 -0
- package/dist-sdk/server/src/room/room-store.service.js +242 -5
- package/dist-sdk/server/src/room/room.d.ts +906 -1
- package/dist-sdk/server/src/room/room.js +1525 -34
- package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
- package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +38 -3
- package/dist-sdk/server/src/rpg/rpg-roster.js +49 -49
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
- package/dist-sdk/server/src/rpg/rpg.service.js +108 -5
- package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
- package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
- package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
- package/dist-sdk/server/src/sdk/briyah.js +285 -7
- package/dist-sdk/server/src/sdk/index.d.ts +0 -1
- package/dist-sdk/server/src/sdk/index.js +24 -3
- package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
- package/dist-sdk/server/src/shared/shared.module.js +13 -5
- package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
- package/dist-sdk/server/src/story/story-message.service.js +43 -0
- package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
- package/dist-sdk/server/src/story/story-progress.service.js +23 -0
- package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
- package/dist-sdk/server/src/story/story-store.service.js +136 -1
- package/dist-sdk/server/src/story/story.service.d.ts +398 -0
- package/dist-sdk/server/src/story/story.service.js +829 -25
- package/dist-sdk/server/src/tools/core/index.d.ts +25 -0
- package/dist-sdk/server/src/tools/core/index.js +31 -0
- package/dist-sdk/server/src/tools/core/rename.tool.d.ts +10 -0
- package/dist-sdk/server/src/tools/core/rename.tool.js +72 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +186 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +192 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +144 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +164 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +188 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +125 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
- package/dist-sdk/server/src/tools/packs/index.d.ts +52 -2
- package/dist-sdk/server/src/tools/packs/index.js +83 -9
- package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
- package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +73 -0
- package/dist-sdk/server/src/tools/tool-execution.service.js +74 -0
- package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
- package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
- package/dist-sdk/shared/types/app.types.d.ts +285 -14
- package/dist-sdk/shared/types/app.types.js +3 -0
- package/package.json +167 -139
- package/data/common/config/random_words.txt +0 -2241
- package/data/common/story_ideas/biblical.json +0 -122
- package/data/common/story_ideas/fantasy.json +0 -82
- package/data/common/story_ideas/historical_fiction.json +0 -82
- package/data/common/story_ideas/science_fiction.json +0 -82
- package/data/packs/acts/agents/character-guide.json +0 -6
- package/data/packs/acts/agents/discipleship-mentor.json +0 -6
- package/data/packs/acts/agents/mentor-coach.json +0 -6
- package/data/packs/acts/agents/student.json +0 -13
- package/data/packs/acts/agents/table-moderator.json +0 -6
- package/data/packs/acts/artifacts/chapter-01-acts-1.md +0 -405
- package/data/packs/acts/artifacts/chapter-02-acts-2.md +0 -443
- package/data/packs/acts/artifacts/chapter-03-acts-3.md +0 -409
- package/data/packs/acts/artifacts/chapter-04-acts-4.md +0 -438
- package/data/packs/acts/artifacts/chapter-05-acts-5.md +0 -434
- package/data/packs/acts/artifacts/chapter-06-acts-6.md +0 -441
- package/data/packs/acts/artifacts/chapter-07-acts-7.md +0 -472
- package/data/packs/acts/artifacts/chapter-08-acts-8.md +0 -512
- package/data/packs/acts/artifacts/chapter-09-acts-9.md +0 -346
- package/data/packs/acts/artifacts/chapter-10-acts-10.md +0 -367
- package/data/packs/acts/artifacts/chapter-11-acts-11.md +0 -391
- package/data/packs/acts/artifacts/chapter-12-acts-12.md +0 -390
- package/data/packs/acts/artifacts/chapter-13-acts-13.md +0 -388
- package/data/packs/acts/artifacts/chapter-14-acts-14.md +0 -466
- package/data/packs/acts/artifacts/chapter-15-acts-15.md +0 -413
- package/data/packs/acts/artifacts/chapter-16-acts-16.md +0 -585
- package/data/packs/acts/artifacts/chapter-17-acts-17.md +0 -428
- package/data/packs/acts/artifacts/chapter-18-acts-18.md +0 -486
- package/data/packs/acts/artifacts/chapter-19-acts-19.md +0 -461
- package/data/packs/acts/artifacts/chapter-20-acts-20.md +0 -389
- package/data/packs/acts/artifacts/chapter-21-acts-21.md +0 -452
- package/data/packs/acts/artifacts/chapter-22-acts-22.md +0 -424
- package/data/packs/acts/artifacts/chapter-23-acts-23.md +0 -395
- package/data/packs/acts/artifacts/chapter-24-acts-24.md +0 -446
- package/data/packs/acts/artifacts/chapter-25-acts-25.md +0 -391
- package/data/packs/acts/artifacts/chapter-26-acts-26.md +0 -431
- package/data/packs/acts/artifacts/chapter-27-acts-27.md +0 -530
- package/data/packs/acts/artifacts/chapter-28-acts-28.md +0 -1871
- package/data/packs/acts/artifacts/chapters.manifest.json +0 -170
- package/data/packs/acts/artifacts/character_guide-creation.md +0 -112
- package/data/packs/acts/artifacts/discipleship_mentor-procedure.md +0 -154
- package/data/packs/acts/artifacts/discipleship_mentor-systems.md +0 -72
- package/data/packs/acts/artifacts/manifest.json +0 -197
- package/data/packs/acts/artifacts/stage-guide.md +0 -94
- package/data/packs/acts/pack.json +0 -6
- package/data/packs/acts/prompts/acts_player/defaults_config.json +0 -5
- package/data/packs/acts/prompts/acts_player/perceive.json +0 -29
- package/data/packs/acts/prompts/acts_player/perceive.prompt +0 -87
- package/data/packs/acts/prompts/acts_player/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/acts_room_moderator/defaults_config.json +0 -9
- package/data/packs/acts/prompts/acts_room_moderator/moderate.json +0 -34
- package/data/packs/acts/prompts/acts_room_moderator/moderate.prompt +0 -70
- package/data/packs/acts/prompts/acts_room_moderator/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/character_guide/defaults_config.json +0 -18
- package/data/packs/acts/prompts/character_guide/perceive.json +0 -29
- package/data/packs/acts/prompts/character_guide/perceive.prompt +0 -140
- package/data/packs/acts/prompts/character_guide/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/discipleship_mentor/defaults_config.json +0 -23
- package/data/packs/acts/prompts/discipleship_mentor/perceive.json +0 -33
- package/data/packs/acts/prompts/discipleship_mentor/perceive.prompt +0 -245
- package/data/packs/acts/prompts/discipleship_mentor/system_instruction.prompt +0 -0
- package/data/packs/acts/prompts/mentor_coach/defaults_config.json +0 -13
- package/data/packs/acts/prompts/mentor_coach/perceive.json +0 -29
- package/data/packs/acts/prompts/mentor_coach/perceive.prompt +0 -87
- package/data/packs/acts/prompts/mentor_coach/system_instruction.prompt +0 -0
- package/data/packs/acts/rooms/session.json +0 -14
- package/data/packs/acts/rooms/training.json +0 -58
- package/dist-sdk/server/src/tools/packs/acts/data/cards.d.ts +0 -53
- package/dist-sdk/server/src/tools/packs/acts/data/cards.js +0 -54
- package/dist-sdk/server/src/tools/packs/acts/data/character-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/character-cards.generated.js +0 -185
- package/dist-sdk/server/src/tools/packs/acts/data/encounters.d.ts +0 -12
- package/dist-sdk/server/src/tools/packs/acts/data/encounters.js +0 -102
- package/dist-sdk/server/src/tools/packs/acts/data/event-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/event-cards.generated.js +0 -196
- package/dist-sdk/server/src/tools/packs/acts/data/item-cards.generated.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/data/item-cards.generated.js +0 -1311
- package/dist-sdk/server/src/tools/packs/acts/engine/cards.d.ts +0 -5
- package/dist-sdk/server/src/tools/packs/acts/engine/cards.js +0 -27
- package/dist-sdk/server/src/tools/packs/acts/engine/challenge.d.ts +0 -37
- package/dist-sdk/server/src/tools/packs/acts/engine/challenge.js +0 -120
- package/dist-sdk/server/src/tools/packs/acts/engine/dice.d.ts +0 -20
- package/dist-sdk/server/src/tools/packs/acts/engine/dice.js +0 -41
- package/dist-sdk/server/src/tools/packs/acts/engine/sheet.d.ts +0 -54
- package/dist-sdk/server/src/tools/packs/acts/engine/sheet.js +0 -200
- package/dist-sdk/server/src/tools/packs/acts/index.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/index.js +0 -24
- package/dist-sdk/server/src/tools/packs/acts/tools/award.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/award.tool.js +0 -184
- package/dist-sdk/server/src/tools/packs/acts/tools/challenge.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/challenge.tool.js +0 -107
- package/dist-sdk/server/src/tools/packs/acts/tools/chapter.tool.d.ts +0 -3
- package/dist-sdk/server/src/tools/packs/acts/tools/chapter.tool.js +0 -146
- package/dist-sdk/server/src/tools/packs/acts/tools/check.tool.d.ts +0 -4
- package/dist-sdk/server/src/tools/packs/acts/tools/check.tool.js +0 -241
- package/dist-sdk/server/src/tools/packs/acts/tools/encounter.tool.d.ts +0 -3
- package/dist-sdk/server/src/tools/packs/acts/tools/encounter.tool.js +0 -72
- package/dist-sdk/server/src/tools/packs/acts/tools/faith.tool.d.ts +0 -2
- package/dist-sdk/server/src/tools/packs/acts/tools/faith.tool.js +0 -75
- package/dist-sdk/server/src/tools/packs/acts/tools/shared.d.ts +0 -20
- package/dist-sdk/server/src/tools/packs/acts/tools/shared.js +0 -70
- package/dist-sdk/server/src/tools/packs/acts/tools/sheet.tools.d.ts +0 -4
- package/dist-sdk/server/src/tools/packs/acts/tools/sheet.tools.js +0 -215
- package/docs/.nojekyll +0 -1
- package/docs/assets/hierarchy.js +0 -1
- package/docs/assets/highlight.css +0 -113
- package/docs/assets/icons.js +0 -18
- package/docs/assets/icons.svg +0 -1
- package/docs/assets/main.js +0 -60
- package/docs/assets/navigation.js +0 -1
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1648
- package/docs/classes/Agent.html +0 -801
- package/docs/classes/Briyah.html +0 -296
- package/docs/classes/BriyahConfigService.html +0 -119
- package/docs/classes/NativeToolRegistry.html +0 -166
- package/docs/classes/PackInstantiationService.html +0 -157
- package/docs/classes/PackService.html +0 -247
- package/docs/classes/Room.html +0 -1338
- package/docs/classes/RoomMessage.html +0 -290
- package/docs/enums/MessageAction.html +0 -136
- package/docs/functions/actsTools.html +0 -44
- package/docs/functions/availableToolPacks.html +0 -41
- package/docs/functions/buildMarkdown.html +0 -54
- package/docs/functions/dnd5eTools.html +0 -44
- package/docs/functions/installToolPacks.html +0 -48
- package/docs/functions/pageMarker.html +0 -45
- package/docs/functions/registerToolPacks.html +0 -54
- package/docs/functions/splitMarkdownIntoPages.html +0 -51
- package/docs/functions/stripWrappingFence.html +0 -52
- package/docs/hierarchy.html +0 -46
- package/docs/index.html +0 -595
- package/docs/interfaces/AgentCreationOptions.html +0 -125
- package/docs/interfaces/AgentInfo.html +0 -218
- package/docs/interfaces/AgentMessagesResponse.html +0 -74
- package/docs/interfaces/AppService.html +0 -3337
- package/docs/interfaces/Artifact.html +0 -95
- package/docs/interfaces/ArtifactMetadata.html +0 -112
- package/docs/interfaces/ArtifactWriteOptions.html +0 -90
- package/docs/interfaces/AttachDocumentResponse.html +0 -62
- package/docs/interfaces/BriyahConfigOptions.html +0 -124
- package/docs/interfaces/ChapterInfo.html +0 -62
- package/docs/interfaces/Character.html +0 -86
- package/docs/interfaces/ConversionAgent.html +0 -78
- package/docs/interfaces/CreateAgentResponse.html +0 -56
- package/docs/interfaces/CreateRoomResponse.html +0 -62
- package/docs/interfaces/CreateStoryResponse.html +0 -56
- package/docs/interfaces/FileList.html +0 -56
- package/docs/interfaces/FileMetadata.html +0 -89
- package/docs/interfaces/IConfigService.html +0 -79
- package/docs/interfaces/InstantiateModels.html +0 -64
- package/docs/interfaces/InstantiateRoomResult.html +0 -70
- package/docs/interfaces/LoadedPack.html +0 -131
- package/docs/interfaces/LoggingOptions.html +0 -92
- package/docs/interfaces/Message.html +0 -84
- package/docs/interfaces/ModelChoice.html +0 -73
- package/docs/interfaces/ModelInfo.html +0 -74
- package/docs/interfaces/NativeToolDefinition.html +0 -107
- package/docs/interfaces/PackAgentTemplate.html +0 -101
- package/docs/interfaces/PackRoomTemplate.html +0 -108
- package/docs/interfaces/PackView.html +0 -172
- package/docs/interfaces/PdfConversionOptions.html +0 -102
- package/docs/interfaces/PdfConversionResult.html +0 -97
- package/docs/interfaces/PdfMarkdownOptions.html +0 -198
- package/docs/interfaces/PdfMarkdownResult.html +0 -106
- package/docs/interfaces/PdfPageMarkdown.html +0 -94
- package/docs/interfaces/PreparedPromptResponse.html +0 -62
- package/docs/interfaces/ProcessTextResponse.html +0 -86
- package/docs/interfaces/PromptFile.html +0 -70
- package/docs/interfaces/PromptFileContent.html +0 -76
- package/docs/interfaces/PromptFilesResponse.html +0 -56
- package/docs/interfaces/PromptFolder.html +0 -80
- package/docs/interfaces/PromptFolderDefaults.html +0 -155
- package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
- package/docs/interfaces/PromptFoldersResponse.html +0 -56
- package/docs/interfaces/RoomDetails.html +0 -151
- package/docs/interfaces/RoomErrorUpdate.html +0 -82
- package/docs/interfaces/RoomInfo.html +0 -88
- package/docs/interfaces/RoomMessageUpdate.html +0 -113
- package/docs/interfaces/RoomMessagesResponse.html +0 -62
- package/docs/interfaces/SendMessageResult.html +0 -62
- package/docs/interfaces/StoryErrorEvent.html +0 -84
- package/docs/interfaces/StoryIdea.html +0 -74
- package/docs/interfaces/StoryInfo.html +0 -198
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
- package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
- package/docs/interfaces/StoryState.html +0 -108
- package/docs/interfaces/StoryStateEvent.html +0 -76
- package/docs/interfaces/ToolArtifact.html +0 -85
- package/docs/interfaces/ToolCaller.html +0 -77
- package/docs/interfaces/ToolDefinition.html +0 -80
- package/docs/interfaces/ToolHelpers.html +0 -105
- package/docs/interfaces/ToolPackDocuments.html +0 -100
- package/docs/interfaces/ToolParameter.html +0 -74
- package/docs/interfaces/ToolRoomAccess.html +0 -227
- package/docs/interfaces/ToolSummary.html +0 -74
- package/docs/interfaces/ToolsResponse.html +0 -68
- package/docs/interfaces/Transaction.html +0 -104
- package/docs/interfaces/TransactionHistoryResponse.html +0 -62
- package/docs/modules.html +0 -53
- package/docs/types/PackOrigin.html +0 -34
- package/docs/types/PromptScope.html +0 -34
- package/docs/types/RoomTurnMode.html +0 -42
- package/docs/types/RoomUpdate.html +0 -36
- package/docs/types/RosterOverrides.html +0 -42
- package/docs/types/ToolContext.html +0 -40
- package/docs/types/ToolRunResult.html +0 -34
- package/src/tools/packs/dnd5e/README.md +0 -867
|
@@ -39,11 +39,19 @@ const fs = __importStar(require("fs"));
|
|
|
39
39
|
const path = __importStar(require("path"));
|
|
40
40
|
const room_store_service_1 = require("./room/room-store.service");
|
|
41
41
|
const prompt_resolver_1 = require("./config/prompt-resolver");
|
|
42
|
+
const core_1 = require("./tools/core");
|
|
42
43
|
const app_types_1 = require("../../shared/types/app.types");
|
|
43
44
|
const pdf_lib_1 = require("pdf-lib");
|
|
44
45
|
const pdf_conversion_1 = require("./documents/pdf-conversion");
|
|
45
46
|
const message_1 = require("./room/message");
|
|
46
47
|
const logger_1 = require("./common/logger");
|
|
48
|
+
/**
|
|
49
|
+
* Up to this many pages, a PDF is converted in one request instead of page by page.
|
|
50
|
+
*
|
|
51
|
+
* Short documents read better whole — a heading and the table under it stay
|
|
52
|
+
* together — and cost one call rather than ten. Past it, page-level retry and
|
|
53
|
+
* partial success matter more than continuity.
|
|
54
|
+
*/
|
|
47
55
|
const WHOLE_PDF_PAGE_LIMIT = 10;
|
|
48
56
|
class AppService {
|
|
49
57
|
aiFactoryService;
|
|
@@ -91,13 +99,21 @@ class AppService {
|
|
|
91
99
|
this.packService = packService;
|
|
92
100
|
this.aiServices = this.aiFactoryService.getAllAiServices();
|
|
93
101
|
}
|
|
102
|
+
/** Packs, as this user sees them. */
|
|
94
103
|
get packs() {
|
|
95
104
|
return this.packService;
|
|
96
105
|
}
|
|
97
106
|
packInstantiationService;
|
|
107
|
+
/**
|
|
108
|
+
* Supplies the service that builds agents and rooms from pack templates.
|
|
109
|
+
*
|
|
110
|
+
* Set after construction rather than injected: it drives this service, so it
|
|
111
|
+
* cannot also be one of its constructor arguments.
|
|
112
|
+
*/
|
|
98
113
|
setPackInstantiation(service) {
|
|
99
114
|
this.packInstantiationService = service;
|
|
100
115
|
}
|
|
116
|
+
/** Builds agents and rooms from pack templates. */
|
|
101
117
|
get packInstantiation() {
|
|
102
118
|
if (!this.packInstantiationService) {
|
|
103
119
|
throw new Error('Pack instantiation service is not set');
|
|
@@ -105,30 +121,77 @@ class AppService {
|
|
|
105
121
|
return this.packInstantiationService;
|
|
106
122
|
}
|
|
107
123
|
rpgCampaignService;
|
|
124
|
+
/**
|
|
125
|
+
* Supplies the service that builds and reads campaigns.
|
|
126
|
+
*
|
|
127
|
+
* Set after construction for the same reason pack instantiation is: it drives
|
|
128
|
+
* this service, so it cannot also be one of its constructor arguments.
|
|
129
|
+
*/
|
|
108
130
|
setRpg(service) {
|
|
109
131
|
this.rpgCampaignService = service;
|
|
110
132
|
}
|
|
133
|
+
/** Campaigns: the streamlined D&D surface, built on packs and published rooms. */
|
|
111
134
|
get rpg() {
|
|
112
135
|
if (!this.rpgCampaignService) {
|
|
113
136
|
throw new Error('RPG service is not set');
|
|
114
137
|
}
|
|
115
138
|
return this.rpgCampaignService;
|
|
116
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* The packs this user has enabled, as a thunk.
|
|
142
|
+
*
|
|
143
|
+
* Handed to the prompt resolver and to every agent this service creates. A
|
|
144
|
+
* thunk rather than an array because both outlive a toggle — see
|
|
145
|
+
* {@link Agent.enabledPacks}.
|
|
146
|
+
*/
|
|
117
147
|
enabledPacks = () => this.packService.enabledPacks();
|
|
148
|
+
/**
|
|
149
|
+
* Returns the names of all available AI service providers.
|
|
150
|
+
*
|
|
151
|
+
* Only providers that have a configured API key are included.
|
|
152
|
+
*
|
|
153
|
+
* @returns Array of provider names (e.g. `'Anthropic'`, `'OpenAI'`, `'GoogleAI'`)
|
|
154
|
+
*/
|
|
118
155
|
getAiServiceNames() {
|
|
119
156
|
return this.aiServices.filter((s) => s.isAvailable).map((s) => s.getServiceName());
|
|
120
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Returns the AI service instance for the given provider name.
|
|
160
|
+
*
|
|
161
|
+
* @internal Returns a framework-level service; SDK consumers should use
|
|
162
|
+
* {@link listAiModels} or higher-level methods rather than handling
|
|
163
|
+
* `BaseAiService` directly.
|
|
164
|
+
* @param serviceName - Provider name as returned by {@link getAiServiceNames}
|
|
165
|
+
* @returns The corresponding AI service instance
|
|
166
|
+
* @throws {Error} If the service name is not recognized
|
|
167
|
+
*/
|
|
121
168
|
getAiServiceFromServiceName(serviceName) {
|
|
122
169
|
return this.aiFactoryService.createAiService(serviceName);
|
|
123
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Fetches available models from the specified AI service provider.
|
|
173
|
+
*
|
|
174
|
+
* @param aiServiceName - Provider name as returned by {@link getAiServiceNames}
|
|
175
|
+
* @returns Array of model descriptors including name, description, and service
|
|
176
|
+
*/
|
|
124
177
|
async listAiModels(aiServiceName) {
|
|
125
178
|
let service = this.getAiServiceFromServiceName(aiServiceName);
|
|
126
179
|
return service.listModels();
|
|
127
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Returns models available for image generation, as configured in
|
|
183
|
+
* `common/config/image_models.json`.
|
|
184
|
+
*
|
|
185
|
+
* @returns Array of model descriptors. Returns an empty array if the config file is missing.
|
|
186
|
+
*/
|
|
128
187
|
async listImageModels() {
|
|
129
188
|
const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
|
|
130
189
|
try {
|
|
131
190
|
const entries = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
|
|
191
|
+
// The dialog presents one image-model dropdown. Each consolidated entry
|
|
192
|
+
// carries its own generation and editing models server-side, so the client
|
|
193
|
+
// only needs the name and description. "No images" is offered as a fixed
|
|
194
|
+
// option in the dialog itself, so it is excluded here.
|
|
132
195
|
return entries
|
|
133
196
|
.filter((entry) => entry.name && entry.name !== 'No images')
|
|
134
197
|
.map((entry) => ({ name: entry.name, description: entry.description ?? '' }));
|
|
@@ -138,6 +201,12 @@ class AppService {
|
|
|
138
201
|
return [];
|
|
139
202
|
}
|
|
140
203
|
}
|
|
204
|
+
/**
|
|
205
|
+
* Returns models available for story generation, as configured in
|
|
206
|
+
* `common/config/story_models.json`.
|
|
207
|
+
*
|
|
208
|
+
* @returns Array of model descriptors. Returns an empty array if the config file is missing.
|
|
209
|
+
*/
|
|
141
210
|
async listStoryModels() {
|
|
142
211
|
const storyModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'story_models.json');
|
|
143
212
|
try {
|
|
@@ -148,6 +217,14 @@ class AppService {
|
|
|
148
217
|
return [];
|
|
149
218
|
}
|
|
150
219
|
}
|
|
220
|
+
/**
|
|
221
|
+
* Returns the available story genre names.
|
|
222
|
+
*
|
|
223
|
+
* Genres are read from `common/story_ideas/` - each `.json` file corresponds to a genre.
|
|
224
|
+
* Pass a genre name to {@link getRandomStoryIdeaByGenre} to get a story idea.
|
|
225
|
+
*
|
|
226
|
+
* @returns Array of genre names (e.g. `['fantasy', 'sci-fi', 'mystery']`)
|
|
227
|
+
*/
|
|
151
228
|
listStoryGenres() {
|
|
152
229
|
const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas');
|
|
153
230
|
try {
|
|
@@ -164,6 +241,14 @@ class AppService {
|
|
|
164
241
|
return [];
|
|
165
242
|
}
|
|
166
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* Returns a random story idea from the specified genre.
|
|
246
|
+
*
|
|
247
|
+
* @param genreName - Genre name as returned by {@link listStoryGenres} (e.g. `'fantasy'`)
|
|
248
|
+
* @returns A random `StoryIdea` object, or `null` if the genre file is empty
|
|
249
|
+
* @throws {NotFoundError} If the genre does not exist
|
|
250
|
+
* @throws {OperationFailedError} If the genre file cannot be read
|
|
251
|
+
*/
|
|
167
252
|
getRandomStoryIdeaByGenre(genreName) {
|
|
168
253
|
const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas', `${genreName}.json`);
|
|
169
254
|
try {
|
|
@@ -174,6 +259,7 @@ class AppService {
|
|
|
174
259
|
if (ideas.length === 0) {
|
|
175
260
|
return null;
|
|
176
261
|
}
|
|
262
|
+
// Return random idea from the array
|
|
177
263
|
const randomIndex = Math.floor(Math.random() * ideas.length);
|
|
178
264
|
return ideas[randomIndex];
|
|
179
265
|
}
|
|
@@ -185,33 +271,82 @@ class AppService {
|
|
|
185
271
|
throw new errors_1.OperationFailedError('Failed to read story ideas');
|
|
186
272
|
}
|
|
187
273
|
}
|
|
274
|
+
/**
|
|
275
|
+
* Returns a random story idea from a randomly selected genre.
|
|
276
|
+
*
|
|
277
|
+
* @returns A random `StoryIdea` object, or `null` if no genres/ideas are available
|
|
278
|
+
*/
|
|
188
279
|
getRandomStoryIdea() {
|
|
189
280
|
const genres = this.listStoryGenres();
|
|
190
281
|
if (genres.length === 0) {
|
|
191
282
|
return null;
|
|
192
283
|
}
|
|
284
|
+
// Pick random genre
|
|
193
285
|
const randomGenre = genres[Math.floor(Math.random() * genres.length)];
|
|
286
|
+
// Get random idea from that genre
|
|
194
287
|
return this.getRandomStoryIdeaByGenre(randomGenre);
|
|
195
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* Creates a new AI agent and registers it in memory.
|
|
291
|
+
*
|
|
292
|
+
* The agent is immediately findable by ID but **not** persisted to disk.
|
|
293
|
+
* Call `agent.save()` when you want to write it to storage.
|
|
294
|
+
*
|
|
295
|
+
* @param aiServiceName - Provider name (e.g. `'Anthropic'`, `'OpenAI'`). Use {@link getAiServiceNames} for valid values.
|
|
296
|
+
* @param agentName - Full name of the agent (used in conversation logs and file storage)
|
|
297
|
+
* @param agentNickname - Short display name shown in the UI
|
|
298
|
+
* @param description - Brief description of the agent's role or personality
|
|
299
|
+
* @param aiModel - Model identifier (e.g. `'claude-haiku-4-5'`, `'gpt-4o'`)
|
|
300
|
+
* @param promptName - Prompt folder under `data/prompts/` that provides the agent's system instruction. Defaults to `'default'`.
|
|
301
|
+
* @param controlledByHuman - If `true`, the agent's responses are driven by a human rather than the AI. Defaults to `false`.
|
|
302
|
+
* @param reasoningEffort - Extended-thinking effort level for models that support it (e.g. Claude 3.7 Sonnet, o1/o3). Pass `null` to disable. Defaults to `undefined` (model default).
|
|
303
|
+
* @param maxOutputTokens - Override the model's default maximum output token limit
|
|
304
|
+
* @param beginInstruction - Optional prompt stored with the agent and sent when the host app triggers a "Begin" action (e.g. `'Begin by reading the attached documents and asking the user the first question.'`)
|
|
305
|
+
* @param options - Everything else an agent can be created with: tool grants, private context, prompt cache TTL, search, the history window and the small-model override. Add new settings here rather than as further positional parameters.
|
|
306
|
+
* @returns The newly created {@link Agent} instance
|
|
307
|
+
*
|
|
308
|
+
* @example
|
|
309
|
+
* ```typescript
|
|
310
|
+
* const agent = appService.createAgent(
|
|
311
|
+
* 'Anthropic',
|
|
312
|
+
* 'AI Assistant',
|
|
313
|
+
* 'James',
|
|
314
|
+
* 'A helpful AI assistant',
|
|
315
|
+
* 'claude-haiku-4-5',
|
|
316
|
+
* );
|
|
317
|
+
* if (!agent.id) throw new Error('Agent creation failed');
|
|
318
|
+
* agent.save(); // persist to disk
|
|
319
|
+
* ```
|
|
320
|
+
*/
|
|
196
321
|
createAgent(aiServiceName, agentName, agentNickname, description, aiModel, promptName = 'default', controlledByHuman, reasoningEffort, maxOutputTokens, beginInstruction, options) {
|
|
322
|
+
// A folder that reaches nothing is not an error here — the agent still runs,
|
|
323
|
+
// on the shared root prompts — but it is never what the caller meant, and
|
|
324
|
+
// the only symptom is a generic agent several LLM calls later.
|
|
197
325
|
if (!this.promptFolderExists(promptName)) {
|
|
198
326
|
logger_1.logger.warn(`Agent "${agentNickname}" names the prompt folder "${promptName}", which does not exist. ` +
|
|
199
327
|
`It will fall back to the shared root prompts and behave generically. ` +
|
|
200
328
|
`A pack's folder is named "<pack>:${promptName}" unless the pack is enabled for this user.`);
|
|
201
329
|
}
|
|
202
330
|
const agent = this.agentFactory.createAgent(aiServiceName, agentName, agentNickname, description, promptName, aiModel);
|
|
331
|
+
// Set the controlledByHuman property
|
|
203
332
|
if (controlledByHuman !== undefined) {
|
|
204
333
|
agent.isControlledByHuman = controlledByHuman;
|
|
205
334
|
}
|
|
335
|
+
// Set the reasoningEffort property
|
|
206
336
|
if (reasoningEffort !== undefined) {
|
|
207
337
|
agent.reasoningEffort = reasoningEffort;
|
|
208
338
|
}
|
|
339
|
+
// Set the reasoningEffort property
|
|
209
340
|
if (maxOutputTokens !== undefined) {
|
|
210
341
|
agent.maxOutputTokens = maxOutputTokens;
|
|
211
342
|
}
|
|
343
|
+
// Set the beginInstruction property
|
|
212
344
|
if (beginInstruction !== undefined) {
|
|
213
345
|
agent.beginInstruction = beginInstruction;
|
|
214
346
|
}
|
|
347
|
+
// Everything without a positional slot. New settings go here rather than
|
|
348
|
+
// lengthening the parameter list, and every one of them is also settable
|
|
349
|
+
// through updateAgent, so nothing is create-only or edit-only.
|
|
215
350
|
if (options) {
|
|
216
351
|
if (options.allowSearch !== undefined)
|
|
217
352
|
agent.allowSearch = options.allowSearch;
|
|
@@ -230,15 +365,72 @@ class AppService {
|
|
|
230
365
|
if (options.ownerRoomId !== undefined)
|
|
231
366
|
agent.ownerRoomId = options.ownerRoomId;
|
|
232
367
|
}
|
|
368
|
+
// Set up SSE callback for this agent
|
|
233
369
|
this.setupAgentStateCallback(agent);
|
|
370
|
+
// Register in memory so the agent is immediately findable by ID,
|
|
371
|
+
// without writing to disk (call agent.save() to persist).
|
|
234
372
|
this.agentStore.registerAgent(agent);
|
|
235
373
|
return agent;
|
|
236
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Creates an agent from a prompt folder, applying everything that folder declares.
|
|
377
|
+
*
|
|
378
|
+
* A folder's `defaults_config.json` names the role: what it is called, which tools
|
|
379
|
+
* it needs, which documents it carries. {@link createAgent} takes none of that —
|
|
380
|
+
* it takes eleven positional arguments and an options object, and leaves the
|
|
381
|
+
* mapping to the caller. Every caller then writes the same mapping: the web
|
|
382
|
+
* client's create-agent dialog, and every SDK host after it. Hard-coding the
|
|
383
|
+
* result instead is worse, because a pack's tool and document lists change and a
|
|
384
|
+
* transcribed copy does not.
|
|
385
|
+
*
|
|
386
|
+
* Differences from {@link createAgent}, each deliberate:
|
|
387
|
+
*
|
|
388
|
+
* - **It saves.** A convenience constructor that leaves the agent in memory only
|
|
389
|
+
* loses it on restart, which is not what a caller reaching for one expects.
|
|
390
|
+
* - **It attaches the folder's documents**, unless `attachDocuments` is false.
|
|
391
|
+
* {@link PromptFolderDefaults.documentIds} describes them as a pre-tick that
|
|
392
|
+
* stays the user's choice, which is right for a dialog where somebody can untick
|
|
393
|
+
* a box; headless there is nobody to untick, and a character creator without its
|
|
394
|
+
* class documents builds sheets with no spells and no class features.
|
|
395
|
+
* - **It is async**, only because attaching is.
|
|
396
|
+
*
|
|
397
|
+
* @param options.folder Prompt folder name, e.g. `'dungeon_master'`
|
|
398
|
+
* @param options.aiServiceName Provider name, e.g. `'Anthropic'`
|
|
399
|
+
* @param options.aiModel Model id for this agent
|
|
400
|
+
* @param options.overrides Fields to override the folder's declared defaults;
|
|
401
|
+
* the same shape, so `{agentNickname: 'Homer', controlledByHuman: true}` is all
|
|
402
|
+
* a human-controlled player needs
|
|
403
|
+
* @param options.attachDocuments Attach the folder's `documentIds` (default true)
|
|
404
|
+
* @returns The created, saved agent
|
|
405
|
+
* @throws {NotFoundError} If the folder does not exist. Unlike {@link createAgent},
|
|
406
|
+
* which warns and carries on, this refuses: the whole point of the call is the
|
|
407
|
+
* folder's recipe, and a folder that is not there has none — the agent would come
|
|
408
|
+
* out with no tools, no documents and the shared root prompts
|
|
409
|
+
* @throws {Error} If the agent could not be created
|
|
410
|
+
*
|
|
411
|
+
* @example
|
|
412
|
+
* ```typescript
|
|
413
|
+
* const dm = await appService.createAgentFromFolder({
|
|
414
|
+
* folder: 'dungeon_master',
|
|
415
|
+
* aiServiceName: 'Anthropic',
|
|
416
|
+
* aiModel: 'claude-sonnet-5',
|
|
417
|
+
* });
|
|
418
|
+
* const you = await appService.createAgentFromFolder({
|
|
419
|
+
* folder: 'dnd_player',
|
|
420
|
+
* aiServiceName: 'Anthropic',
|
|
421
|
+
* aiModel: 'claude-haiku-4-5',
|
|
422
|
+
* overrides: { agentNickname: 'Homer', controlledByHuman: true },
|
|
423
|
+
* });
|
|
424
|
+
* ```
|
|
425
|
+
*/
|
|
237
426
|
async createAgentFromFolder(options) {
|
|
238
427
|
this.requirePromptFolder(options.folder);
|
|
239
428
|
const { defaults } = this.getPromptFolderDefaults(options.folder);
|
|
240
429
|
const settings = { ...defaults, ...options.overrides };
|
|
241
|
-
const agent = this.createAgent(options.aiServiceName,
|
|
430
|
+
const agent = this.createAgent(options.aiServiceName,
|
|
431
|
+
// A folder that names neither falls back to its own name, which is at
|
|
432
|
+
// least addressable — an agent with an empty nickname is not.
|
|
433
|
+
settings.agentName ?? options.folder, settings.agentNickname ?? settings.agentName ?? options.folder, settings.description ?? '', options.aiModel, options.folder, settings.controlledByHuman, settings.reasoningEffort ?? null, undefined, settings.beginInstruction, {
|
|
242
434
|
toolNames: settings.toolNames ?? [],
|
|
243
435
|
allowSearch: settings.allowSearch,
|
|
244
436
|
useModerator: settings.useModerator,
|
|
@@ -258,14 +450,37 @@ class AppService {
|
|
|
258
450
|
}
|
|
259
451
|
return agent;
|
|
260
452
|
}
|
|
453
|
+
/**
|
|
454
|
+
* Sends a text prompt to an agent and returns its response.
|
|
455
|
+
*
|
|
456
|
+
* The exchange is added to the agent's conversation history and persisted to disk.
|
|
457
|
+
*
|
|
458
|
+
* @param agentId - The agent's ID (from {@link createAgent} or {@link listAgents})
|
|
459
|
+
* @param text - The prompt text to send
|
|
460
|
+
* @returns Object containing the agent's reply text (`result`), the latest formatted
|
|
461
|
+
* message, its index in the history, and cumulative token counts and cost
|
|
462
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
463
|
+
*
|
|
464
|
+
* @example
|
|
465
|
+
* ```typescript
|
|
466
|
+
* const result = await appService.processText(agent.id, 'What is the capital of France?');
|
|
467
|
+
* console.log(result.result); // 'Paris'
|
|
468
|
+
* console.log(result.totalCost); // e.g. 0.000023
|
|
469
|
+
* ```
|
|
470
|
+
*/
|
|
261
471
|
async processText(agentId, text) {
|
|
472
|
+
// Retrieve the agent from the store
|
|
262
473
|
const agent = await this.agentStore.getAgent(agentId);
|
|
263
474
|
if (!agent) {
|
|
264
475
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
265
476
|
}
|
|
477
|
+
// Set up SSE callback for this agent (if not already set)
|
|
266
478
|
this.setupAgentStateCallback(agent);
|
|
479
|
+
// Process the text using the agent context
|
|
267
480
|
const result = await agent.textPrompt(text, null, true, null, true);
|
|
481
|
+
// Save agent state to persist history changes and trigger SSE update
|
|
268
482
|
agent.save();
|
|
483
|
+
// Return latest message and its index
|
|
269
484
|
const messages = agent.getFormattedMessages();
|
|
270
485
|
return {
|
|
271
486
|
result,
|
|
@@ -276,22 +491,64 @@ class AppService {
|
|
|
276
491
|
totalCost: agent.totalCost,
|
|
277
492
|
};
|
|
278
493
|
}
|
|
494
|
+
/**
|
|
495
|
+
* Attaches a document to an agent so it can reference the file's contents in prompts.
|
|
496
|
+
*
|
|
497
|
+
* The file is stored on disk and uploaded to the AI provider if required
|
|
498
|
+
* (e.g. OpenAI file uploads, Grok file uploads). The agent state is persisted after attachment.
|
|
499
|
+
*
|
|
500
|
+
* @param agentId - The agent's ID
|
|
501
|
+
* @param fileName - File name including extension (e.g. `'report.pdf'`)
|
|
502
|
+
* @param fileData - Raw file bytes as a `Buffer`
|
|
503
|
+
* @returns Object containing a `documentId` that can be used with {@link deleteAttachedFileById}
|
|
504
|
+
* @throws {Error} If no agent with the given ID exists
|
|
505
|
+
*/
|
|
279
506
|
async attachDocument(agentId, fileName, fileData) {
|
|
280
507
|
let agent = await this.agentStore.getAgent(agentId);
|
|
281
508
|
if (!agent)
|
|
282
509
|
throw new Error(`Agent with ID ${agentId} not found`);
|
|
510
|
+
// Store the file using the AttachedFileService
|
|
283
511
|
const fileId = this.attachedFileService.storeFile(agentId, fileName, new Uint8Array(fileData));
|
|
512
|
+
// Get the file metadata and add it to the agent's attachedFiles array
|
|
284
513
|
const fileMetadata = this.attachedFileService.getFileMetadataByName(agentId, fileName);
|
|
285
514
|
if (fileMetadata && !agent.attachedFiles.some((f) => f.fileName === fileName)) {
|
|
286
515
|
agent.attachedFiles.push(fileMetadata);
|
|
287
516
|
}
|
|
517
|
+
// Process the document with the AI service
|
|
288
518
|
await agent.attachDocument(fileName, new Uint8Array(fileData));
|
|
519
|
+
// Save agent to persist serviceMetadata added by AI service
|
|
289
520
|
agent.save();
|
|
290
521
|
return { documentId: fileId };
|
|
291
522
|
}
|
|
523
|
+
/**
|
|
524
|
+
* Returns every prompt folder name this user can reach.
|
|
525
|
+
*
|
|
526
|
+
* Covers the common and user prompt directories plus the folders of any pack
|
|
527
|
+
* the user has enabled, which appear pack-qualified (`dnd5e:dungeon_master`).
|
|
528
|
+
* A folder in more than one directory appears once.
|
|
529
|
+
*
|
|
530
|
+
* @returns Sorted array of folder names
|
|
531
|
+
*/
|
|
292
532
|
listPromptFolders() {
|
|
293
533
|
return (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, { enabledPacks: this.enabledPacks }).map((folder) => folder.value);
|
|
294
534
|
}
|
|
535
|
+
/**
|
|
536
|
+
* Returns prompt folder names annotated with where they came from.
|
|
537
|
+
*
|
|
538
|
+
* When the same folder name exists in both the user and common directories the
|
|
539
|
+
* user copy wins and the entry reports `scope: 'user'`. A pack's folder is a
|
|
540
|
+
* separate entry under its qualified name, so a pack shipping a `witness`
|
|
541
|
+
* folder does not collide with a `witness` folder the user wrote.
|
|
542
|
+
*
|
|
543
|
+
* Pack folders are listed only for enabled packs. That is the difference
|
|
544
|
+
* between listing and resolving: a disabled pack's folder still resolves when
|
|
545
|
+
* an agent names it, it just stops being offered.
|
|
546
|
+
*
|
|
547
|
+
* @param scope - Optional filter: `'common'` returns only system-provided folders
|
|
548
|
+
* (including packs', which are read-only in the same way), `'user'` returns only
|
|
549
|
+
* the user's own folders and their pack overlays, omit to return all
|
|
550
|
+
* @returns Object with a `folders` array, sorted by name
|
|
551
|
+
*/
|
|
295
552
|
listPromptFoldersWithScope(scope) {
|
|
296
553
|
const folders = (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, {
|
|
297
554
|
enabledPacks: this.enabledPacks,
|
|
@@ -304,40 +561,85 @@ class AppService {
|
|
|
304
561
|
}));
|
|
305
562
|
return { folders };
|
|
306
563
|
}
|
|
564
|
+
/**
|
|
565
|
+
* Returns all prepared prompt template names available to a specific agent.
|
|
566
|
+
*
|
|
567
|
+
* Merges prompts from the agent's own prompt folder and the root prompts directory,
|
|
568
|
+
* deduplicating across both. These names can be passed to {@link runPreparedPrompt}.
|
|
569
|
+
*
|
|
570
|
+
* @param agentId - The agent's ID
|
|
571
|
+
* @returns Array of prompt template names (without file extension)
|
|
572
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
573
|
+
*/
|
|
307
574
|
async listPrompts(agentId) {
|
|
575
|
+
// Retrieve the agent from the store
|
|
308
576
|
const agent = await this.agentStore.getAgent(agentId);
|
|
309
577
|
if (!agent) {
|
|
310
578
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
311
579
|
}
|
|
580
|
+
// Get the prompt path from the agent
|
|
312
581
|
let agentPromptsDir = path.join(this.userPaths.getPromptsDir(), agent.promptFolder);
|
|
313
582
|
let promptFiles = [];
|
|
583
|
+
// Check if directory exists
|
|
314
584
|
if (fs.existsSync(agentPromptsDir)) {
|
|
585
|
+
// Get all .prompt files in the agent's prompt folder
|
|
315
586
|
promptFiles = fs
|
|
316
587
|
.readdirSync(agentPromptsDir)
|
|
317
588
|
.filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
|
|
318
589
|
.map((file) => file.replace('.prompt', ''));
|
|
319
590
|
}
|
|
591
|
+
// Also get prompts from the root prompts directory
|
|
320
592
|
const rootPromptFiles = fs
|
|
321
593
|
.readdirSync(this.userPaths.getPromptsDir())
|
|
322
594
|
.filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
|
|
323
595
|
.map((file) => file.replace('.prompt', ''));
|
|
596
|
+
// Combine the prompt files, avoiding duplicates
|
|
324
597
|
promptFiles = [...new Set([...promptFiles, ...rootPromptFiles])];
|
|
325
598
|
return promptFiles;
|
|
326
599
|
}
|
|
600
|
+
/**
|
|
601
|
+
* Executes a named Handlebars prompt template against an agent.
|
|
602
|
+
*
|
|
603
|
+
* The template is loaded from the agent's prompt folder (with the standard 4-level
|
|
604
|
+
* fallback). `variables` are substituted into the template before sending.
|
|
605
|
+
*
|
|
606
|
+
* @param agentId - The agent's ID
|
|
607
|
+
* @param promptName - Template name returned by {@link listPrompts} (without extension)
|
|
608
|
+
* @param variables - Key-value pairs substituted into the template's `{{variable}}` placeholders
|
|
609
|
+
* @returns Object with a `result` string containing the agent's response
|
|
610
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
611
|
+
*/
|
|
327
612
|
async runPreparedPrompt(agentId, promptName, variables = {}) {
|
|
613
|
+
// Retrieve the agent from the store
|
|
328
614
|
const agent = await this.agentStore.getAgent(agentId);
|
|
329
615
|
if (!agent) {
|
|
330
616
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
331
617
|
}
|
|
618
|
+
// Use Agent.preparedPrompt so cache config is computed via getCacheConfig()
|
|
619
|
+
// rather than left as the bare default - required by Anthropic's API.
|
|
332
620
|
const result = await agent.preparedPrompt(promptName, variables || {}, true);
|
|
333
621
|
return { result };
|
|
334
622
|
}
|
|
623
|
+
/**
|
|
624
|
+
* Lists all top-level agents belonging to this user.
|
|
625
|
+
*
|
|
626
|
+
* Agents that are owned by a room or story are excluded - use
|
|
627
|
+
* {@link getRoomDetails} or story methods to access those agents.
|
|
628
|
+
*
|
|
629
|
+
* @param includeRoomAgents - Also return the agents owned by a room or story.
|
|
630
|
+
* Only for offering an existing agent as something to copy; the agent list a
|
|
631
|
+
* user manages is the default, unowned one.
|
|
632
|
+
* @returns Array of agent metadata objects
|
|
633
|
+
*/
|
|
335
634
|
async listAgents(includeRoomAgents = false) {
|
|
635
|
+
// Get all agent IDs from the store
|
|
336
636
|
const agentIds = await this.agentStore.getAllAgentIds();
|
|
637
|
+
// Map each ID to an object with agent details
|
|
337
638
|
const agentInfos = [];
|
|
338
639
|
for (const id of agentIds) {
|
|
339
640
|
const agent = await this.agentStore.getAgent(id);
|
|
340
641
|
if (agent) {
|
|
642
|
+
// Don't show agents that belong to a cloned room (or a story)
|
|
341
643
|
if (agent.ownerRoomId && !includeRoomAgents)
|
|
342
644
|
continue;
|
|
343
645
|
agentInfos.push({
|
|
@@ -366,6 +668,12 @@ class AppService {
|
|
|
366
668
|
}
|
|
367
669
|
return agentInfos;
|
|
368
670
|
}
|
|
671
|
+
/**
|
|
672
|
+
* Returns detailed metadata for a specific agent.
|
|
673
|
+
*
|
|
674
|
+
* @param agentId - The agent's ID
|
|
675
|
+
* @returns Agent metadata object, or `null` if no agent with the given ID exists
|
|
676
|
+
*/
|
|
369
677
|
async getAgentDetails(agentId) {
|
|
370
678
|
try {
|
|
371
679
|
const agent = await this.agentStore.getAgent(agentId);
|
|
@@ -394,6 +702,8 @@ class AppService {
|
|
|
394
702
|
canModerate: this.canAgentModerate(agent),
|
|
395
703
|
privateContext: agent.privateContext,
|
|
396
704
|
promptCacheTTL: agent.promptCacheTTL,
|
|
705
|
+
// The rest of what an agent is configured with, so copying one into
|
|
706
|
+
// a room reproduces it rather than a partly-defaulted lookalike.
|
|
397
707
|
maxHistoryMessages: agent.maxHistoryMessages,
|
|
398
708
|
smallModelName: agent.smallModelName,
|
|
399
709
|
ownerRoomId: agent.ownerRoomId,
|
|
@@ -406,12 +716,65 @@ class AppService {
|
|
|
406
716
|
return null;
|
|
407
717
|
}
|
|
408
718
|
}
|
|
719
|
+
/**
|
|
720
|
+
* Creates a new room and populates it with the specified agents.
|
|
721
|
+
*
|
|
722
|
+
* @param roomName - Display name for the room
|
|
723
|
+
* @param goal - Description of the room's purpose or objective, shared with all agents
|
|
724
|
+
* @param agentIds - IDs of the agents to add to the room. May be empty: a room
|
|
725
|
+
* is created before the agents that belong to it exist, and they are added
|
|
726
|
+
* afterwards with {@link createRoomAgent}.
|
|
727
|
+
* @param roomLeader - Nickname (or name) of the member agent to lead the room.
|
|
728
|
+
* Defaults to the first agent.
|
|
729
|
+
* @param turnMode - `'broadcast'` (default) prompts every agent for each message;
|
|
730
|
+
* `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
|
|
731
|
+
* @param moderator - Nickname of the agent that places messages the room cannot
|
|
732
|
+
* route mechanically. Only consulted in `'moderated'` mode.
|
|
733
|
+
* @returns Object containing the new `roomId`
|
|
734
|
+
* @throws {NotFoundError} If any agent ID does not exist
|
|
735
|
+
*
|
|
736
|
+
* @example
|
|
737
|
+
* ```typescript
|
|
738
|
+
* const { roomId } = await appService.createRoom(
|
|
739
|
+
* 'Research Session',
|
|
740
|
+
* 'Analyze the provided documents and produce a summary',
|
|
741
|
+
* [analystId, writerAgentId],
|
|
742
|
+
* );
|
|
743
|
+
* ```
|
|
744
|
+
*/
|
|
745
|
+
/**
|
|
746
|
+
* Whether a prompt folder provides the `moderate.prompt` a moderator needs.
|
|
747
|
+
*
|
|
748
|
+
* The one definition of "could moderate", shared by the check that refuses a
|
|
749
|
+
* misconfigured room and the {@link AgentInfo.canModerate} the client picks a
|
|
750
|
+
* moderator with. Two definitions would eventually disagree, and the way they
|
|
751
|
+
* would show it is a room offering a moderator the server then rejects.
|
|
752
|
+
*/
|
|
409
753
|
folderProvidesModeratePrompt(promptFolder) {
|
|
410
754
|
return !!this.getPromptFile(promptFolder, 'moderate.prompt').scope;
|
|
411
755
|
}
|
|
756
|
+
/**
|
|
757
|
+
* Whether this agent could be a room's moderator.
|
|
758
|
+
*
|
|
759
|
+
* Both halves matter: moderating means answering a prompt, which a human agent
|
|
760
|
+
* never does, and it means having that prompt to answer.
|
|
761
|
+
*/
|
|
412
762
|
canAgentModerate(agent) {
|
|
413
763
|
return !agent.isControlledByHuman && this.folderProvidesModeratePrompt(agent.promptFolder);
|
|
414
764
|
}
|
|
765
|
+
/**
|
|
766
|
+
* Why the room cannot moderate, or null when it can.
|
|
767
|
+
*
|
|
768
|
+
* "Can" is deliberately stronger than "a moderator is named". A moderator whose
|
|
769
|
+
* prompt folder has no `moderate.prompt` fails in the worst possible way: the
|
|
770
|
+
* prompt lookup throws, {@link Room} swallows the throw, and the message
|
|
771
|
+
* disappears leaving only a log line. Catching that here is the difference
|
|
772
|
+
* between an error the user can act on and a room that quietly eats messages.
|
|
773
|
+
*
|
|
774
|
+
* @param roster The membership to resolve the moderator against, which is not
|
|
775
|
+
* always the room's current one — an agent being added is checked before it
|
|
776
|
+
* arrives.
|
|
777
|
+
*/
|
|
415
778
|
describeMissingModerator(room, roster) {
|
|
416
779
|
const named = room.getModerator();
|
|
417
780
|
if (!named?.trim()) {
|
|
@@ -429,6 +792,16 @@ class AppService {
|
|
|
429
792
|
}
|
|
430
793
|
return null;
|
|
431
794
|
}
|
|
795
|
+
/**
|
|
796
|
+
* Refuses a configuration in which an agent that sends MODERATE messages has no
|
|
797
|
+
* moderator to route them.
|
|
798
|
+
*
|
|
799
|
+
* Checked when the combination can come into being — creating a room, adding an
|
|
800
|
+
* agent to one, changing a room's moderator, turning the flag on — and never on
|
|
801
|
+
* load, which would make an existing room unopenable rather than fixable.
|
|
802
|
+
*
|
|
803
|
+
* @param arriving An agent not yet in the room, checked as though it were.
|
|
804
|
+
*/
|
|
432
805
|
assertModeratorAvailable(room, arriving) {
|
|
433
806
|
const roster = arriving ? [...room.getAgents(), arriving] : room.getAgents();
|
|
434
807
|
const needsModerator = roster.filter((agent) => agent.useModerator);
|
|
@@ -442,17 +815,22 @@ class AppService {
|
|
|
442
815
|
`so room "${room.getName()}" needs one. ${reason}`);
|
|
443
816
|
}
|
|
444
817
|
async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator) {
|
|
818
|
+
// Validate that all agents exist before creating the room
|
|
445
819
|
for (const agentId of agentIds) {
|
|
446
820
|
const agent = await this.agentStore.getAgent(agentId);
|
|
447
821
|
if (!agent) {
|
|
448
822
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
449
823
|
}
|
|
450
824
|
}
|
|
825
|
+
// Create a new room with the specified name and goal
|
|
451
826
|
const room = this.roomFactory.createRoom(roomName, goal);
|
|
827
|
+
// Add each agent to the room
|
|
452
828
|
for (const agentId of agentIds) {
|
|
453
829
|
const agent = await this.agentStore.getAgent(agentId);
|
|
454
830
|
room.arrive(agent);
|
|
455
831
|
}
|
|
832
|
+
// Leader and turn mode are set after the roster so the leader can be
|
|
833
|
+
// validated against it.
|
|
456
834
|
if (roomLeader !== undefined) {
|
|
457
835
|
room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
|
|
458
836
|
}
|
|
@@ -462,24 +840,53 @@ class AppService {
|
|
|
462
840
|
if (moderator !== undefined) {
|
|
463
841
|
room.setModerator(moderator);
|
|
464
842
|
}
|
|
843
|
+
// Before saveMetadata, so a room that cannot route its members' messages is
|
|
844
|
+
// never written to disk.
|
|
465
845
|
this.assertModeratorAvailable(room);
|
|
466
846
|
room.ready();
|
|
847
|
+
// Store the room and get its ID
|
|
467
848
|
const roomId = room.saveMetadata();
|
|
849
|
+
// Set up SSE callback for real-time updates
|
|
468
850
|
this.setupRoomStateCallback(room);
|
|
469
851
|
return { roomId };
|
|
470
852
|
}
|
|
853
|
+
/**
|
|
854
|
+
* Updates the name, goal, and/or agent membership of an existing room.
|
|
855
|
+
*
|
|
856
|
+
* Published room instances cannot be edited - edit the template instead.
|
|
857
|
+
*
|
|
858
|
+
* @param roomId - The room's ID
|
|
859
|
+
* @param roomName - New display name
|
|
860
|
+
* @param goal - New goal description
|
|
861
|
+
* @param baseRoomDir - Optional override for the room's base storage directory
|
|
862
|
+
* @param agentIds - Replacement list of agent IDs (replaces current membership
|
|
863
|
+
* entirely). Omit to leave membership unchanged, which is what the client
|
|
864
|
+
* does: membership is managed through {@link createRoomAgent} and
|
|
865
|
+
* {@link removeRoomAgent}, not by re-sending the roster with every rename.
|
|
866
|
+
* @param roomLeader - Nickname (or name) of the member agent to lead the room.
|
|
867
|
+
* Omit to leave the current leader unchanged.
|
|
868
|
+
* @param turnMode - How the room chooses who responds. Omit to leave unchanged.
|
|
869
|
+
* See {@link RoomTurnMode}.
|
|
870
|
+
* @param moderator - Nickname of the moderator agent. Omit to leave unchanged.
|
|
871
|
+
* @throws {NotFoundError} If the room does not exist
|
|
872
|
+
* @throws {OperationFailedError} If attempting to edit a published room instance
|
|
873
|
+
*/
|
|
471
874
|
async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack) {
|
|
875
|
+
// Get the existing room
|
|
472
876
|
const room = await this.roomStore.getRoom(roomId);
|
|
473
877
|
if (!room) {
|
|
474
878
|
throw new errors_1.NotFoundError('Room not found');
|
|
475
879
|
}
|
|
880
|
+
// Prevent editing published instances
|
|
476
881
|
if (room.getIsPublished() && room.getTemplateRoomId()) {
|
|
477
882
|
throw new errors_1.OperationFailedError('Cannot edit published room instances');
|
|
478
883
|
}
|
|
884
|
+
// Update room properties
|
|
479
885
|
const previousName = room.getName();
|
|
480
886
|
room.setName(roomName);
|
|
481
887
|
room.setGoal(goal);
|
|
482
888
|
room.setBaseRoomDir(baseRoomDir || '');
|
|
889
|
+
// Update agents
|
|
483
890
|
if (agentIds) {
|
|
484
891
|
const newAgents = [];
|
|
485
892
|
for (const agentId of agentIds) {
|
|
@@ -493,9 +900,14 @@ class AppService {
|
|
|
493
900
|
}
|
|
494
901
|
room.setAgents(newAgents);
|
|
495
902
|
}
|
|
903
|
+
// A renamed room renames the agents it owns, whose names carry its name as
|
|
904
|
+
// a prefix. Without this the prefix records what the room was called when
|
|
905
|
+
// each agent was added, which is worse than no prefix at all.
|
|
496
906
|
if (roomName !== previousName) {
|
|
497
907
|
this.renameOwnedAgents(room, previousName, roomName);
|
|
498
908
|
}
|
|
909
|
+
// After setAgents, so a leader is validated against the new membership
|
|
910
|
+
// rather than the roster it is replacing.
|
|
499
911
|
if (roomLeader !== undefined) {
|
|
500
912
|
room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
|
|
501
913
|
}
|
|
@@ -508,17 +920,39 @@ class AppService {
|
|
|
508
920
|
if (pack !== undefined) {
|
|
509
921
|
room.setPack(pack);
|
|
510
922
|
}
|
|
923
|
+
// Catches clearing the moderator, or pointing it at an agent this edit just
|
|
924
|
+
// removed, while a member still needs one.
|
|
511
925
|
this.assertModeratorAvailable(room);
|
|
926
|
+
// Save the updated room
|
|
512
927
|
room.saveMetadata();
|
|
513
928
|
}
|
|
929
|
+
/**
|
|
930
|
+
* Separates a room's name from the bare name of an agent that belongs to it.
|
|
931
|
+
*/
|
|
514
932
|
static ROOM_AGENT_SEPARATOR = ' - ';
|
|
933
|
+
/**
|
|
934
|
+
* The stored name of an agent that belongs to a room.
|
|
935
|
+
*
|
|
936
|
+
* Every agent lives inside exactly one room, so an unqualified "Narrator" says
|
|
937
|
+
* nothing about which table it sits at once there are three of them.
|
|
938
|
+
*/
|
|
515
939
|
static prefixedAgentName(roomName, bareName) {
|
|
516
940
|
return `${roomName}${AppService.ROOM_AGENT_SEPARATOR}${bareName}`;
|
|
517
941
|
}
|
|
942
|
+
/**
|
|
943
|
+
* Strips a room-name prefix from an agent name, leaving the bare name.
|
|
944
|
+
* An agent that does not carry the prefix is returned unchanged.
|
|
945
|
+
*/
|
|
518
946
|
static bareAgentName(roomName, agentName) {
|
|
519
947
|
const prefix = roomName + AppService.ROOM_AGENT_SEPARATOR;
|
|
520
948
|
return agentName.startsWith(prefix) ? agentName.slice(prefix.length) : agentName;
|
|
521
949
|
}
|
|
950
|
+
/**
|
|
951
|
+
* Re-prefixes the agents a renamed room owns.
|
|
952
|
+
*
|
|
953
|
+
* Only the display name moves. The nickname is what every handoff, target and
|
|
954
|
+
* tool call addresses an agent by, so renaming the room must not touch it.
|
|
955
|
+
*/
|
|
522
956
|
renameOwnedAgents(room, previousName, roomName) {
|
|
523
957
|
for (const agent of room.getAgents()) {
|
|
524
958
|
if (agent.ownerRoomId !== room.getId())
|
|
@@ -528,6 +962,24 @@ class AppService {
|
|
|
528
962
|
agent.save();
|
|
529
963
|
}
|
|
530
964
|
}
|
|
965
|
+
/**
|
|
966
|
+
* Creates an agent that belongs to a room and adds it to that room.
|
|
967
|
+
*
|
|
968
|
+
* This is the only way an agent joins a room. The agent is owned by it: it is
|
|
969
|
+
* left out of {@link listAgents} and deleted with the room, so a room is a
|
|
970
|
+
* self-contained cast rather than a set of references to a shared pool.
|
|
971
|
+
*
|
|
972
|
+
* `request.agentName` is the bare name. It is stored prefixed with the room's
|
|
973
|
+
* name, while the nickname is derived from the bare name — otherwise every
|
|
974
|
+
* agent in the room would be addressed by the room's first word.
|
|
975
|
+
*
|
|
976
|
+
* @param roomId - The room the agent will belong to
|
|
977
|
+
* @param request - The same fields {@link createAgent} takes
|
|
978
|
+
* @returns Object containing the new `agentId`
|
|
979
|
+
* @throws {NotFoundError} If the room does not exist
|
|
980
|
+
* @throws {OperationFailedError} If the room is a published instance, or another
|
|
981
|
+
* agent in the room already answers to the same nickname
|
|
982
|
+
*/
|
|
531
983
|
async createRoomAgent(roomId, request) {
|
|
532
984
|
const room = await this.roomStore.getRoom(roomId);
|
|
533
985
|
if (!room) {
|
|
@@ -537,7 +989,11 @@ class AppService {
|
|
|
537
989
|
throw new errors_1.OperationFailedError('Cannot add agents to a published room instance');
|
|
538
990
|
}
|
|
539
991
|
const bareName = request.agentName.trim();
|
|
992
|
+
// Mirrors Agent.generateNickname, but over the bare name: left to the
|
|
993
|
+
// default the prefixed name would make every agent here "<RoomName>".
|
|
540
994
|
const nickname = request.agentNickname?.trim() || bareName.split(/\s+/)[0];
|
|
995
|
+
// Checked against the request rather than the created agent, so a room with
|
|
996
|
+
// no moderator refuses the agent instead of creating one and rolling it back.
|
|
541
997
|
if (request.useModerator) {
|
|
542
998
|
const reason = this.describeMissingModerator(room, room.getAgents());
|
|
543
999
|
if (reason) {
|
|
@@ -554,6 +1010,8 @@ class AppService {
|
|
|
554
1010
|
smallModelName: request.smallModelName || undefined,
|
|
555
1011
|
ownerRoomId: roomId,
|
|
556
1012
|
});
|
|
1013
|
+
// arrive() refuses a nickname the room already uses. Take the agent back
|
|
1014
|
+
// out rather than leaving one behind that belongs to a room it never joined.
|
|
557
1015
|
if (!room.arrive(agent)) {
|
|
558
1016
|
this.agentStore.removeAgent(agent.id);
|
|
559
1017
|
throw new errors_1.OperationFailedError(`An agent in this room is already addressed as "${nickname}"`);
|
|
@@ -562,10 +1020,37 @@ class AppService {
|
|
|
562
1020
|
room.saveMetadata();
|
|
563
1021
|
return { agentId: agent.id };
|
|
564
1022
|
}
|
|
1023
|
+
/**
|
|
1024
|
+
* Adds an agent to a room, built from a prompt folder's declared defaults.
|
|
1025
|
+
*
|
|
1026
|
+
* The room-scoped counterpart to {@link createAgentFromFolder}, and the piece a
|
|
1027
|
+
* pack's room template is instantiated through. Everything a folder already
|
|
1028
|
+
* declares — name, nickname, description, tool grants, documents, cache TTL —
|
|
1029
|
+
* comes from its `defaults_config.json`, so a template only has to say what
|
|
1030
|
+
* differs.
|
|
1031
|
+
*
|
|
1032
|
+
* Routed through {@link createRoomAgent} rather than {@link createAgentFromFolder},
|
|
1033
|
+
* which does none of what a room member needs: the stored name is prefixed with
|
|
1034
|
+
* the room's, the nickname is derived from the bare name, `ownerRoomId` is set,
|
|
1035
|
+
* the moderator requirement is checked, and an agent whose nickname collides is
|
|
1036
|
+
* removed again instead of being left behind belonging to a room it never joined.
|
|
1037
|
+
*
|
|
1038
|
+
* @param roomId - The room to add to
|
|
1039
|
+
* @param options - The folder to build from, the model to use, and any overrides
|
|
1040
|
+
* @returns The new agent's id, its resolved nickname, and any document ids that
|
|
1041
|
+
* resolved to nothing — returned rather than swallowed, because a document that
|
|
1042
|
+
* silently fails to attach is a capability the agent appears to have and does not
|
|
1043
|
+
* @throws {NotFoundError} If the room does not exist, or the folder does not.
|
|
1044
|
+
* See {@link createAgentFromFolder} for why a missing folder is fatal here
|
|
1045
|
+
* @throws {ValidationError} If the agent needs a moderator the room does not have
|
|
1046
|
+
* @throws {OperationFailedError} If the nickname is already taken in the room
|
|
1047
|
+
*/
|
|
565
1048
|
async createRoomAgentFromFolder(roomId, options) {
|
|
566
1049
|
this.requirePromptFolder(options.folder);
|
|
567
1050
|
const { defaults } = this.getPromptFolderDefaults(options.folder);
|
|
568
1051
|
const settings = { ...defaults, ...options.overrides };
|
|
1052
|
+
// A folder that names neither falls back to its own name, which is at least
|
|
1053
|
+
// addressable. Mirrors createAgentFromFolder.
|
|
569
1054
|
const bareName = settings.agentName ?? options.folder;
|
|
570
1055
|
const nickname = settings.agentNickname ?? bareName.split(/\s+/)[0];
|
|
571
1056
|
const { agentId } = await this.createRoomAgent(roomId, {
|
|
@@ -606,6 +1091,16 @@ class AppService {
|
|
|
606
1091
|
}
|
|
607
1092
|
return { agentId, nickname, unresolvedDocumentIds };
|
|
608
1093
|
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Removes an agent from a room, and deletes it if the room owns it.
|
|
1096
|
+
*
|
|
1097
|
+
* @param roomId - The room's ID
|
|
1098
|
+
* @param agentId - The agent's ID
|
|
1099
|
+
* @throws {NotFoundError} If the room does not exist, or the agent is not in it
|
|
1100
|
+
* @throws {OperationFailedError} If the room is a published instance
|
|
1101
|
+
* @throws {ValidationError} If removing the moderator would leave an agent that
|
|
1102
|
+
* sends MODERATE messages with nothing to route them
|
|
1103
|
+
*/
|
|
609
1104
|
async removeRoomAgent(roomId, agentId) {
|
|
610
1105
|
const room = await this.roomStore.getRoom(roomId);
|
|
611
1106
|
if (!room) {
|
|
@@ -620,6 +1115,10 @@ class AppService {
|
|
|
620
1115
|
throw new errors_1.NotFoundError('Agent is not in this room');
|
|
621
1116
|
}
|
|
622
1117
|
const remaining = agents.filter((a) => a.id !== agentId);
|
|
1118
|
+
// Removing the moderator is the one removal that can quietly break the room:
|
|
1119
|
+
// a message from an agent that sends MODERATE has nowhere to go, and the room
|
|
1120
|
+
// drops it with only a log line. Hand the role on where something can take it,
|
|
1121
|
+
// and refuse where nothing can, rather than leaving that behind.
|
|
623
1122
|
if (room.getModerator() === departing.agentNickname) {
|
|
624
1123
|
const heir = remaining.find((a) => this.canAgentModerate(a));
|
|
625
1124
|
const stillNeeded = remaining.filter((a) => a.useModerator);
|
|
@@ -632,6 +1131,8 @@ class AppService {
|
|
|
632
1131
|
room.setModerator(heir?.agentNickname ?? '');
|
|
633
1132
|
}
|
|
634
1133
|
room.setAgents(remaining);
|
|
1134
|
+
// A leader who has left would make getRoomLeader() name someone absent;
|
|
1135
|
+
// clearing it falls back to the first remaining agent.
|
|
635
1136
|
if (room.getRoomLeader() === departing.agentNickname) {
|
|
636
1137
|
room.setRoomLeader('');
|
|
637
1138
|
}
|
|
@@ -640,15 +1141,31 @@ class AppService {
|
|
|
640
1141
|
await this.deleteAgent(agentId);
|
|
641
1142
|
}
|
|
642
1143
|
}
|
|
1144
|
+
/**
|
|
1145
|
+
* Lists the rooms this user builds and owns.
|
|
1146
|
+
*
|
|
1147
|
+
* Published instances are excluded — use {@link getPublishedRoomInstances} for
|
|
1148
|
+
* those, which is also how the client reaches them.
|
|
1149
|
+
*
|
|
1150
|
+
* @returns Array of room summary objects (id, name, goal, agent count)
|
|
1151
|
+
*/
|
|
643
1152
|
async listRooms() {
|
|
644
1153
|
return await this.roomStore.getTemplateRooms();
|
|
645
1154
|
}
|
|
1155
|
+
/**
|
|
1156
|
+
* Returns full details for a room, including the metadata of each member agent.
|
|
1157
|
+
*
|
|
1158
|
+
* @param roomId - The room's ID
|
|
1159
|
+
* @returns Room details object, or `null` if no room with the given ID exists
|
|
1160
|
+
*/
|
|
646
1161
|
async getRoomDetails(roomId) {
|
|
647
1162
|
const room = await this.roomStore.getRoom(roomId);
|
|
648
1163
|
if (!room) {
|
|
649
1164
|
return null;
|
|
650
1165
|
}
|
|
1166
|
+
// Get all agents in the room
|
|
651
1167
|
const roomAgents = room.getAgents();
|
|
1168
|
+
// Fetch detailed information for each agent
|
|
652
1169
|
const agents = [];
|
|
653
1170
|
for (const agent of roomAgents) {
|
|
654
1171
|
const agentDetails = await this.getAgentDetails(agent.id);
|
|
@@ -673,9 +1190,28 @@ class AppService {
|
|
|
673
1190
|
processingInProgress: room.isProcessingInProgress(),
|
|
674
1191
|
};
|
|
675
1192
|
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Returns the raw `Room` object for a given ID.
|
|
1195
|
+
*
|
|
1196
|
+
* Use {@link getRoomDetails} for a plain metadata object. This method exposes
|
|
1197
|
+
* the full `Room` instance, which is useful for advanced operations.
|
|
1198
|
+
*
|
|
1199
|
+
* @param roomId - The room's ID
|
|
1200
|
+
* @returns The `Room` instance, or `null` if not found
|
|
1201
|
+
*/
|
|
676
1202
|
async getRoomById(roomId) {
|
|
677
1203
|
return await this.roomStore.getRoom(roomId);
|
|
678
1204
|
}
|
|
1205
|
+
/**
|
|
1206
|
+
* Sets which agent leads the room's conversation and persists the change.
|
|
1207
|
+
*
|
|
1208
|
+
* The room leader is given conversational authority in the default room
|
|
1209
|
+
* prompts (other agents defer to it) and is consulted on adjournment.
|
|
1210
|
+
*
|
|
1211
|
+
* @param roomId - The room's ID
|
|
1212
|
+
* @param agentNickname - Nickname of the member agent to make leader
|
|
1213
|
+
* @throws {NotFoundError} If the room does not exist
|
|
1214
|
+
*/
|
|
679
1215
|
async setRoomLeader(roomId, agentNickname) {
|
|
680
1216
|
const room = await this.roomStore.getRoom(roomId);
|
|
681
1217
|
if (!room) {
|
|
@@ -684,6 +1220,19 @@ class AppService {
|
|
|
684
1220
|
room.setRoomLeader(agentNickname);
|
|
685
1221
|
room.saveMetadata();
|
|
686
1222
|
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Returns messages from a room's conversation log starting from a given index.
|
|
1225
|
+
*
|
|
1226
|
+
* Pass the index of the last message you received as `fromIndex` to poll for
|
|
1227
|
+
* new messages only.
|
|
1228
|
+
*
|
|
1229
|
+
* @param roomId - The room's ID
|
|
1230
|
+
* @param fromIndex - Zero-based index to start from (default `0` returns all messages)
|
|
1231
|
+
* @param includeThoughts - If `true`, includes `'think'` action messages which are
|
|
1232
|
+
* normally hidden (agents' internal reasoning). Default `false`.
|
|
1233
|
+
* @returns Object with the messages array and total cost across all agents.
|
|
1234
|
+
* Returns empty messages with zero cost if the room is not found.
|
|
1235
|
+
*/
|
|
687
1236
|
async getRoomMessages(roomId, fromIndex = 0, includeThoughts = false) {
|
|
688
1237
|
const room = await this.roomStore.getRoom(roomId);
|
|
689
1238
|
if (!room) {
|
|
@@ -692,6 +1241,7 @@ class AppService {
|
|
|
692
1241
|
totalCost: 0,
|
|
693
1242
|
};
|
|
694
1243
|
}
|
|
1244
|
+
// Get messages from the specified index
|
|
695
1245
|
const indexedMessages = room.getLatestRoomMessages(fromIndex, includeThoughts);
|
|
696
1246
|
const totalCost = room
|
|
697
1247
|
.getAgents()
|
|
@@ -702,6 +1252,17 @@ class AppService {
|
|
|
702
1252
|
totalCost: totalCost,
|
|
703
1253
|
};
|
|
704
1254
|
}
|
|
1255
|
+
/**
|
|
1256
|
+
* Returns an agent's conversation history starting from a given index.
|
|
1257
|
+
*
|
|
1258
|
+
* Pass the `messageIndex` from a previous response as `fromIndex` to
|
|
1259
|
+
* retrieve only new messages since the last poll.
|
|
1260
|
+
*
|
|
1261
|
+
* @param agentId - The agent's ID
|
|
1262
|
+
* @param fromIndex - Zero-based index to start from (default `0` returns all messages)
|
|
1263
|
+
* @returns Object with the messages array and cumulative token/cost totals.
|
|
1264
|
+
* Returns empty messages with zero counts if the agent is not found.
|
|
1265
|
+
*/
|
|
705
1266
|
async getAgentMessages(agentId, fromIndex = 0) {
|
|
706
1267
|
const agent = await this.agentStore.getAgent(agentId);
|
|
707
1268
|
if (!agent) {
|
|
@@ -712,7 +1273,9 @@ class AppService {
|
|
|
712
1273
|
totalCost: 0,
|
|
713
1274
|
};
|
|
714
1275
|
}
|
|
1276
|
+
// Set up SSE callback for this agent (if not already set)
|
|
715
1277
|
this.setupAgentStateCallback(agent);
|
|
1278
|
+
// Use the agent's getFormattedMessages method
|
|
716
1279
|
const formattedMessages = agent.getFormattedMessages(fromIndex);
|
|
717
1280
|
return {
|
|
718
1281
|
messages: formattedMessages,
|
|
@@ -721,6 +1284,12 @@ class AppService {
|
|
|
721
1284
|
totalCost: agent.totalCost,
|
|
722
1285
|
};
|
|
723
1286
|
}
|
|
1287
|
+
/**
|
|
1288
|
+
* Gets messages from a story's room starting from a specific index
|
|
1289
|
+
* @param storyId The story ID
|
|
1290
|
+
* @param fromIndex The index to start from (0-based)
|
|
1291
|
+
* @returns Array of indexed messages and total story cost
|
|
1292
|
+
*/
|
|
724
1293
|
async getStoryMessages(storyId, fromIndex) {
|
|
725
1294
|
const story = this.storyStore.getStory(storyId);
|
|
726
1295
|
if (!story) {
|
|
@@ -734,11 +1303,48 @@ class AppService {
|
|
|
734
1303
|
const totalCost = story.totalCost || 0;
|
|
735
1304
|
return { messages, totalCost };
|
|
736
1305
|
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Adds a message to a room's pending queue to be processed by the agents.
|
|
1308
|
+
*
|
|
1309
|
+
* **Action values:**
|
|
1310
|
+
* - `'moderate'` *(default)* - routes the message through the room's moderator (story rooms only)
|
|
1311
|
+
* - `'speak'` - all agents hear the message; `targets` (if provided) restricts which agents may respond
|
|
1312
|
+
* - `'whisper'` - only agents listed in `targets` hear the message
|
|
1313
|
+
* - `'think'` - inaudible; stays only in the sender's history, not shown to other agents
|
|
1314
|
+
* - `'shout'` - overrides all other conversations; all agents hear and respond
|
|
1315
|
+
* - `'adjourn'` - signals intent to halt the conversation; the room adjourns once every agent agrees
|
|
1316
|
+
*
|
|
1317
|
+
* Anything else is sent as `'speak'`. To create an artifact use {@link publishArtifact}
|
|
1318
|
+
* rather than this method.
|
|
1319
|
+
*
|
|
1320
|
+
* @param roomId - The room's ID
|
|
1321
|
+
* @param content - The message text (or artifact body when `action` is `'publish'`)
|
|
1322
|
+
* @param sender - Display name of the sender (e.g. `'User'`, `'System'`)
|
|
1323
|
+
* @param action - Message action type (default `'moderate'`)
|
|
1324
|
+
* @param targets - Agent names to receive or respond to the message (behavior varies by action)
|
|
1325
|
+
* @param clearQueue - If `true`, clears any pending messages before adding this one. Default `false`.
|
|
1326
|
+
* @returns Whether the message was accepted. A human agent's message is rejected
|
|
1327
|
+
* (`accepted: false` with a `reason`) when it is not the human's turn to speak.
|
|
1328
|
+
* @throws {NotFoundError} If the room does not exist
|
|
1329
|
+
*
|
|
1330
|
+
* @example
|
|
1331
|
+
* ```typescript
|
|
1332
|
+
* // Broadcast a message that all agents can respond to
|
|
1333
|
+
* await appService.sendRoomMessage(roomId, 'Hello everyone!', 'User', 'speak');
|
|
1334
|
+
*
|
|
1335
|
+
* // Whisper to a specific agent
|
|
1336
|
+
* const result = await appService.sendRoomMessage(roomId, 'Just between us...', 'User', 'whisper', ['James']);
|
|
1337
|
+
* if (!result.accepted) {
|
|
1338
|
+
* console.log(result.reason); // e.g. "It is James's turn to speak"
|
|
1339
|
+
* }
|
|
1340
|
+
* ```
|
|
1341
|
+
*/
|
|
737
1342
|
async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false, context) {
|
|
738
1343
|
const room = await this.roomStore.getRoom(roomId);
|
|
739
1344
|
if (!room) {
|
|
740
1345
|
throw new errors_1.NotFoundError('Room not found');
|
|
741
1346
|
}
|
|
1347
|
+
// Map the action string to MessageAction enum
|
|
742
1348
|
let messageAction;
|
|
743
1349
|
switch (action.toLowerCase()) {
|
|
744
1350
|
case 'moderate':
|
|
@@ -764,8 +1370,18 @@ class AppService {
|
|
|
764
1370
|
messageAction = app_types_1.MessageAction.SPEAK;
|
|
765
1371
|
}
|
|
766
1372
|
room.ready();
|
|
1373
|
+
// Create a message from the system. `context` is an opaque, host-supplied
|
|
1374
|
+
// value threaded to any tool the resulting turn invokes (never persisted).
|
|
767
1375
|
return room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue, context);
|
|
768
1376
|
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Pauses message processing in a room.
|
|
1379
|
+
*
|
|
1380
|
+
* Pending messages remain in the queue. Call {@link resumeRoom} to continue processing.
|
|
1381
|
+
*
|
|
1382
|
+
* @param roomId - The room's ID
|
|
1383
|
+
* @throws {NotFoundError} If the room does not exist
|
|
1384
|
+
*/
|
|
769
1385
|
async pauseRoom(roomId) {
|
|
770
1386
|
const room = await this.roomStore.getRoom(roomId);
|
|
771
1387
|
if (!room) {
|
|
@@ -773,6 +1389,12 @@ class AppService {
|
|
|
773
1389
|
}
|
|
774
1390
|
room.pause();
|
|
775
1391
|
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Resumes message processing in a room that was previously paused.
|
|
1394
|
+
*
|
|
1395
|
+
* @param roomId - The room's ID
|
|
1396
|
+
* @throws {NotFoundError} If the room does not exist
|
|
1397
|
+
*/
|
|
776
1398
|
async resumeRoom(roomId) {
|
|
777
1399
|
const room = await this.roomStore.getRoom(roomId);
|
|
778
1400
|
if (!room) {
|
|
@@ -780,29 +1402,64 @@ class AppService {
|
|
|
780
1402
|
}
|
|
781
1403
|
room.resume();
|
|
782
1404
|
}
|
|
1405
|
+
/**
|
|
1406
|
+
* Permanently deletes an agent and all its stored data.
|
|
1407
|
+
*
|
|
1408
|
+
* If the agent is a published instance, its entry is also removed from the
|
|
1409
|
+
* published agents mapping.
|
|
1410
|
+
*
|
|
1411
|
+
* @param agentId - The agent's ID
|
|
1412
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
1413
|
+
*/
|
|
783
1414
|
async deleteAgent(agentId) {
|
|
784
1415
|
const agent = await this.agentStore.getAgent(agentId);
|
|
785
1416
|
if (!agent) {
|
|
786
1417
|
throw new errors_1.NotFoundError('Agent not found');
|
|
787
1418
|
}
|
|
1419
|
+
// If this is a published agent, remove it from the published agents mapping
|
|
788
1420
|
if (agent.isPublished) {
|
|
789
1421
|
this.publishedAgentsService.removePublishedAgent(agentId);
|
|
790
1422
|
}
|
|
791
1423
|
await agent.deleteAgent();
|
|
792
1424
|
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Creates a publicly accessible clone of a template agent.
|
|
1427
|
+
*
|
|
1428
|
+
* The new instance is independent of the template's conversation history.
|
|
1429
|
+
* Multiple instances can be created from a single template. Use
|
|
1430
|
+
* {@link resetPublishedInstance} to restore an instance to the template's
|
|
1431
|
+
* current state.
|
|
1432
|
+
*
|
|
1433
|
+
* @param templateId - ID of the template agent to clone
|
|
1434
|
+
* @param instanceName - Display name for the new instance
|
|
1435
|
+
* @returns Object with the new `instanceId` and the `publicUrl` path
|
|
1436
|
+
* @throws {NotFoundError} If the template agent does not exist
|
|
1437
|
+
* @see {@link getPublishedInstances}
|
|
1438
|
+
* @see {@link resetPublishedInstance}
|
|
1439
|
+
*/
|
|
793
1440
|
async publishAgentInstance(templateId, instanceName) {
|
|
1441
|
+
// Validate template exists
|
|
794
1442
|
const template = await this.agentStore.getAgent(templateId);
|
|
795
1443
|
if (!template) {
|
|
796
1444
|
throw new errors_1.NotFoundError('Template agent not found');
|
|
797
1445
|
}
|
|
1446
|
+
// Create the published instance
|
|
798
1447
|
const userId = this.userPaths.getUserId();
|
|
799
1448
|
const instanceId = await this.agentStore.cloneAgentAsPublished(templateId, instanceName, userId);
|
|
1449
|
+
// Add to published agents mapping
|
|
800
1450
|
this.publishedAgentsService.addPublishedAgent(instanceId, userId);
|
|
801
1451
|
return {
|
|
802
1452
|
instanceId,
|
|
803
1453
|
publicUrl: `/public/agents/${instanceId}`,
|
|
804
1454
|
};
|
|
805
1455
|
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Returns all published instances created from a template agent.
|
|
1458
|
+
*
|
|
1459
|
+
* @param templateId - ID of the template agent
|
|
1460
|
+
* @returns Array of agent metadata objects for each published instance
|
|
1461
|
+
* @see {@link publishAgentInstance}
|
|
1462
|
+
*/
|
|
806
1463
|
async getPublishedInstances(templateId) {
|
|
807
1464
|
const instances = await this.agentStore.getPublishedInstances(templateId);
|
|
808
1465
|
return instances.map((agent) => ({
|
|
@@ -826,6 +1483,16 @@ class AppService {
|
|
|
826
1483
|
useModerator: agent.useModerator,
|
|
827
1484
|
}));
|
|
828
1485
|
}
|
|
1486
|
+
/**
|
|
1487
|
+
* Resets a published agent instance to its template's current state.
|
|
1488
|
+
*
|
|
1489
|
+
* Clears the instance's conversation history and regenerates it from
|
|
1490
|
+
* the template agent. Does not affect the template itself.
|
|
1491
|
+
*
|
|
1492
|
+
* @param instanceId - ID of the published instance to reset
|
|
1493
|
+
* @throws {NotFoundError} If the instance does not exist
|
|
1494
|
+
* @throws {OperationFailedError} If the agent is not a published instance
|
|
1495
|
+
*/
|
|
829
1496
|
async resetPublishedInstance(instanceId) {
|
|
830
1497
|
const instance = await this.agentStore.getAgent(instanceId);
|
|
831
1498
|
if (!instance) {
|
|
@@ -836,11 +1503,22 @@ class AppService {
|
|
|
836
1503
|
}
|
|
837
1504
|
await this.agentStore.resetPublishedInstance(instanceId, instance.templateAgentId);
|
|
838
1505
|
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Lists all published agent instances belonging to this user.
|
|
1508
|
+
*
|
|
1509
|
+
* Published agents are clones of template agents that are accessible
|
|
1510
|
+
* via the public API (e.g. for end-users to chat with). Agents owned
|
|
1511
|
+
* by rooms are excluded from this list.
|
|
1512
|
+
*
|
|
1513
|
+
* @returns Array of agent metadata objects for all published instances
|
|
1514
|
+
* @see {@link publishAgentInstance}
|
|
1515
|
+
*/
|
|
839
1516
|
async listPublishedAgents() {
|
|
840
1517
|
const agentIds = await this.agentStore.getAllAgentIds();
|
|
841
1518
|
const agents = [];
|
|
842
1519
|
for (const id of agentIds) {
|
|
843
1520
|
const agent = await this.agentStore.getAgent(id);
|
|
1521
|
+
// Filter: only include agents that are published AND not owned by a room
|
|
844
1522
|
if (agent && agent.isPublished && !agent.ownerRoomId) {
|
|
845
1523
|
agents.push({
|
|
846
1524
|
id: agent.id,
|
|
@@ -866,27 +1544,56 @@ class AppService {
|
|
|
866
1544
|
}
|
|
867
1545
|
return agents;
|
|
868
1546
|
}
|
|
1547
|
+
/**
|
|
1548
|
+
* Permanently deletes a room and all its data.
|
|
1549
|
+
*
|
|
1550
|
+
* If the room is a template, all of its published instances are deleted first.
|
|
1551
|
+
* The agents the room owns, its attached files and its published room mapping
|
|
1552
|
+
* are also cleaned up.
|
|
1553
|
+
*
|
|
1554
|
+
* @param roomId - The room's ID
|
|
1555
|
+
* @throws {NotFoundError} If the room does not exist
|
|
1556
|
+
* @throws {OperationFailedError} If deletion fails
|
|
1557
|
+
*/
|
|
869
1558
|
async deleteRoom(roomId) {
|
|
1559
|
+
// Check if the room exists
|
|
870
1560
|
const room = await this.roomStore.getRoom(roomId);
|
|
871
1561
|
if (!room) {
|
|
872
1562
|
throw new errors_1.NotFoundError('Room not found');
|
|
873
1563
|
}
|
|
874
|
-
const isTemplate = !room.getTemplateRoomId();
|
|
1564
|
+
const isTemplate = !room.getTemplateRoomId(); // No template ID means it's a template
|
|
1565
|
+
// If deleting a template, cascade delete all published instances first
|
|
875
1566
|
if (isTemplate) {
|
|
876
1567
|
const instances = await this.roomStore.getPublishedInstances(roomId);
|
|
877
1568
|
for (const instance of instances) {
|
|
1569
|
+
// Recursively delete each published instance (which deletes their agents)
|
|
878
1570
|
await this.deleteRoom(instance.getId());
|
|
879
1571
|
}
|
|
880
1572
|
}
|
|
1573
|
+
// Delete all attached files for this room
|
|
881
1574
|
this.attachedFileService.deleteAllFiles(roomId);
|
|
1575
|
+
// Remove from published mapping if this is a published instance
|
|
882
1576
|
if (room.getIsPublished()) {
|
|
883
1577
|
this.publishedRoomsService.removePublishedRoom(roomId);
|
|
884
1578
|
}
|
|
1579
|
+
// Remove the room from the store, along with the agents it owns
|
|
885
1580
|
const removed = this.roomStore.removeRoom(roomId);
|
|
886
1581
|
if (!removed) {
|
|
887
1582
|
throw new errors_1.OperationFailedError('Failed to delete room');
|
|
888
1583
|
}
|
|
889
1584
|
}
|
|
1585
|
+
/**
|
|
1586
|
+
* Creates a publicly accessible clone of a template room.
|
|
1587
|
+
*
|
|
1588
|
+
* The instance is a full copy of the template including all agents.
|
|
1589
|
+
* Use {@link resetPublishedRoomInstance} to restore it to the template's state.
|
|
1590
|
+
*
|
|
1591
|
+
* @param templateId - ID of the template room to clone
|
|
1592
|
+
* @param publishedName - Display name for the instance (defaults to the template's name)
|
|
1593
|
+
* @param userId - The owning user's ID (used for public access mapping)
|
|
1594
|
+
* @returns The new instance's room ID
|
|
1595
|
+
* @throws {NotFoundError} If the template room does not exist
|
|
1596
|
+
*/
|
|
890
1597
|
async publishRoom(templateId, publishedName, userId) {
|
|
891
1598
|
const template = await this.roomStore.getRoom(templateId);
|
|
892
1599
|
if (!template) {
|
|
@@ -896,6 +1603,14 @@ class AppService {
|
|
|
896
1603
|
this.publishedRoomsService.addPublishedRoom(instanceId, userId);
|
|
897
1604
|
return instanceId;
|
|
898
1605
|
}
|
|
1606
|
+
/**
|
|
1607
|
+
* Summarizes a room for a listing.
|
|
1608
|
+
*
|
|
1609
|
+
* The cost is summed from the room's agents rather than held on the room —
|
|
1610
|
+
* the same sum {@link getRoomMessages} reports, so the two never disagree.
|
|
1611
|
+
* @param room - The room to summarize
|
|
1612
|
+
* @returns The room's summary
|
|
1613
|
+
*/
|
|
899
1614
|
static toRoomInfo(room) {
|
|
900
1615
|
return {
|
|
901
1616
|
id: room.getId(),
|
|
@@ -909,14 +1624,41 @@ class AppService {
|
|
|
909
1624
|
.reduce((total, cost) => total + cost, 0),
|
|
910
1625
|
};
|
|
911
1626
|
}
|
|
1627
|
+
/**
|
|
1628
|
+
* Returns all published instances created from a template room.
|
|
1629
|
+
*
|
|
1630
|
+
* @param templateId - ID of the template room
|
|
1631
|
+
* @returns Array of room summary objects for each published instance
|
|
1632
|
+
* @see {@link publishRoom}
|
|
1633
|
+
*/
|
|
912
1634
|
async getPublishedRoomInstances(templateId) {
|
|
913
1635
|
const instances = await this.roomStore.getPublishedInstances(templateId);
|
|
914
1636
|
return instances.map(AppService.toRoomInfo);
|
|
915
1637
|
}
|
|
1638
|
+
/**
|
|
1639
|
+
* Lists every published room instance this user owns.
|
|
1640
|
+
*
|
|
1641
|
+
* The room counterpart to {@link listPublishedAgents}, and the only view of
|
|
1642
|
+
* them that is not filtered by which template they came from — a published
|
|
1643
|
+
* room is a live public link, and the point of the list is seeing all of them
|
|
1644
|
+
* and what they have cost.
|
|
1645
|
+
*
|
|
1646
|
+
* @returns Array of room summary objects, one per published instance
|
|
1647
|
+
*/
|
|
916
1648
|
async listPublishedRooms() {
|
|
917
1649
|
const instances = await this.roomStore.getAllPublishedInstances();
|
|
918
1650
|
return instances.map(AppService.toRoomInfo);
|
|
919
1651
|
}
|
|
1652
|
+
/**
|
|
1653
|
+
* Resets a published room instance to a clean state.
|
|
1654
|
+
*
|
|
1655
|
+
* Clears the instance's messages and artifacts, and resets all of its
|
|
1656
|
+
* cloned agents to their template state. Does not affect the template room.
|
|
1657
|
+
*
|
|
1658
|
+
* @param instanceId - ID of the published room instance to reset
|
|
1659
|
+
* @throws {NotFoundError} If the instance does not exist
|
|
1660
|
+
* @throws {OperationFailedError} If the room is not a published instance
|
|
1661
|
+
*/
|
|
920
1662
|
async resetPublishedRoomInstance(instanceId) {
|
|
921
1663
|
const instance = await this.roomStore.getRoom(instanceId);
|
|
922
1664
|
if (!instance) {
|
|
@@ -926,10 +1668,19 @@ class AppService {
|
|
|
926
1668
|
if (!templateId) {
|
|
927
1669
|
throw new errors_1.OperationFailedError('Not a published instance');
|
|
928
1670
|
}
|
|
1671
|
+
// Clear messages and artifacts
|
|
929
1672
|
this.roomStore.clearRoomMessages(instanceId);
|
|
930
1673
|
const storageDir = this.roomStore.getDefaultStorageDir();
|
|
1674
|
+
// Deleted through the store, which works off the directory rather than
|
|
1675
|
+
// rebuilding each filename from the artifact's name. Rebuilding was wrong:
|
|
1676
|
+
// an artifact is written under a *sanitized* name, so "Sheet: Kerith" lives
|
|
1677
|
+
// in "Sheet_ Kerith.artifact" and the reconstructed path matched nothing.
|
|
1678
|
+
// The file survived while setArtifacts([]) dropped it from memory, so every
|
|
1679
|
+
// character sheet quietly came back the next time the room loaded — a reset
|
|
1680
|
+
// that reset everything except the thing the players had accumulated.
|
|
931
1681
|
this.roomStore.deleteAllArtifactFiles(instanceId, storageDir);
|
|
932
1682
|
instance.setArtifacts([]);
|
|
1683
|
+
// Reset all cloned agents
|
|
933
1684
|
const instanceAgents = instance.getAgents();
|
|
934
1685
|
for (const agent of instanceAgents) {
|
|
935
1686
|
if (agent.templateAgentId) {
|
|
@@ -938,39 +1689,92 @@ class AppService {
|
|
|
938
1689
|
}
|
|
939
1690
|
instance.saveMetadata();
|
|
940
1691
|
}
|
|
1692
|
+
/**
|
|
1693
|
+
* Returns the user's stored preferences object.
|
|
1694
|
+
*
|
|
1695
|
+
* Preferences are application-defined - Briyah stores and returns them as-is.
|
|
1696
|
+
* Returns `{}` if no preferences have been saved yet.
|
|
1697
|
+
*
|
|
1698
|
+
* @returns The preferences object previously written by {@link saveUserPreferences},
|
|
1699
|
+
* or an empty object if none exist
|
|
1700
|
+
*/
|
|
941
1701
|
getUserPreferences() {
|
|
1702
|
+
// Check if the file exists
|
|
942
1703
|
if (!this.userPaths.exists(this.userPreferencesFile)) {
|
|
1704
|
+
// Return empty preferences if file doesn't exist
|
|
943
1705
|
return {};
|
|
944
1706
|
}
|
|
1707
|
+
// Read and parse the preferences file
|
|
945
1708
|
const preferencesData = this.userPaths.load(this.userPreferencesFile);
|
|
946
1709
|
return preferencesData ? JSON.parse(preferencesData) : {};
|
|
947
1710
|
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Persists the user's preferences object to disk.
|
|
1713
|
+
*
|
|
1714
|
+
* The shape of `preferences` is application-defined. Pass any serializable object;
|
|
1715
|
+
* it will be stored as JSON and returned verbatim by {@link getUserPreferences}.
|
|
1716
|
+
*
|
|
1717
|
+
* @param preferences - Serializable preferences object to store
|
|
1718
|
+
*/
|
|
948
1719
|
saveUserPreferences(preferences) {
|
|
1720
|
+
// Write the preferences to the file
|
|
949
1721
|
this.userPaths.store(this.userPreferencesFile, JSON.stringify(preferences, null, 2));
|
|
950
1722
|
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Returns the names of all prompt files in a folder, merged from both the common
|
|
1725
|
+
* and user prompt directories.
|
|
1726
|
+
*
|
|
1727
|
+
* Pass `'shared'` as `folderName` to list files in the root prompts directory.
|
|
1728
|
+
* Files that exist in both directories appear once in the result.
|
|
1729
|
+
*
|
|
1730
|
+
* @param folderName - Folder to list, or `'shared'` for the root prompts directory
|
|
1731
|
+
* @returns Object with a `files` array of base names (no extension), sorted alphabetically
|
|
1732
|
+
*/
|
|
951
1733
|
listPromptFiles(folderName) {
|
|
952
1734
|
const baseNames = new Set();
|
|
1735
|
+
// Helper function to scan a directory and add files
|
|
953
1736
|
const scanDirectory = (baseDir) => {
|
|
954
1737
|
let targetDir = baseDir;
|
|
1738
|
+
// If not 'shared', look in the specific folder
|
|
955
1739
|
if (folderName !== 'shared') {
|
|
956
1740
|
targetDir = path.join(baseDir, folderName);
|
|
957
1741
|
}
|
|
1742
|
+
// Check if directory exists
|
|
958
1743
|
if (!fs.existsSync(targetDir)) {
|
|
959
1744
|
return;
|
|
960
1745
|
}
|
|
1746
|
+
// Get all files in the directory
|
|
961
1747
|
const allFiles = fs.readdirSync(targetDir);
|
|
1748
|
+
// Filter to only .prompt and .json files
|
|
962
1749
|
const promptFiles = allFiles.filter((file) => file.endsWith('.prompt') || file.endsWith('.json'));
|
|
1750
|
+
// Extract base names without extensions
|
|
963
1751
|
promptFiles.forEach((file) => {
|
|
964
1752
|
const baseName = file.replace(/\.(prompt|json)$/, '');
|
|
965
1753
|
baseNames.add(baseName);
|
|
966
1754
|
});
|
|
967
1755
|
};
|
|
1756
|
+
// Scan common prompts directory first
|
|
968
1757
|
scanDirectory(this.userPaths.getCommonPromptsDir());
|
|
1758
|
+
// Scan user prompts directory (will add or override common files)
|
|
969
1759
|
scanDirectory(this.userPaths.getUserPromptsDir());
|
|
970
1760
|
return { files: Array.from(baseNames).sort() };
|
|
971
1761
|
}
|
|
1762
|
+
/**
|
|
1763
|
+
* Returns prompt file names in a folder annotated with their origin scope.
|
|
1764
|
+
*
|
|
1765
|
+
* When the same file name exists in both the common and user directories,
|
|
1766
|
+
* the user copy wins and the entry is reported as `scope: 'user'`.
|
|
1767
|
+
* Pass `'shared'` as `folderName` to list files in the root prompts directory.
|
|
1768
|
+
*
|
|
1769
|
+
* @param folderName - Folder to list, or `'shared'` for the root prompts directory
|
|
1770
|
+
* @returns Object with a `files` array of `{ name, scope }` entries, sorted alphabetically
|
|
1771
|
+
*/
|
|
972
1772
|
listPromptFilesWithScope(folderName) {
|
|
973
1773
|
const fileMap = new Map();
|
|
1774
|
+
// Lowest precedence first, so a higher tier's copy of the same file name
|
|
1775
|
+
// overwrites the entry and the reported scope is the one that would actually
|
|
1776
|
+
// be read. This is the same directory list the resolver searches, which is
|
|
1777
|
+
// why a pack folder's files appear here at all.
|
|
974
1778
|
for (const { dir, scope, pack } of (0, prompt_resolver_1.promptFolderDirsLowestFirst)(this.userPaths, folderName, { enabledPacks: this.enabledPacks })) {
|
|
975
1779
|
if (!fs.existsSync(dir))
|
|
976
1780
|
continue;
|
|
@@ -983,7 +1787,26 @@ class AppService {
|
|
|
983
1787
|
const files = [...fileMap.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
984
1788
|
return { files };
|
|
985
1789
|
}
|
|
1790
|
+
/**
|
|
1791
|
+
* Reads a prompt file, applying the shared lookup order (`prompt-resolver.ts`).
|
|
1792
|
+
*
|
|
1793
|
+
* For a bare folder that is the historical four levels — `user/{folder}`,
|
|
1794
|
+
* `user/root`, `common/{folder}`, `common/root` — plus the folders of any pack
|
|
1795
|
+
* this user has enabled. For a pack-qualified folder (`dnd5e:battle_master`) it
|
|
1796
|
+
* is the pack's own tiers, then the shared roots.
|
|
1797
|
+
*
|
|
1798
|
+
* The returned `scope` collapses the four tiers onto the two the client knows:
|
|
1799
|
+
* a pack overlay reports `'user'`, a pack's own file reports `'common'`. `pack`
|
|
1800
|
+
* and `tier` carry the detail, and are populated even when the reference was
|
|
1801
|
+
* bare. Returns `{ content: '' }` if the file does not exist in any location.
|
|
1802
|
+
*
|
|
1803
|
+
* @param folderName - Prompt folder name, `'shared'` for the root prompts directory,
|
|
1804
|
+
* or a pack-qualified name like `dnd5e:dungeon_master`
|
|
1805
|
+
* @param fileName - Base name of the prompt file (with or without `.prompt`/`.json` extension)
|
|
1806
|
+
* @returns `{ content, scope, pack, tier }` where all but `content` are omitted when not found
|
|
1807
|
+
*/
|
|
986
1808
|
getPromptFile(folderName, fileName) {
|
|
1809
|
+
// Determine file extension (.prompt or .json)
|
|
987
1810
|
const fileExtension = fileName.endsWith('.prompt') || fileName.endsWith('.json') ? '' : '.prompt';
|
|
988
1811
|
const found = (0, prompt_resolver_1.resolvePromptFile)(this.userPaths, folderName, fileName, fileExtension, {
|
|
989
1812
|
enabledPacks: this.enabledPacks,
|
|
@@ -998,6 +1821,24 @@ class AppService {
|
|
|
998
1821
|
...(found.pack && { pack: found.pack }),
|
|
999
1822
|
};
|
|
1000
1823
|
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Reads a prompt folder's `defaults_config.json` — the agent settings the create-agent
|
|
1826
|
+
* form pre-fills when that folder is chosen.
|
|
1827
|
+
*
|
|
1828
|
+
* Resolved through the same 4-level fallback as any other prompt file, so a user copy
|
|
1829
|
+
* overrides the shipped one and a file at the prompts root supplies defaults for every
|
|
1830
|
+
* folder that has none of its own.
|
|
1831
|
+
*
|
|
1832
|
+
* A missing file and an unparseable one both return `{ defaults: {} }`: defaults are a
|
|
1833
|
+
* convenience, and a folder must stay usable when its config is broken. Unparseable is
|
|
1834
|
+
* logged; missing is not, since most folders have no config at all.
|
|
1835
|
+
*
|
|
1836
|
+
* Every field is coerced to its declared type and unknown keys are dropped, so a typo
|
|
1837
|
+
* in a hand-edited file cannot ride through to the create-agent request.
|
|
1838
|
+
*
|
|
1839
|
+
* @param folderName - Prompt folder name, or `'shared'` for the root prompts directory
|
|
1840
|
+
* @returns The declared defaults, and the scope the file was read from
|
|
1841
|
+
*/
|
|
1001
1842
|
getPromptFolderDefaults(folderName) {
|
|
1002
1843
|
const exists = this.promptFolderExists(folderName);
|
|
1003
1844
|
const file = this.getPromptFile(folderName, 'defaults_config.json');
|
|
@@ -1063,9 +1904,27 @@ class AppService {
|
|
|
1063
1904
|
}
|
|
1064
1905
|
return { defaults, scope: file.scope, exists };
|
|
1065
1906
|
}
|
|
1907
|
+
/**
|
|
1908
|
+
* Whether a prompt folder reference reaches a folder that exists.
|
|
1909
|
+
*
|
|
1910
|
+
* The check every "build an agent from a folder" path makes before it builds
|
|
1911
|
+
* one: a reference that reaches nothing does not fail, it falls back to the
|
|
1912
|
+
* shared root prompts and produces a generic conversational agent. A bare name
|
|
1913
|
+
* for a pack this user has not enabled counts as not existing, because that is
|
|
1914
|
+
* how it will behave.
|
|
1915
|
+
*
|
|
1916
|
+
* @param folderName - Prompt folder name, bare or `pack:folder`
|
|
1917
|
+
* @returns True when the folder exists, or names the prompts root
|
|
1918
|
+
*/
|
|
1066
1919
|
promptFolderExists(folderName) {
|
|
1067
1920
|
return (0, prompt_resolver_1.promptFolderExists)(this.userPaths, folderName, { enabledPacks: this.enabledPacks });
|
|
1068
1921
|
}
|
|
1922
|
+
/**
|
|
1923
|
+
* Refuses a prompt folder that reaches nothing, naming the likely cause.
|
|
1924
|
+
*
|
|
1925
|
+
* @param folderName - The folder the caller asked for
|
|
1926
|
+
* @throws {NotFoundError} If no tier has the folder
|
|
1927
|
+
*/
|
|
1069
1928
|
requirePromptFolder(folderName) {
|
|
1070
1929
|
if (this.promptFolderExists(folderName))
|
|
1071
1930
|
return;
|
|
@@ -1075,22 +1934,54 @@ class AppService {
|
|
|
1075
1934
|
: `A pack's folder must be named "<pack>:${folderName}", or the pack enabled for this user${enabled.length ? ` (enabled: ${enabled.join(', ')})` : ' (this user has none enabled)'}.`;
|
|
1076
1935
|
throw new errors_1.NotFoundError(`No prompt folder "${folderName}". ${hint}`);
|
|
1077
1936
|
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Writes content to a prompt file in the user prompt directory.
|
|
1939
|
+
*
|
|
1940
|
+
* Always saves to the user directory - common prompt files are never overwritten.
|
|
1941
|
+
* If the target folder does not exist it is created automatically.
|
|
1942
|
+
* Passing `'shared'` as `folderName` writes to the root user prompts directory.
|
|
1943
|
+
*
|
|
1944
|
+
* Special case: passing an empty `content` for a `'json'` file deletes the file
|
|
1945
|
+
* rather than writing an empty document.
|
|
1946
|
+
*
|
|
1947
|
+
* @param folderName - Prompt folder name, or `'shared'` for the root user prompts directory
|
|
1948
|
+
* @param fileName - Base name of the file (without extension)
|
|
1949
|
+
* @param content - File content to write
|
|
1950
|
+
* @param fileType - `'prompt'` (writes a `.prompt` file) or `'json'` (writes a `.json` file)
|
|
1951
|
+
*/
|
|
1078
1952
|
savePromptFile(folderName, fileName, content, fileType) {
|
|
1953
|
+
// Never the directory the file was read from: a write goes to the user's own
|
|
1954
|
+
// tier, and for a pack-qualified folder that is a private overlay of the pack.
|
|
1955
|
+
// promptWriteDir also validates the name, which is the only thing standing
|
|
1956
|
+
// between a route parameter and path.join.
|
|
1079
1957
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
1080
1958
|
(0, prompt_resolver_1.assertPathSafe)(fileName);
|
|
1959
|
+
// Create directory if it doesn't exist
|
|
1081
1960
|
if (!fs.existsSync(targetDir)) {
|
|
1082
1961
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
1083
1962
|
}
|
|
1963
|
+
// Determine file extension
|
|
1084
1964
|
const fileExtension = fileType === 'json' ? '.json' : '.prompt';
|
|
1085
1965
|
const filePath = path.join(targetDir, fileName + fileExtension);
|
|
1966
|
+
// If content is empty and it's a JSON file, delete the file if it exists
|
|
1086
1967
|
if (content.trim() === '' && fileType === 'json') {
|
|
1087
1968
|
if (fs.existsSync(filePath)) {
|
|
1088
1969
|
fs.unlinkSync(filePath);
|
|
1089
1970
|
}
|
|
1090
1971
|
return;
|
|
1091
1972
|
}
|
|
1973
|
+
// Write content to file
|
|
1092
1974
|
fs.writeFileSync(filePath, content);
|
|
1093
1975
|
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Deletes a prompt file from the user prompts directory.
|
|
1978
|
+
*
|
|
1979
|
+
* Removes both the `.prompt` and `.json` variants if they exist.
|
|
1980
|
+
* This is a no-op if neither file is present.
|
|
1981
|
+
*
|
|
1982
|
+
* @param folderName - Prompt folder name, or `'shared'` for the root prompts directory
|
|
1983
|
+
* @param fileName - Base name of the file to delete (without extension)
|
|
1984
|
+
*/
|
|
1094
1985
|
deletePromptFile(folderName, fileName) {
|
|
1095
1986
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
1096
1987
|
(0, prompt_resolver_1.assertPathSafe)(fileName);
|
|
@@ -1108,14 +1999,40 @@ class AppService {
|
|
|
1108
1999
|
}
|
|
1109
2000
|
}
|
|
1110
2001
|
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Returns all artifacts published in a room.
|
|
2004
|
+
*
|
|
2005
|
+
* Artifacts are collaborative documents created by agents via the `'publish'` action.
|
|
2006
|
+
*
|
|
2007
|
+
* @param roomId - The room's ID
|
|
2008
|
+
* @returns Object with an `artifacts` array. Returns `{ artifacts: [] }` if the room is not found.
|
|
2009
|
+
* @see {@link publishArtifact}
|
|
2010
|
+
*/
|
|
1111
2011
|
async getRoomArtifacts(roomId) {
|
|
2012
|
+
// Check if the room exists
|
|
1112
2013
|
const room = await this.roomStore.getRoom(roomId);
|
|
1113
2014
|
if (!room) {
|
|
1114
2015
|
return { artifacts: [] };
|
|
1115
2016
|
}
|
|
2017
|
+
// Get all artifacts from the room
|
|
1116
2018
|
const artifacts = room.getArtifacts();
|
|
2019
|
+
// Return the artifacts
|
|
1117
2020
|
return { artifacts };
|
|
1118
2021
|
}
|
|
2022
|
+
/**
|
|
2023
|
+
* Programmatically publishes an artifact to a room.
|
|
2024
|
+
*
|
|
2025
|
+
* This is the imperative equivalent of an agent sending a `'publish'` action message.
|
|
2026
|
+
* Agents in the room can read and reference the artifact in subsequent prompts.
|
|
2027
|
+
*
|
|
2028
|
+
* @param roomId - The room's ID
|
|
2029
|
+
* @param name - Artifact name (unique within the room)
|
|
2030
|
+
* @param creator - Display name of the creator
|
|
2031
|
+
* @param body - The artifact's text content
|
|
2032
|
+
* @param viewers - Agent names that can view this artifact (empty array = all agents)
|
|
2033
|
+
* @throws {NotFoundError} If the room does not exist
|
|
2034
|
+
* @throws {OperationFailedError} If `name` is empty
|
|
2035
|
+
*/
|
|
1119
2036
|
async publishArtifact(roomId, name, creator, body, viewers = []) {
|
|
1120
2037
|
const room = await this.roomStore.getRoom(roomId);
|
|
1121
2038
|
if (!room)
|
|
@@ -1124,30 +2041,80 @@ class AppService {
|
|
|
1124
2041
|
throw new errors_1.OperationFailedError('Artifact name is required');
|
|
1125
2042
|
room.publishArtifact(name, creator, body, viewers);
|
|
1126
2043
|
}
|
|
2044
|
+
/**
|
|
2045
|
+
* Creates a new prompt folder in the user prompts directory.
|
|
2046
|
+
*
|
|
2047
|
+
* An empty `system_instruction.prompt` file is created inside the folder so that
|
|
2048
|
+
* it is immediately usable as a prompt source for agents.
|
|
2049
|
+
*
|
|
2050
|
+
* @param folderName - Name of the folder to create
|
|
2051
|
+
* @throws {OperationFailedError} If a folder with that name already exists
|
|
2052
|
+
*/
|
|
1127
2053
|
createPromptFolder(folderName) {
|
|
1128
2054
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
2055
|
+
// Check if folder already exists
|
|
1129
2056
|
if (fs.existsSync(targetDir)) {
|
|
1130
2057
|
throw new errors_1.OperationFailedError(`Folder ${folderName} already exists`);
|
|
1131
2058
|
}
|
|
2059
|
+
// Create the folder
|
|
1132
2060
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
2061
|
+
// Create empty system_instruction.prompt file
|
|
1133
2062
|
const systemInstructionPath = path.join(targetDir, 'system_instruction.prompt');
|
|
1134
2063
|
fs.writeFileSync(systemInstructionPath, '');
|
|
1135
2064
|
}
|
|
2065
|
+
/**
|
|
2066
|
+
* Deletes a prompt folder and all its contents from the user prompts directory.
|
|
2067
|
+
*
|
|
2068
|
+
* Only user-owned folders can be deleted; common folders are not affected.
|
|
2069
|
+
*
|
|
2070
|
+
* @param folderName - Name of the folder to delete
|
|
2071
|
+
* @throws {OperationFailedError} If `folderName` is `'shared'`
|
|
2072
|
+
* @throws {NotFoundError} If the folder does not exist in the user prompts directory
|
|
2073
|
+
*/
|
|
1136
2074
|
deletePromptFolder(folderName) {
|
|
2075
|
+
// Prevent deletion of the 'shared' folder
|
|
1137
2076
|
if (folderName === 'shared') {
|
|
1138
2077
|
throw new errors_1.OperationFailedError('Cannot delete the shared folder');
|
|
1139
2078
|
}
|
|
2079
|
+
// Only ever the user's own copy. For a pack-qualified folder that is their
|
|
2080
|
+
// overlay, so deleting reverts their edits rather than removing the pack's.
|
|
1140
2081
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
2082
|
+
// Check if folder exists
|
|
1141
2083
|
if (!fs.existsSync(targetDir)) {
|
|
1142
2084
|
throw new errors_1.NotFoundError(`Folder ${folderName} does not exist`);
|
|
1143
2085
|
}
|
|
2086
|
+
// Delete the folder recursively
|
|
1144
2087
|
fs.rmSync(targetDir, { recursive: true, force: true });
|
|
1145
2088
|
}
|
|
2089
|
+
/**
|
|
2090
|
+
* Updates one or more properties of an existing agent and persists the changes.
|
|
2091
|
+
*
|
|
2092
|
+
* Only fields that are present in the `updates` object are changed;
|
|
2093
|
+
* omitted fields are left as-is.
|
|
2094
|
+
*
|
|
2095
|
+
* @param agentId - The agent's ID
|
|
2096
|
+
* @param updates - Fields to update:
|
|
2097
|
+
* - `agentNickname` - short display name
|
|
2098
|
+
* - `description` - role or personality description
|
|
2099
|
+
* - `modelName` - model identifier (e.g. `'claude-haiku-4-5'`)
|
|
2100
|
+
* - `reasoningEffort` - `'low' | 'medium' | 'high' | null`
|
|
2101
|
+
* - `isControlledByHuman` - whether a human drives this agent's responses
|
|
2102
|
+
* - `maxOutputTokens` - override the model's default output token limit
|
|
2103
|
+
* - `allowSearch` - enable web search capability (provider must support it)
|
|
2104
|
+
* - `beginInstruction` - prompt sent when the host app triggers a "Begin" action
|
|
2105
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
2106
|
+
*/
|
|
1146
2107
|
async updateAgent(agentId, updates) {
|
|
1147
2108
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1148
2109
|
if (!agent) {
|
|
1149
2110
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1150
2111
|
}
|
|
2112
|
+
// Turning moderated messaging on needs a moderator in the agent's room,
|
|
2113
|
+
// checked before anything is written. Only the transition is checked: an
|
|
2114
|
+
// agent that already has the flag must stay editable even if its room has
|
|
2115
|
+
// since lost its moderator, or the flag becomes impossible to turn back off.
|
|
2116
|
+
// Room-owned agents are the ones reachable from here; an agent that joined a
|
|
2117
|
+
// room some other way is covered by the checks in createRoom and editRoom.
|
|
1151
2118
|
if (updates.useModerator === true && !agent.useModerator && agent.ownerRoomId) {
|
|
1152
2119
|
const room = await this.roomStore.getRoom(agent.ownerRoomId);
|
|
1153
2120
|
const reason = room ? this.describeMissingModerator(room, room.getAgents()) : null;
|
|
@@ -1156,8 +2123,10 @@ class AppService {
|
|
|
1156
2123
|
`"${room.getName()}" needs one. ${reason}`);
|
|
1157
2124
|
}
|
|
1158
2125
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
2126
|
+
// Update only provided fields
|
|
2127
|
+
if (updates.agentNickname !== undefined) {
|
|
2128
|
+
await this.renameAgentEverywhere(agent, updates.agentNickname);
|
|
2129
|
+
}
|
|
1161
2130
|
if (updates.description !== undefined)
|
|
1162
2131
|
agent.description = updates.description;
|
|
1163
2132
|
if (updates.modelName !== undefined)
|
|
@@ -1183,30 +2152,119 @@ class AppService {
|
|
|
1183
2152
|
agent.privateContext = updates.privateContext;
|
|
1184
2153
|
if (updates.promptCacheTTL !== undefined)
|
|
1185
2154
|
agent.promptCacheTTL = updates.promptCacheTTL;
|
|
2155
|
+
// 0 and '' mean "no limit" and "no override", so they clear rather than set.
|
|
1186
2156
|
if (updates.maxHistoryMessages !== undefined)
|
|
1187
2157
|
agent.maxHistoryMessages = updates.maxHistoryMessages || undefined;
|
|
1188
2158
|
if (updates.smallModelName !== undefined)
|
|
1189
2159
|
agent.smallModelName = updates.smallModelName || undefined;
|
|
1190
|
-
agent.save();
|
|
2160
|
+
agent.save(); // Persists all changes and triggers SSE updates
|
|
2161
|
+
}
|
|
2162
|
+
/**
|
|
2163
|
+
* Renames an agent, and repoints every room that named it.
|
|
2164
|
+
*
|
|
2165
|
+
* The manual counterpart to `ToolRoomAccess.renameAgent`. That one is
|
|
2166
|
+
* synchronous by contract and so fixes only the room it runs in, which is
|
|
2167
|
+
* complete for a room-owned agent; this path reaches an agent shared across
|
|
2168
|
+
* several rooms, where a rename would otherwise leave the other rooms pointing
|
|
2169
|
+
* at a nickname nobody answers to — including their leader, and the `viewers`
|
|
2170
|
+
* of every artifact the agent could read.
|
|
2171
|
+
*
|
|
2172
|
+
* Every room is checked before any is changed. A rename applied to two rooms
|
|
2173
|
+
* and refused by a third would leave the agent named one thing and half its
|
|
2174
|
+
* rooms naming another, which is worse than not renaming at all.
|
|
2175
|
+
*
|
|
2176
|
+
* @param agent The agent to rename
|
|
2177
|
+
* @param newName The new name; the routing nickname is its first word
|
|
2178
|
+
* @throws {ValidationError} If any room it sits in already has that name
|
|
2179
|
+
*/
|
|
2180
|
+
async renameAgentEverywhere(agent, newName) {
|
|
2181
|
+
const previous = agent.agentNickname;
|
|
2182
|
+
const trimmed = (newName || '').trim();
|
|
2183
|
+
if (!trimmed || trimmed === previous) {
|
|
2184
|
+
if (trimmed)
|
|
2185
|
+
agent.agentNickname = trimmed;
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
const rooms = (await this.roomStore.getAllRooms()).filter((room) => room.getAgents().some((a) => a.id === agent.id));
|
|
2189
|
+
for (const room of rooms) {
|
|
2190
|
+
const clash = room.conflictingNickname(agent, trimmed);
|
|
2191
|
+
if (clash) {
|
|
2192
|
+
throw new errors_1.ValidationError(`"${trimmed}" would be confused with "${clash}" in room "${room.getName()}". ` +
|
|
2193
|
+
'Two agents in a room must not share a name, or a first word — the room routes by name and could not tell them apart.');
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
agent.agentNickname = trimmed;
|
|
2197
|
+
for (const room of rooms) {
|
|
2198
|
+
room.repointNickname(previous, trimmed);
|
|
2199
|
+
}
|
|
1191
2200
|
}
|
|
2201
|
+
/**
|
|
2202
|
+
* Whether this deployment permits users to author and run their own tools.
|
|
2203
|
+
* Native (host-registered) tools are always available regardless.
|
|
2204
|
+
*/
|
|
1192
2205
|
get userAuthoredToolsEnabled() {
|
|
1193
2206
|
return this.toolExecution.userAuthoredToolsEnabled;
|
|
1194
2207
|
}
|
|
2208
|
+
/**
|
|
2209
|
+
* Lists user-authored tools (with code). Empty when authoring is disabled.
|
|
2210
|
+
*
|
|
2211
|
+
* @returns Array of user-authored tool definitions
|
|
2212
|
+
*/
|
|
1195
2213
|
async listTools() {
|
|
1196
2214
|
if (!this.userAuthoredToolsEnabled)
|
|
1197
2215
|
return [];
|
|
1198
2216
|
return this.toolStore.listTools();
|
|
1199
2217
|
}
|
|
2218
|
+
/**
|
|
2219
|
+
* Lists native (host-registered) tools as code-free summaries. These are
|
|
2220
|
+
* grantable to agents but not editable through the API.
|
|
2221
|
+
*
|
|
2222
|
+
* @returns Array of native tool summaries
|
|
2223
|
+
*/
|
|
2224
|
+
/**
|
|
2225
|
+
* Keeps grants the client could not have seen when it built its list.
|
|
2226
|
+
*
|
|
2227
|
+
* The edit form sends the whole grant list, and it filters that list against the
|
|
2228
|
+
* tools it was offered. Those are only the tools of the packs this user has
|
|
2229
|
+
* enabled — so opening an agent whose pack is off and pressing Save would send a
|
|
2230
|
+
* list with every one of its grants missing, and the agent would lose them for
|
|
2231
|
+
* good with nothing said.
|
|
2232
|
+
*
|
|
2233
|
+
* The server cannot tell "the user removed it" from "the client never saw it" by
|
|
2234
|
+
* looking at the list, so it looks at the tool instead: a name the user could not
|
|
2235
|
+
* have been offered is kept, and a name they could have been offered is theirs to
|
|
2236
|
+
* remove. A grant for a tool nothing registers at all is also kept, since the
|
|
2237
|
+
* form drops those from its list too.
|
|
2238
|
+
*
|
|
2239
|
+
* @param current The agent's grants before the update
|
|
2240
|
+
* @param requested The grants the client sent
|
|
2241
|
+
* @returns The grants to store
|
|
2242
|
+
*/
|
|
1200
2243
|
preserveHiddenGrants(current, requested) {
|
|
1201
2244
|
const offered = new Set(this.listNativeToolSummaries().map((tool) => tool.name));
|
|
1202
2245
|
const kept = current.filter((name) => !offered.has(name) && !requested.includes(name));
|
|
1203
2246
|
return kept.length > 0 ? [...requested, ...kept] : requested;
|
|
1204
2247
|
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Native tools this user may grant.
|
|
2250
|
+
*
|
|
2251
|
+
* Filtered to the packs they have enabled. Two kinds are always listed: a tool
|
|
2252
|
+
* with no `group`, registered by the host directly rather than by a pack, and a
|
|
2253
|
+
* **core** tool, which belongs to the engine rather than to a domain and so has
|
|
2254
|
+
* no pack to enable. Filtering core out would hide `rename_agent` from every
|
|
2255
|
+
* user permanently, since `core` never appears in anyone's enabled list.
|
|
2256
|
+
*
|
|
2257
|
+
* Listing only. {@link ToolExecutionService} and `Room.buildAvailableTools`
|
|
2258
|
+
* deliberately do not filter, so disabling a pack hides its tools from the
|
|
2259
|
+
* pickers without stopping an agent that already holds one from calling it.
|
|
2260
|
+
*
|
|
2261
|
+
* @returns Code-free summaries of the grantable native tools
|
|
2262
|
+
*/
|
|
1205
2263
|
listNativeToolSummaries() {
|
|
1206
2264
|
const enabled = new Set(this.enabledPacks());
|
|
1207
2265
|
return this.toolExecution
|
|
1208
2266
|
.listNativeTools()
|
|
1209
|
-
.filter((t) => !t.group || enabled.has(t.group))
|
|
2267
|
+
.filter((t) => !t.group || t.group === core_1.CORE_TOOL_GROUP || enabled.has(t.group))
|
|
1210
2268
|
.map((t) => ({
|
|
1211
2269
|
name: t.name,
|
|
1212
2270
|
description: t.description,
|
|
@@ -1214,6 +2272,13 @@ class AppService {
|
|
|
1214
2272
|
group: t.group,
|
|
1215
2273
|
}));
|
|
1216
2274
|
}
|
|
2275
|
+
/**
|
|
2276
|
+
* Creates a new user-authored tool.
|
|
2277
|
+
*
|
|
2278
|
+
* @param tool - The tool definition to create
|
|
2279
|
+
* @returns The created tool definition
|
|
2280
|
+
* @throws {OperationFailedError} If authoring is disabled or the name already exists
|
|
2281
|
+
*/
|
|
1217
2282
|
async createTool(tool) {
|
|
1218
2283
|
this.assertUserAuthoringAllowed();
|
|
1219
2284
|
const existing = await this.toolStore.getTool(tool.name);
|
|
@@ -1222,6 +2287,15 @@ class AppService {
|
|
|
1222
2287
|
}
|
|
1223
2288
|
return this.toolStore.saveTool(tool);
|
|
1224
2289
|
}
|
|
2290
|
+
/**
|
|
2291
|
+
* Updates an existing user-authored tool.
|
|
2292
|
+
*
|
|
2293
|
+
* @param name - The tool's name
|
|
2294
|
+
* @param tool - The updated tool definition
|
|
2295
|
+
* @returns The saved tool definition
|
|
2296
|
+
* @throws {NotFoundError} If the tool does not exist
|
|
2297
|
+
* @throws {OperationFailedError} If authoring is disabled
|
|
2298
|
+
*/
|
|
1225
2299
|
async updateTool(name, tool) {
|
|
1226
2300
|
this.assertUserAuthoringAllowed();
|
|
1227
2301
|
const existing = await this.toolStore.getTool(name);
|
|
@@ -1230,6 +2304,14 @@ class AppService {
|
|
|
1230
2304
|
}
|
|
1231
2305
|
return this.toolStore.saveTool({ ...tool, name });
|
|
1232
2306
|
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Deletes a user-authored tool. Agents granted the tool keep the (now dangling)
|
|
2309
|
+
* grant; the room silently drops missing tools from their prompts.
|
|
2310
|
+
*
|
|
2311
|
+
* @param name - The tool's name
|
|
2312
|
+
* @throws {NotFoundError} If the tool does not exist
|
|
2313
|
+
* @throws {OperationFailedError} If authoring is disabled
|
|
2314
|
+
*/
|
|
1233
2315
|
async deleteTool(name) {
|
|
1234
2316
|
this.assertUserAuthoringAllowed();
|
|
1235
2317
|
const deleted = await this.toolStore.deleteTool(name);
|
|
@@ -1242,30 +2324,70 @@ class AppService {
|
|
|
1242
2324
|
throw new errors_1.OperationFailedError('User-authored tools are disabled on this deployment');
|
|
1243
2325
|
}
|
|
1244
2326
|
}
|
|
2327
|
+
/**
|
|
2328
|
+
* Runs a tool with the given arguments for testing from the Tools page.
|
|
2329
|
+
* Failures are returned in-band as `{ ok: false, error }`.
|
|
2330
|
+
*
|
|
2331
|
+
* @param name - The tool's name
|
|
2332
|
+
* @param args - Named arguments for the tool
|
|
2333
|
+
* @returns The tool run result
|
|
2334
|
+
*/
|
|
1245
2335
|
async testTool(name, args) {
|
|
1246
2336
|
return this.toolExecution.test(name, args);
|
|
1247
2337
|
}
|
|
2338
|
+
/**
|
|
2339
|
+
* Lists the files currently attached to an agent.
|
|
2340
|
+
*
|
|
2341
|
+
* @param agentId - The agent's ID
|
|
2342
|
+
* @returns Object with a `files` array of file names. Returns `{ files: [] }` if the agent is not found.
|
|
2343
|
+
*/
|
|
1248
2344
|
async listAttachedFiles(agentId) {
|
|
2345
|
+
// Check if the agent exists
|
|
1249
2346
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1250
2347
|
if (!agent) {
|
|
1251
2348
|
return { files: [] };
|
|
1252
2349
|
}
|
|
2350
|
+
// Get the list of files from the AttachedFileService
|
|
1253
2351
|
const files = this.attachedFileService.listFiles(agentId);
|
|
1254
2352
|
return { files };
|
|
1255
2353
|
}
|
|
2354
|
+
/**
|
|
2355
|
+
* Removes a file from an agent by its file name.
|
|
2356
|
+
*
|
|
2357
|
+
* Deletes the file from storage and updates the agent's metadata.
|
|
2358
|
+
* Use {@link deleteAttachedFileById} if you have the document ID instead.
|
|
2359
|
+
*
|
|
2360
|
+
* @param agentId - The agent's ID
|
|
2361
|
+
* @param fileName - Name of the file to remove (e.g. `'report.pdf'`)
|
|
2362
|
+
* @throws {NotFoundError} If the agent or file is not found
|
|
2363
|
+
*/
|
|
1256
2364
|
async deleteAttachedFile(agentId, fileName) {
|
|
2365
|
+
// Check if the agent exists
|
|
1257
2366
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1258
2367
|
if (!agent) {
|
|
1259
2368
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1260
2369
|
}
|
|
2370
|
+
// Delete the file
|
|
1261
2371
|
const deleted = this.attachedFileService.deleteFileByName(agentId, fileName);
|
|
1262
2372
|
if (!deleted) {
|
|
1263
2373
|
throw new errors_1.NotFoundError(`File ${fileName} not found`);
|
|
1264
2374
|
}
|
|
2375
|
+
// Update the agent's attachedFiles array
|
|
1265
2376
|
agent.attachedFiles = agent.attachedFiles.filter((file) => file.fileName !== fileName);
|
|
1266
2377
|
agent.save();
|
|
1267
2378
|
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Removes an attached file by its document ID (as returned by {@link attachDocument}).
|
|
2381
|
+
*
|
|
2382
|
+
* Searches all agents to locate the owner, removes the file from storage,
|
|
2383
|
+
* and updates the agent's metadata.
|
|
2384
|
+
*
|
|
2385
|
+
* @param documentId - The `documentId` returned by {@link attachDocument}
|
|
2386
|
+
* @throws {NotFoundError} If no file with the given ID exists
|
|
2387
|
+
* @throws {OperationFailedError} If deletion fails
|
|
2388
|
+
*/
|
|
1268
2389
|
async deleteAttachedFileById(documentId) {
|
|
2390
|
+
// Find the agent that owns this file
|
|
1269
2391
|
const allAgentIds = await this.agentStore.getAllAgentIds();
|
|
1270
2392
|
let ownerAgent = null;
|
|
1271
2393
|
let fileMetadata = null;
|
|
@@ -1283,20 +2405,36 @@ class AppService {
|
|
|
1283
2405
|
if (!ownerAgent || !fileMetadata) {
|
|
1284
2406
|
throw new errors_1.NotFoundError('File not found');
|
|
1285
2407
|
}
|
|
2408
|
+
// Delete the file using the attachedFileService
|
|
1286
2409
|
const deleted = this.attachedFileService.deleteFile(ownerAgent.id, documentId);
|
|
1287
2410
|
if (!deleted) {
|
|
1288
2411
|
throw new errors_1.OperationFailedError('Failed to delete file');
|
|
1289
2412
|
}
|
|
2413
|
+
// Update the agent's attachedFiles array
|
|
1290
2414
|
ownerAgent.attachedFiles = ownerAgent.attachedFiles.filter((file) => file.fileId !== documentId);
|
|
1291
2415
|
ownerAgent.save();
|
|
1292
2416
|
}
|
|
2417
|
+
/**
|
|
2418
|
+
* Clears an agent's conversation history while preserving its configuration
|
|
2419
|
+
* and re-attaching any previously uploaded files.
|
|
2420
|
+
*
|
|
2421
|
+
* Useful for starting a fresh conversation without recreating the agent.
|
|
2422
|
+
* If the history begins with a summary block (from a prior compaction), only
|
|
2423
|
+
* messages after the summary are cleared.
|
|
2424
|
+
*
|
|
2425
|
+
* @param agentId - The agent's ID
|
|
2426
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
2427
|
+
*/
|
|
1293
2428
|
async reloadAgent(agentId) {
|
|
2429
|
+
// Check if the agent exists
|
|
1294
2430
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1295
2431
|
if (!agent) {
|
|
1296
2432
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1297
2433
|
}
|
|
2434
|
+
// Get the agent's service
|
|
1298
2435
|
const serviceName = agent.serviceName;
|
|
1299
2436
|
const aiService = this.getAiServiceFromServiceName(serviceName);
|
|
2437
|
+
// Create a new history array
|
|
1300
2438
|
if (agent.history &&
|
|
1301
2439
|
agent.history.length > 0 &&
|
|
1302
2440
|
agent.history[0].content &&
|
|
@@ -1304,6 +2442,7 @@ class AppService {
|
|
|
1304
2442
|
agent.history.splice(1);
|
|
1305
2443
|
else
|
|
1306
2444
|
agent.history = [];
|
|
2445
|
+
// Re-attach all files
|
|
1307
2446
|
const fileMetadataList = agent.attachedFiles;
|
|
1308
2447
|
for (const metadata of fileMetadataList) {
|
|
1309
2448
|
const fileData = this.attachedFileService.getFile(agent.id, metadata.fileId);
|
|
@@ -1313,6 +2452,13 @@ class AppService {
|
|
|
1313
2452
|
}
|
|
1314
2453
|
agent.save();
|
|
1315
2454
|
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Compacts an agent's conversation history into a single summary message.
|
|
2457
|
+
* Uses the `compact_agent` prompt (role folder first, common-root as fallback).
|
|
2458
|
+
*
|
|
2459
|
+
* @param agentId - The agent's ID
|
|
2460
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
2461
|
+
*/
|
|
1316
2462
|
async compactAgentConversation(agentId) {
|
|
1317
2463
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1318
2464
|
if (!agent) {
|
|
@@ -1320,54 +2466,85 @@ class AppService {
|
|
|
1320
2466
|
}
|
|
1321
2467
|
await agent.compact();
|
|
1322
2468
|
}
|
|
2469
|
+
/**
|
|
2470
|
+
* Clears a room's message history and artifacts, and resets all member agents.
|
|
2471
|
+
*
|
|
2472
|
+
* Agent configurations (model, prompt, files) are preserved; only conversation
|
|
2473
|
+
* history and artifacts are removed.
|
|
2474
|
+
*
|
|
2475
|
+
* @param roomId - The room's ID
|
|
2476
|
+
* @throws {NotFoundError} If the room does not exist
|
|
2477
|
+
*/
|
|
1323
2478
|
async resetRoom(roomId) {
|
|
2479
|
+
// Get the room
|
|
1324
2480
|
const room = await this.roomStore.getRoom(roomId);
|
|
1325
2481
|
if (!room) {
|
|
1326
2482
|
throw new errors_1.NotFoundError('Room not found');
|
|
1327
2483
|
}
|
|
1328
2484
|
const roomName = room.getName();
|
|
1329
2485
|
const storageDir = room.getStorageDir() || this.roomStore.getDefaultStorageDir();
|
|
2486
|
+
// Clear room messages (both in-memory and on disk)
|
|
1330
2487
|
this.roomStore.clearRoomMessages(roomId, storageDir);
|
|
2488
|
+
// Clear all artifacts (delete files and clear in-memory)
|
|
1331
2489
|
this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
|
|
1332
2490
|
room.setArtifacts([]);
|
|
2491
|
+
// Reset each agent using the existing reloadAgent logic
|
|
1333
2492
|
const warnings = [];
|
|
1334
2493
|
for (const agent of room.getAgents()) {
|
|
1335
2494
|
try {
|
|
2495
|
+
// Use existing reloadAgent functionality to clear history and re-attach files
|
|
1336
2496
|
this.reloadAgent(agent.id);
|
|
1337
2497
|
}
|
|
1338
2498
|
catch (agentError) {
|
|
1339
2499
|
warnings.push(`Failed to reset agent ${agent.agentName}: ${agentError.message}`);
|
|
1340
2500
|
}
|
|
1341
2501
|
}
|
|
2502
|
+
// Log warnings if any
|
|
1342
2503
|
if (warnings.length > 0) {
|
|
1343
2504
|
logger_1.logger.warn(`Room "${roomName}" reset with warnings:`, warnings);
|
|
1344
2505
|
}
|
|
1345
2506
|
}
|
|
2507
|
+
/**
|
|
2508
|
+
* Resets a story to the beginning while preserving artifacts and the opening scene.
|
|
2509
|
+
*
|
|
2510
|
+
* If a chapter 1 backup exists, agents are restored from it; otherwise their
|
|
2511
|
+
* conversation histories are cleared. The list of declined characters is also cleared.
|
|
2512
|
+
*
|
|
2513
|
+
* @param storyId - The story's ID
|
|
2514
|
+
* @throws {NotFoundError} If the story or its room does not exist
|
|
2515
|
+
*/
|
|
1346
2516
|
async resetStory(storyId) {
|
|
2517
|
+
// Get the story metadata
|
|
1347
2518
|
const story = this.storyStore.getStory(storyId);
|
|
1348
2519
|
if (!story || !story.roomId) {
|
|
1349
2520
|
throw new errors_1.NotFoundError('Story not found');
|
|
1350
2521
|
}
|
|
1351
2522
|
const storyName = story.name;
|
|
2523
|
+
// Get the room
|
|
1352
2524
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1353
2525
|
if (!room) {
|
|
1354
2526
|
throw new errors_1.NotFoundError('Story room not found');
|
|
1355
2527
|
}
|
|
2528
|
+
// Find and preserve the Opening Scene message before clearing
|
|
1356
2529
|
const roomMessages = room.getLatestRoomMessages();
|
|
1357
2530
|
const openingSceneMessage = roomMessages.find((msg) => msg.sender === 'Opening Scene');
|
|
1358
2531
|
const openingSceneText = openingSceneMessage?.content || '';
|
|
1359
2532
|
const storageDir = room.getStorageDir() ||
|
|
1360
2533
|
path.join(this.userPaths.getUserDataDir(), 'stories', storyId, 'rooms');
|
|
2534
|
+
// Clear room messages (both in-memory and on disk)
|
|
1361
2535
|
this.roomStore.clearRoomMessages(story.roomId, storageDir);
|
|
1362
2536
|
room.setRoomMessages([]);
|
|
2537
|
+
// Restore agents from chapter 1 backup instead of calling reloadAgent
|
|
1363
2538
|
const chapters = this.storyStore.listChapters(storyId);
|
|
1364
2539
|
const warnings = [];
|
|
1365
2540
|
if (chapters.length > 0) {
|
|
2541
|
+
// Chapter 1 backup exists - restore agents from it
|
|
1366
2542
|
logger_1.logger.log(`Restoring agents from chapter 1 backup for story ${storyId}`);
|
|
1367
2543
|
const restoredAgentIds = await this.storyStore.restoreAgentsFromChapter(storyId, 1, this.agentStore);
|
|
1368
2544
|
logger_1.logger.log(`Restored ${restoredAgentIds.length} agents from chapter 1 backup`);
|
|
1369
2545
|
}
|
|
1370
2546
|
else {
|
|
2547
|
+
// No chapter backup exists - fallback to reloadAgent (clear histories)
|
|
1371
2548
|
logger_1.logger.warn(`No chapter 1 backup found for story ${storyId}, clearing agent histories`);
|
|
1372
2549
|
for (const agent of room.getAgents()) {
|
|
1373
2550
|
try {
|
|
@@ -1378,35 +2555,209 @@ class AppService {
|
|
|
1378
2555
|
}
|
|
1379
2556
|
}
|
|
1380
2557
|
}
|
|
2558
|
+
// Re-add the opening scene message and populate agent histories
|
|
1381
2559
|
if (openingSceneText) {
|
|
1382
2560
|
this.storyService.populateStoryHistory(room, openingSceneText);
|
|
1383
2561
|
}
|
|
2562
|
+
// Clear declined characters when resetting story
|
|
1384
2563
|
if (story) {
|
|
1385
2564
|
story.declinedCharacters = [];
|
|
1386
2565
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1387
2566
|
}
|
|
2567
|
+
// Log warnings if any
|
|
1388
2568
|
if (warnings.length > 0) {
|
|
1389
2569
|
logger_1.logger.warn(`Story "${storyName}" reset with warnings:`, warnings);
|
|
1390
2570
|
}
|
|
1391
2571
|
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Reverts the most recent chapter progression for a story. Restores room
|
|
2574
|
+
* messages, artifacts, and agent histories from the previous chapter
|
|
2575
|
+
* backup, then deletes that backup. Only valid when the current chapter
|
|
2576
|
+
* has not been played past the opening scene.
|
|
2577
|
+
*
|
|
2578
|
+
* @param storyId - The story's ID
|
|
2579
|
+
* @throws {NotFoundError} If the story or its room does not exist
|
|
2580
|
+
* @throws {OperationFailedError} If revert is not currently valid
|
|
2581
|
+
*/
|
|
1392
2582
|
async revertStoryChapter(storyId) {
|
|
1393
2583
|
return this.storyService.revertStoryChapter(storyId);
|
|
1394
2584
|
}
|
|
2585
|
+
/**
|
|
2586
|
+
* Creates a new interactive story with AI-driven characters.
|
|
2587
|
+
*
|
|
2588
|
+
* When this method returns, the story is **immediately playable**: brief character
|
|
2589
|
+
* backgrounds and the opening scene have already been generated. A background job
|
|
2590
|
+
* then generates the detailed plot plan and full character profiles; subscribe to
|
|
2591
|
+
* {@link getStoryProgressEmitter} to be notified when that finishes (`step === 'complete'`),
|
|
2592
|
+
* but there is no need to wait for it before letting the player interact.
|
|
2593
|
+
*
|
|
2594
|
+
* @param name - Display name for the story
|
|
2595
|
+
* @param idea - Brief premise or concept for the story
|
|
2596
|
+
* @param userCharacterDesc - Description of the character the human player will portray
|
|
2597
|
+
* @param otherCharactersDesc - Description of other prominent characters to generate
|
|
2598
|
+
* @param storyModel - Model identifier from `story_models.json` (e.g. `'claude-haiku-4-5'`). Defaults to the configured default.
|
|
2599
|
+
* @param isImport - Set `true` when reconstructing a story from exported data. Default `false`.
|
|
2600
|
+
* @param imageModelName - Optional image model name from image_models.json (supplies both the generation and editing models)
|
|
2601
|
+
* @param skipDetailedPlot - Set `true` to generate a simple plot scenario instead of a detailed plot plan with secrets, twists, and events. Default `false`.
|
|
2602
|
+
* @returns Story metadata including the new `id` - story is ready to play immediately
|
|
2603
|
+
*
|
|
2604
|
+
* @example
|
|
2605
|
+
* ```typescript
|
|
2606
|
+
* // Story is playable as soon as createStory returns
|
|
2607
|
+
* const story = await appService.createStory(
|
|
2608
|
+
* 'The Lost Kingdom',
|
|
2609
|
+
* 'A medieval fantasy adventure',
|
|
2610
|
+
* 'A young knight seeking redemption',
|
|
2611
|
+
* 'A wise wizard and a cunning rogue',
|
|
2612
|
+
* );
|
|
2613
|
+
*
|
|
2614
|
+
* // Optionally listen for background completion (plot plan + detailed profiles)
|
|
2615
|
+
* const emitter = appService.getStoryProgressEmitter(story.id);
|
|
2616
|
+
* emitter?.on('progress', ({ step, message }) => {
|
|
2617
|
+
* if (step === 'complete') console.log('Background setup finished');
|
|
2618
|
+
* });
|
|
2619
|
+
* ```
|
|
2620
|
+
*/
|
|
1395
2621
|
async createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot) {
|
|
2622
|
+
// Delegate to StoryService for business logic
|
|
1396
2623
|
return this.storyService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot);
|
|
1397
2624
|
}
|
|
2625
|
+
/**
|
|
2626
|
+
* Reconstructs a story from a previously exported zip archive.
|
|
2627
|
+
*
|
|
2628
|
+
* @param zipBuffer - Raw bytes of the zip file produced by {@link exportStoryData}
|
|
2629
|
+
* @returns Story metadata for the newly imported story
|
|
2630
|
+
*/
|
|
1398
2631
|
async importStoryFromZip(zipBuffer) {
|
|
1399
2632
|
return this.storyService.importStoryFromZip(zipBuffer);
|
|
1400
2633
|
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Returns the `EventEmitter` for tracking background story work.
|
|
2636
|
+
*
|
|
2637
|
+
* Subscribe to the `'progress'` event. Each event payload is
|
|
2638
|
+
* `{ step: string, message: string, timestamp: number }`.
|
|
2639
|
+
*
|
|
2640
|
+
* **`step` values emitted after {@link createStory} returns:**
|
|
2641
|
+
*
|
|
2642
|
+
* The story is already playable when `createStory` returns. There is no `'ready'`
|
|
2643
|
+
* step for story creation - the storyId does not exist until `createStory` returns,
|
|
2644
|
+
* so the client cannot subscribe to the progress emitter until after that point.
|
|
2645
|
+
* These steps describe the optional background job (plot plan + detailed profiles)
|
|
2646
|
+
* that continues after the method returns:
|
|
2647
|
+
* - `'start'` - background job has begun
|
|
2648
|
+
* - `'profiles'` - generating detailed character profiles
|
|
2649
|
+
* - `'portraits'` - generating character portrait images (only if an image model is configured)
|
|
2650
|
+
* - `'complete'` - background job finished; detailed profiles and plot plan are now available
|
|
2651
|
+
* - `'error'` - background job failed; `message` contains the error text
|
|
2652
|
+
*
|
|
2653
|
+
* **`step` values emitted during {@link progressStory}:**
|
|
2654
|
+
*
|
|
2655
|
+
* `'ready'` fires just before `progressStory` returns, so the story is playable
|
|
2656
|
+
* as soon as the Promise resolves - no need to separately listen for `'ready'`.
|
|
2657
|
+
* The event is emitted for the benefit of SSE clients that want to update their UI
|
|
2658
|
+
* in real time. After `'ready'`, a background job continues:
|
|
2659
|
+
* - `'opening-scene'` - writing the new chapter's opening scene
|
|
2660
|
+
* - `'chapter-backup'` - saving chapter checkpoint data
|
|
2661
|
+
* - `'ready'` - chapter ready; fired just before `progressStory` resolves
|
|
2662
|
+
* - `'profiles'` - (background) recreating plot plan and character profiles
|
|
2663
|
+
* - `'complete'` - (background) all chapter work done
|
|
2664
|
+
* - `'error'` - progression failed
|
|
2665
|
+
*
|
|
2666
|
+
* The emitter is removed after the terminal step (`'complete'`, `'ready'`, or `'error'`),
|
|
2667
|
+
* so this method returns `undefined` once a terminal step has fired.
|
|
2668
|
+
*
|
|
2669
|
+
* @param storyId - The story's ID
|
|
2670
|
+
* @returns `EventEmitter` emitting `'progress'` events, or `undefined` if already complete
|
|
2671
|
+
*/
|
|
1401
2672
|
getStoryProgressEmitter(storyId) {
|
|
1402
2673
|
return this.storyService.getProgressEmitter(storyId);
|
|
1403
2674
|
}
|
|
2675
|
+
/**
|
|
2676
|
+
* Returns the `EventEmitter` for real-time story updates.
|
|
2677
|
+
*
|
|
2678
|
+
* The emitter fires four named events. Each payload includes a `timestamp` field.
|
|
2679
|
+
*
|
|
2680
|
+
* ---
|
|
2681
|
+
*
|
|
2682
|
+
* **`'story-state'`** - {@link StoryStateEvent}
|
|
2683
|
+
* Fires after every room turn with the complete updated game state.
|
|
2684
|
+
* ```typescript
|
|
2685
|
+
* emitter.on('story-state', (event: StoryStateEvent) => {
|
|
2686
|
+
* const myTurn = event.state.currentSpeaker === event.state.userAgentName;
|
|
2687
|
+
* });
|
|
2688
|
+
* ```
|
|
2689
|
+
* Use `state.currentSpeaker === state.userAgentName` to detect the player's turn.
|
|
2690
|
+
* Do **not** use `state.humanPrompt` for turn detection - it is a UI display string
|
|
2691
|
+
* (e.g. `"What does Elena do next?"`) present even when it is not the player's turn.
|
|
2692
|
+
*
|
|
2693
|
+
* ---
|
|
2694
|
+
*
|
|
2695
|
+
* **`'suggest-introduce-character'`** - {@link StoryIntroduceCharacterEvent}
|
|
2696
|
+
* Fires when the narrator wants to add a new character. The host app should surface
|
|
2697
|
+
* this to the player before acting.
|
|
2698
|
+
* - **Accept:** call {@link introduceCharacterToStory} with `fromNarratorSuggestion: true`
|
|
2699
|
+
* - **Reject:** call {@link declineCharacter}
|
|
2700
|
+
* ```typescript
|
|
2701
|
+
* emitter.on('suggest-introduce-character', (event: StoryIntroduceCharacterEvent) => {
|
|
2702
|
+
* // event.characterName is the narrator-chosen name
|
|
2703
|
+
* });
|
|
2704
|
+
* ```
|
|
2705
|
+
*
|
|
2706
|
+
* ---
|
|
2707
|
+
*
|
|
2708
|
+
* **`'suggest-progress-chapter'`** - {@link StoryProgressChapterEvent}
|
|
2709
|
+
* Fires when the narrator wants to advance to the next chapter. The host app should
|
|
2710
|
+
* surface this to the player before acting.
|
|
2711
|
+
* - **Accept:** call {@link progressStory}
|
|
2712
|
+
* - **Stay in current chapter:** ignore the event (no rejection call needed)
|
|
2713
|
+
*
|
|
2714
|
+
* ---
|
|
2715
|
+
*
|
|
2716
|
+
* **`'story-error'`** - {@link StoryErrorEvent}
|
|
2717
|
+
* Fires when the story engine encounters a fatal error during room processing.
|
|
2718
|
+
* Named `'story-error'` rather than `'error'` to avoid Node.js throwing an uncaught
|
|
2719
|
+
* exception when no listener is attached to `'error'`.
|
|
2720
|
+
* Check `event.errorType === 'InsufficientBalanceError'` for balance failures.
|
|
2721
|
+
*
|
|
2722
|
+
* ---
|
|
2723
|
+
*
|
|
2724
|
+
* @param storyId - The story's ID
|
|
2725
|
+
* @returns `EventEmitter` emitting `'story-state'`, `'suggest-introduce-character'`,
|
|
2726
|
+
* `'suggest-progress-chapter'`, and `'story-error'` events
|
|
2727
|
+
*/
|
|
1404
2728
|
getStoryMessageEmitter(storyId) {
|
|
1405
2729
|
return this.storyService.getMessageEmitter(storyId);
|
|
1406
2730
|
}
|
|
2731
|
+
/**
|
|
2732
|
+
* Returns a Node.js `EventEmitter` that fires whenever this agent's state changes
|
|
2733
|
+
* (new message, token count update, etc.).
|
|
2734
|
+
*
|
|
2735
|
+
* Useful for building real-time UIs. Subscribe to the `'update'` event to receive
|
|
2736
|
+
* agent state payloads without polling.
|
|
2737
|
+
*
|
|
2738
|
+
* @param agentId - The agent's ID
|
|
2739
|
+
* @returns `EventEmitter` that emits `'update'` events with agent state payloads
|
|
2740
|
+
*
|
|
2741
|
+
* @example
|
|
2742
|
+
* ```typescript
|
|
2743
|
+
* const emitter = appService.getAgentMessageEmitter(agent.id);
|
|
2744
|
+
* emitter.on('update', (state) => {
|
|
2745
|
+
* console.log('New message:', state.latestMessage);
|
|
2746
|
+
* });
|
|
2747
|
+
* ```
|
|
2748
|
+
*/
|
|
1407
2749
|
getAgentMessageEmitter(agentId) {
|
|
1408
2750
|
return this.agentMessageService.getOrCreateEmitter(agentId);
|
|
1409
2751
|
}
|
|
2752
|
+
/**
|
|
2753
|
+
* Ensures the real-time state callback is registered for an agent.
|
|
2754
|
+
*
|
|
2755
|
+
* Normally called automatically by {@link processText} and {@link getAgentMessages}.
|
|
2756
|
+
* Call this explicitly when connecting a new SSE client to an agent that was
|
|
2757
|
+
* loaded from disk (not yet touched in this session).
|
|
2758
|
+
*
|
|
2759
|
+
* @param agentId - The agent's ID
|
|
2760
|
+
*/
|
|
1410
2761
|
async ensureAgentStateCallback(agentId) {
|
|
1411
2762
|
try {
|
|
1412
2763
|
const agent = await this.agentStore.getAgent(agentId);
|
|
@@ -1418,12 +2769,17 @@ class AppService {
|
|
|
1418
2769
|
logger_1.logger.warn(`Could not set up SSE callback for agent ${agentId}:`, error.message);
|
|
1419
2770
|
}
|
|
1420
2771
|
}
|
|
2772
|
+
/**
|
|
2773
|
+
* Sets up the state change callback for an agent to emit SSE updates
|
|
2774
|
+
* @param agent The agent to set up the callback for
|
|
2775
|
+
*/
|
|
1421
2776
|
setupAgentStateCallback(agent) {
|
|
1422
2777
|
if (!agent.id) {
|
|
1423
2778
|
logger_1.logger.warn('Cannot set up SSE callback for agent without ID');
|
|
1424
2779
|
return;
|
|
1425
2780
|
}
|
|
1426
2781
|
agent.setOnStateChange(() => {
|
|
2782
|
+
// Get current agent state - send only latest message + index
|
|
1427
2783
|
const messages = agent.getFormattedMessages();
|
|
1428
2784
|
const agentState = {
|
|
1429
2785
|
agentId: agent.id,
|
|
@@ -1433,15 +2789,42 @@ class AppService {
|
|
|
1433
2789
|
totalOutputTokens: agent.totalOutputTokens,
|
|
1434
2790
|
totalCost: agent.totalCost,
|
|
1435
2791
|
};
|
|
2792
|
+
// Emit update to all connected SSE clients
|
|
1436
2793
|
this.agentMessageService.emitUpdate(agent.id, agentState);
|
|
1437
2794
|
});
|
|
1438
2795
|
}
|
|
2796
|
+
/**
|
|
2797
|
+
* Returns a Node.js `EventEmitter` that fires whenever a new message arrives in the room.
|
|
2798
|
+
*
|
|
2799
|
+
* Subscribe to the `'update'` event to receive room message payloads in real time
|
|
2800
|
+
* without polling.
|
|
2801
|
+
*
|
|
2802
|
+
* @param roomId - The room's ID
|
|
2803
|
+
* @returns `EventEmitter` that emits `'update'` events with room message payloads
|
|
2804
|
+
*/
|
|
1439
2805
|
getRoomMessageEmitter(roomId) {
|
|
1440
2806
|
return this.roomMessageService.getOrCreateEmitter(roomId);
|
|
1441
2807
|
}
|
|
2808
|
+
/**
|
|
2809
|
+
* Returns a Node.js `EventEmitter` that fires whenever the user's balance changes.
|
|
2810
|
+
*
|
|
2811
|
+
* Subscribe to the `'update'` event to push real-time balance updates to a connected
|
|
2812
|
+
* client (e.g. via SSE) without polling.
|
|
2813
|
+
*
|
|
2814
|
+
* @param userId - The user's ID (typically the same ID used with `getAppService`)
|
|
2815
|
+
* @returns `EventEmitter` that emits `'update'` events with the new balance value
|
|
2816
|
+
*/
|
|
1442
2817
|
getBalanceMessageEmitter(userId) {
|
|
1443
2818
|
return this.balanceMessageService.getOrCreateEmitter(userId);
|
|
1444
2819
|
}
|
|
2820
|
+
/**
|
|
2821
|
+
* Ensures the real-time state callback is registered for a room.
|
|
2822
|
+
*
|
|
2823
|
+
* Normally called automatically. Call this explicitly when connecting a new
|
|
2824
|
+
* SSE client to a room that was loaded from disk (not yet touched in this session).
|
|
2825
|
+
*
|
|
2826
|
+
* @param roomId - The room's ID
|
|
2827
|
+
*/
|
|
1445
2828
|
async ensureRoomStateCallback(roomId) {
|
|
1446
2829
|
try {
|
|
1447
2830
|
const room = await this.roomStore.getRoom(roomId);
|
|
@@ -1459,10 +2842,23 @@ class AppService {
|
|
|
1459
2842
|
logger_1.logger.warn('Cannot set up SSE callback for room without ID');
|
|
1460
2843
|
return;
|
|
1461
2844
|
}
|
|
2845
|
+
// Failures go down the same channel as everything else, as
|
|
2846
|
+
// `{type: 'error', errorType, message}`. Without this a turn that dies —
|
|
2847
|
+
// most importantly on a spent balance — simply stopped: no message, no
|
|
2848
|
+
// event, nothing to await. A host watching the room saw it go quiet and had
|
|
2849
|
+
// no way to learn why, which is the worst shape a paid API can fail in.
|
|
1462
2850
|
room.setOnError('app-service', (error) => {
|
|
1463
2851
|
this.roomMessageService.emitError(roomId, error);
|
|
1464
2852
|
});
|
|
1465
2853
|
room.setOnStateChange('app-service', () => {
|
|
2854
|
+
// Everything the room logged, thoughts and tool notices included, so
|
|
2855
|
+
// that this stream and a reader's own message list count in the same
|
|
2856
|
+
// space. Carrying only the audible ones meant the position published
|
|
2857
|
+
// here and the index on the message disagreed for any reader holding
|
|
2858
|
+
// thoughts, and disagreed by an amount neither number could express —
|
|
2859
|
+
// so the only way back in step was to refetch the whole transcript.
|
|
2860
|
+
// A consumer that does not want the internal traffic drops it on
|
|
2861
|
+
// `action`, which costs nothing and cannot fall out of step.
|
|
1466
2862
|
const messages = room.getLatestRoomMessages(0, true);
|
|
1467
2863
|
const latestMessage = messages.length > 0 ? messages[messages.length - 1] : undefined;
|
|
1468
2864
|
const totalCost = room
|
|
@@ -1470,9 +2866,14 @@ class AppService {
|
|
|
1470
2866
|
.map((a) => a.totalCost)
|
|
1471
2867
|
.reduce((acc, v) => acc + v, 0);
|
|
1472
2868
|
const roomState = {
|
|
2869
|
+
// Both variants travel on the room's 'update' event, so a host that
|
|
2870
|
+
// narrows on `type` needs it present on the ordinary one too.
|
|
1473
2871
|
type: 'state',
|
|
1474
2872
|
roomId: roomId,
|
|
1475
2873
|
latestMessage: latestMessage,
|
|
2874
|
+
// The message's own index, not its position in this array. They
|
|
2875
|
+
// are the same number for an unfiltered list, and saying which
|
|
2876
|
+
// one is meant is what keeps them the same.
|
|
1476
2877
|
messageIndex: latestMessage?.index,
|
|
1477
2878
|
totalCost: totalCost,
|
|
1478
2879
|
isPaused: room.getPaused(),
|
|
@@ -1483,9 +2884,22 @@ class AppService {
|
|
|
1483
2884
|
this.roomMessageService.emitUpdate(roomId, roomState);
|
|
1484
2885
|
});
|
|
1485
2886
|
}
|
|
2887
|
+
/**
|
|
2888
|
+
* Lists all stories belonging to this user.
|
|
2889
|
+
*
|
|
2890
|
+
* @returns Array of story metadata objects
|
|
2891
|
+
*/
|
|
1486
2892
|
listStories() {
|
|
1487
2893
|
return this.storyStore.getAllStories();
|
|
1488
2894
|
}
|
|
2895
|
+
/**
|
|
2896
|
+
* Resumes any stories that were paused due to insufficient balance.
|
|
2897
|
+
*
|
|
2898
|
+
* Call this after adding balance via {@link addBalance} to allow stories that
|
|
2899
|
+
* stalled mid-processing to continue from where they left off.
|
|
2900
|
+
*
|
|
2901
|
+
* @returns The number of stories that were resumed
|
|
2902
|
+
*/
|
|
1489
2903
|
async resumePausedStories() {
|
|
1490
2904
|
const stories = this.storyStore.getAllStories();
|
|
1491
2905
|
let resumedCount = 0;
|
|
@@ -1496,11 +2910,14 @@ class AppService {
|
|
|
1496
2910
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1497
2911
|
if (!room)
|
|
1498
2912
|
continue;
|
|
2913
|
+
// Check if room is paused (not processing but has pending messages)
|
|
1499
2914
|
const isPaused = !room.isProcessingInProgress() && room['pendingMessages']?.length > 0;
|
|
1500
2915
|
if (isPaused) {
|
|
1501
2916
|
logger_1.logger.log(`Resuming paused story: ${story.name} (${story.id})`);
|
|
2917
|
+
// Add a system message to notify about resumption
|
|
1502
2918
|
const resumeMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, 'Balance added. Conversation resumed.', [], null, null);
|
|
1503
2919
|
room.addRoomMessage(resumeMessage);
|
|
2920
|
+
// Resume processing by calling processPendingMessages
|
|
1504
2921
|
room['processPendingMessages']();
|
|
1505
2922
|
resumedCount++;
|
|
1506
2923
|
}
|
|
@@ -1514,129 +2931,477 @@ class AppService {
|
|
|
1514
2931
|
}
|
|
1515
2932
|
return resumedCount;
|
|
1516
2933
|
}
|
|
2934
|
+
/**
|
|
2935
|
+
* Permanently deletes a story, its room, all characters, chapters, and artifacts.
|
|
2936
|
+
*
|
|
2937
|
+
* @param storyId - The story's ID
|
|
2938
|
+
*/
|
|
1517
2939
|
async deleteStory(storyId) {
|
|
1518
2940
|
await this.storyService.deleteStory(storyId);
|
|
1519
2941
|
}
|
|
2942
|
+
/**
|
|
2943
|
+
* Summarizes and compresses agent conversation histories to reduce token usage.
|
|
2944
|
+
*
|
|
2945
|
+
* Uses story-specific prompts: the narrator summarizes plot events,
|
|
2946
|
+
* characters summarize their relationships and experiences. The original
|
|
2947
|
+
* messages are replaced with a compact summary block.
|
|
2948
|
+
*
|
|
2949
|
+
* @param storyId - The story's ID
|
|
2950
|
+
* @returns Object with `success` flag, optional `message`, and compaction `details`
|
|
2951
|
+
*/
|
|
1520
2952
|
async compactStory(storyId) {
|
|
1521
2953
|
return this.storyService.compactStory(storyId);
|
|
1522
2954
|
}
|
|
2955
|
+
/**
|
|
2956
|
+
* Advances the story to the next chapter.
|
|
2957
|
+
*
|
|
2958
|
+
* Creates a checkpoint of the current chapter state and rebuilds the opening scene.
|
|
2959
|
+
* The story is **immediately playable when this Promise resolves** - the `'ready'`
|
|
2960
|
+
* progress event fires just before the function returns, so awaiting this call is
|
|
2961
|
+
* sufficient; there is no need to separately wait for the event.
|
|
2962
|
+
*
|
|
2963
|
+
* After the function returns, a background job recreates the plot plan and character
|
|
2964
|
+
* profiles for the new chapter (`'profiles'` --> `'complete'`). Agent
|
|
2965
|
+
* conversation histories are **not** compacted here - each agent compacts
|
|
2966
|
+
* independently on demand when it individually reaches the compaction threshold
|
|
2967
|
+
* (see {@link compactStory} for manual compaction).
|
|
2968
|
+
*
|
|
2969
|
+
* @param storyId - The story's ID
|
|
2970
|
+
* @returns Object with the new `chapterIndex`
|
|
2971
|
+
*/
|
|
1523
2972
|
async progressStory(storyId) {
|
|
1524
2973
|
return this.storyService.progressStoryToNextChapter(storyId);
|
|
1525
2974
|
}
|
|
2975
|
+
/**
|
|
2976
|
+
* Returns the current runtime state of a story.
|
|
2977
|
+
*
|
|
2978
|
+
* Includes messages, pending message count, processing status, and story metadata.
|
|
2979
|
+
* Useful for restoring UI state after reconnecting.
|
|
2980
|
+
*
|
|
2981
|
+
* @param storyId - The story's ID
|
|
2982
|
+
* @returns Full story state object
|
|
2983
|
+
*/
|
|
1526
2984
|
async getStoryState(storyId) {
|
|
1527
2985
|
return this.storyService.getStoryState(storyId);
|
|
1528
2986
|
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Returns metadata for a specific story.
|
|
2989
|
+
*
|
|
2990
|
+
* @param storyId - The story's ID
|
|
2991
|
+
* @returns Story metadata, or `undefined` if not found
|
|
2992
|
+
*/
|
|
1529
2993
|
async getStoryInfo(storyId) {
|
|
1530
2994
|
return this.storyStore.getStory(storyId);
|
|
1531
2995
|
}
|
|
2996
|
+
/**
|
|
2997
|
+
* Submits the human player's response to the story.
|
|
2998
|
+
*
|
|
2999
|
+
* Adds the content as a player message and triggers the AI characters
|
|
3000
|
+
* to continue the narrative.
|
|
3001
|
+
*
|
|
3002
|
+
* Pass the literal string `'PASS'` (case-insensitive) to skip the player's
|
|
3003
|
+
* turn and let the AI characters continue without player input.
|
|
3004
|
+
*
|
|
3005
|
+
* @param storyId - The story's ID
|
|
3006
|
+
* @param content - The player's message or action, or `'PASS'` to skip the turn
|
|
3007
|
+
*/
|
|
1532
3008
|
async respondToStory(storyId, content) {
|
|
1533
3009
|
return this.storyService.respondToStory(storyId, content);
|
|
1534
3010
|
}
|
|
3011
|
+
/**
|
|
3012
|
+
* Cancels any pending AI turns and forces the human's turn.
|
|
3013
|
+
*
|
|
3014
|
+
* Drops the room's pending message queue and pauses processing so the
|
|
3015
|
+
* human-controlled agent becomes the current speaker. Any in-flight LLM
|
|
3016
|
+
* calls (perceive or moderator) will discard their responses on return.
|
|
3017
|
+
*
|
|
3018
|
+
* @param storyId - The story's ID
|
|
3019
|
+
*/
|
|
1535
3020
|
async interruptStory(storyId) {
|
|
1536
3021
|
return this.storyService.interruptStory(storyId);
|
|
1537
3022
|
}
|
|
3023
|
+
/**
|
|
3024
|
+
* Adds a new AI character to an existing story.
|
|
3025
|
+
*
|
|
3026
|
+
* Creates a character agent and integrates it into the story's room.
|
|
3027
|
+
* The character profile is generated by the AI based on the provided description.
|
|
3028
|
+
*
|
|
3029
|
+
* When {@link getStoryMessageEmitter} fires a `'suggestion'` update with
|
|
3030
|
+
* `suggestion.type === 'introduce_character'`, pass `suggestion.characterName` as
|
|
3031
|
+
* `name` and set `fromNarratorSuggestion: true` to accept the suggestion.
|
|
3032
|
+
* To reject it instead, call {@link declineCharacter}.
|
|
3033
|
+
*
|
|
3034
|
+
* @param storyId - The story's ID
|
|
3035
|
+
* @param name - The character's name
|
|
3036
|
+
* @param description - Brief description of the character's personality and role
|
|
3037
|
+
* @param storyModel - Optional model override from `story_models.json`
|
|
3038
|
+
* @param fromNarratorSuggestion - Set `true` when accepting a narrator `'suggestion'` update. Default `false`.
|
|
3039
|
+
*/
|
|
1538
3040
|
async introduceCharacterToStory(storyId, name, description, storyModel, fromNarratorSuggestion) {
|
|
1539
3041
|
await this.storyService.introduceCharacter(storyId, name, description, storyModel, fromNarratorSuggestion);
|
|
1540
3042
|
}
|
|
3043
|
+
/**
|
|
3044
|
+
* Records that the player declined a narrator-suggested character introduction.
|
|
3045
|
+
*
|
|
3046
|
+
* Prevents the narrator from suggesting the same character again in this story.
|
|
3047
|
+
*
|
|
3048
|
+
* @param storyId - The story's ID
|
|
3049
|
+
* @param characterName - The character name that was declined
|
|
3050
|
+
*/
|
|
1541
3051
|
async declineCharacter(storyId, characterName) {
|
|
1542
3052
|
await this.storyService.declineCharacter(storyId, characterName);
|
|
1543
3053
|
}
|
|
3054
|
+
/**
|
|
3055
|
+
* Removes a character's agent from the story while preserving their profile file.
|
|
3056
|
+
*
|
|
3057
|
+
* The character can be reintroduced later via {@link introduceCharacterToStory}
|
|
3058
|
+
* and their profile will be available.
|
|
3059
|
+
*
|
|
3060
|
+
* @param storyId - The story's ID
|
|
3061
|
+
* @param characterName - The character's name
|
|
3062
|
+
*/
|
|
1544
3063
|
async deleteCharacterFromStory(storyId, characterName) {
|
|
1545
3064
|
await this.storyService.deleteCharacter(storyId, characterName);
|
|
1546
3065
|
}
|
|
3066
|
+
/**
|
|
3067
|
+
* Returns all chapter checkpoints for a story.
|
|
3068
|
+
*
|
|
3069
|
+
* Chapters are created by {@link progressStory} and can be read with {@link getChapter}.
|
|
3070
|
+
*
|
|
3071
|
+
* @param storyId - The story's ID
|
|
3072
|
+
* @returns Object with a `chapters` array of chapter info objects
|
|
3073
|
+
*/
|
|
1547
3074
|
listChapters(storyId) {
|
|
1548
3075
|
const chapters = this.storyStore.listChapters(storyId);
|
|
1549
3076
|
return { chapters };
|
|
1550
3077
|
}
|
|
3078
|
+
/**
|
|
3079
|
+
* Returns the messages from a specific chapter checkpoint.
|
|
3080
|
+
*
|
|
3081
|
+
* @param storyId - The story's ID
|
|
3082
|
+
* @param chapterIndex - The chapter number (1-based, as returned by {@link listChapters})
|
|
3083
|
+
* @returns Array of room messages from that chapter
|
|
3084
|
+
*/
|
|
1551
3085
|
async getChapter(storyId, chapterIndex) {
|
|
1552
3086
|
return await this.storyStore.getChapterContent(storyId, chapterIndex);
|
|
1553
3087
|
}
|
|
3088
|
+
/**
|
|
3089
|
+
* Overwrites the content of a chapter checkpoint.
|
|
3090
|
+
*
|
|
3091
|
+
* @param storyId - The story's ID
|
|
3092
|
+
* @param chapterIndex - The chapter number to overwrite
|
|
3093
|
+
* @param content - The new chapter content
|
|
3094
|
+
* @throws {OperationFailedError} If the chapter cannot be saved
|
|
3095
|
+
*/
|
|
1554
3096
|
saveChapter(storyId, chapterIndex, content) {
|
|
1555
3097
|
const saved = this.storyStore.saveChapterContent(storyId, chapterIndex, content);
|
|
1556
3098
|
if (!saved) {
|
|
1557
3099
|
throw new errors_1.OperationFailedError('Failed to save chapter');
|
|
1558
3100
|
}
|
|
1559
3101
|
}
|
|
3102
|
+
/**
|
|
3103
|
+
* Deletes a chapter checkpoint from a story.
|
|
3104
|
+
*
|
|
3105
|
+
* @param storyId - The story's ID
|
|
3106
|
+
* @param chapterIndex - The chapter number to delete
|
|
3107
|
+
* @throws {NotFoundError} If the chapter does not exist
|
|
3108
|
+
*/
|
|
1560
3109
|
deleteChapter(storyId, chapterIndex) {
|
|
1561
3110
|
const deleted = this.storyStore.deleteChapter(storyId, chapterIndex);
|
|
1562
3111
|
if (!deleted) {
|
|
1563
3112
|
throw new errors_1.NotFoundError('Chapter not found');
|
|
1564
3113
|
}
|
|
1565
3114
|
}
|
|
3115
|
+
/**
|
|
3116
|
+
* Returns all current characters in a story.
|
|
3117
|
+
*
|
|
3118
|
+
* @param storyId - The story's ID
|
|
3119
|
+
* @returns Array of character objects (derived from the story's room agents)
|
|
3120
|
+
*/
|
|
1566
3121
|
async listCharacters(storyId) {
|
|
1567
3122
|
return await this.storyService.listCharacters(storyId);
|
|
1568
3123
|
}
|
|
3124
|
+
/**
|
|
3125
|
+
* Returns the profile for a specific character.
|
|
3126
|
+
*
|
|
3127
|
+
* @param storyId - The story's ID
|
|
3128
|
+
* @param characterName - The character's name
|
|
3129
|
+
* @returns Object with `content` containing the character profile markdown
|
|
3130
|
+
*/
|
|
1569
3131
|
async getCharacter(storyId, characterName) {
|
|
1570
3132
|
const content = await this.storyService.getCharacter(storyId, characterName);
|
|
1571
3133
|
return { content: content || '' };
|
|
1572
3134
|
}
|
|
3135
|
+
/**
|
|
3136
|
+
* Saves a character's profile markdown.
|
|
3137
|
+
*
|
|
3138
|
+
* @param storyId - The story's ID
|
|
3139
|
+
* @param characterName - The character's name
|
|
3140
|
+
* @param content - Markdown content for the character profile
|
|
3141
|
+
*/
|
|
1573
3142
|
saveCharacter(storyId, characterName, content) {
|
|
1574
3143
|
this.storyService.saveCharacter(storyId, characterName, content);
|
|
1575
3144
|
}
|
|
3145
|
+
/**
|
|
3146
|
+
* Returns the inventory for a specific character.
|
|
3147
|
+
*
|
|
3148
|
+
* @param storyId - The story's ID
|
|
3149
|
+
* @param characterName - The character's name
|
|
3150
|
+
* @returns Object with `content` containing the inventory markdown
|
|
3151
|
+
*/
|
|
1576
3152
|
async getCharacterInventory(storyId, characterName) {
|
|
1577
3153
|
const content = await this.storyService.getCharacterInventory(storyId, characterName);
|
|
1578
3154
|
return { content: content || '' };
|
|
1579
3155
|
}
|
|
3156
|
+
/**
|
|
3157
|
+
* Saves a character's inventory markdown.
|
|
3158
|
+
*
|
|
3159
|
+
* @param storyId - The story's ID
|
|
3160
|
+
* @param characterName - The character's name
|
|
3161
|
+
* @param content - Markdown content for the character inventory
|
|
3162
|
+
*/
|
|
1580
3163
|
async saveCharacterInventory(storyId, characterName, content) {
|
|
1581
3164
|
await this.storyService.saveCharacterInventory(storyId, characterName, content);
|
|
1582
3165
|
}
|
|
3166
|
+
/**
|
|
3167
|
+
* Returns the story's plot plan.
|
|
3168
|
+
*
|
|
3169
|
+
* The plot plan is a room artifact generated by the narrator at story creation
|
|
3170
|
+
* and updated as the story progresses.
|
|
3171
|
+
*
|
|
3172
|
+
* @param storyId - The story's ID
|
|
3173
|
+
* @returns Object with `content` containing the plot plan markdown
|
|
3174
|
+
*/
|
|
1583
3175
|
async getPlotPlan(storyId) {
|
|
1584
3176
|
const content = await this.storyService.getPlotPlan(storyId);
|
|
1585
3177
|
return { content: content || '' };
|
|
1586
3178
|
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Generates the full story as a single markdown document.
|
|
3181
|
+
*
|
|
3182
|
+
* Combines all chapters and room messages in narrative order.
|
|
3183
|
+
*
|
|
3184
|
+
* @param storyId - The story's ID
|
|
3185
|
+
* @returns The complete story formatted as markdown text
|
|
3186
|
+
*/
|
|
1587
3187
|
async downloadStoryMarkdown(storyId) {
|
|
1588
3188
|
return await this.storyService.generateStoryMarkdown(storyId);
|
|
1589
3189
|
}
|
|
3190
|
+
/**
|
|
3191
|
+
* Exports the complete story data as a downloadable zip archive.
|
|
3192
|
+
*
|
|
3193
|
+
* The archive can be re-imported via {@link importStoryFromZip}.
|
|
3194
|
+
*
|
|
3195
|
+
* @param storyId - The story's ID
|
|
3196
|
+
* @returns Object with a `stream` (readable zip stream) and `filename` for the download
|
|
3197
|
+
*/
|
|
1590
3198
|
async exportStoryData(storyId) {
|
|
1591
3199
|
return await this.storyService.exportStoryData(storyId);
|
|
1592
3200
|
}
|
|
3201
|
+
/**
|
|
3202
|
+
* Returns the formatted conversation history for a specific character in a story.
|
|
3203
|
+
*
|
|
3204
|
+
* @param storyId - The story's ID
|
|
3205
|
+
* @param agentId - The character agent's ID
|
|
3206
|
+
* @returns Object with `content` containing the formatted history text
|
|
3207
|
+
*/
|
|
1593
3208
|
async getAgentHistory(storyId, agentId) {
|
|
1594
3209
|
const history = await this.storyService.getAgentHistory(storyId, agentId);
|
|
1595
3210
|
return { content: history };
|
|
1596
3211
|
}
|
|
3212
|
+
/**
|
|
3213
|
+
* Saves the story's plot plan.
|
|
3214
|
+
*
|
|
3215
|
+
* Persists the content as a room artifact via the publish mechanism.
|
|
3216
|
+
*
|
|
3217
|
+
* @param storyId - The story's ID
|
|
3218
|
+
* @param content - The plot plan markdown to save
|
|
3219
|
+
*/
|
|
1597
3220
|
async savePlotPlan(storyId, content) {
|
|
1598
3221
|
await this.storyService.savePlotPlan(storyId, content);
|
|
1599
3222
|
}
|
|
3223
|
+
/**
|
|
3224
|
+
* Returns the user's current credit balance in dollars.
|
|
3225
|
+
*
|
|
3226
|
+
* The balance is decremented automatically after each AI call based on token usage
|
|
3227
|
+
* and any configured markup. Calls that would exceed the balance throw
|
|
3228
|
+
* `InsufficientBalanceError` before the request is sent.
|
|
3229
|
+
*
|
|
3230
|
+
* @returns Current balance in dollars
|
|
3231
|
+
*/
|
|
1600
3232
|
getBalance() {
|
|
1601
3233
|
return this.balanceService.getBalance();
|
|
1602
3234
|
}
|
|
3235
|
+
/**
|
|
3236
|
+
* Adds funds to the user's balance.
|
|
3237
|
+
*
|
|
3238
|
+
* Use this to credit a user after a payment is processed by your application.
|
|
3239
|
+
*
|
|
3240
|
+
* @param amount - Dollar amount to add (must be positive)
|
|
3241
|
+
*/
|
|
1603
3242
|
addBalance(amount) {
|
|
1604
3243
|
return this.balanceService.addBalance(amount);
|
|
1605
3244
|
}
|
|
3245
|
+
/**
|
|
3246
|
+
* Records a new payment transaction.
|
|
3247
|
+
*
|
|
3248
|
+
* Call this when your payment provider confirms a payment has been initiated.
|
|
3249
|
+
* The `paymentId` should be the unique identifier issued by your payment provider
|
|
3250
|
+
* (e.g. a Stripe Payment Intent ID). Use {@link updateTransactionStatus} to update
|
|
3251
|
+
* the status once the provider confirms success or failure.
|
|
3252
|
+
*
|
|
3253
|
+
* @param amount - Dollar amount of the transaction
|
|
3254
|
+
* @param paymentId - Unique payment identifier from your payment provider
|
|
3255
|
+
* @param status - Initial status; defaults to `'pending'`
|
|
3256
|
+
* @returns The created `Transaction` record
|
|
3257
|
+
*/
|
|
1606
3258
|
async recordTransaction(amount, paymentId, status = 'pending') {
|
|
1607
3259
|
return this.transactionService.recordTransaction(amount, paymentId, status);
|
|
1608
3260
|
}
|
|
3261
|
+
/**
|
|
3262
|
+
* Updates the status of an existing transaction.
|
|
3263
|
+
*
|
|
3264
|
+
* Call this when your payment provider webhook confirms the final outcome of a payment.
|
|
3265
|
+
*
|
|
3266
|
+
* @param paymentId - The payment provider ID used when the transaction was recorded
|
|
3267
|
+
* @param status - New status (`'succeeded'`, `'failed'`, or `'cancelled'`)
|
|
3268
|
+
*/
|
|
1609
3269
|
async updateTransactionStatus(paymentId, status) {
|
|
1610
3270
|
return this.transactionService.updateTransactionStatus(paymentId, status);
|
|
1611
3271
|
}
|
|
3272
|
+
/**
|
|
3273
|
+
* Retrieves a single transaction by its payment provider ID.
|
|
3274
|
+
*
|
|
3275
|
+
* @param paymentId - The payment provider ID used when the transaction was recorded
|
|
3276
|
+
* @returns The matching `Transaction`, or `null` if not found
|
|
3277
|
+
*/
|
|
1612
3278
|
async getTransactionByPaymentId(paymentId) {
|
|
1613
3279
|
return this.transactionService.getTransactionByPaymentId(paymentId);
|
|
1614
3280
|
}
|
|
3281
|
+
/**
|
|
3282
|
+
* Returns paginated transaction history for this user, sorted newest-first.
|
|
3283
|
+
*
|
|
3284
|
+
* @param limit - Maximum number of records to return (default: 50)
|
|
3285
|
+
* @param offset - Number of records to skip for pagination (default: 0)
|
|
3286
|
+
* @returns Object with a `transactions` array and a `total` count
|
|
3287
|
+
*/
|
|
1615
3288
|
async getTransactions(limit = 50, offset = 0) {
|
|
1616
3289
|
return this.transactionService.getTransactions(limit, offset);
|
|
1617
3290
|
}
|
|
3291
|
+
// ==================== Artifact Management ====================
|
|
3292
|
+
/**
|
|
3293
|
+
* Returns metadata for all artifacts owned by this user.
|
|
3294
|
+
*
|
|
3295
|
+
* Artifacts are persistent named documents that can be attached to agents
|
|
3296
|
+
* (see {@link attachArtifactToAgent}) or shared with rooms via the `'publish'` action.
|
|
3297
|
+
* Use {@link getUserArtifact} to retrieve the actual content.
|
|
3298
|
+
*
|
|
3299
|
+
* @returns Array of artifact metadata objects (ID, name, creation date, etc.)
|
|
3300
|
+
*/
|
|
1618
3301
|
listUserArtifacts() {
|
|
1619
3302
|
return this.artifactService.listArtifacts();
|
|
1620
3303
|
}
|
|
3304
|
+
/**
|
|
3305
|
+
* Returns the content of a user artifact.
|
|
3306
|
+
*
|
|
3307
|
+
* Text artifacts are returned as `string`; binary artifacts (e.g. converted PDFs
|
|
3308
|
+
* in intermediate state) may be returned as `Buffer`.
|
|
3309
|
+
*
|
|
3310
|
+
* @param artifactId - The artifact's ID (from {@link listUserArtifacts})
|
|
3311
|
+
* @returns The artifact content, or `null` if no artifact with that ID exists
|
|
3312
|
+
*/
|
|
1621
3313
|
getUserArtifact(artifactId) {
|
|
1622
3314
|
return this.artifactService.getArtifact(artifactId);
|
|
1623
3315
|
}
|
|
3316
|
+
/**
|
|
3317
|
+
* Creates a new named artifact and returns its ID.
|
|
3318
|
+
*
|
|
3319
|
+
* The artifact is persisted immediately. Use the returned ID to attach it to
|
|
3320
|
+
* agents ({@link attachArtifactToAgent}) or reference it in room messages.
|
|
3321
|
+
*
|
|
3322
|
+
* @param name - Human-readable display name for the artifact
|
|
3323
|
+
* @param content - Initial text content (typically Markdown)
|
|
3324
|
+
* @returns The new artifact's ID
|
|
3325
|
+
*/
|
|
1624
3326
|
createUserArtifact(name, content) {
|
|
1625
3327
|
return this.artifactService.storeArtifact(name, content);
|
|
1626
3328
|
}
|
|
3329
|
+
/**
|
|
3330
|
+
* Replaces the content of an existing artifact.
|
|
3331
|
+
*
|
|
3332
|
+
* @param artifactId - The artifact's ID (from {@link listUserArtifacts})
|
|
3333
|
+
* @param content - New content to write
|
|
3334
|
+
* @returns `true` on success, `false` if no artifact with that ID exists
|
|
3335
|
+
*/
|
|
1627
3336
|
updateUserArtifact(artifactId, content) {
|
|
1628
3337
|
return this.artifactService.updateArtifact(artifactId, content);
|
|
1629
3338
|
}
|
|
3339
|
+
/**
|
|
3340
|
+
* Creates an artifact from a PDF by converting it to Markdown, running the
|
|
3341
|
+
* conversion in the background.
|
|
3342
|
+
*
|
|
3343
|
+
* Returns the artifact ID immediately with placeholder content. The artifact
|
|
3344
|
+
* content is replaced with the converted Markdown when the background job
|
|
3345
|
+
* finishes. If conversion fails, the artifact content is replaced with an
|
|
3346
|
+
* error message.
|
|
3347
|
+
*
|
|
3348
|
+
* Requires the `DOC_CONVERSION_AI_SERVICE` and `DOC_CONVERSION_AI_MODEL`
|
|
3349
|
+
* environment variables to be set to an AI service that supports PDF documents.
|
|
3350
|
+
*
|
|
3351
|
+
* A PDF over ten pages is converted page by page, at most
|
|
3352
|
+
* `PDF_CONVERT_CONCURRENCY` at a time, with each page retried before it is
|
|
3353
|
+
* given up on. A page that is given up on does not fail the document: the
|
|
3354
|
+
* artifact still lands, naming the pages that are missing from it so they can
|
|
3355
|
+
* be re-run. Only a conversion that produces nothing at all replaces the
|
|
3356
|
+
* artifact with an error.
|
|
3357
|
+
*
|
|
3358
|
+
* @param name - Display name for the artifact
|
|
3359
|
+
* @param pdfBuffer - Buffer containing the raw PDF data
|
|
3360
|
+
* @returns The new artifact's ID (content is a placeholder until conversion completes)
|
|
3361
|
+
*/
|
|
1630
3362
|
convertUserArtifact(name, pdfBuffer) {
|
|
3363
|
+
// 1. Create placeholder artifact immediately
|
|
1631
3364
|
const placeholderContent = 'Converting PDF. This text will be replaced when the conversion is finished.';
|
|
1632
3365
|
const artifactId = this.artifactService.storeArtifact(name, placeholderContent);
|
|
3366
|
+
// 2. Start async conversion (don't await)
|
|
1633
3367
|
this.convertPdfInBackground(artifactId, name, pdfBuffer).catch((error) => {
|
|
1634
3368
|
logger_1.logger.error(`Background PDF conversion failed for ${artifactId}:`, error);
|
|
3369
|
+
// Update artifact with error message
|
|
1635
3370
|
const errorContent = `# Conversion Failed\n\nThe PDF conversion failed with the following error:\n\n${error.message}\n\nPlease try uploading the file again.`;
|
|
1636
3371
|
this.artifactService.updateArtifact(artifactId, errorContent);
|
|
1637
3372
|
});
|
|
3373
|
+
// 3. Return immediately
|
|
1638
3374
|
return artifactId;
|
|
1639
3375
|
}
|
|
3376
|
+
/**
|
|
3377
|
+
* Converts a PDF to Markdown a page at a time and returns the pages.
|
|
3378
|
+
*
|
|
3379
|
+
* The building block under {@link convertUserArtifact}, public because a host
|
|
3380
|
+
* embedding Briyah usually wants the pages and the cost rather than an
|
|
3381
|
+
* artifact — to extract records from each page, to cache the result under its
|
|
3382
|
+
* own key, or to show progress. Every page is converted by its own throwaway
|
|
3383
|
+
* agent, so nothing accumulates history and pages stay independent.
|
|
3384
|
+
*
|
|
3385
|
+
* Bounded, retried and non-fatal: at most {@link PdfMarkdownOptions.concurrency}
|
|
3386
|
+
* pages are in flight, each page is retried on an empty response, a thrown
|
|
3387
|
+
* error or a timeout, and a page that exhausts its attempts is reported in
|
|
3388
|
+
* `failedPages` rather than failing the document.
|
|
3389
|
+
*
|
|
3390
|
+
* @param pdfBuffer - The raw PDF
|
|
3391
|
+
* @param options - Models, prompt, hints and limits; every field has a default
|
|
3392
|
+
* @returns The pages, the assembled Markdown, what failed, and the cost
|
|
3393
|
+
* @throws {ValidationError} If no conversion service or model is configured
|
|
3394
|
+
*
|
|
3395
|
+
* @example
|
|
3396
|
+
* ```typescript
|
|
3397
|
+
* const result = await appService.convertPdfToMarkdownPages(buffer, {
|
|
3398
|
+
* concurrency: 8,
|
|
3399
|
+
* fidelityHints: 'chapter and verse numbers',
|
|
3400
|
+
* onProgress: (message) => console.log(message),
|
|
3401
|
+
* });
|
|
3402
|
+
* if (result.failedPages.length) console.warn('Re-run pages', result.failedPages);
|
|
3403
|
+
* ```
|
|
3404
|
+
*/
|
|
1640
3405
|
async convertPdfToMarkdownPages(pdfBuffer, options = {}) {
|
|
1641
3406
|
const aiServiceName = options.aiServiceName || process.env.DOC_CONVERSION_AI_SERVICE;
|
|
1642
3407
|
const aiModel = options.aiModel || process.env.DOC_CONVERSION_AI_MODEL;
|
|
@@ -1650,6 +3415,9 @@ class AppService {
|
|
|
1650
3415
|
const promptFile = options.promptFile || 'convert_pdf_page';
|
|
1651
3416
|
const finishAgents = options.finishAgents !== false;
|
|
1652
3417
|
const renderPage = async (pageBuffer, pageNum, pageCount) => {
|
|
3418
|
+
// A fresh agent per attempt, not per page: a retry after an empty
|
|
3419
|
+
// response must not carry that empty response in its history, which is
|
|
3420
|
+
// exactly what makes the second ask worth making.
|
|
1653
3421
|
const agent = this.agentFactory.createAgent(aiServiceName, options.agentName || 'PDF Converter', '', `Converts page ${pageNum} of ${pageCount} to Markdown`, promptFolder, aiModel);
|
|
1654
3422
|
if (options.reasoningEffort !== undefined) {
|
|
1655
3423
|
agent.reasoningEffort = options.reasoningEffort;
|
|
@@ -1659,6 +3427,8 @@ class AppService {
|
|
|
1659
3427
|
await agent.attachDocument(fileName, pageBuffer);
|
|
1660
3428
|
const response = await agent.preparedPrompt(promptFile, {
|
|
1661
3429
|
fileName,
|
|
3430
|
+
// Both spellings, so a caller pointing at its own prompt
|
|
3431
|
+
// folder does not have to match Briyah's variable names.
|
|
1662
3432
|
pageNum,
|
|
1663
3433
|
pageNumber: pageNum,
|
|
1664
3434
|
pageCount,
|
|
@@ -1682,6 +3452,13 @@ class AppService {
|
|
|
1682
3452
|
const result = await (0, pdf_conversion_1.convertPdfToMarkdown)(pdfBuffer, renderPage, options);
|
|
1683
3453
|
return result;
|
|
1684
3454
|
}
|
|
3455
|
+
/**
|
|
3456
|
+
* Converts a whole PDF in one request, for a document short enough that page
|
|
3457
|
+
* continuity is worth more than page-level recovery.
|
|
3458
|
+
*
|
|
3459
|
+
* Retried on the same policy as a page, since an empty response here loses the
|
|
3460
|
+
* entire document rather than one page of it.
|
|
3461
|
+
*/
|
|
1685
3462
|
async convertWholePdf(name, pdfBuffer) {
|
|
1686
3463
|
const limits = (0, pdf_conversion_1.conversionLimits)();
|
|
1687
3464
|
let lastError = 'the conversion returned nothing';
|
|
@@ -1708,6 +3485,17 @@ class AppService {
|
|
|
1708
3485
|
}
|
|
1709
3486
|
throw new Error(`The PDF conversion produced no content after ${limits.attempts} attempts: ${lastError}`);
|
|
1710
3487
|
}
|
|
3488
|
+
/**
|
|
3489
|
+
* Background conversion process - updates the artifact when complete.
|
|
3490
|
+
*
|
|
3491
|
+
* A document of more than ten pages is converted page-by-page, which is what
|
|
3492
|
+
* makes a partial failure survivable: the artifact still lands, carrying the
|
|
3493
|
+
* pages that converted and naming the ones that did not.
|
|
3494
|
+
*
|
|
3495
|
+
* @param artifactId The artifact ID to update
|
|
3496
|
+
* @param name The artifact name
|
|
3497
|
+
* @param pdfBuffer Buffer containing PDF data
|
|
3498
|
+
*/
|
|
1711
3499
|
async convertPdfInBackground(artifactId, name, pdfBuffer) {
|
|
1712
3500
|
logger_1.logger.log(`Starting background PDF conversion for artifact ${artifactId}`);
|
|
1713
3501
|
if (!process.env.DOC_CONVERSION_AI_SERVICE)
|
|
@@ -1733,23 +3521,70 @@ class AppService {
|
|
|
1733
3521
|
`${result.failedPages.length} failed${result.failedPages.length ? `: ${result.failedPages.join(', ')}` : ''}), ` +
|
|
1734
3522
|
`Output: ${result.markdown.length} chars (total cost: $${result.totalCost.toFixed(4)})`);
|
|
1735
3523
|
}
|
|
3524
|
+
/**
|
|
3525
|
+
* Changes the display name of an artifact.
|
|
3526
|
+
*
|
|
3527
|
+
* @param artifactId - The artifact's ID (from {@link listUserArtifacts})
|
|
3528
|
+
* @param newName - New display name for the artifact
|
|
3529
|
+
* @returns `true` on success, `false` if no artifact with that ID exists
|
|
3530
|
+
*/
|
|
1736
3531
|
renameUserArtifact(artifactId, newName) {
|
|
1737
3532
|
return this.artifactService.renameArtifact(artifactId, newName);
|
|
1738
3533
|
}
|
|
3534
|
+
/**
|
|
3535
|
+
* Permanently deletes a user artifact.
|
|
3536
|
+
*
|
|
3537
|
+
* Any agents that have the artifact attached will lose access to it after deletion.
|
|
3538
|
+
*
|
|
3539
|
+
* @param artifactId - The artifact's ID (from {@link listUserArtifacts})
|
|
3540
|
+
* @returns `true` on success, `false` if no artifact with that ID exists
|
|
3541
|
+
*/
|
|
1739
3542
|
deleteUserArtifact(artifactId) {
|
|
1740
3543
|
return this.artifactService.deleteArtifact(artifactId);
|
|
1741
3544
|
}
|
|
3545
|
+
/**
|
|
3546
|
+
* Gets the artifact service for a story
|
|
3547
|
+
* @param storyId The story ID
|
|
3548
|
+
* @returns The story-specific artifact service
|
|
3549
|
+
*/
|
|
1742
3550
|
getStoryArtifactService(storyId) {
|
|
1743
3551
|
return this.storyService.getStoryArtifactService(storyId);
|
|
1744
3552
|
}
|
|
3553
|
+
/**
|
|
3554
|
+
* Returns all artifacts associated with a story.
|
|
3555
|
+
*
|
|
3556
|
+
* Story artifacts include the plot plan and any documents published by agents
|
|
3557
|
+
* during the narrative.
|
|
3558
|
+
*
|
|
3559
|
+
* @param storyId - The story's ID
|
|
3560
|
+
* @returns Array of artifact metadata objects
|
|
3561
|
+
*/
|
|
1745
3562
|
listStoryArtifacts(storyId) {
|
|
1746
3563
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1747
3564
|
return storyArtifactService.listArtifacts();
|
|
1748
3565
|
}
|
|
3566
|
+
/**
|
|
3567
|
+
* Returns the content of a specific story artifact.
|
|
3568
|
+
*
|
|
3569
|
+
* @param storyId - The story's ID
|
|
3570
|
+
* @param artifactId - The artifact's ID (from {@link listStoryArtifacts})
|
|
3571
|
+
* @returns The artifact content as a string or Buffer, or `null` if not found
|
|
3572
|
+
*/
|
|
1749
3573
|
getStoryArtifact(storyId, artifactId) {
|
|
1750
3574
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1751
3575
|
return storyArtifactService.getArtifact(artifactId);
|
|
1752
3576
|
}
|
|
3577
|
+
/**
|
|
3578
|
+
* Returns metadata for all artifacts currently attached to an agent.
|
|
3579
|
+
*
|
|
3580
|
+
* Attached artifacts are included in the agent's context on every prompt, allowing
|
|
3581
|
+
* the agent to reference their content. Use {@link attachArtifactToAgent} and
|
|
3582
|
+
* {@link detachArtifactFromAgent} to manage attachments.
|
|
3583
|
+
*
|
|
3584
|
+
* @param agentId - The agent's ID
|
|
3585
|
+
* @returns Array of artifact metadata objects for the agent's attached artifacts
|
|
3586
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
3587
|
+
*/
|
|
1753
3588
|
async listAgentArtifacts(agentId) {
|
|
1754
3589
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1755
3590
|
if (!agent) {
|
|
@@ -1759,11 +3594,22 @@ class AppService {
|
|
|
1759
3594
|
const allArtifacts = this.artifactService.listArtifacts();
|
|
1760
3595
|
return allArtifacts.filter((a) => artifactIds.includes(a.artifactId));
|
|
1761
3596
|
}
|
|
3597
|
+
/**
|
|
3598
|
+
* Attaches a user artifact to an agent so the agent can read its content in prompts.
|
|
3599
|
+
*
|
|
3600
|
+
* The attachment is persisted immediately via `agent.save()`. The artifact content
|
|
3601
|
+
* is injected into the agent's context on each subsequent call.
|
|
3602
|
+
*
|
|
3603
|
+
* @param agentId - The agent's ID
|
|
3604
|
+
* @param artifactId - The artifact's ID (from {@link listUserArtifacts})
|
|
3605
|
+
* @throws {NotFoundError} If the agent or artifact does not exist
|
|
3606
|
+
*/
|
|
1762
3607
|
async attachArtifactToAgent(agentId, artifactId) {
|
|
1763
3608
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1764
3609
|
if (!agent) {
|
|
1765
3610
|
throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
|
|
1766
3611
|
}
|
|
3612
|
+
// Verify artifact exists
|
|
1767
3613
|
const artifact = this.artifactService.getArtifactMetadata(artifactId);
|
|
1768
3614
|
if (!artifact) {
|
|
1769
3615
|
throw new errors_1.NotFoundError(`Artifact ${artifactId} not found`);
|
|
@@ -1771,6 +3617,16 @@ class AppService {
|
|
|
1771
3617
|
agent.attachArtifact(artifactId);
|
|
1772
3618
|
agent.save();
|
|
1773
3619
|
}
|
|
3620
|
+
/**
|
|
3621
|
+
* Removes an artifact attachment from an agent.
|
|
3622
|
+
*
|
|
3623
|
+
* The artifact itself is not deleted - only the link between the agent and the artifact
|
|
3624
|
+
* is removed. Changes are persisted immediately via `agent.save()`.
|
|
3625
|
+
*
|
|
3626
|
+
* @param agentId - The agent's ID
|
|
3627
|
+
* @param artifactId - The artifact's ID to detach
|
|
3628
|
+
* @throws {NotFoundError} If no agent with the given ID exists
|
|
3629
|
+
*/
|
|
1774
3630
|
async detachArtifactFromAgent(agentId, artifactId) {
|
|
1775
3631
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1776
3632
|
if (!agent) {
|