briyah 2.0.3 → 2.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -7
- package/data/common/config/LICENSE-model-prices.md +65 -0
- package/data/common/config/model_prices.json +47443 -46295
- package/data/common/prompts/narrator/create_story.prompt +2 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +103 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +173 -2
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +172 -3
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +241 -5
- package/dist-sdk/server/src/ai/LLM/comfyui-client.d.ts +26 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-client.js +25 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.d.ts +54 -0
- package/dist-sdk/server/src/ai/LLM/comfyui-workflow.js +59 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.d.ts +21 -1
- package/dist-sdk/server/src/ai/LLM/comfyui.service.js +25 -1
- package/dist-sdk/server/src/ai/LLM/deepseek.service.d.ts +52 -0
- package/dist-sdk/server/src/ai/LLM/deepseek.service.js +102 -3
- package/dist-sdk/server/src/ai/LLM/fal.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/LLM/fal.service.js +55 -1
- package/dist-sdk/server/src/ai/LLM/googleai.service.d.ts +19 -0
- package/dist-sdk/server/src/ai/LLM/googleai.service.js +42 -1
- package/dist-sdk/server/src/ai/LLM/grok.service.d.ts +22 -0
- package/dist-sdk/server/src/ai/LLM/grok.service.js +54 -2
- package/dist-sdk/server/src/ai/LLM/mock.service.js +31 -4
- package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/openai.service.js +80 -2
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.d.ts +21 -0
- package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +44 -2
- package/dist-sdk/server/src/ai/LLM/together.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/LLM/together.service.js +60 -2
- package/dist-sdk/server/src/ai/agent-config.d.ts +15 -0
- package/dist-sdk/server/src/ai/agent-factory.d.ts +16 -0
- package/dist-sdk/server/src/ai/agent-factory.js +20 -0
- package/dist-sdk/server/src/ai/agent-message.service.d.ts +30 -0
- package/dist-sdk/server/src/ai/agent-message.service.js +30 -0
- package/dist-sdk/server/src/ai/agent-store.service.d.ts +80 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +166 -5
- package/dist-sdk/server/src/ai/agent.d.ts +196 -0
- package/dist-sdk/server/src/ai/agent.js +224 -11
- package/dist-sdk/server/src/ai/ai-debug-logger.d.ts +18 -0
- package/dist-sdk/server/src/ai/ai-debug-logger.js +19 -0
- package/dist-sdk/server/src/ai/ai-factory.service.d.ts +9 -0
- package/dist-sdk/server/src/ai/ai-factory.service.js +9 -0
- package/dist-sdk/server/src/ai/artifact.service.d.ts +131 -0
- package/dist-sdk/server/src/ai/artifact.service.js +148 -3
- package/dist-sdk/server/src/ai/attached-file.service.d.ts +87 -0
- package/dist-sdk/server/src/ai/attached-file.service.js +105 -0
- package/dist-sdk/server/src/ai/model_prices.d.ts +30 -0
- package/dist-sdk/server/src/ai/model_prices.js +91 -5
- package/dist-sdk/server/src/ai/pack-artifacts.d.ts +84 -0
- package/dist-sdk/server/src/ai/pack-artifacts.js +168 -0
- package/dist-sdk/server/src/ai/published-agents.service.d.ts +25 -0
- package/dist-sdk/server/src/ai/published-agents.service.js +30 -3
- package/dist-sdk/server/src/app/balance-message.service.d.ts +24 -0
- package/dist-sdk/server/src/app/balance-message.service.js +24 -0
- package/dist-sdk/server/src/app/balance.module.d.ts +4 -0
- package/dist-sdk/server/src/app/balance.module.js +4 -0
- package/dist-sdk/server/src/app/balance.service.d.ts +37 -0
- package/dist-sdk/server/src/app/balance.service.js +54 -0
- package/dist-sdk/server/src/app/stripe.controller.d.ts +21 -0
- package/dist-sdk/server/src/app/stripe.controller.js +35 -0
- package/dist-sdk/server/src/app/stripe.service.d.ts +43 -0
- package/dist-sdk/server/src/app/stripe.service.js +62 -0
- package/dist-sdk/server/src/app/transaction.service.d.ts +27 -0
- package/dist-sdk/server/src/app/transaction.service.js +36 -0
- package/dist-sdk/server/src/app/user-service-factory.d.ts +8 -0
- package/dist-sdk/server/src/app/user-service-factory.js +38 -1
- package/dist-sdk/server/src/app/user-service-manager.d.ts +27 -0
- package/dist-sdk/server/src/app/user-service-manager.js +43 -0
- package/dist-sdk/server/src/app.controller.d.ts +87 -0
- package/dist-sdk/server/src/app.controller.js +272 -12
- package/dist-sdk/server/src/app.module.js +28 -6
- package/dist-sdk/server/src/app.service.d.ts +1661 -0
- package/dist-sdk/server/src/app.service.js +1837 -4
- package/dist-sdk/server/src/auth/agent-access.decorator.d.ts +17 -0
- package/dist-sdk/server/src/auth/agent-access.decorator.js +17 -0
- package/dist-sdk/server/src/auth/auth.controller.js +46 -0
- package/dist-sdk/server/src/auth/auth.module.js +3 -2
- package/dist-sdk/server/src/auth/auth.service.d.ts +33 -0
- package/dist-sdk/server/src/auth/auth.service.js +39 -3
- package/dist-sdk/server/src/auth/jwt-auth.guard.js +18 -0
- package/dist-sdk/server/src/auth/jwt.strategy.js +2 -2
- package/dist-sdk/server/src/auth/owner-only.decorator.d.ts +9 -0
- package/dist-sdk/server/src/auth/owner-only.decorator.js +9 -0
- package/dist-sdk/server/src/auth/phone-validation.service.d.ts +25 -0
- package/dist-sdk/server/src/auth/phone-validation.service.js +30 -0
- package/dist-sdk/server/src/auth/rate-limit.service.d.ts +19 -0
- package/dist-sdk/server/src/auth/rate-limit.service.js +24 -0
- package/dist-sdk/server/src/auth/room-access.decorator.d.ts +8 -0
- package/dist-sdk/server/src/auth/room-access.decorator.js +8 -0
- package/dist-sdk/server/src/auth/scopes.decorator.d.ts +7 -0
- package/dist-sdk/server/src/auth/scopes.decorator.js +7 -0
- package/dist-sdk/server/src/auth/scopes.guard.d.ts +16 -0
- package/dist-sdk/server/src/auth/scopes.guard.js +30 -0
- package/dist-sdk/server/src/auth/session.guard.d.ts +4 -0
- package/dist-sdk/server/src/auth/session.guard.js +8 -0
- package/dist-sdk/server/src/auth/twilio.service.d.ts +27 -0
- package/dist-sdk/server/src/auth/twilio.service.js +30 -4
- package/dist-sdk/server/src/auth/users.service.d.ts +30 -0
- package/dist-sdk/server/src/auth/users.service.js +42 -0
- package/dist-sdk/server/src/common/errors.d.ts +20 -0
- package/dist-sdk/server/src/common/errors.js +21 -0
- package/dist-sdk/server/src/config/env-config.d.ts +7 -0
- package/dist-sdk/server/src/config/prompt-resolver.d.ts +180 -0
- package/dist-sdk/server/src/config/prompt-resolver.js +182 -0
- package/dist-sdk/server/src/config/user-config.service.d.ts +59 -0
- package/dist-sdk/server/src/config/user-config.service.js +57 -0
- package/dist-sdk/server/src/config/user-paths.service.d.ts +61 -0
- package/dist-sdk/server/src/config/user-paths.service.js +67 -0
- package/dist-sdk/server/src/documents/pdf-conversion.d.ts +121 -1
- package/dist-sdk/server/src/documents/pdf-conversion.js +94 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.d.ts +98 -0
- package/dist-sdk/server/src/packs/pack-instantiation.service.js +99 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +100 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +58 -0
- package/dist-sdk/server/src/packs/pack.service.d.ts +99 -1
- package/dist-sdk/server/src/packs/pack.service.js +98 -1
- package/dist-sdk/server/src/room/artifact-store.service.d.ts +27 -0
- package/dist-sdk/server/src/room/artifact-store.service.js +49 -3
- package/dist-sdk/server/src/room/artifact.d.ts +18 -0
- package/dist-sdk/server/src/room/message.d.ts +64 -0
- package/dist-sdk/server/src/room/message.js +77 -2
- package/dist-sdk/server/src/room/nickname.d.ts +26 -0
- package/dist-sdk/server/src/room/nickname.js +26 -0
- package/dist-sdk/server/src/room/published-rooms.service.js +2 -0
- package/dist-sdk/server/src/room/room-config.d.ts +26 -0
- package/dist-sdk/server/src/room/room-factory.d.ts +12 -0
- package/dist-sdk/server/src/room/room-factory.js +14 -0
- package/dist-sdk/server/src/room/room-message.service.d.ts +28 -0
- package/dist-sdk/server/src/room/room-message.service.js +28 -0
- package/dist-sdk/server/src/room/room-store.service.d.ts +176 -0
- package/dist-sdk/server/src/room/room-store.service.js +238 -5
- package/dist-sdk/server/src/room/room.d.ts +878 -0
- package/dist-sdk/server/src/room/room.js +1291 -23
- package/dist-sdk/server/src/rpg/rpg-models.d.ts +50 -0
- package/dist-sdk/server/src/rpg/rpg-models.js +53 -0
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +37 -0
- package/dist-sdk/server/src/rpg/rpg-roster.js +37 -0
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +87 -0
- package/dist-sdk/server/src/rpg/rpg.service.js +103 -0
- package/dist-sdk/server/src/sdk/briyah-config.d.ts +57 -0
- package/dist-sdk/server/src/sdk/briyah-config.js +17 -0
- package/dist-sdk/server/src/sdk/briyah.d.ts +228 -0
- package/dist-sdk/server/src/sdk/briyah.js +285 -7
- package/dist-sdk/server/src/sdk/index.js +23 -0
- package/dist-sdk/server/src/shared/shared.module.d.ts +8 -0
- package/dist-sdk/server/src/shared/shared.module.js +13 -5
- package/dist-sdk/server/src/story/story-message.service.d.ts +43 -0
- package/dist-sdk/server/src/story/story-message.service.js +43 -0
- package/dist-sdk/server/src/story/story-progress.service.d.ts +23 -0
- package/dist-sdk/server/src/story/story-progress.service.js +23 -0
- package/dist-sdk/server/src/story/story-store.service.d.ts +92 -0
- package/dist-sdk/server/src/story/story-store.service.js +136 -1
- package/dist-sdk/server/src/story/story.service.d.ts +398 -0
- package/dist-sdk/server/src/story/story.service.js +829 -25
- package/dist-sdk/server/src/tools/core/index.d.ts +22 -0
- package/dist-sdk/server/src/tools/core/index.js +22 -0
- package/dist-sdk/server/src/tools/core/rename.tool.d.ts +8 -0
- package/dist-sdk/server/src/tools/core/rename.tool.js +11 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.d.ts +22 -0
- package/dist-sdk/server/src/tools/native-tool-registry.service.js +22 -0
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +176 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/backgrounds.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.d.ts +46 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/cantrips.js +40 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.d.ts +33 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/feats.js +19 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.d.ts +37 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.d.ts +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.generated.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/gear.js +27 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/kits.js +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.d.ts +32 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/magic-items.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/monsters.js +20 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.d.ts +36 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/races.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.d.ts +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.generated.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/spells.js +21 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.d.ts +95 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/srd.js +66 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.d.ts +50 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/data/weapons.js +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.d.ts +92 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/bestiary.js +152 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.d.ts +28 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/campaign-items.js +29 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.d.ts +31 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/cantrips.js +36 -2
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.d.ts +261 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/character.js +401 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.d.ts +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/coerce.js +11 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/dice.js +67 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.d.ts +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encounter.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.d.ts +66 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/encumbrance.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.d.ts +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/feats.js +49 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.d.ts +42 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/foes.js +59 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.d.ts +72 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/guides.js +63 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.d.ts +57 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/items.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.d.ts +81 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/kits.js +85 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.d.ts +60 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/races.js +64 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.d.ts +169 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/rules.js +203 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +192 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +144 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.d.ts +56 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/spells.js +54 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.d.ts +65 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/engine/weapons.js +73 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.d.ts +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/index.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.d.ts +4 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/check.tool.js +116 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.d.ts +14 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/class.tool.js +17 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/dice.tools.js +35 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.d.ts +6 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/encounter.tool.js +25 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.d.ts +7 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/item.tool.js +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.d.ts +8 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/monster.tool.js +55 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +164 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +188 -1
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +116 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.d.ts +13 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/spell.tool.js +18 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/state.tools.js +23 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.d.ts +1 -0
- package/dist-sdk/server/src/tools/packs/dnd5e/tools/world.tools.js +35 -0
- package/dist-sdk/server/src/tools/packs/index.d.ts +49 -0
- package/dist-sdk/server/src/tools/packs/index.js +66 -0
- package/dist-sdk/server/src/tools/shared/coerce.d.ts +95 -0
- package/dist-sdk/server/src/tools/shared/coerce.js +98 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +73 -0
- package/dist-sdk/server/src/tools/tool-execution.service.js +74 -0
- package/dist-sdk/server/src/tools/tool-store.service.d.ts +11 -0
- package/dist-sdk/server/src/tools/tool-store.service.js +13 -1
- package/dist-sdk/shared/types/app.types.d.ts +285 -13
- package/dist-sdk/shared/types/app.types.js +3 -0
- package/package.json +167 -168
- package/data/common/config/random_words.txt +0 -2241
- package/data/common/story_ideas/biblical.json +0 -122
- package/data/common/story_ideas/fantasy.json +0 -82
- package/data/common/story_ideas/historical_fiction.json +0 -82
- package/data/common/story_ideas/science_fiction.json +0 -82
- package/docs/.nojekyll +0 -1
- package/docs/assets/hierarchy.js +0 -1
- package/docs/assets/highlight.css +0 -113
- package/docs/assets/icons.js +0 -18
- package/docs/assets/icons.svg +0 -1
- package/docs/assets/main.js +0 -60
- package/docs/assets/navigation.js +0 -1
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1648
- package/docs/classes/Agent.html +0 -801
- package/docs/classes/Briyah.html +0 -296
- package/docs/classes/BriyahConfigService.html +0 -119
- package/docs/classes/NativeToolRegistry.html +0 -166
- package/docs/classes/PackInstantiationService.html +0 -157
- package/docs/classes/PackService.html +0 -247
- package/docs/classes/Room.html +0 -1434
- package/docs/classes/RoomMessage.html +0 -290
- package/docs/enums/MessageAction.html +0 -136
- package/docs/functions/availableToolPacks.html +0 -41
- package/docs/functions/buildMarkdown.html +0 -54
- package/docs/functions/dnd5eTools.html +0 -44
- package/docs/functions/installToolPacks.html +0 -51
- package/docs/functions/pageMarker.html +0 -45
- package/docs/functions/registerToolPacks.html +0 -54
- package/docs/functions/splitMarkdownIntoPages.html +0 -51
- package/docs/functions/stripWrappingFence.html +0 -52
- package/docs/hierarchy.html +0 -46
- package/docs/index.html +0 -595
- package/docs/interfaces/AgentCreationOptions.html +0 -125
- package/docs/interfaces/AgentInfo.html +0 -218
- package/docs/interfaces/AgentMessagesResponse.html +0 -74
- package/docs/interfaces/AppService.html +0 -3340
- package/docs/interfaces/Artifact.html +0 -95
- package/docs/interfaces/ArtifactMetadata.html +0 -112
- package/docs/interfaces/ArtifactWriteOptions.html +0 -90
- package/docs/interfaces/AttachDocumentResponse.html +0 -62
- package/docs/interfaces/BriyahConfigOptions.html +0 -124
- package/docs/interfaces/ChapterInfo.html +0 -62
- package/docs/interfaces/Character.html +0 -86
- package/docs/interfaces/ConversionAgent.html +0 -78
- package/docs/interfaces/CreateAgentResponse.html +0 -56
- package/docs/interfaces/CreateRoomResponse.html +0 -62
- package/docs/interfaces/CreateStoryResponse.html +0 -56
- package/docs/interfaces/FileList.html +0 -56
- package/docs/interfaces/FileMetadata.html +0 -89
- package/docs/interfaces/IConfigService.html +0 -79
- package/docs/interfaces/InstantiateModels.html +0 -64
- package/docs/interfaces/InstantiateRoomResult.html +0 -70
- package/docs/interfaces/LoadedPack.html +0 -131
- package/docs/interfaces/LoggingOptions.html +0 -92
- package/docs/interfaces/Message.html +0 -84
- package/docs/interfaces/ModelChoice.html +0 -73
- package/docs/interfaces/ModelInfo.html +0 -74
- package/docs/interfaces/NativeToolDefinition.html +0 -107
- package/docs/interfaces/PackAgentTemplate.html +0 -101
- package/docs/interfaces/PackRoomTemplate.html +0 -108
- package/docs/interfaces/PackView.html +0 -172
- package/docs/interfaces/PdfConversionOptions.html +0 -102
- package/docs/interfaces/PdfConversionResult.html +0 -97
- package/docs/interfaces/PdfMarkdownOptions.html +0 -198
- package/docs/interfaces/PdfMarkdownResult.html +0 -106
- package/docs/interfaces/PdfPageMarkdown.html +0 -94
- package/docs/interfaces/PreparedPromptResponse.html +0 -62
- package/docs/interfaces/ProcessTextResponse.html +0 -86
- package/docs/interfaces/PromptFile.html +0 -70
- package/docs/interfaces/PromptFileContent.html +0 -76
- package/docs/interfaces/PromptFilesResponse.html +0 -56
- package/docs/interfaces/PromptFolder.html +0 -80
- package/docs/interfaces/PromptFolderDefaults.html +0 -155
- package/docs/interfaces/PromptFolderDefaultsResponse.html +0 -79
- package/docs/interfaces/PromptFoldersResponse.html +0 -56
- package/docs/interfaces/RoomDetails.html +0 -151
- package/docs/interfaces/RoomErrorUpdate.html +0 -82
- package/docs/interfaces/RoomInfo.html +0 -88
- package/docs/interfaces/RoomMessageUpdate.html +0 -113
- package/docs/interfaces/RoomMessagesResponse.html +0 -62
- package/docs/interfaces/SendMessageResult.html +0 -62
- package/docs/interfaces/StoryErrorEvent.html +0 -84
- package/docs/interfaces/StoryIdea.html +0 -74
- package/docs/interfaces/StoryInfo.html +0 -198
- package/docs/interfaces/StoryIntroduceCharacterEvent.html +0 -79
- package/docs/interfaces/StoryProgressChapterEvent.html +0 -72
- package/docs/interfaces/StoryState.html +0 -108
- package/docs/interfaces/StoryStateEvent.html +0 -76
- package/docs/interfaces/ToolArtifact.html +0 -85
- package/docs/interfaces/ToolCaller.html +0 -77
- package/docs/interfaces/ToolDefinition.html +0 -80
- package/docs/interfaces/ToolHelpers.html +0 -105
- package/docs/interfaces/ToolPackDocuments.html +0 -100
- package/docs/interfaces/ToolParameter.html +0 -74
- package/docs/interfaces/ToolRoomAccess.html +0 -260
- package/docs/interfaces/ToolSummary.html +0 -74
- package/docs/interfaces/ToolsResponse.html +0 -68
- package/docs/interfaces/Transaction.html +0 -104
- package/docs/interfaces/TransactionHistoryResponse.html +0 -62
- package/docs/modules.html +0 -53
- package/docs/types/PackOrigin.html +0 -34
- package/docs/types/PromptScope.html +0 -34
- package/docs/types/RoomTurnMode.html +0 -42
- package/docs/types/RoomUpdate.html +0 -36
- package/docs/types/RosterOverrides.html +0 -42
- package/docs/types/ToolContext.html +0 -40
- package/docs/types/ToolRunResult.html +0 -34
- package/src/tools/packs/dnd5e/README.md +0 -867
|
@@ -45,6 +45,13 @@ const pdf_lib_1 = require("pdf-lib");
|
|
|
45
45
|
const pdf_conversion_1 = require("./documents/pdf-conversion");
|
|
46
46
|
const message_1 = require("./room/message");
|
|
47
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
|
+
*/
|
|
48
55
|
const WHOLE_PDF_PAGE_LIMIT = 10;
|
|
49
56
|
class AppService {
|
|
50
57
|
aiFactoryService;
|
|
@@ -92,13 +99,21 @@ class AppService {
|
|
|
92
99
|
this.packService = packService;
|
|
93
100
|
this.aiServices = this.aiFactoryService.getAllAiServices();
|
|
94
101
|
}
|
|
102
|
+
/** Packs, as this user sees them. */
|
|
95
103
|
get packs() {
|
|
96
104
|
return this.packService;
|
|
97
105
|
}
|
|
98
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
|
+
*/
|
|
99
113
|
setPackInstantiation(service) {
|
|
100
114
|
this.packInstantiationService = service;
|
|
101
115
|
}
|
|
116
|
+
/** Builds agents and rooms from pack templates. */
|
|
102
117
|
get packInstantiation() {
|
|
103
118
|
if (!this.packInstantiationService) {
|
|
104
119
|
throw new Error('Pack instantiation service is not set');
|
|
@@ -106,30 +121,77 @@ class AppService {
|
|
|
106
121
|
return this.packInstantiationService;
|
|
107
122
|
}
|
|
108
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
|
+
*/
|
|
109
130
|
setRpg(service) {
|
|
110
131
|
this.rpgCampaignService = service;
|
|
111
132
|
}
|
|
133
|
+
/** Campaigns: the streamlined D&D surface, built on packs and published rooms. */
|
|
112
134
|
get rpg() {
|
|
113
135
|
if (!this.rpgCampaignService) {
|
|
114
136
|
throw new Error('RPG service is not set');
|
|
115
137
|
}
|
|
116
138
|
return this.rpgCampaignService;
|
|
117
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
|
+
*/
|
|
118
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
|
+
*/
|
|
119
155
|
getAiServiceNames() {
|
|
120
156
|
return this.aiServices.filter((s) => s.isAvailable).map((s) => s.getServiceName());
|
|
121
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
|
+
*/
|
|
122
168
|
getAiServiceFromServiceName(serviceName) {
|
|
123
169
|
return this.aiFactoryService.createAiService(serviceName);
|
|
124
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
|
+
*/
|
|
125
177
|
async listAiModels(aiServiceName) {
|
|
126
178
|
let service = this.getAiServiceFromServiceName(aiServiceName);
|
|
127
179
|
return service.listModels();
|
|
128
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
|
+
*/
|
|
129
187
|
async listImageModels() {
|
|
130
188
|
const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
|
|
131
189
|
try {
|
|
132
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.
|
|
133
195
|
return entries
|
|
134
196
|
.filter((entry) => entry.name && entry.name !== 'No images')
|
|
135
197
|
.map((entry) => ({ name: entry.name, description: entry.description ?? '' }));
|
|
@@ -139,6 +201,12 @@ class AppService {
|
|
|
139
201
|
return [];
|
|
140
202
|
}
|
|
141
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
|
+
*/
|
|
142
210
|
async listStoryModels() {
|
|
143
211
|
const storyModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'story_models.json');
|
|
144
212
|
try {
|
|
@@ -149,6 +217,14 @@ class AppService {
|
|
|
149
217
|
return [];
|
|
150
218
|
}
|
|
151
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
|
+
*/
|
|
152
228
|
listStoryGenres() {
|
|
153
229
|
const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas');
|
|
154
230
|
try {
|
|
@@ -165,6 +241,14 @@ class AppService {
|
|
|
165
241
|
return [];
|
|
166
242
|
}
|
|
167
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
|
+
*/
|
|
168
252
|
getRandomStoryIdeaByGenre(genreName) {
|
|
169
253
|
const storyIdeasPath = path.join(this.userPaths.getDataDir(), 'common', 'story_ideas', `${genreName}.json`);
|
|
170
254
|
try {
|
|
@@ -175,6 +259,7 @@ class AppService {
|
|
|
175
259
|
if (ideas.length === 0) {
|
|
176
260
|
return null;
|
|
177
261
|
}
|
|
262
|
+
// Return random idea from the array
|
|
178
263
|
const randomIndex = Math.floor(Math.random() * ideas.length);
|
|
179
264
|
return ideas[randomIndex];
|
|
180
265
|
}
|
|
@@ -186,33 +271,82 @@ class AppService {
|
|
|
186
271
|
throw new errors_1.OperationFailedError('Failed to read story ideas');
|
|
187
272
|
}
|
|
188
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
|
+
*/
|
|
189
279
|
getRandomStoryIdea() {
|
|
190
280
|
const genres = this.listStoryGenres();
|
|
191
281
|
if (genres.length === 0) {
|
|
192
282
|
return null;
|
|
193
283
|
}
|
|
284
|
+
// Pick random genre
|
|
194
285
|
const randomGenre = genres[Math.floor(Math.random() * genres.length)];
|
|
286
|
+
// Get random idea from that genre
|
|
195
287
|
return this.getRandomStoryIdeaByGenre(randomGenre);
|
|
196
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
|
+
*/
|
|
197
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.
|
|
198
325
|
if (!this.promptFolderExists(promptName)) {
|
|
199
326
|
logger_1.logger.warn(`Agent "${agentNickname}" names the prompt folder "${promptName}", which does not exist. ` +
|
|
200
327
|
`It will fall back to the shared root prompts and behave generically. ` +
|
|
201
328
|
`A pack's folder is named "<pack>:${promptName}" unless the pack is enabled for this user.`);
|
|
202
329
|
}
|
|
203
330
|
const agent = this.agentFactory.createAgent(aiServiceName, agentName, agentNickname, description, promptName, aiModel);
|
|
331
|
+
// Set the controlledByHuman property
|
|
204
332
|
if (controlledByHuman !== undefined) {
|
|
205
333
|
agent.isControlledByHuman = controlledByHuman;
|
|
206
334
|
}
|
|
335
|
+
// Set the reasoningEffort property
|
|
207
336
|
if (reasoningEffort !== undefined) {
|
|
208
337
|
agent.reasoningEffort = reasoningEffort;
|
|
209
338
|
}
|
|
339
|
+
// Set the reasoningEffort property
|
|
210
340
|
if (maxOutputTokens !== undefined) {
|
|
211
341
|
agent.maxOutputTokens = maxOutputTokens;
|
|
212
342
|
}
|
|
343
|
+
// Set the beginInstruction property
|
|
213
344
|
if (beginInstruction !== undefined) {
|
|
214
345
|
agent.beginInstruction = beginInstruction;
|
|
215
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.
|
|
216
350
|
if (options) {
|
|
217
351
|
if (options.allowSearch !== undefined)
|
|
218
352
|
agent.allowSearch = options.allowSearch;
|
|
@@ -231,15 +365,72 @@ class AppService {
|
|
|
231
365
|
if (options.ownerRoomId !== undefined)
|
|
232
366
|
agent.ownerRoomId = options.ownerRoomId;
|
|
233
367
|
}
|
|
368
|
+
// Set up SSE callback for this agent
|
|
234
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).
|
|
235
372
|
this.agentStore.registerAgent(agent);
|
|
236
373
|
return agent;
|
|
237
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
|
+
*/
|
|
238
426
|
async createAgentFromFolder(options) {
|
|
239
427
|
this.requirePromptFolder(options.folder);
|
|
240
428
|
const { defaults } = this.getPromptFolderDefaults(options.folder);
|
|
241
429
|
const settings = { ...defaults, ...options.overrides };
|
|
242
|
-
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, {
|
|
243
434
|
toolNames: settings.toolNames ?? [],
|
|
244
435
|
allowSearch: settings.allowSearch,
|
|
245
436
|
useModerator: settings.useModerator,
|
|
@@ -259,14 +450,37 @@ class AppService {
|
|
|
259
450
|
}
|
|
260
451
|
return agent;
|
|
261
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
|
+
*/
|
|
262
471
|
async processText(agentId, text) {
|
|
472
|
+
// Retrieve the agent from the store
|
|
263
473
|
const agent = await this.agentStore.getAgent(agentId);
|
|
264
474
|
if (!agent) {
|
|
265
475
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
266
476
|
}
|
|
477
|
+
// Set up SSE callback for this agent (if not already set)
|
|
267
478
|
this.setupAgentStateCallback(agent);
|
|
479
|
+
// Process the text using the agent context
|
|
268
480
|
const result = await agent.textPrompt(text, null, true, null, true);
|
|
481
|
+
// Save agent state to persist history changes and trigger SSE update
|
|
269
482
|
agent.save();
|
|
483
|
+
// Return latest message and its index
|
|
270
484
|
const messages = agent.getFormattedMessages();
|
|
271
485
|
return {
|
|
272
486
|
result,
|
|
@@ -277,22 +491,64 @@ class AppService {
|
|
|
277
491
|
totalCost: agent.totalCost,
|
|
278
492
|
};
|
|
279
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
|
+
*/
|
|
280
506
|
async attachDocument(agentId, fileName, fileData) {
|
|
281
507
|
let agent = await this.agentStore.getAgent(agentId);
|
|
282
508
|
if (!agent)
|
|
283
509
|
throw new Error(`Agent with ID ${agentId} not found`);
|
|
510
|
+
// Store the file using the AttachedFileService
|
|
284
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
|
|
285
513
|
const fileMetadata = this.attachedFileService.getFileMetadataByName(agentId, fileName);
|
|
286
514
|
if (fileMetadata && !agent.attachedFiles.some((f) => f.fileName === fileName)) {
|
|
287
515
|
agent.attachedFiles.push(fileMetadata);
|
|
288
516
|
}
|
|
517
|
+
// Process the document with the AI service
|
|
289
518
|
await agent.attachDocument(fileName, new Uint8Array(fileData));
|
|
519
|
+
// Save agent to persist serviceMetadata added by AI service
|
|
290
520
|
agent.save();
|
|
291
521
|
return { documentId: fileId };
|
|
292
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
|
+
*/
|
|
293
532
|
listPromptFolders() {
|
|
294
533
|
return (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, { enabledPacks: this.enabledPacks }).map((folder) => folder.value);
|
|
295
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
|
+
*/
|
|
296
552
|
listPromptFoldersWithScope(scope) {
|
|
297
553
|
const folders = (0, prompt_resolver_1.listPromptFolderRefs)(this.userPaths, {
|
|
298
554
|
enabledPacks: this.enabledPacks,
|
|
@@ -305,40 +561,85 @@ class AppService {
|
|
|
305
561
|
}));
|
|
306
562
|
return { folders };
|
|
307
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
|
+
*/
|
|
308
574
|
async listPrompts(agentId) {
|
|
575
|
+
// Retrieve the agent from the store
|
|
309
576
|
const agent = await this.agentStore.getAgent(agentId);
|
|
310
577
|
if (!agent) {
|
|
311
578
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
312
579
|
}
|
|
580
|
+
// Get the prompt path from the agent
|
|
313
581
|
let agentPromptsDir = path.join(this.userPaths.getPromptsDir(), agent.promptFolder);
|
|
314
582
|
let promptFiles = [];
|
|
583
|
+
// Check if directory exists
|
|
315
584
|
if (fs.existsSync(agentPromptsDir)) {
|
|
585
|
+
// Get all .prompt files in the agent's prompt folder
|
|
316
586
|
promptFiles = fs
|
|
317
587
|
.readdirSync(agentPromptsDir)
|
|
318
588
|
.filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
|
|
319
589
|
.map((file) => file.replace('.prompt', ''));
|
|
320
590
|
}
|
|
591
|
+
// Also get prompts from the root prompts directory
|
|
321
592
|
const rootPromptFiles = fs
|
|
322
593
|
.readdirSync(this.userPaths.getPromptsDir())
|
|
323
594
|
.filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
|
|
324
595
|
.map((file) => file.replace('.prompt', ''));
|
|
596
|
+
// Combine the prompt files, avoiding duplicates
|
|
325
597
|
promptFiles = [...new Set([...promptFiles, ...rootPromptFiles])];
|
|
326
598
|
return promptFiles;
|
|
327
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
|
+
*/
|
|
328
612
|
async runPreparedPrompt(agentId, promptName, variables = {}) {
|
|
613
|
+
// Retrieve the agent from the store
|
|
329
614
|
const agent = await this.agentStore.getAgent(agentId);
|
|
330
615
|
if (!agent) {
|
|
331
616
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
332
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.
|
|
333
620
|
const result = await agent.preparedPrompt(promptName, variables || {}, true);
|
|
334
621
|
return { result };
|
|
335
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
|
+
*/
|
|
336
634
|
async listAgents(includeRoomAgents = false) {
|
|
635
|
+
// Get all agent IDs from the store
|
|
337
636
|
const agentIds = await this.agentStore.getAllAgentIds();
|
|
637
|
+
// Map each ID to an object with agent details
|
|
338
638
|
const agentInfos = [];
|
|
339
639
|
for (const id of agentIds) {
|
|
340
640
|
const agent = await this.agentStore.getAgent(id);
|
|
341
641
|
if (agent) {
|
|
642
|
+
// Don't show agents that belong to a cloned room (or a story)
|
|
342
643
|
if (agent.ownerRoomId && !includeRoomAgents)
|
|
343
644
|
continue;
|
|
344
645
|
agentInfos.push({
|
|
@@ -367,6 +668,12 @@ class AppService {
|
|
|
367
668
|
}
|
|
368
669
|
return agentInfos;
|
|
369
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
|
+
*/
|
|
370
677
|
async getAgentDetails(agentId) {
|
|
371
678
|
try {
|
|
372
679
|
const agent = await this.agentStore.getAgent(agentId);
|
|
@@ -395,6 +702,8 @@ class AppService {
|
|
|
395
702
|
canModerate: this.canAgentModerate(agent),
|
|
396
703
|
privateContext: agent.privateContext,
|
|
397
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.
|
|
398
707
|
maxHistoryMessages: agent.maxHistoryMessages,
|
|
399
708
|
smallModelName: agent.smallModelName,
|
|
400
709
|
ownerRoomId: agent.ownerRoomId,
|
|
@@ -407,12 +716,65 @@ class AppService {
|
|
|
407
716
|
return null;
|
|
408
717
|
}
|
|
409
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
|
+
*/
|
|
410
753
|
folderProvidesModeratePrompt(promptFolder) {
|
|
411
754
|
return !!this.getPromptFile(promptFolder, 'moderate.prompt').scope;
|
|
412
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
|
+
*/
|
|
413
762
|
canAgentModerate(agent) {
|
|
414
763
|
return !agent.isControlledByHuman && this.folderProvidesModeratePrompt(agent.promptFolder);
|
|
415
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
|
+
*/
|
|
416
778
|
describeMissingModerator(room, roster) {
|
|
417
779
|
const named = room.getModerator();
|
|
418
780
|
if (!named?.trim()) {
|
|
@@ -430,6 +792,16 @@ class AppService {
|
|
|
430
792
|
}
|
|
431
793
|
return null;
|
|
432
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
|
+
*/
|
|
433
805
|
assertModeratorAvailable(room, arriving) {
|
|
434
806
|
const roster = arriving ? [...room.getAgents(), arriving] : room.getAgents();
|
|
435
807
|
const needsModerator = roster.filter((agent) => agent.useModerator);
|
|
@@ -443,17 +815,22 @@ class AppService {
|
|
|
443
815
|
`so room "${room.getName()}" needs one. ${reason}`);
|
|
444
816
|
}
|
|
445
817
|
async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator) {
|
|
818
|
+
// Validate that all agents exist before creating the room
|
|
446
819
|
for (const agentId of agentIds) {
|
|
447
820
|
const agent = await this.agentStore.getAgent(agentId);
|
|
448
821
|
if (!agent) {
|
|
449
822
|
throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
|
|
450
823
|
}
|
|
451
824
|
}
|
|
825
|
+
// Create a new room with the specified name and goal
|
|
452
826
|
const room = this.roomFactory.createRoom(roomName, goal);
|
|
827
|
+
// Add each agent to the room
|
|
453
828
|
for (const agentId of agentIds) {
|
|
454
829
|
const agent = await this.agentStore.getAgent(agentId);
|
|
455
830
|
room.arrive(agent);
|
|
456
831
|
}
|
|
832
|
+
// Leader and turn mode are set after the roster so the leader can be
|
|
833
|
+
// validated against it.
|
|
457
834
|
if (roomLeader !== undefined) {
|
|
458
835
|
room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
|
|
459
836
|
}
|
|
@@ -463,24 +840,53 @@ class AppService {
|
|
|
463
840
|
if (moderator !== undefined) {
|
|
464
841
|
room.setModerator(moderator);
|
|
465
842
|
}
|
|
843
|
+
// Before saveMetadata, so a room that cannot route its members' messages is
|
|
844
|
+
// never written to disk.
|
|
466
845
|
this.assertModeratorAvailable(room);
|
|
467
846
|
room.ready();
|
|
847
|
+
// Store the room and get its ID
|
|
468
848
|
const roomId = room.saveMetadata();
|
|
849
|
+
// Set up SSE callback for real-time updates
|
|
469
850
|
this.setupRoomStateCallback(room);
|
|
470
851
|
return { roomId };
|
|
471
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
|
+
*/
|
|
472
874
|
async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack) {
|
|
875
|
+
// Get the existing room
|
|
473
876
|
const room = await this.roomStore.getRoom(roomId);
|
|
474
877
|
if (!room) {
|
|
475
878
|
throw new errors_1.NotFoundError('Room not found');
|
|
476
879
|
}
|
|
880
|
+
// Prevent editing published instances
|
|
477
881
|
if (room.getIsPublished() && room.getTemplateRoomId()) {
|
|
478
882
|
throw new errors_1.OperationFailedError('Cannot edit published room instances');
|
|
479
883
|
}
|
|
884
|
+
// Update room properties
|
|
480
885
|
const previousName = room.getName();
|
|
481
886
|
room.setName(roomName);
|
|
482
887
|
room.setGoal(goal);
|
|
483
888
|
room.setBaseRoomDir(baseRoomDir || '');
|
|
889
|
+
// Update agents
|
|
484
890
|
if (agentIds) {
|
|
485
891
|
const newAgents = [];
|
|
486
892
|
for (const agentId of agentIds) {
|
|
@@ -494,9 +900,14 @@ class AppService {
|
|
|
494
900
|
}
|
|
495
901
|
room.setAgents(newAgents);
|
|
496
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.
|
|
497
906
|
if (roomName !== previousName) {
|
|
498
907
|
this.renameOwnedAgents(room, previousName, roomName);
|
|
499
908
|
}
|
|
909
|
+
// After setAgents, so a leader is validated against the new membership
|
|
910
|
+
// rather than the roster it is replacing.
|
|
500
911
|
if (roomLeader !== undefined) {
|
|
501
912
|
room.setRoomLeader(room_store_service_1.RoomStoreService.resolveLeaderNickname(room, roomLeader));
|
|
502
913
|
}
|
|
@@ -509,17 +920,39 @@ class AppService {
|
|
|
509
920
|
if (pack !== undefined) {
|
|
510
921
|
room.setPack(pack);
|
|
511
922
|
}
|
|
923
|
+
// Catches clearing the moderator, or pointing it at an agent this edit just
|
|
924
|
+
// removed, while a member still needs one.
|
|
512
925
|
this.assertModeratorAvailable(room);
|
|
926
|
+
// Save the updated room
|
|
513
927
|
room.saveMetadata();
|
|
514
928
|
}
|
|
929
|
+
/**
|
|
930
|
+
* Separates a room's name from the bare name of an agent that belongs to it.
|
|
931
|
+
*/
|
|
515
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
|
+
*/
|
|
516
939
|
static prefixedAgentName(roomName, bareName) {
|
|
517
940
|
return `${roomName}${AppService.ROOM_AGENT_SEPARATOR}${bareName}`;
|
|
518
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
|
+
*/
|
|
519
946
|
static bareAgentName(roomName, agentName) {
|
|
520
947
|
const prefix = roomName + AppService.ROOM_AGENT_SEPARATOR;
|
|
521
948
|
return agentName.startsWith(prefix) ? agentName.slice(prefix.length) : agentName;
|
|
522
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
|
+
*/
|
|
523
956
|
renameOwnedAgents(room, previousName, roomName) {
|
|
524
957
|
for (const agent of room.getAgents()) {
|
|
525
958
|
if (agent.ownerRoomId !== room.getId())
|
|
@@ -529,6 +962,24 @@ class AppService {
|
|
|
529
962
|
agent.save();
|
|
530
963
|
}
|
|
531
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
|
+
*/
|
|
532
983
|
async createRoomAgent(roomId, request) {
|
|
533
984
|
const room = await this.roomStore.getRoom(roomId);
|
|
534
985
|
if (!room) {
|
|
@@ -538,7 +989,11 @@ class AppService {
|
|
|
538
989
|
throw new errors_1.OperationFailedError('Cannot add agents to a published room instance');
|
|
539
990
|
}
|
|
540
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>".
|
|
541
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.
|
|
542
997
|
if (request.useModerator) {
|
|
543
998
|
const reason = this.describeMissingModerator(room, room.getAgents());
|
|
544
999
|
if (reason) {
|
|
@@ -555,6 +1010,8 @@ class AppService {
|
|
|
555
1010
|
smallModelName: request.smallModelName || undefined,
|
|
556
1011
|
ownerRoomId: roomId,
|
|
557
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.
|
|
558
1015
|
if (!room.arrive(agent)) {
|
|
559
1016
|
this.agentStore.removeAgent(agent.id);
|
|
560
1017
|
throw new errors_1.OperationFailedError(`An agent in this room is already addressed as "${nickname}"`);
|
|
@@ -563,10 +1020,37 @@ class AppService {
|
|
|
563
1020
|
room.saveMetadata();
|
|
564
1021
|
return { agentId: agent.id };
|
|
565
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
|
+
*/
|
|
566
1048
|
async createRoomAgentFromFolder(roomId, options) {
|
|
567
1049
|
this.requirePromptFolder(options.folder);
|
|
568
1050
|
const { defaults } = this.getPromptFolderDefaults(options.folder);
|
|
569
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.
|
|
570
1054
|
const bareName = settings.agentName ?? options.folder;
|
|
571
1055
|
const nickname = settings.agentNickname ?? bareName.split(/\s+/)[0];
|
|
572
1056
|
const { agentId } = await this.createRoomAgent(roomId, {
|
|
@@ -607,6 +1091,16 @@ class AppService {
|
|
|
607
1091
|
}
|
|
608
1092
|
return { agentId, nickname, unresolvedDocumentIds };
|
|
609
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
|
+
*/
|
|
610
1104
|
async removeRoomAgent(roomId, agentId) {
|
|
611
1105
|
const room = await this.roomStore.getRoom(roomId);
|
|
612
1106
|
if (!room) {
|
|
@@ -621,6 +1115,10 @@ class AppService {
|
|
|
621
1115
|
throw new errors_1.NotFoundError('Agent is not in this room');
|
|
622
1116
|
}
|
|
623
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.
|
|
624
1122
|
if (room.getModerator() === departing.agentNickname) {
|
|
625
1123
|
const heir = remaining.find((a) => this.canAgentModerate(a));
|
|
626
1124
|
const stillNeeded = remaining.filter((a) => a.useModerator);
|
|
@@ -633,6 +1131,8 @@ class AppService {
|
|
|
633
1131
|
room.setModerator(heir?.agentNickname ?? '');
|
|
634
1132
|
}
|
|
635
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.
|
|
636
1136
|
if (room.getRoomLeader() === departing.agentNickname) {
|
|
637
1137
|
room.setRoomLeader('');
|
|
638
1138
|
}
|
|
@@ -641,15 +1141,31 @@ class AppService {
|
|
|
641
1141
|
await this.deleteAgent(agentId);
|
|
642
1142
|
}
|
|
643
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
|
+
*/
|
|
644
1152
|
async listRooms() {
|
|
645
1153
|
return await this.roomStore.getTemplateRooms();
|
|
646
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
|
+
*/
|
|
647
1161
|
async getRoomDetails(roomId) {
|
|
648
1162
|
const room = await this.roomStore.getRoom(roomId);
|
|
649
1163
|
if (!room) {
|
|
650
1164
|
return null;
|
|
651
1165
|
}
|
|
1166
|
+
// Get all agents in the room
|
|
652
1167
|
const roomAgents = room.getAgents();
|
|
1168
|
+
// Fetch detailed information for each agent
|
|
653
1169
|
const agents = [];
|
|
654
1170
|
for (const agent of roomAgents) {
|
|
655
1171
|
const agentDetails = await this.getAgentDetails(agent.id);
|
|
@@ -674,9 +1190,28 @@ class AppService {
|
|
|
674
1190
|
processingInProgress: room.isProcessingInProgress(),
|
|
675
1191
|
};
|
|
676
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
|
+
*/
|
|
677
1202
|
async getRoomById(roomId) {
|
|
678
1203
|
return await this.roomStore.getRoom(roomId);
|
|
679
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
|
+
*/
|
|
680
1215
|
async setRoomLeader(roomId, agentNickname) {
|
|
681
1216
|
const room = await this.roomStore.getRoom(roomId);
|
|
682
1217
|
if (!room) {
|
|
@@ -685,6 +1220,19 @@ class AppService {
|
|
|
685
1220
|
room.setRoomLeader(agentNickname);
|
|
686
1221
|
room.saveMetadata();
|
|
687
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
|
+
*/
|
|
688
1236
|
async getRoomMessages(roomId, fromIndex = 0, includeThoughts = false) {
|
|
689
1237
|
const room = await this.roomStore.getRoom(roomId);
|
|
690
1238
|
if (!room) {
|
|
@@ -693,6 +1241,7 @@ class AppService {
|
|
|
693
1241
|
totalCost: 0,
|
|
694
1242
|
};
|
|
695
1243
|
}
|
|
1244
|
+
// Get messages from the specified index
|
|
696
1245
|
const indexedMessages = room.getLatestRoomMessages(fromIndex, includeThoughts);
|
|
697
1246
|
const totalCost = room
|
|
698
1247
|
.getAgents()
|
|
@@ -703,6 +1252,17 @@ class AppService {
|
|
|
703
1252
|
totalCost: totalCost,
|
|
704
1253
|
};
|
|
705
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
|
+
*/
|
|
706
1266
|
async getAgentMessages(agentId, fromIndex = 0) {
|
|
707
1267
|
const agent = await this.agentStore.getAgent(agentId);
|
|
708
1268
|
if (!agent) {
|
|
@@ -713,7 +1273,9 @@ class AppService {
|
|
|
713
1273
|
totalCost: 0,
|
|
714
1274
|
};
|
|
715
1275
|
}
|
|
1276
|
+
// Set up SSE callback for this agent (if not already set)
|
|
716
1277
|
this.setupAgentStateCallback(agent);
|
|
1278
|
+
// Use the agent's getFormattedMessages method
|
|
717
1279
|
const formattedMessages = agent.getFormattedMessages(fromIndex);
|
|
718
1280
|
return {
|
|
719
1281
|
messages: formattedMessages,
|
|
@@ -722,6 +1284,12 @@ class AppService {
|
|
|
722
1284
|
totalCost: agent.totalCost,
|
|
723
1285
|
};
|
|
724
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
|
+
*/
|
|
725
1293
|
async getStoryMessages(storyId, fromIndex) {
|
|
726
1294
|
const story = this.storyStore.getStory(storyId);
|
|
727
1295
|
if (!story) {
|
|
@@ -735,11 +1303,48 @@ class AppService {
|
|
|
735
1303
|
const totalCost = story.totalCost || 0;
|
|
736
1304
|
return { messages, totalCost };
|
|
737
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
|
+
*/
|
|
738
1342
|
async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false, context) {
|
|
739
1343
|
const room = await this.roomStore.getRoom(roomId);
|
|
740
1344
|
if (!room) {
|
|
741
1345
|
throw new errors_1.NotFoundError('Room not found');
|
|
742
1346
|
}
|
|
1347
|
+
// Map the action string to MessageAction enum
|
|
743
1348
|
let messageAction;
|
|
744
1349
|
switch (action.toLowerCase()) {
|
|
745
1350
|
case 'moderate':
|
|
@@ -765,8 +1370,18 @@ class AppService {
|
|
|
765
1370
|
messageAction = app_types_1.MessageAction.SPEAK;
|
|
766
1371
|
}
|
|
767
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).
|
|
768
1375
|
return room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue, context);
|
|
769
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
|
+
*/
|
|
770
1385
|
async pauseRoom(roomId) {
|
|
771
1386
|
const room = await this.roomStore.getRoom(roomId);
|
|
772
1387
|
if (!room) {
|
|
@@ -774,6 +1389,12 @@ class AppService {
|
|
|
774
1389
|
}
|
|
775
1390
|
room.pause();
|
|
776
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
|
+
*/
|
|
777
1398
|
async resumeRoom(roomId) {
|
|
778
1399
|
const room = await this.roomStore.getRoom(roomId);
|
|
779
1400
|
if (!room) {
|
|
@@ -781,29 +1402,64 @@ class AppService {
|
|
|
781
1402
|
}
|
|
782
1403
|
room.resume();
|
|
783
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
|
+
*/
|
|
784
1414
|
async deleteAgent(agentId) {
|
|
785
1415
|
const agent = await this.agentStore.getAgent(agentId);
|
|
786
1416
|
if (!agent) {
|
|
787
1417
|
throw new errors_1.NotFoundError('Agent not found');
|
|
788
1418
|
}
|
|
1419
|
+
// If this is a published agent, remove it from the published agents mapping
|
|
789
1420
|
if (agent.isPublished) {
|
|
790
1421
|
this.publishedAgentsService.removePublishedAgent(agentId);
|
|
791
1422
|
}
|
|
792
1423
|
await agent.deleteAgent();
|
|
793
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
|
+
*/
|
|
794
1440
|
async publishAgentInstance(templateId, instanceName) {
|
|
1441
|
+
// Validate template exists
|
|
795
1442
|
const template = await this.agentStore.getAgent(templateId);
|
|
796
1443
|
if (!template) {
|
|
797
1444
|
throw new errors_1.NotFoundError('Template agent not found');
|
|
798
1445
|
}
|
|
1446
|
+
// Create the published instance
|
|
799
1447
|
const userId = this.userPaths.getUserId();
|
|
800
1448
|
const instanceId = await this.agentStore.cloneAgentAsPublished(templateId, instanceName, userId);
|
|
1449
|
+
// Add to published agents mapping
|
|
801
1450
|
this.publishedAgentsService.addPublishedAgent(instanceId, userId);
|
|
802
1451
|
return {
|
|
803
1452
|
instanceId,
|
|
804
1453
|
publicUrl: `/public/agents/${instanceId}`,
|
|
805
1454
|
};
|
|
806
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
|
+
*/
|
|
807
1463
|
async getPublishedInstances(templateId) {
|
|
808
1464
|
const instances = await this.agentStore.getPublishedInstances(templateId);
|
|
809
1465
|
return instances.map((agent) => ({
|
|
@@ -827,6 +1483,16 @@ class AppService {
|
|
|
827
1483
|
useModerator: agent.useModerator,
|
|
828
1484
|
}));
|
|
829
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
|
+
*/
|
|
830
1496
|
async resetPublishedInstance(instanceId) {
|
|
831
1497
|
const instance = await this.agentStore.getAgent(instanceId);
|
|
832
1498
|
if (!instance) {
|
|
@@ -837,11 +1503,22 @@ class AppService {
|
|
|
837
1503
|
}
|
|
838
1504
|
await this.agentStore.resetPublishedInstance(instanceId, instance.templateAgentId);
|
|
839
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
|
+
*/
|
|
840
1516
|
async listPublishedAgents() {
|
|
841
1517
|
const agentIds = await this.agentStore.getAllAgentIds();
|
|
842
1518
|
const agents = [];
|
|
843
1519
|
for (const id of agentIds) {
|
|
844
1520
|
const agent = await this.agentStore.getAgent(id);
|
|
1521
|
+
// Filter: only include agents that are published AND not owned by a room
|
|
845
1522
|
if (agent && agent.isPublished && !agent.ownerRoomId) {
|
|
846
1523
|
agents.push({
|
|
847
1524
|
id: agent.id,
|
|
@@ -867,27 +1544,56 @@ class AppService {
|
|
|
867
1544
|
}
|
|
868
1545
|
return agents;
|
|
869
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
|
+
*/
|
|
870
1558
|
async deleteRoom(roomId) {
|
|
1559
|
+
// Check if the room exists
|
|
871
1560
|
const room = await this.roomStore.getRoom(roomId);
|
|
872
1561
|
if (!room) {
|
|
873
1562
|
throw new errors_1.NotFoundError('Room not found');
|
|
874
1563
|
}
|
|
875
|
-
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
|
|
876
1566
|
if (isTemplate) {
|
|
877
1567
|
const instances = await this.roomStore.getPublishedInstances(roomId);
|
|
878
1568
|
for (const instance of instances) {
|
|
1569
|
+
// Recursively delete each published instance (which deletes their agents)
|
|
879
1570
|
await this.deleteRoom(instance.getId());
|
|
880
1571
|
}
|
|
881
1572
|
}
|
|
1573
|
+
// Delete all attached files for this room
|
|
882
1574
|
this.attachedFileService.deleteAllFiles(roomId);
|
|
1575
|
+
// Remove from published mapping if this is a published instance
|
|
883
1576
|
if (room.getIsPublished()) {
|
|
884
1577
|
this.publishedRoomsService.removePublishedRoom(roomId);
|
|
885
1578
|
}
|
|
1579
|
+
// Remove the room from the store, along with the agents it owns
|
|
886
1580
|
const removed = this.roomStore.removeRoom(roomId);
|
|
887
1581
|
if (!removed) {
|
|
888
1582
|
throw new errors_1.OperationFailedError('Failed to delete room');
|
|
889
1583
|
}
|
|
890
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
|
+
*/
|
|
891
1597
|
async publishRoom(templateId, publishedName, userId) {
|
|
892
1598
|
const template = await this.roomStore.getRoom(templateId);
|
|
893
1599
|
if (!template) {
|
|
@@ -897,6 +1603,14 @@ class AppService {
|
|
|
897
1603
|
this.publishedRoomsService.addPublishedRoom(instanceId, userId);
|
|
898
1604
|
return instanceId;
|
|
899
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
|
+
*/
|
|
900
1614
|
static toRoomInfo(room) {
|
|
901
1615
|
return {
|
|
902
1616
|
id: room.getId(),
|
|
@@ -910,14 +1624,41 @@ class AppService {
|
|
|
910
1624
|
.reduce((total, cost) => total + cost, 0),
|
|
911
1625
|
};
|
|
912
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
|
+
*/
|
|
913
1634
|
async getPublishedRoomInstances(templateId) {
|
|
914
1635
|
const instances = await this.roomStore.getPublishedInstances(templateId);
|
|
915
1636
|
return instances.map(AppService.toRoomInfo);
|
|
916
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
|
+
*/
|
|
917
1648
|
async listPublishedRooms() {
|
|
918
1649
|
const instances = await this.roomStore.getAllPublishedInstances();
|
|
919
1650
|
return instances.map(AppService.toRoomInfo);
|
|
920
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
|
+
*/
|
|
921
1662
|
async resetPublishedRoomInstance(instanceId) {
|
|
922
1663
|
const instance = await this.roomStore.getRoom(instanceId);
|
|
923
1664
|
if (!instance) {
|
|
@@ -927,10 +1668,19 @@ class AppService {
|
|
|
927
1668
|
if (!templateId) {
|
|
928
1669
|
throw new errors_1.OperationFailedError('Not a published instance');
|
|
929
1670
|
}
|
|
1671
|
+
// Clear messages and artifacts
|
|
930
1672
|
this.roomStore.clearRoomMessages(instanceId);
|
|
931
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.
|
|
932
1681
|
this.roomStore.deleteAllArtifactFiles(instanceId, storageDir);
|
|
933
1682
|
instance.setArtifacts([]);
|
|
1683
|
+
// Reset all cloned agents
|
|
934
1684
|
const instanceAgents = instance.getAgents();
|
|
935
1685
|
for (const agent of instanceAgents) {
|
|
936
1686
|
if (agent.templateAgentId) {
|
|
@@ -939,39 +1689,92 @@ class AppService {
|
|
|
939
1689
|
}
|
|
940
1690
|
instance.saveMetadata();
|
|
941
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
|
+
*/
|
|
942
1701
|
getUserPreferences() {
|
|
1702
|
+
// Check if the file exists
|
|
943
1703
|
if (!this.userPaths.exists(this.userPreferencesFile)) {
|
|
1704
|
+
// Return empty preferences if file doesn't exist
|
|
944
1705
|
return {};
|
|
945
1706
|
}
|
|
1707
|
+
// Read and parse the preferences file
|
|
946
1708
|
const preferencesData = this.userPaths.load(this.userPreferencesFile);
|
|
947
1709
|
return preferencesData ? JSON.parse(preferencesData) : {};
|
|
948
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
|
+
*/
|
|
949
1719
|
saveUserPreferences(preferences) {
|
|
1720
|
+
// Write the preferences to the file
|
|
950
1721
|
this.userPaths.store(this.userPreferencesFile, JSON.stringify(preferences, null, 2));
|
|
951
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
|
+
*/
|
|
952
1733
|
listPromptFiles(folderName) {
|
|
953
1734
|
const baseNames = new Set();
|
|
1735
|
+
// Helper function to scan a directory and add files
|
|
954
1736
|
const scanDirectory = (baseDir) => {
|
|
955
1737
|
let targetDir = baseDir;
|
|
1738
|
+
// If not 'shared', look in the specific folder
|
|
956
1739
|
if (folderName !== 'shared') {
|
|
957
1740
|
targetDir = path.join(baseDir, folderName);
|
|
958
1741
|
}
|
|
1742
|
+
// Check if directory exists
|
|
959
1743
|
if (!fs.existsSync(targetDir)) {
|
|
960
1744
|
return;
|
|
961
1745
|
}
|
|
1746
|
+
// Get all files in the directory
|
|
962
1747
|
const allFiles = fs.readdirSync(targetDir);
|
|
1748
|
+
// Filter to only .prompt and .json files
|
|
963
1749
|
const promptFiles = allFiles.filter((file) => file.endsWith('.prompt') || file.endsWith('.json'));
|
|
1750
|
+
// Extract base names without extensions
|
|
964
1751
|
promptFiles.forEach((file) => {
|
|
965
1752
|
const baseName = file.replace(/\.(prompt|json)$/, '');
|
|
966
1753
|
baseNames.add(baseName);
|
|
967
1754
|
});
|
|
968
1755
|
};
|
|
1756
|
+
// Scan common prompts directory first
|
|
969
1757
|
scanDirectory(this.userPaths.getCommonPromptsDir());
|
|
1758
|
+
// Scan user prompts directory (will add or override common files)
|
|
970
1759
|
scanDirectory(this.userPaths.getUserPromptsDir());
|
|
971
1760
|
return { files: Array.from(baseNames).sort() };
|
|
972
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
|
+
*/
|
|
973
1772
|
listPromptFilesWithScope(folderName) {
|
|
974
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.
|
|
975
1778
|
for (const { dir, scope, pack } of (0, prompt_resolver_1.promptFolderDirsLowestFirst)(this.userPaths, folderName, { enabledPacks: this.enabledPacks })) {
|
|
976
1779
|
if (!fs.existsSync(dir))
|
|
977
1780
|
continue;
|
|
@@ -984,7 +1787,26 @@ class AppService {
|
|
|
984
1787
|
const files = [...fileMap.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
985
1788
|
return { files };
|
|
986
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
|
+
*/
|
|
987
1808
|
getPromptFile(folderName, fileName) {
|
|
1809
|
+
// Determine file extension (.prompt or .json)
|
|
988
1810
|
const fileExtension = fileName.endsWith('.prompt') || fileName.endsWith('.json') ? '' : '.prompt';
|
|
989
1811
|
const found = (0, prompt_resolver_1.resolvePromptFile)(this.userPaths, folderName, fileName, fileExtension, {
|
|
990
1812
|
enabledPacks: this.enabledPacks,
|
|
@@ -999,6 +1821,24 @@ class AppService {
|
|
|
999
1821
|
...(found.pack && { pack: found.pack }),
|
|
1000
1822
|
};
|
|
1001
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
|
+
*/
|
|
1002
1842
|
getPromptFolderDefaults(folderName) {
|
|
1003
1843
|
const exists = this.promptFolderExists(folderName);
|
|
1004
1844
|
const file = this.getPromptFile(folderName, 'defaults_config.json');
|
|
@@ -1064,9 +1904,27 @@ class AppService {
|
|
|
1064
1904
|
}
|
|
1065
1905
|
return { defaults, scope: file.scope, exists };
|
|
1066
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
|
+
*/
|
|
1067
1919
|
promptFolderExists(folderName) {
|
|
1068
1920
|
return (0, prompt_resolver_1.promptFolderExists)(this.userPaths, folderName, { enabledPacks: this.enabledPacks });
|
|
1069
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
|
+
*/
|
|
1070
1928
|
requirePromptFolder(folderName) {
|
|
1071
1929
|
if (this.promptFolderExists(folderName))
|
|
1072
1930
|
return;
|
|
@@ -1076,22 +1934,54 @@ class AppService {
|
|
|
1076
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)'}.`;
|
|
1077
1935
|
throw new errors_1.NotFoundError(`No prompt folder "${folderName}". ${hint}`);
|
|
1078
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
|
+
*/
|
|
1079
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.
|
|
1080
1957
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
1081
1958
|
(0, prompt_resolver_1.assertPathSafe)(fileName);
|
|
1959
|
+
// Create directory if it doesn't exist
|
|
1082
1960
|
if (!fs.existsSync(targetDir)) {
|
|
1083
1961
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
1084
1962
|
}
|
|
1963
|
+
// Determine file extension
|
|
1085
1964
|
const fileExtension = fileType === 'json' ? '.json' : '.prompt';
|
|
1086
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
|
|
1087
1967
|
if (content.trim() === '' && fileType === 'json') {
|
|
1088
1968
|
if (fs.existsSync(filePath)) {
|
|
1089
1969
|
fs.unlinkSync(filePath);
|
|
1090
1970
|
}
|
|
1091
1971
|
return;
|
|
1092
1972
|
}
|
|
1973
|
+
// Write content to file
|
|
1093
1974
|
fs.writeFileSync(filePath, content);
|
|
1094
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
|
+
*/
|
|
1095
1985
|
deletePromptFile(folderName, fileName) {
|
|
1096
1986
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
1097
1987
|
(0, prompt_resolver_1.assertPathSafe)(fileName);
|
|
@@ -1109,14 +1999,40 @@ class AppService {
|
|
|
1109
1999
|
}
|
|
1110
2000
|
}
|
|
1111
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
|
+
*/
|
|
1112
2011
|
async getRoomArtifacts(roomId) {
|
|
2012
|
+
// Check if the room exists
|
|
1113
2013
|
const room = await this.roomStore.getRoom(roomId);
|
|
1114
2014
|
if (!room) {
|
|
1115
2015
|
return { artifacts: [] };
|
|
1116
2016
|
}
|
|
2017
|
+
// Get all artifacts from the room
|
|
1117
2018
|
const artifacts = room.getArtifacts();
|
|
2019
|
+
// Return the artifacts
|
|
1118
2020
|
return { artifacts };
|
|
1119
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
|
+
*/
|
|
1120
2036
|
async publishArtifact(roomId, name, creator, body, viewers = []) {
|
|
1121
2037
|
const room = await this.roomStore.getRoom(roomId);
|
|
1122
2038
|
if (!room)
|
|
@@ -1125,30 +2041,80 @@ class AppService {
|
|
|
1125
2041
|
throw new errors_1.OperationFailedError('Artifact name is required');
|
|
1126
2042
|
room.publishArtifact(name, creator, body, viewers);
|
|
1127
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
|
+
*/
|
|
1128
2053
|
createPromptFolder(folderName) {
|
|
1129
2054
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
2055
|
+
// Check if folder already exists
|
|
1130
2056
|
if (fs.existsSync(targetDir)) {
|
|
1131
2057
|
throw new errors_1.OperationFailedError(`Folder ${folderName} already exists`);
|
|
1132
2058
|
}
|
|
2059
|
+
// Create the folder
|
|
1133
2060
|
fs.mkdirSync(targetDir, { recursive: true });
|
|
2061
|
+
// Create empty system_instruction.prompt file
|
|
1134
2062
|
const systemInstructionPath = path.join(targetDir, 'system_instruction.prompt');
|
|
1135
2063
|
fs.writeFileSync(systemInstructionPath, '');
|
|
1136
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
|
+
*/
|
|
1137
2074
|
deletePromptFolder(folderName) {
|
|
2075
|
+
// Prevent deletion of the 'shared' folder
|
|
1138
2076
|
if (folderName === 'shared') {
|
|
1139
2077
|
throw new errors_1.OperationFailedError('Cannot delete the shared folder');
|
|
1140
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.
|
|
1141
2081
|
const targetDir = (0, prompt_resolver_1.promptWriteDir)(this.userPaths, folderName);
|
|
2082
|
+
// Check if folder exists
|
|
1142
2083
|
if (!fs.existsSync(targetDir)) {
|
|
1143
2084
|
throw new errors_1.NotFoundError(`Folder ${folderName} does not exist`);
|
|
1144
2085
|
}
|
|
2086
|
+
// Delete the folder recursively
|
|
1145
2087
|
fs.rmSync(targetDir, { recursive: true, force: true });
|
|
1146
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
|
+
*/
|
|
1147
2107
|
async updateAgent(agentId, updates) {
|
|
1148
2108
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1149
2109
|
if (!agent) {
|
|
1150
2110
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1151
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.
|
|
1152
2118
|
if (updates.useModerator === true && !agent.useModerator && agent.ownerRoomId) {
|
|
1153
2119
|
const room = await this.roomStore.getRoom(agent.ownerRoomId);
|
|
1154
2120
|
const reason = room ? this.describeMissingModerator(room, room.getAgents()) : null;
|
|
@@ -1157,6 +2123,7 @@ class AppService {
|
|
|
1157
2123
|
`"${room.getName()}" needs one. ${reason}`);
|
|
1158
2124
|
}
|
|
1159
2125
|
}
|
|
2126
|
+
// Update only provided fields
|
|
1160
2127
|
if (updates.agentNickname !== undefined) {
|
|
1161
2128
|
await this.renameAgentEverywhere(agent, updates.agentNickname);
|
|
1162
2129
|
}
|
|
@@ -1185,12 +2152,31 @@ class AppService {
|
|
|
1185
2152
|
agent.privateContext = updates.privateContext;
|
|
1186
2153
|
if (updates.promptCacheTTL !== undefined)
|
|
1187
2154
|
agent.promptCacheTTL = updates.promptCacheTTL;
|
|
2155
|
+
// 0 and '' mean "no limit" and "no override", so they clear rather than set.
|
|
1188
2156
|
if (updates.maxHistoryMessages !== undefined)
|
|
1189
2157
|
agent.maxHistoryMessages = updates.maxHistoryMessages || undefined;
|
|
1190
2158
|
if (updates.smallModelName !== undefined)
|
|
1191
2159
|
agent.smallModelName = updates.smallModelName || undefined;
|
|
1192
|
-
agent.save();
|
|
1193
|
-
}
|
|
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
|
+
*/
|
|
1194
2180
|
async renameAgentEverywhere(agent, newName) {
|
|
1195
2181
|
const previous = agent.agentNickname;
|
|
1196
2182
|
const trimmed = (newName || '').trim();
|
|
@@ -1212,19 +2198,68 @@ class AppService {
|
|
|
1212
2198
|
room.repointNickname(previous, trimmed);
|
|
1213
2199
|
}
|
|
1214
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
|
+
*/
|
|
1215
2205
|
get userAuthoredToolsEnabled() {
|
|
1216
2206
|
return this.toolExecution.userAuthoredToolsEnabled;
|
|
1217
2207
|
}
|
|
2208
|
+
/**
|
|
2209
|
+
* Lists user-authored tools (with code). Empty when authoring is disabled.
|
|
2210
|
+
*
|
|
2211
|
+
* @returns Array of user-authored tool definitions
|
|
2212
|
+
*/
|
|
1218
2213
|
async listTools() {
|
|
1219
2214
|
if (!this.userAuthoredToolsEnabled)
|
|
1220
2215
|
return [];
|
|
1221
2216
|
return this.toolStore.listTools();
|
|
1222
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
|
+
*/
|
|
1223
2243
|
preserveHiddenGrants(current, requested) {
|
|
1224
2244
|
const offered = new Set(this.listNativeToolSummaries().map((tool) => tool.name));
|
|
1225
2245
|
const kept = current.filter((name) => !offered.has(name) && !requested.includes(name));
|
|
1226
2246
|
return kept.length > 0 ? [...requested, ...kept] : requested;
|
|
1227
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
|
+
*/
|
|
1228
2263
|
listNativeToolSummaries() {
|
|
1229
2264
|
const enabled = new Set(this.enabledPacks());
|
|
1230
2265
|
return this.toolExecution
|
|
@@ -1237,6 +2272,13 @@ class AppService {
|
|
|
1237
2272
|
group: t.group,
|
|
1238
2273
|
}));
|
|
1239
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
|
+
*/
|
|
1240
2282
|
async createTool(tool) {
|
|
1241
2283
|
this.assertUserAuthoringAllowed();
|
|
1242
2284
|
const existing = await this.toolStore.getTool(tool.name);
|
|
@@ -1245,6 +2287,15 @@ class AppService {
|
|
|
1245
2287
|
}
|
|
1246
2288
|
return this.toolStore.saveTool(tool);
|
|
1247
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
|
+
*/
|
|
1248
2299
|
async updateTool(name, tool) {
|
|
1249
2300
|
this.assertUserAuthoringAllowed();
|
|
1250
2301
|
const existing = await this.toolStore.getTool(name);
|
|
@@ -1253,6 +2304,14 @@ class AppService {
|
|
|
1253
2304
|
}
|
|
1254
2305
|
return this.toolStore.saveTool({ ...tool, name });
|
|
1255
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
|
+
*/
|
|
1256
2315
|
async deleteTool(name) {
|
|
1257
2316
|
this.assertUserAuthoringAllowed();
|
|
1258
2317
|
const deleted = await this.toolStore.deleteTool(name);
|
|
@@ -1265,30 +2324,70 @@ class AppService {
|
|
|
1265
2324
|
throw new errors_1.OperationFailedError('User-authored tools are disabled on this deployment');
|
|
1266
2325
|
}
|
|
1267
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
|
+
*/
|
|
1268
2335
|
async testTool(name, args) {
|
|
1269
2336
|
return this.toolExecution.test(name, args);
|
|
1270
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
|
+
*/
|
|
1271
2344
|
async listAttachedFiles(agentId) {
|
|
2345
|
+
// Check if the agent exists
|
|
1272
2346
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1273
2347
|
if (!agent) {
|
|
1274
2348
|
return { files: [] };
|
|
1275
2349
|
}
|
|
2350
|
+
// Get the list of files from the AttachedFileService
|
|
1276
2351
|
const files = this.attachedFileService.listFiles(agentId);
|
|
1277
2352
|
return { files };
|
|
1278
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
|
+
*/
|
|
1279
2364
|
async deleteAttachedFile(agentId, fileName) {
|
|
2365
|
+
// Check if the agent exists
|
|
1280
2366
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1281
2367
|
if (!agent) {
|
|
1282
2368
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1283
2369
|
}
|
|
2370
|
+
// Delete the file
|
|
1284
2371
|
const deleted = this.attachedFileService.deleteFileByName(agentId, fileName);
|
|
1285
2372
|
if (!deleted) {
|
|
1286
2373
|
throw new errors_1.NotFoundError(`File ${fileName} not found`);
|
|
1287
2374
|
}
|
|
2375
|
+
// Update the agent's attachedFiles array
|
|
1288
2376
|
agent.attachedFiles = agent.attachedFiles.filter((file) => file.fileName !== fileName);
|
|
1289
2377
|
agent.save();
|
|
1290
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
|
+
*/
|
|
1291
2389
|
async deleteAttachedFileById(documentId) {
|
|
2390
|
+
// Find the agent that owns this file
|
|
1292
2391
|
const allAgentIds = await this.agentStore.getAllAgentIds();
|
|
1293
2392
|
let ownerAgent = null;
|
|
1294
2393
|
let fileMetadata = null;
|
|
@@ -1306,20 +2405,36 @@ class AppService {
|
|
|
1306
2405
|
if (!ownerAgent || !fileMetadata) {
|
|
1307
2406
|
throw new errors_1.NotFoundError('File not found');
|
|
1308
2407
|
}
|
|
2408
|
+
// Delete the file using the attachedFileService
|
|
1309
2409
|
const deleted = this.attachedFileService.deleteFile(ownerAgent.id, documentId);
|
|
1310
2410
|
if (!deleted) {
|
|
1311
2411
|
throw new errors_1.OperationFailedError('Failed to delete file');
|
|
1312
2412
|
}
|
|
2413
|
+
// Update the agent's attachedFiles array
|
|
1313
2414
|
ownerAgent.attachedFiles = ownerAgent.attachedFiles.filter((file) => file.fileId !== documentId);
|
|
1314
2415
|
ownerAgent.save();
|
|
1315
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
|
+
*/
|
|
1316
2428
|
async reloadAgent(agentId) {
|
|
2429
|
+
// Check if the agent exists
|
|
1317
2430
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1318
2431
|
if (!agent) {
|
|
1319
2432
|
throw new errors_1.NotFoundError('Agent not found');
|
|
1320
2433
|
}
|
|
2434
|
+
// Get the agent's service
|
|
1321
2435
|
const serviceName = agent.serviceName;
|
|
1322
2436
|
const aiService = this.getAiServiceFromServiceName(serviceName);
|
|
2437
|
+
// Create a new history array
|
|
1323
2438
|
if (agent.history &&
|
|
1324
2439
|
agent.history.length > 0 &&
|
|
1325
2440
|
agent.history[0].content &&
|
|
@@ -1327,6 +2442,7 @@ class AppService {
|
|
|
1327
2442
|
agent.history.splice(1);
|
|
1328
2443
|
else
|
|
1329
2444
|
agent.history = [];
|
|
2445
|
+
// Re-attach all files
|
|
1330
2446
|
const fileMetadataList = agent.attachedFiles;
|
|
1331
2447
|
for (const metadata of fileMetadataList) {
|
|
1332
2448
|
const fileData = this.attachedFileService.getFile(agent.id, metadata.fileId);
|
|
@@ -1336,6 +2452,13 @@ class AppService {
|
|
|
1336
2452
|
}
|
|
1337
2453
|
agent.save();
|
|
1338
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
|
+
*/
|
|
1339
2462
|
async compactAgentConversation(agentId) {
|
|
1340
2463
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1341
2464
|
if (!agent) {
|
|
@@ -1343,54 +2466,85 @@ class AppService {
|
|
|
1343
2466
|
}
|
|
1344
2467
|
await agent.compact();
|
|
1345
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
|
+
*/
|
|
1346
2478
|
async resetRoom(roomId) {
|
|
2479
|
+
// Get the room
|
|
1347
2480
|
const room = await this.roomStore.getRoom(roomId);
|
|
1348
2481
|
if (!room) {
|
|
1349
2482
|
throw new errors_1.NotFoundError('Room not found');
|
|
1350
2483
|
}
|
|
1351
2484
|
const roomName = room.getName();
|
|
1352
2485
|
const storageDir = room.getStorageDir() || this.roomStore.getDefaultStorageDir();
|
|
2486
|
+
// Clear room messages (both in-memory and on disk)
|
|
1353
2487
|
this.roomStore.clearRoomMessages(roomId, storageDir);
|
|
2488
|
+
// Clear all artifacts (delete files and clear in-memory)
|
|
1354
2489
|
this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
|
|
1355
2490
|
room.setArtifacts([]);
|
|
2491
|
+
// Reset each agent using the existing reloadAgent logic
|
|
1356
2492
|
const warnings = [];
|
|
1357
2493
|
for (const agent of room.getAgents()) {
|
|
1358
2494
|
try {
|
|
2495
|
+
// Use existing reloadAgent functionality to clear history and re-attach files
|
|
1359
2496
|
this.reloadAgent(agent.id);
|
|
1360
2497
|
}
|
|
1361
2498
|
catch (agentError) {
|
|
1362
2499
|
warnings.push(`Failed to reset agent ${agent.agentName}: ${agentError.message}`);
|
|
1363
2500
|
}
|
|
1364
2501
|
}
|
|
2502
|
+
// Log warnings if any
|
|
1365
2503
|
if (warnings.length > 0) {
|
|
1366
2504
|
logger_1.logger.warn(`Room "${roomName}" reset with warnings:`, warnings);
|
|
1367
2505
|
}
|
|
1368
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
|
+
*/
|
|
1369
2516
|
async resetStory(storyId) {
|
|
2517
|
+
// Get the story metadata
|
|
1370
2518
|
const story = this.storyStore.getStory(storyId);
|
|
1371
2519
|
if (!story || !story.roomId) {
|
|
1372
2520
|
throw new errors_1.NotFoundError('Story not found');
|
|
1373
2521
|
}
|
|
1374
2522
|
const storyName = story.name;
|
|
2523
|
+
// Get the room
|
|
1375
2524
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1376
2525
|
if (!room) {
|
|
1377
2526
|
throw new errors_1.NotFoundError('Story room not found');
|
|
1378
2527
|
}
|
|
2528
|
+
// Find and preserve the Opening Scene message before clearing
|
|
1379
2529
|
const roomMessages = room.getLatestRoomMessages();
|
|
1380
2530
|
const openingSceneMessage = roomMessages.find((msg) => msg.sender === 'Opening Scene');
|
|
1381
2531
|
const openingSceneText = openingSceneMessage?.content || '';
|
|
1382
2532
|
const storageDir = room.getStorageDir() ||
|
|
1383
2533
|
path.join(this.userPaths.getUserDataDir(), 'stories', storyId, 'rooms');
|
|
2534
|
+
// Clear room messages (both in-memory and on disk)
|
|
1384
2535
|
this.roomStore.clearRoomMessages(story.roomId, storageDir);
|
|
1385
2536
|
room.setRoomMessages([]);
|
|
2537
|
+
// Restore agents from chapter 1 backup instead of calling reloadAgent
|
|
1386
2538
|
const chapters = this.storyStore.listChapters(storyId);
|
|
1387
2539
|
const warnings = [];
|
|
1388
2540
|
if (chapters.length > 0) {
|
|
2541
|
+
// Chapter 1 backup exists - restore agents from it
|
|
1389
2542
|
logger_1.logger.log(`Restoring agents from chapter 1 backup for story ${storyId}`);
|
|
1390
2543
|
const restoredAgentIds = await this.storyStore.restoreAgentsFromChapter(storyId, 1, this.agentStore);
|
|
1391
2544
|
logger_1.logger.log(`Restored ${restoredAgentIds.length} agents from chapter 1 backup`);
|
|
1392
2545
|
}
|
|
1393
2546
|
else {
|
|
2547
|
+
// No chapter backup exists - fallback to reloadAgent (clear histories)
|
|
1394
2548
|
logger_1.logger.warn(`No chapter 1 backup found for story ${storyId}, clearing agent histories`);
|
|
1395
2549
|
for (const agent of room.getAgents()) {
|
|
1396
2550
|
try {
|
|
@@ -1401,35 +2555,209 @@ class AppService {
|
|
|
1401
2555
|
}
|
|
1402
2556
|
}
|
|
1403
2557
|
}
|
|
2558
|
+
// Re-add the opening scene message and populate agent histories
|
|
1404
2559
|
if (openingSceneText) {
|
|
1405
2560
|
this.storyService.populateStoryHistory(room, openingSceneText);
|
|
1406
2561
|
}
|
|
2562
|
+
// Clear declined characters when resetting story
|
|
1407
2563
|
if (story) {
|
|
1408
2564
|
story.declinedCharacters = [];
|
|
1409
2565
|
this.storyStore.updateStoryMetadata(storyId, story);
|
|
1410
2566
|
}
|
|
2567
|
+
// Log warnings if any
|
|
1411
2568
|
if (warnings.length > 0) {
|
|
1412
2569
|
logger_1.logger.warn(`Story "${storyName}" reset with warnings:`, warnings);
|
|
1413
2570
|
}
|
|
1414
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
|
+
*/
|
|
1415
2582
|
async revertStoryChapter(storyId) {
|
|
1416
2583
|
return this.storyService.revertStoryChapter(storyId);
|
|
1417
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
|
+
*/
|
|
1418
2621
|
async createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot) {
|
|
2622
|
+
// Delegate to StoryService for business logic
|
|
1419
2623
|
return this.storyService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, illustrateStory, storyModel, isImport, imageModelName, skipDetailedPlot);
|
|
1420
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
|
+
*/
|
|
1421
2631
|
async importStoryFromZip(zipBuffer) {
|
|
1422
2632
|
return this.storyService.importStoryFromZip(zipBuffer);
|
|
1423
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
|
+
*/
|
|
1424
2672
|
getStoryProgressEmitter(storyId) {
|
|
1425
2673
|
return this.storyService.getProgressEmitter(storyId);
|
|
1426
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
|
+
*/
|
|
1427
2728
|
getStoryMessageEmitter(storyId) {
|
|
1428
2729
|
return this.storyService.getMessageEmitter(storyId);
|
|
1429
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
|
+
*/
|
|
1430
2749
|
getAgentMessageEmitter(agentId) {
|
|
1431
2750
|
return this.agentMessageService.getOrCreateEmitter(agentId);
|
|
1432
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
|
+
*/
|
|
1433
2761
|
async ensureAgentStateCallback(agentId) {
|
|
1434
2762
|
try {
|
|
1435
2763
|
const agent = await this.agentStore.getAgent(agentId);
|
|
@@ -1441,12 +2769,17 @@ class AppService {
|
|
|
1441
2769
|
logger_1.logger.warn(`Could not set up SSE callback for agent ${agentId}:`, error.message);
|
|
1442
2770
|
}
|
|
1443
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
|
+
*/
|
|
1444
2776
|
setupAgentStateCallback(agent) {
|
|
1445
2777
|
if (!agent.id) {
|
|
1446
2778
|
logger_1.logger.warn('Cannot set up SSE callback for agent without ID');
|
|
1447
2779
|
return;
|
|
1448
2780
|
}
|
|
1449
2781
|
agent.setOnStateChange(() => {
|
|
2782
|
+
// Get current agent state - send only latest message + index
|
|
1450
2783
|
const messages = agent.getFormattedMessages();
|
|
1451
2784
|
const agentState = {
|
|
1452
2785
|
agentId: agent.id,
|
|
@@ -1456,15 +2789,42 @@ class AppService {
|
|
|
1456
2789
|
totalOutputTokens: agent.totalOutputTokens,
|
|
1457
2790
|
totalCost: agent.totalCost,
|
|
1458
2791
|
};
|
|
2792
|
+
// Emit update to all connected SSE clients
|
|
1459
2793
|
this.agentMessageService.emitUpdate(agent.id, agentState);
|
|
1460
2794
|
});
|
|
1461
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
|
+
*/
|
|
1462
2805
|
getRoomMessageEmitter(roomId) {
|
|
1463
2806
|
return this.roomMessageService.getOrCreateEmitter(roomId);
|
|
1464
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
|
+
*/
|
|
1465
2817
|
getBalanceMessageEmitter(userId) {
|
|
1466
2818
|
return this.balanceMessageService.getOrCreateEmitter(userId);
|
|
1467
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
|
+
*/
|
|
1468
2828
|
async ensureRoomStateCallback(roomId) {
|
|
1469
2829
|
try {
|
|
1470
2830
|
const room = await this.roomStore.getRoom(roomId);
|
|
@@ -1482,10 +2842,23 @@ class AppService {
|
|
|
1482
2842
|
logger_1.logger.warn('Cannot set up SSE callback for room without ID');
|
|
1483
2843
|
return;
|
|
1484
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.
|
|
1485
2850
|
room.setOnError('app-service', (error) => {
|
|
1486
2851
|
this.roomMessageService.emitError(roomId, error);
|
|
1487
2852
|
});
|
|
1488
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.
|
|
1489
2862
|
const messages = room.getLatestRoomMessages(0, true);
|
|
1490
2863
|
const latestMessage = messages.length > 0 ? messages[messages.length - 1] : undefined;
|
|
1491
2864
|
const totalCost = room
|
|
@@ -1493,9 +2866,14 @@ class AppService {
|
|
|
1493
2866
|
.map((a) => a.totalCost)
|
|
1494
2867
|
.reduce((acc, v) => acc + v, 0);
|
|
1495
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.
|
|
1496
2871
|
type: 'state',
|
|
1497
2872
|
roomId: roomId,
|
|
1498
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.
|
|
1499
2877
|
messageIndex: latestMessage?.index,
|
|
1500
2878
|
totalCost: totalCost,
|
|
1501
2879
|
isPaused: room.getPaused(),
|
|
@@ -1506,9 +2884,22 @@ class AppService {
|
|
|
1506
2884
|
this.roomMessageService.emitUpdate(roomId, roomState);
|
|
1507
2885
|
});
|
|
1508
2886
|
}
|
|
2887
|
+
/**
|
|
2888
|
+
* Lists all stories belonging to this user.
|
|
2889
|
+
*
|
|
2890
|
+
* @returns Array of story metadata objects
|
|
2891
|
+
*/
|
|
1509
2892
|
listStories() {
|
|
1510
2893
|
return this.storyStore.getAllStories();
|
|
1511
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
|
+
*/
|
|
1512
2903
|
async resumePausedStories() {
|
|
1513
2904
|
const stories = this.storyStore.getAllStories();
|
|
1514
2905
|
let resumedCount = 0;
|
|
@@ -1519,11 +2910,14 @@ class AppService {
|
|
|
1519
2910
|
const room = await this.roomStore.getRoom(story.roomId);
|
|
1520
2911
|
if (!room)
|
|
1521
2912
|
continue;
|
|
2913
|
+
// Check if room is paused (not processing but has pending messages)
|
|
1522
2914
|
const isPaused = !room.isProcessingInProgress() && room['pendingMessages']?.length > 0;
|
|
1523
2915
|
if (isPaused) {
|
|
1524
2916
|
logger_1.logger.log(`Resuming paused story: ${story.name} (${story.id})`);
|
|
2917
|
+
// Add a system message to notify about resumption
|
|
1525
2918
|
const resumeMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, 'Balance added. Conversation resumed.', [], null, null);
|
|
1526
2919
|
room.addRoomMessage(resumeMessage);
|
|
2920
|
+
// Resume processing by calling processPendingMessages
|
|
1527
2921
|
room['processPendingMessages']();
|
|
1528
2922
|
resumedCount++;
|
|
1529
2923
|
}
|
|
@@ -1537,129 +2931,477 @@ class AppService {
|
|
|
1537
2931
|
}
|
|
1538
2932
|
return resumedCount;
|
|
1539
2933
|
}
|
|
2934
|
+
/**
|
|
2935
|
+
* Permanently deletes a story, its room, all characters, chapters, and artifacts.
|
|
2936
|
+
*
|
|
2937
|
+
* @param storyId - The story's ID
|
|
2938
|
+
*/
|
|
1540
2939
|
async deleteStory(storyId) {
|
|
1541
2940
|
await this.storyService.deleteStory(storyId);
|
|
1542
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
|
+
*/
|
|
1543
2952
|
async compactStory(storyId) {
|
|
1544
2953
|
return this.storyService.compactStory(storyId);
|
|
1545
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
|
+
*/
|
|
1546
2972
|
async progressStory(storyId) {
|
|
1547
2973
|
return this.storyService.progressStoryToNextChapter(storyId);
|
|
1548
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
|
+
*/
|
|
1549
2984
|
async getStoryState(storyId) {
|
|
1550
2985
|
return this.storyService.getStoryState(storyId);
|
|
1551
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
|
+
*/
|
|
1552
2993
|
async getStoryInfo(storyId) {
|
|
1553
2994
|
return this.storyStore.getStory(storyId);
|
|
1554
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
|
+
*/
|
|
1555
3008
|
async respondToStory(storyId, content) {
|
|
1556
3009
|
return this.storyService.respondToStory(storyId, content);
|
|
1557
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
|
+
*/
|
|
1558
3020
|
async interruptStory(storyId) {
|
|
1559
3021
|
return this.storyService.interruptStory(storyId);
|
|
1560
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
|
+
*/
|
|
1561
3040
|
async introduceCharacterToStory(storyId, name, description, storyModel, fromNarratorSuggestion) {
|
|
1562
3041
|
await this.storyService.introduceCharacter(storyId, name, description, storyModel, fromNarratorSuggestion);
|
|
1563
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
|
+
*/
|
|
1564
3051
|
async declineCharacter(storyId, characterName) {
|
|
1565
3052
|
await this.storyService.declineCharacter(storyId, characterName);
|
|
1566
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
|
+
*/
|
|
1567
3063
|
async deleteCharacterFromStory(storyId, characterName) {
|
|
1568
3064
|
await this.storyService.deleteCharacter(storyId, characterName);
|
|
1569
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
|
+
*/
|
|
1570
3074
|
listChapters(storyId) {
|
|
1571
3075
|
const chapters = this.storyStore.listChapters(storyId);
|
|
1572
3076
|
return { chapters };
|
|
1573
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
|
+
*/
|
|
1574
3085
|
async getChapter(storyId, chapterIndex) {
|
|
1575
3086
|
return await this.storyStore.getChapterContent(storyId, chapterIndex);
|
|
1576
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
|
+
*/
|
|
1577
3096
|
saveChapter(storyId, chapterIndex, content) {
|
|
1578
3097
|
const saved = this.storyStore.saveChapterContent(storyId, chapterIndex, content);
|
|
1579
3098
|
if (!saved) {
|
|
1580
3099
|
throw new errors_1.OperationFailedError('Failed to save chapter');
|
|
1581
3100
|
}
|
|
1582
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
|
+
*/
|
|
1583
3109
|
deleteChapter(storyId, chapterIndex) {
|
|
1584
3110
|
const deleted = this.storyStore.deleteChapter(storyId, chapterIndex);
|
|
1585
3111
|
if (!deleted) {
|
|
1586
3112
|
throw new errors_1.NotFoundError('Chapter not found');
|
|
1587
3113
|
}
|
|
1588
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
|
+
*/
|
|
1589
3121
|
async listCharacters(storyId) {
|
|
1590
3122
|
return await this.storyService.listCharacters(storyId);
|
|
1591
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
|
+
*/
|
|
1592
3131
|
async getCharacter(storyId, characterName) {
|
|
1593
3132
|
const content = await this.storyService.getCharacter(storyId, characterName);
|
|
1594
3133
|
return { content: content || '' };
|
|
1595
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
|
+
*/
|
|
1596
3142
|
saveCharacter(storyId, characterName, content) {
|
|
1597
3143
|
this.storyService.saveCharacter(storyId, characterName, content);
|
|
1598
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
|
+
*/
|
|
1599
3152
|
async getCharacterInventory(storyId, characterName) {
|
|
1600
3153
|
const content = await this.storyService.getCharacterInventory(storyId, characterName);
|
|
1601
3154
|
return { content: content || '' };
|
|
1602
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
|
+
*/
|
|
1603
3163
|
async saveCharacterInventory(storyId, characterName, content) {
|
|
1604
3164
|
await this.storyService.saveCharacterInventory(storyId, characterName, content);
|
|
1605
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
|
+
*/
|
|
1606
3175
|
async getPlotPlan(storyId) {
|
|
1607
3176
|
const content = await this.storyService.getPlotPlan(storyId);
|
|
1608
3177
|
return { content: content || '' };
|
|
1609
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
|
+
*/
|
|
1610
3187
|
async downloadStoryMarkdown(storyId) {
|
|
1611
3188
|
return await this.storyService.generateStoryMarkdown(storyId);
|
|
1612
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
|
+
*/
|
|
1613
3198
|
async exportStoryData(storyId) {
|
|
1614
3199
|
return await this.storyService.exportStoryData(storyId);
|
|
1615
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
|
+
*/
|
|
1616
3208
|
async getAgentHistory(storyId, agentId) {
|
|
1617
3209
|
const history = await this.storyService.getAgentHistory(storyId, agentId);
|
|
1618
3210
|
return { content: history };
|
|
1619
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
|
+
*/
|
|
1620
3220
|
async savePlotPlan(storyId, content) {
|
|
1621
3221
|
await this.storyService.savePlotPlan(storyId, content);
|
|
1622
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
|
+
*/
|
|
1623
3232
|
getBalance() {
|
|
1624
3233
|
return this.balanceService.getBalance();
|
|
1625
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
|
+
*/
|
|
1626
3242
|
addBalance(amount) {
|
|
1627
3243
|
return this.balanceService.addBalance(amount);
|
|
1628
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
|
+
*/
|
|
1629
3258
|
async recordTransaction(amount, paymentId, status = 'pending') {
|
|
1630
3259
|
return this.transactionService.recordTransaction(amount, paymentId, status);
|
|
1631
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
|
+
*/
|
|
1632
3269
|
async updateTransactionStatus(paymentId, status) {
|
|
1633
3270
|
return this.transactionService.updateTransactionStatus(paymentId, status);
|
|
1634
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
|
+
*/
|
|
1635
3278
|
async getTransactionByPaymentId(paymentId) {
|
|
1636
3279
|
return this.transactionService.getTransactionByPaymentId(paymentId);
|
|
1637
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
|
+
*/
|
|
1638
3288
|
async getTransactions(limit = 50, offset = 0) {
|
|
1639
3289
|
return this.transactionService.getTransactions(limit, offset);
|
|
1640
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
|
+
*/
|
|
1641
3301
|
listUserArtifacts() {
|
|
1642
3302
|
return this.artifactService.listArtifacts();
|
|
1643
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
|
+
*/
|
|
1644
3313
|
getUserArtifact(artifactId) {
|
|
1645
3314
|
return this.artifactService.getArtifact(artifactId);
|
|
1646
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
|
+
*/
|
|
1647
3326
|
createUserArtifact(name, content) {
|
|
1648
3327
|
return this.artifactService.storeArtifact(name, content);
|
|
1649
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
|
+
*/
|
|
1650
3336
|
updateUserArtifact(artifactId, content) {
|
|
1651
3337
|
return this.artifactService.updateArtifact(artifactId, content);
|
|
1652
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
|
+
*/
|
|
1653
3362
|
convertUserArtifact(name, pdfBuffer) {
|
|
3363
|
+
// 1. Create placeholder artifact immediately
|
|
1654
3364
|
const placeholderContent = 'Converting PDF. This text will be replaced when the conversion is finished.';
|
|
1655
3365
|
const artifactId = this.artifactService.storeArtifact(name, placeholderContent);
|
|
3366
|
+
// 2. Start async conversion (don't await)
|
|
1656
3367
|
this.convertPdfInBackground(artifactId, name, pdfBuffer).catch((error) => {
|
|
1657
3368
|
logger_1.logger.error(`Background PDF conversion failed for ${artifactId}:`, error);
|
|
3369
|
+
// Update artifact with error message
|
|
1658
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.`;
|
|
1659
3371
|
this.artifactService.updateArtifact(artifactId, errorContent);
|
|
1660
3372
|
});
|
|
3373
|
+
// 3. Return immediately
|
|
1661
3374
|
return artifactId;
|
|
1662
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
|
+
*/
|
|
1663
3405
|
async convertPdfToMarkdownPages(pdfBuffer, options = {}) {
|
|
1664
3406
|
const aiServiceName = options.aiServiceName || process.env.DOC_CONVERSION_AI_SERVICE;
|
|
1665
3407
|
const aiModel = options.aiModel || process.env.DOC_CONVERSION_AI_MODEL;
|
|
@@ -1673,6 +3415,9 @@ class AppService {
|
|
|
1673
3415
|
const promptFile = options.promptFile || 'convert_pdf_page';
|
|
1674
3416
|
const finishAgents = options.finishAgents !== false;
|
|
1675
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.
|
|
1676
3421
|
const agent = this.agentFactory.createAgent(aiServiceName, options.agentName || 'PDF Converter', '', `Converts page ${pageNum} of ${pageCount} to Markdown`, promptFolder, aiModel);
|
|
1677
3422
|
if (options.reasoningEffort !== undefined) {
|
|
1678
3423
|
agent.reasoningEffort = options.reasoningEffort;
|
|
@@ -1682,6 +3427,8 @@ class AppService {
|
|
|
1682
3427
|
await agent.attachDocument(fileName, pageBuffer);
|
|
1683
3428
|
const response = await agent.preparedPrompt(promptFile, {
|
|
1684
3429
|
fileName,
|
|
3430
|
+
// Both spellings, so a caller pointing at its own prompt
|
|
3431
|
+
// folder does not have to match Briyah's variable names.
|
|
1685
3432
|
pageNum,
|
|
1686
3433
|
pageNumber: pageNum,
|
|
1687
3434
|
pageCount,
|
|
@@ -1705,6 +3452,13 @@ class AppService {
|
|
|
1705
3452
|
const result = await (0, pdf_conversion_1.convertPdfToMarkdown)(pdfBuffer, renderPage, options);
|
|
1706
3453
|
return result;
|
|
1707
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
|
+
*/
|
|
1708
3462
|
async convertWholePdf(name, pdfBuffer) {
|
|
1709
3463
|
const limits = (0, pdf_conversion_1.conversionLimits)();
|
|
1710
3464
|
let lastError = 'the conversion returned nothing';
|
|
@@ -1731,6 +3485,17 @@ class AppService {
|
|
|
1731
3485
|
}
|
|
1732
3486
|
throw new Error(`The PDF conversion produced no content after ${limits.attempts} attempts: ${lastError}`);
|
|
1733
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
|
+
*/
|
|
1734
3499
|
async convertPdfInBackground(artifactId, name, pdfBuffer) {
|
|
1735
3500
|
logger_1.logger.log(`Starting background PDF conversion for artifact ${artifactId}`);
|
|
1736
3501
|
if (!process.env.DOC_CONVERSION_AI_SERVICE)
|
|
@@ -1756,23 +3521,70 @@ class AppService {
|
|
|
1756
3521
|
`${result.failedPages.length} failed${result.failedPages.length ? `: ${result.failedPages.join(', ')}` : ''}), ` +
|
|
1757
3522
|
`Output: ${result.markdown.length} chars (total cost: $${result.totalCost.toFixed(4)})`);
|
|
1758
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
|
+
*/
|
|
1759
3531
|
renameUserArtifact(artifactId, newName) {
|
|
1760
3532
|
return this.artifactService.renameArtifact(artifactId, newName);
|
|
1761
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
|
+
*/
|
|
1762
3542
|
deleteUserArtifact(artifactId) {
|
|
1763
3543
|
return this.artifactService.deleteArtifact(artifactId);
|
|
1764
3544
|
}
|
|
3545
|
+
/**
|
|
3546
|
+
* Gets the artifact service for a story
|
|
3547
|
+
* @param storyId The story ID
|
|
3548
|
+
* @returns The story-specific artifact service
|
|
3549
|
+
*/
|
|
1765
3550
|
getStoryArtifactService(storyId) {
|
|
1766
3551
|
return this.storyService.getStoryArtifactService(storyId);
|
|
1767
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
|
+
*/
|
|
1768
3562
|
listStoryArtifacts(storyId) {
|
|
1769
3563
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1770
3564
|
return storyArtifactService.listArtifacts();
|
|
1771
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
|
+
*/
|
|
1772
3573
|
getStoryArtifact(storyId, artifactId) {
|
|
1773
3574
|
const storyArtifactService = this.getStoryArtifactService(storyId);
|
|
1774
3575
|
return storyArtifactService.getArtifact(artifactId);
|
|
1775
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
|
+
*/
|
|
1776
3588
|
async listAgentArtifacts(agentId) {
|
|
1777
3589
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1778
3590
|
if (!agent) {
|
|
@@ -1782,11 +3594,22 @@ class AppService {
|
|
|
1782
3594
|
const allArtifacts = this.artifactService.listArtifacts();
|
|
1783
3595
|
return allArtifacts.filter((a) => artifactIds.includes(a.artifactId));
|
|
1784
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
|
+
*/
|
|
1785
3607
|
async attachArtifactToAgent(agentId, artifactId) {
|
|
1786
3608
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1787
3609
|
if (!agent) {
|
|
1788
3610
|
throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
|
|
1789
3611
|
}
|
|
3612
|
+
// Verify artifact exists
|
|
1790
3613
|
const artifact = this.artifactService.getArtifactMetadata(artifactId);
|
|
1791
3614
|
if (!artifact) {
|
|
1792
3615
|
throw new errors_1.NotFoundError(`Artifact ${artifactId} not found`);
|
|
@@ -1794,6 +3617,16 @@ class AppService {
|
|
|
1794
3617
|
agent.attachArtifact(artifactId);
|
|
1795
3618
|
agent.save();
|
|
1796
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
|
+
*/
|
|
1797
3630
|
async detachArtifactFromAgent(agentId, artifactId) {
|
|
1798
3631
|
const agent = await this.agentStore.getAgent(agentId);
|
|
1799
3632
|
if (!agent) {
|