briyah 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/.prettierrc +7 -0
  2. package/dist/ai/LLM/anthropic.module.d.ts +2 -0
  3. package/dist/ai/LLM/anthropic.module.js +21 -0
  4. package/dist/ai/LLM/anthropic.service.d.ts +27 -0
  5. package/dist/ai/LLM/anthropic.service.js +329 -0
  6. package/dist/ai/LLM/base-ai.service.d.ts +45 -0
  7. package/dist/ai/LLM/base-ai.service.js +409 -0
  8. package/dist/ai/LLM/deepseek.module.d.ts +2 -0
  9. package/dist/ai/LLM/deepseek.module.js +21 -0
  10. package/dist/ai/LLM/deepseek.service.d.ts +15 -0
  11. package/dist/ai/LLM/deepseek.service.js +279 -0
  12. package/dist/ai/LLM/fal.module.d.ts +2 -0
  13. package/dist/ai/LLM/fal.module.js +21 -0
  14. package/dist/ai/LLM/fal.service.d.ts +17 -0
  15. package/dist/ai/LLM/fal.service.js +314 -0
  16. package/dist/ai/LLM/googleai.module.d.ts +2 -0
  17. package/dist/ai/LLM/googleai.module.js +21 -0
  18. package/dist/ai/LLM/googleai.service.d.ts +20 -0
  19. package/dist/ai/LLM/googleai.service.js +271 -0
  20. package/dist/ai/LLM/grok.module.d.ts +2 -0
  21. package/dist/ai/LLM/grok.module.js +21 -0
  22. package/dist/ai/LLM/grok.service.d.ts +14 -0
  23. package/dist/ai/LLM/grok.service.js +263 -0
  24. package/dist/ai/LLM/mock.module.d.ts +2 -0
  25. package/dist/ai/LLM/mock.module.js +21 -0
  26. package/dist/ai/LLM/mock.service.d.ts +13 -0
  27. package/dist/ai/LLM/mock.service.js +194 -0
  28. package/dist/ai/LLM/openai.module.d.ts +2 -0
  29. package/dist/ai/LLM/openai.module.js +21 -0
  30. package/dist/ai/LLM/openai.service.d.ts +21 -0
  31. package/dist/ai/LLM/openai.service.js +421 -0
  32. package/dist/ai/LLM/together.module.d.ts +2 -0
  33. package/dist/ai/LLM/together.module.js +21 -0
  34. package/dist/ai/LLM/together.service.d.ts +18 -0
  35. package/dist/ai/LLM/together.service.js +285 -0
  36. package/dist/ai/LLM/vertexai.module.d.ts +2 -0
  37. package/dist/ai/LLM/vertexai.module.js +21 -0
  38. package/dist/ai/LLM/vertexai.service.d.ts +17 -0
  39. package/dist/ai/LLM/vertexai.service.js +323 -0
  40. package/dist/ai/agent-config.d.ts +32 -0
  41. package/dist/ai/agent-config.js +2 -0
  42. package/dist/ai/agent-factory.d.ts +15 -0
  43. package/dist/ai/agent-factory.js +24 -0
  44. package/dist/ai/agent-message.service.d.ts +9 -0
  45. package/dist/ai/agent-message.service.js +56 -0
  46. package/dist/ai/agent-store.module.d.ts +2 -0
  47. package/dist/ai/agent-store.module.js +21 -0
  48. package/dist/ai/agent-store.service.d.ts +31 -0
  49. package/dist/ai/agent-store.service.js +352 -0
  50. package/dist/ai/agent.d.ts +75 -0
  51. package/dist/ai/agent.js +174 -0
  52. package/dist/ai/ai-factory.module.d.ts +2 -0
  53. package/dist/ai/ai-factory.module.js +40 -0
  54. package/dist/ai/ai-factory.service.d.ts +24 -0
  55. package/dist/ai/ai-factory.service.js +94 -0
  56. package/dist/ai/artifact.module.d.ts +2 -0
  57. package/dist/ai/artifact.module.js +22 -0
  58. package/dist/ai/artifact.service.d.ts +21 -0
  59. package/dist/ai/artifact.service.js +239 -0
  60. package/dist/ai/attached-file.module.d.ts +2 -0
  61. package/dist/ai/attached-file.module.js +22 -0
  62. package/dist/ai/attached-file.service.d.ts +35 -0
  63. package/dist/ai/attached-file.service.js +253 -0
  64. package/dist/ai/model_prices.d.ts +2 -0
  65. package/dist/ai/model_prices.js +54 -0
  66. package/dist/ai/published-agents.service.d.ts +13 -0
  67. package/dist/ai/published-agents.service.js +118 -0
  68. package/dist/app/balance-message.service.d.ts +8 -0
  69. package/dist/app/balance-message.service.js +45 -0
  70. package/dist/app/balance.module.d.ts +2 -0
  71. package/dist/app/balance.module.js +20 -0
  72. package/dist/app/balance.service.d.ts +18 -0
  73. package/dist/app/balance.service.js +158 -0
  74. package/dist/app/stripe.controller.d.ts +31 -0
  75. package/dist/app/stripe.controller.js +150 -0
  76. package/dist/app/stripe.module.d.ts +2 -0
  77. package/dist/app/stripe.module.js +22 -0
  78. package/dist/app/stripe.service.d.ts +28 -0
  79. package/dist/app/stripe.service.js +198 -0
  80. package/dist/app/transaction.service.d.ts +15 -0
  81. package/dist/app/transaction.service.js +139 -0
  82. package/dist/app/user-service-factory.d.ts +21 -0
  83. package/dist/app/user-service-factory.js +81 -0
  84. package/dist/app/user-service-manager.d.ts +28 -0
  85. package/dist/app/user-service-manager.js +102 -0
  86. package/dist/app.controller.d.ts +232 -0
  87. package/dist/app.controller.js +2536 -0
  88. package/dist/app.module.d.ts +2 -0
  89. package/dist/app.module.js +45 -0
  90. package/dist/app.service.d.ts +186 -0
  91. package/dist/app.service.js +1334 -0
  92. package/dist/auth/agent-access.decorator.d.ts +2 -0
  93. package/dist/auth/agent-access.decorator.js +10 -0
  94. package/dist/auth/auth.controller.d.ts +38 -0
  95. package/dist/auth/auth.controller.js +356 -0
  96. package/dist/auth/auth.module.d.ts +2 -0
  97. package/dist/auth/auth.module.js +55 -0
  98. package/dist/auth/auth.service.d.ts +14 -0
  99. package/dist/auth/auth.service.js +84 -0
  100. package/dist/auth/dto/bot-login.dto.d.ts +4 -0
  101. package/dist/auth/dto/bot-login.dto.js +2 -0
  102. package/dist/auth/dto/password-reset.dto.d.ts +11 -0
  103. package/dist/auth/dto/password-reset.dto.js +2 -0
  104. package/dist/auth/dto/phone-login.dto.d.ts +8 -0
  105. package/dist/auth/dto/phone-login.dto.js +2 -0
  106. package/dist/auth/dto/phone-verification.dto.d.ts +9 -0
  107. package/dist/auth/dto/phone-verification.dto.js +2 -0
  108. package/dist/auth/jwt-auth.guard.d.ts +13 -0
  109. package/dist/auth/jwt-auth.guard.js +143 -0
  110. package/dist/auth/jwt.strategy.d.ts +17 -0
  111. package/dist/auth/jwt.strategy.js +45 -0
  112. package/dist/auth/phone-validation.service.d.ts +7 -0
  113. package/dist/auth/phone-validation.service.js +50 -0
  114. package/dist/auth/public.decorator.d.ts +2 -0
  115. package/dist/auth/public.decorator.js +7 -0
  116. package/dist/auth/rate-limit.service.d.ts +16 -0
  117. package/dist/auth/rate-limit.service.js +84 -0
  118. package/dist/auth/room-access.decorator.d.ts +2 -0
  119. package/dist/auth/room-access.decorator.js +10 -0
  120. package/dist/auth/scopes.decorator.d.ts +2 -0
  121. package/dist/auth/scopes.decorator.js +7 -0
  122. package/dist/auth/scopes.guard.d.ts +9 -0
  123. package/dist/auth/scopes.guard.js +82 -0
  124. package/dist/auth/session.guard.d.ts +7 -0
  125. package/dist/auth/session.guard.js +55 -0
  126. package/dist/auth/twilio.service.d.ts +15 -0
  127. package/dist/auth/twilio.service.js +139 -0
  128. package/dist/auth/users.service.d.ts +24 -0
  129. package/dist/auth/users.service.js +149 -0
  130. package/dist/common/errors.d.ts +12 -0
  131. package/dist/common/errors.js +43 -0
  132. package/dist/config/configuration.module.d.ts +2 -0
  133. package/dist/config/configuration.module.js +20 -0
  134. package/dist/config/configuration.service.d.ts +26 -0
  135. package/dist/config/configuration.service.js +131 -0
  136. package/dist/main.js +15749 -0
  137. package/dist/room/artifact-store.service.d.ts +15 -0
  138. package/dist/room/artifact-store.service.js +226 -0
  139. package/dist/room/artifact.d.ts +6 -0
  140. package/dist/room/artifact.js +2 -0
  141. package/dist/room/message.d.ts +19 -0
  142. package/dist/room/message.js +70 -0
  143. package/dist/room/published-rooms.service.d.ts +12 -0
  144. package/dist/room/published-rooms.service.js +108 -0
  145. package/dist/room/room-config.d.ts +12 -0
  146. package/dist/room/room-config.js +2 -0
  147. package/dist/room/room-factory.d.ts +7 -0
  148. package/dist/room/room-factory.js +16 -0
  149. package/dist/room/room-message.module.d.ts +2 -0
  150. package/dist/room/room-message.module.js +21 -0
  151. package/dist/room/room-message.service.d.ts +8 -0
  152. package/dist/room/room-message.service.js +44 -0
  153. package/dist/room/room-store.module.d.ts +2 -0
  154. package/dist/room/room-store.module.js +25 -0
  155. package/dist/room/room-store.service.d.ts +38 -0
  156. package/dist/room/room-store.service.js +353 -0
  157. package/dist/room/room.d.ts +107 -0
  158. package/dist/room/room.js +833 -0
  159. package/dist/sdk/briyah-config.d.ts +13 -0
  160. package/dist/sdk/briyah-config.js +32 -0
  161. package/dist/sdk/briyah.d.ts +36 -0
  162. package/dist/sdk/briyah.js +122 -0
  163. package/dist/sdk/index.d.ts +6 -0
  164. package/dist/sdk/index.js +11 -0
  165. package/dist/server/src/ai/LLM/anthropic.module.d.ts +2 -0
  166. package/dist/server/src/ai/LLM/anthropic.module.js +21 -0
  167. package/dist/server/src/ai/LLM/anthropic.service.d.ts +27 -0
  168. package/dist/server/src/ai/LLM/anthropic.service.js +329 -0
  169. package/dist/server/src/ai/LLM/base-ai.service.d.ts +45 -0
  170. package/dist/server/src/ai/LLM/base-ai.service.js +409 -0
  171. package/dist/server/src/ai/LLM/deepseek.module.d.ts +2 -0
  172. package/dist/server/src/ai/LLM/deepseek.module.js +21 -0
  173. package/dist/server/src/ai/LLM/deepseek.service.d.ts +15 -0
  174. package/dist/server/src/ai/LLM/deepseek.service.js +279 -0
  175. package/dist/server/src/ai/LLM/fal.module.d.ts +2 -0
  176. package/dist/server/src/ai/LLM/fal.module.js +21 -0
  177. package/dist/server/src/ai/LLM/fal.service.d.ts +17 -0
  178. package/dist/server/src/ai/LLM/fal.service.js +314 -0
  179. package/dist/server/src/ai/LLM/googleai.module.d.ts +2 -0
  180. package/dist/server/src/ai/LLM/googleai.module.js +21 -0
  181. package/dist/server/src/ai/LLM/googleai.service.d.ts +20 -0
  182. package/dist/server/src/ai/LLM/googleai.service.js +271 -0
  183. package/dist/server/src/ai/LLM/grok.module.d.ts +2 -0
  184. package/dist/server/src/ai/LLM/grok.module.js +21 -0
  185. package/dist/server/src/ai/LLM/grok.service.d.ts +14 -0
  186. package/dist/server/src/ai/LLM/grok.service.js +263 -0
  187. package/dist/server/src/ai/LLM/mock.module.d.ts +2 -0
  188. package/dist/server/src/ai/LLM/mock.module.js +21 -0
  189. package/dist/server/src/ai/LLM/mock.service.d.ts +13 -0
  190. package/dist/server/src/ai/LLM/mock.service.js +194 -0
  191. package/dist/server/src/ai/LLM/openai.module.d.ts +2 -0
  192. package/dist/server/src/ai/LLM/openai.module.js +21 -0
  193. package/dist/server/src/ai/LLM/openai.service.d.ts +21 -0
  194. package/dist/server/src/ai/LLM/openai.service.js +421 -0
  195. package/dist/server/src/ai/LLM/together.module.d.ts +2 -0
  196. package/dist/server/src/ai/LLM/together.module.js +21 -0
  197. package/dist/server/src/ai/LLM/together.service.d.ts +18 -0
  198. package/dist/server/src/ai/LLM/together.service.js +285 -0
  199. package/dist/server/src/ai/LLM/vertexai.module.d.ts +2 -0
  200. package/dist/server/src/ai/LLM/vertexai.module.js +21 -0
  201. package/dist/server/src/ai/LLM/vertexai.service.d.ts +17 -0
  202. package/dist/server/src/ai/LLM/vertexai.service.js +323 -0
  203. package/dist/server/src/ai/agent-config.d.ts +32 -0
  204. package/dist/server/src/ai/agent-config.js +2 -0
  205. package/dist/server/src/ai/agent-factory.d.ts +15 -0
  206. package/dist/server/src/ai/agent-factory.js +24 -0
  207. package/dist/server/src/ai/agent-message.service.d.ts +9 -0
  208. package/dist/server/src/ai/agent-message.service.js +56 -0
  209. package/dist/server/src/ai/agent-store.module.d.ts +2 -0
  210. package/dist/server/src/ai/agent-store.module.js +21 -0
  211. package/dist/server/src/ai/agent-store.service.d.ts +31 -0
  212. package/dist/server/src/ai/agent-store.service.js +352 -0
  213. package/dist/server/src/ai/agent.d.ts +75 -0
  214. package/dist/server/src/ai/agent.js +174 -0
  215. package/dist/server/src/ai/ai-factory.module.d.ts +2 -0
  216. package/dist/server/src/ai/ai-factory.module.js +40 -0
  217. package/dist/server/src/ai/ai-factory.service.d.ts +24 -0
  218. package/dist/server/src/ai/ai-factory.service.js +94 -0
  219. package/dist/server/src/ai/artifact.module.d.ts +2 -0
  220. package/dist/server/src/ai/artifact.module.js +22 -0
  221. package/dist/server/src/ai/artifact.service.d.ts +21 -0
  222. package/dist/server/src/ai/artifact.service.js +239 -0
  223. package/dist/server/src/ai/attached-file.module.d.ts +2 -0
  224. package/dist/server/src/ai/attached-file.module.js +22 -0
  225. package/dist/server/src/ai/attached-file.service.d.ts +35 -0
  226. package/dist/server/src/ai/attached-file.service.js +253 -0
  227. package/dist/server/src/ai/model_prices.d.ts +2 -0
  228. package/dist/server/src/ai/model_prices.js +54 -0
  229. package/dist/server/src/ai/published-agents.service.d.ts +13 -0
  230. package/dist/server/src/ai/published-agents.service.js +118 -0
  231. package/dist/server/src/app/balance-message.service.d.ts +8 -0
  232. package/dist/server/src/app/balance-message.service.js +45 -0
  233. package/dist/server/src/app/balance.module.d.ts +2 -0
  234. package/dist/server/src/app/balance.module.js +20 -0
  235. package/dist/server/src/app/balance.service.d.ts +18 -0
  236. package/dist/server/src/app/balance.service.js +158 -0
  237. package/dist/server/src/app/stripe.controller.d.ts +31 -0
  238. package/dist/server/src/app/stripe.controller.js +148 -0
  239. package/dist/server/src/app/stripe.module.d.ts +2 -0
  240. package/dist/server/src/app/stripe.module.js +22 -0
  241. package/dist/server/src/app/stripe.service.d.ts +28 -0
  242. package/dist/server/src/app/stripe.service.js +198 -0
  243. package/dist/server/src/app/transaction.service.d.ts +15 -0
  244. package/dist/server/src/app/transaction.service.js +139 -0
  245. package/dist/server/src/app/user-service-factory.d.ts +21 -0
  246. package/dist/server/src/app/user-service-factory.js +81 -0
  247. package/dist/server/src/app/user-service-manager.d.ts +28 -0
  248. package/dist/server/src/app/user-service-manager.js +102 -0
  249. package/dist/server/src/app.controller.d.ts +232 -0
  250. package/dist/server/src/app.controller.js +2534 -0
  251. package/dist/server/src/app.module.d.ts +2 -0
  252. package/dist/server/src/app.module.js +45 -0
  253. package/dist/server/src/app.service.d.ts +186 -0
  254. package/dist/server/src/app.service.js +1334 -0
  255. package/dist/server/src/auth/agent-access.decorator.d.ts +2 -0
  256. package/dist/server/src/auth/agent-access.decorator.js +10 -0
  257. package/dist/server/src/auth/auth.controller.d.ts +38 -0
  258. package/dist/server/src/auth/auth.controller.js +356 -0
  259. package/dist/server/src/auth/auth.module.d.ts +2 -0
  260. package/dist/server/src/auth/auth.module.js +55 -0
  261. package/dist/server/src/auth/auth.service.d.ts +14 -0
  262. package/dist/server/src/auth/auth.service.js +84 -0
  263. package/dist/server/src/auth/dto/bot-login.dto.d.ts +4 -0
  264. package/dist/server/src/auth/dto/bot-login.dto.js +2 -0
  265. package/dist/server/src/auth/dto/password-reset.dto.d.ts +11 -0
  266. package/dist/server/src/auth/dto/password-reset.dto.js +2 -0
  267. package/dist/server/src/auth/dto/phone-login.dto.d.ts +8 -0
  268. package/dist/server/src/auth/dto/phone-login.dto.js +2 -0
  269. package/dist/server/src/auth/dto/phone-verification.dto.d.ts +9 -0
  270. package/dist/server/src/auth/dto/phone-verification.dto.js +2 -0
  271. package/dist/server/src/auth/jwt-auth.guard.d.ts +13 -0
  272. package/dist/server/src/auth/jwt-auth.guard.js +143 -0
  273. package/dist/server/src/auth/jwt.strategy.d.ts +17 -0
  274. package/dist/server/src/auth/jwt.strategy.js +45 -0
  275. package/dist/server/src/auth/phone-validation.service.d.ts +7 -0
  276. package/dist/server/src/auth/phone-validation.service.js +50 -0
  277. package/dist/server/src/auth/public.decorator.d.ts +2 -0
  278. package/dist/server/src/auth/public.decorator.js +7 -0
  279. package/dist/server/src/auth/rate-limit.service.d.ts +16 -0
  280. package/dist/server/src/auth/rate-limit.service.js +84 -0
  281. package/dist/server/src/auth/room-access.decorator.d.ts +2 -0
  282. package/dist/server/src/auth/room-access.decorator.js +10 -0
  283. package/dist/server/src/auth/scopes.decorator.d.ts +2 -0
  284. package/dist/server/src/auth/scopes.decorator.js +7 -0
  285. package/dist/server/src/auth/scopes.guard.d.ts +9 -0
  286. package/dist/server/src/auth/scopes.guard.js +82 -0
  287. package/dist/server/src/auth/session.guard.d.ts +7 -0
  288. package/dist/server/src/auth/session.guard.js +55 -0
  289. package/dist/server/src/auth/twilio.service.d.ts +15 -0
  290. package/dist/server/src/auth/twilio.service.js +139 -0
  291. package/dist/server/src/auth/users.service.d.ts +24 -0
  292. package/dist/server/src/auth/users.service.js +149 -0
  293. package/dist/server/src/common/errors.d.ts +12 -0
  294. package/dist/server/src/common/errors.js +43 -0
  295. package/dist/server/src/config/configuration.module.d.ts +2 -0
  296. package/dist/server/src/config/configuration.module.js +20 -0
  297. package/dist/server/src/config/configuration.service.d.ts +26 -0
  298. package/dist/server/src/config/configuration.service.js +131 -0
  299. package/dist/server/src/room/artifact-store.service.d.ts +15 -0
  300. package/dist/server/src/room/artifact-store.service.js +226 -0
  301. package/dist/server/src/room/artifact.d.ts +6 -0
  302. package/dist/server/src/room/artifact.js +2 -0
  303. package/dist/server/src/room/message.d.ts +19 -0
  304. package/dist/server/src/room/message.js +70 -0
  305. package/dist/server/src/room/published-rooms.service.d.ts +12 -0
  306. package/dist/server/src/room/published-rooms.service.js +108 -0
  307. package/dist/server/src/room/room-config.d.ts +12 -0
  308. package/dist/server/src/room/room-config.js +2 -0
  309. package/dist/server/src/room/room-factory.d.ts +7 -0
  310. package/dist/server/src/room/room-factory.js +16 -0
  311. package/dist/server/src/room/room-message.module.d.ts +2 -0
  312. package/dist/server/src/room/room-message.module.js +21 -0
  313. package/dist/server/src/room/room-message.service.d.ts +8 -0
  314. package/dist/server/src/room/room-message.service.js +44 -0
  315. package/dist/server/src/room/room-store.module.d.ts +2 -0
  316. package/dist/server/src/room/room-store.module.js +25 -0
  317. package/dist/server/src/room/room-store.service.d.ts +38 -0
  318. package/dist/server/src/room/room-store.service.js +353 -0
  319. package/dist/server/src/room/room.d.ts +107 -0
  320. package/dist/server/src/room/room.js +833 -0
  321. package/dist/server/src/sdk/briyah-config.d.ts +13 -0
  322. package/dist/server/src/sdk/briyah-config.js +32 -0
  323. package/dist/server/src/sdk/briyah.d.ts +36 -0
  324. package/dist/server/src/sdk/briyah.js +122 -0
  325. package/dist/server/src/sdk/index.d.ts +6 -0
  326. package/dist/server/src/sdk/index.js +11 -0
  327. package/dist/server/src/shared/shared.module.d.ts +2 -0
  328. package/dist/server/src/shared/shared.module.js +46 -0
  329. package/dist/server/src/story/story-message.service.d.ts +10 -0
  330. package/dist/server/src/story/story-message.service.js +57 -0
  331. package/dist/server/src/story/story-progress.service.d.ts +8 -0
  332. package/dist/server/src/story/story-progress.service.js +44 -0
  333. package/dist/server/src/story/story-store.module.d.ts +2 -0
  334. package/dist/server/src/story/story-store.module.js +22 -0
  335. package/dist/server/src/story/story-store.service.d.ts +23 -0
  336. package/dist/server/src/story/story-store.service.js +392 -0
  337. package/dist/server/src/story/story.service.d.ts +94 -0
  338. package/dist/server/src/story/story.service.js +1797 -0
  339. package/dist/shared/shared.module.d.ts +2 -0
  340. package/dist/shared/shared.module.js +46 -0
  341. package/dist/shared/types/app.types.d.ts +296 -0
  342. package/dist/shared/types/app.types.js +17 -0
  343. package/dist/story/story-message.service.d.ts +10 -0
  344. package/dist/story/story-message.service.js +57 -0
  345. package/dist/story/story-progress.service.d.ts +8 -0
  346. package/dist/story/story-progress.service.js +44 -0
  347. package/dist/story/story-store.module.d.ts +2 -0
  348. package/dist/story/story-store.module.js +22 -0
  349. package/dist/story/story-store.service.d.ts +23 -0
  350. package/dist/story/story-store.service.js +392 -0
  351. package/dist/story/story.service.d.ts +94 -0
  352. package/dist/story/story.service.js +1797 -0
  353. package/eslint.config.js +29 -0
  354. package/package.json +125 -0
@@ -0,0 +1,1334 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.AppService = void 0;
37
+ const errors_1 = require("./common/errors");
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const app_types_1 = require("@shared/types/app.types");
41
+ const pdf_lib_1 = require("pdf-lib");
42
+ const message_1 = require("./room/message");
43
+ class AppService {
44
+ aiFactoryService;
45
+ agentStore;
46
+ agentMessageService;
47
+ roomStore;
48
+ roomMessageService;
49
+ configService;
50
+ attachedFileService;
51
+ artifactService;
52
+ storyStore;
53
+ storyService;
54
+ publishedAgentsService;
55
+ publishedRoomsService;
56
+ balanceService;
57
+ balanceMessageService;
58
+ transactionService;
59
+ agentFactory;
60
+ roomFactory;
61
+ aiServices;
62
+ userPreferencesFile = 'user-preferences.json';
63
+ constructor(aiFactoryService, agentStore, agentMessageService, roomStore, roomMessageService, configService, attachedFileService, artifactService, storyStore, storyService, publishedAgentsService, publishedRoomsService, balanceService, balanceMessageService, transactionService, agentFactory, roomFactory) {
64
+ this.aiFactoryService = aiFactoryService;
65
+ this.agentStore = agentStore;
66
+ this.agentMessageService = agentMessageService;
67
+ this.roomStore = roomStore;
68
+ this.roomMessageService = roomMessageService;
69
+ this.configService = configService;
70
+ this.attachedFileService = attachedFileService;
71
+ this.artifactService = artifactService;
72
+ this.storyStore = storyStore;
73
+ this.storyService = storyService;
74
+ this.publishedAgentsService = publishedAgentsService;
75
+ this.publishedRoomsService = publishedRoomsService;
76
+ this.balanceService = balanceService;
77
+ this.balanceMessageService = balanceMessageService;
78
+ this.transactionService = transactionService;
79
+ this.agentFactory = agentFactory;
80
+ this.roomFactory = roomFactory;
81
+ this.aiServices = this.aiFactoryService.getAllAiServices();
82
+ }
83
+ getAiServiceNames() {
84
+ return this.aiServices.map((s) => s.getServiceName());
85
+ }
86
+ getAiServiceFromServiceName(serviceName) {
87
+ return this.aiFactoryService.createAiService(serviceName);
88
+ }
89
+ async listAiModels(aiServiceName) {
90
+ let service = this.getAiServiceFromServiceName(aiServiceName);
91
+ return service.listModels();
92
+ }
93
+ async listImageModels() {
94
+ const imageModelsPath = path.join(this.configService.getCommonConfigDir(), 'image_models.json');
95
+ try {
96
+ return JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
97
+ }
98
+ catch (error) {
99
+ console.error(`Image models file could not be read from ${imageModelsPath}: `, error);
100
+ return [];
101
+ }
102
+ }
103
+ async listStoryModels() {
104
+ const storyModelsPath = path.join(this.configService.getCommonConfigDir(), 'story_models.json');
105
+ try {
106
+ return JSON.parse(fs.readFileSync(storyModelsPath, 'utf8'));
107
+ }
108
+ catch (error) {
109
+ console.error(`Story models file could not be read from ${storyModelsPath}: `, error);
110
+ return [];
111
+ }
112
+ }
113
+ listStoryGenres() {
114
+ const storyIdeasPath = path.join(this.configService.getDataDir(), 'common', 'story_ideas');
115
+ try {
116
+ if (!fs.existsSync(storyIdeasPath)) {
117
+ console.warn(`Story ideas directory does not exist: ${storyIdeasPath}`);
118
+ return [];
119
+ }
120
+ return fs.readdirSync(storyIdeasPath)
121
+ .filter(file => file.endsWith('.json'))
122
+ .map(file => file.replace('.json', ''));
123
+ }
124
+ catch (error) {
125
+ console.error('Error reading story genres:', error);
126
+ return [];
127
+ }
128
+ }
129
+ getRandomStoryIdeaByGenre(genreName) {
130
+ const storyIdeasPath = path.join(this.configService.getDataDir(), 'common', 'story_ideas', `${genreName}.json`);
131
+ try {
132
+ if (!fs.existsSync(storyIdeasPath)) {
133
+ throw new errors_1.NotFoundError(`Genre "${genreName}" not found`);
134
+ }
135
+ const ideas = JSON.parse(fs.readFileSync(storyIdeasPath, 'utf8'));
136
+ if (ideas.length === 0) {
137
+ return null;
138
+ }
139
+ const randomIndex = Math.floor(Math.random() * ideas.length);
140
+ return ideas[randomIndex];
141
+ }
142
+ catch (error) {
143
+ if (error instanceof errors_1.NotFoundError) {
144
+ throw error;
145
+ }
146
+ console.error(`Error reading story ideas for genre ${genreName}:`, error);
147
+ throw new errors_1.OperationFailedError('Failed to read story ideas');
148
+ }
149
+ }
150
+ getRandomStoryIdea() {
151
+ const genres = this.listStoryGenres();
152
+ if (genres.length === 0) {
153
+ return null;
154
+ }
155
+ const randomGenre = genres[Math.floor(Math.random() * genres.length)];
156
+ return this.getRandomStoryIdeaByGenre(randomGenre);
157
+ }
158
+ createAgent(aiServiceName, agentName, agentNickname, description, aiModel, promptName = 'default', controlledByHuman, reasoningEffort, maxOutputTokens, beginInstruction) {
159
+ const agent = this.agentFactory.createAgent(aiServiceName, agentName, agentNickname, description, promptName, aiModel);
160
+ if (controlledByHuman !== undefined) {
161
+ agent.isControlledByHuman = controlledByHuman;
162
+ }
163
+ if (reasoningEffort !== undefined) {
164
+ agent.reasoningEffort = reasoningEffort;
165
+ }
166
+ if (maxOutputTokens !== undefined) {
167
+ agent.maxOutputTokens = maxOutputTokens;
168
+ }
169
+ if (beginInstruction !== undefined) {
170
+ agent.beginInstruction = beginInstruction;
171
+ }
172
+ this.setupAgentStateCallback(agent);
173
+ return agent;
174
+ }
175
+ async processText(agentId, text) {
176
+ const agent = await this.agentStore.getAgent(agentId);
177
+ if (!agent) {
178
+ throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
179
+ }
180
+ this.setupAgentStateCallback(agent);
181
+ const result = await agent.textPrompt(text, null, true, null, true);
182
+ agent.save();
183
+ const messages = agent.getFormattedMessages();
184
+ return {
185
+ result,
186
+ latestMessage: messages[messages.length - 1],
187
+ messageIndex: messages.length - 1,
188
+ totalInputTokens: agent.totalInputTokens,
189
+ totalOutputTokens: agent.totalOutputTokens,
190
+ totalCost: agent.totalCost,
191
+ };
192
+ }
193
+ async attachDocument(agentId, fileName, fileData) {
194
+ let agent = await this.agentStore.getAgent(agentId);
195
+ if (!agent)
196
+ throw new Error(`Agent with ID ${agentId} not found`);
197
+ const fileId = this.attachedFileService.storeFile(agentId, fileName, new Uint8Array(fileData));
198
+ const fileMetadata = this.attachedFileService.getFileMetadataByName(agentId, fileName);
199
+ if (fileMetadata && !agent.attachedFiles.some((f) => f.fileName === fileName)) {
200
+ agent.attachedFiles.push(fileMetadata);
201
+ }
202
+ await agent.attachDocument(fileName, new Uint8Array(fileData));
203
+ agent.save();
204
+ return { documentId: fileId };
205
+ }
206
+ listPromptFolders() {
207
+ const folders = new Set();
208
+ const commonDir = this.configService.getCommonPromptsDir();
209
+ if (fs.existsSync(commonDir)) {
210
+ fs.readdirSync(commonDir, { withFileTypes: true })
211
+ .filter((dirent) => dirent.isDirectory())
212
+ .forEach((dirent) => folders.add(dirent.name));
213
+ }
214
+ const userDir = this.configService.getUserPromptsDir();
215
+ if (fs.existsSync(userDir)) {
216
+ fs.readdirSync(userDir, { withFileTypes: true })
217
+ .filter((dirent) => dirent.isDirectory())
218
+ .forEach((dirent) => folders.add(dirent.name));
219
+ }
220
+ return Array.from(folders).sort();
221
+ }
222
+ listPromptFoldersWithScope(scope) {
223
+ const folders = [];
224
+ const folderMap = new Map();
225
+ const commonDir = this.configService.getCommonPromptsDir();
226
+ if ((!scope || scope === 'common') && fs.existsSync(commonDir)) {
227
+ fs.readdirSync(commonDir, { withFileTypes: true })
228
+ .filter((dirent) => dirent.isDirectory())
229
+ .forEach((dirent) => {
230
+ folderMap.set(dirent.name, 'common');
231
+ });
232
+ }
233
+ const userDir = this.configService.getUserPromptsDir();
234
+ if ((!scope || scope === 'user') && fs.existsSync(userDir)) {
235
+ fs.readdirSync(userDir, { withFileTypes: true })
236
+ .filter((dirent) => dirent.isDirectory())
237
+ .forEach((dirent) => {
238
+ folderMap.set(dirent.name, 'user');
239
+ });
240
+ }
241
+ folderMap.forEach((folderScope, name) => {
242
+ folders.push({ name, scope: folderScope });
243
+ });
244
+ folders.sort((a, b) => a.name.localeCompare(b.name));
245
+ return { folders };
246
+ }
247
+ async listPrompts(agentId) {
248
+ const agent = await this.agentStore.getAgent(agentId);
249
+ if (!agent) {
250
+ throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
251
+ }
252
+ let agentPromptsDir = path.join(this.configService.getPromptsDir(), agent.promptFolder);
253
+ let promptFiles = [];
254
+ if (fs.existsSync(agentPromptsDir)) {
255
+ promptFiles = fs
256
+ .readdirSync(agentPromptsDir)
257
+ .filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
258
+ .map((file) => file.replace('.prompt', ''));
259
+ }
260
+ const rootPromptFiles = fs
261
+ .readdirSync(this.configService.getPromptsDir())
262
+ .filter((file) => file.endsWith('.prompt') && file !== 'system_instruction.prompt')
263
+ .map((file) => file.replace('.prompt', ''));
264
+ promptFiles = [...new Set([...promptFiles, ...rootPromptFiles])];
265
+ return promptFiles;
266
+ }
267
+ async runPreparedPrompt(agentId, promptName, variables = {}) {
268
+ const agent = await this.agentStore.getAgent(agentId);
269
+ if (!agent) {
270
+ throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
271
+ }
272
+ const serviceName = agent.serviceName;
273
+ let service = this.getAiServiceFromServiceName(serviceName);
274
+ const result = await service.preparedPrompt(agent, promptName, variables || {}, true);
275
+ return { result };
276
+ }
277
+ async listAgents() {
278
+ const agentIds = await this.agentStore.getAllAgentIds();
279
+ const agentInfos = [];
280
+ for (const id of agentIds) {
281
+ const agent = await this.agentStore.getAgent(id);
282
+ if (agent) {
283
+ if (agent.ownerRoomId)
284
+ continue;
285
+ agentInfos.push({
286
+ id,
287
+ name: agent.agentName,
288
+ agentNickname: agent.agentNickname,
289
+ description: agent.description,
290
+ aiService: agent.serviceName,
291
+ aiModel: agent.modelName,
292
+ promptFolder: agent.promptFolder,
293
+ reasoningEffort: agent.reasoningEffort,
294
+ allowSearch: agent.allowSearch,
295
+ maxOutputTokens: agent.maxOutputTokens,
296
+ controlledByHuman: agent.isControlledByHuman,
297
+ totalInputTokens: agent.totalInputTokens,
298
+ totalOutputTokens: agent.totalOutputTokens,
299
+ totalCost: agent.totalCost,
300
+ isPublished: agent.isPublished,
301
+ beginInstruction: agent.beginInstruction,
302
+ });
303
+ }
304
+ }
305
+ return agentInfos;
306
+ }
307
+ async getAgentDetails(agentId) {
308
+ try {
309
+ const agent = await this.agentStore.getAgent(agentId);
310
+ if (!agent) {
311
+ return null;
312
+ }
313
+ return {
314
+ id: agentId,
315
+ name: agent.agentName,
316
+ agentNickname: agent.agentNickname,
317
+ description: agent.description,
318
+ aiService: agent.serviceName,
319
+ aiModel: agent.modelName,
320
+ promptFolder: agent.promptFolder,
321
+ reasoningEffort: agent.reasoningEffort,
322
+ allowSearch: agent.allowSearch,
323
+ maxOutputTokens: agent.maxOutputTokens,
324
+ controlledByHuman: agent.isControlledByHuman,
325
+ totalInputTokens: agent.totalInputTokens,
326
+ totalOutputTokens: agent.totalOutputTokens,
327
+ totalCost: agent.totalCost,
328
+ isPublished: agent.isPublished,
329
+ beginInstruction: agent.beginInstruction,
330
+ };
331
+ }
332
+ catch (error) {
333
+ console.error('Error getting agent details:', error);
334
+ return null;
335
+ }
336
+ }
337
+ async createRoom(roomName, goal, agentIds) {
338
+ for (const agentId of agentIds) {
339
+ const agent = await this.agentStore.getAgent(agentId);
340
+ if (!agent) {
341
+ throw new errors_1.NotFoundError(`Agent with ID ${agentId} not found`);
342
+ }
343
+ }
344
+ const room = this.roomFactory.createRoom(roomName, goal);
345
+ for (const agentId of agentIds) {
346
+ const agent = await this.agentStore.getAgent(agentId);
347
+ room.arrive(agent);
348
+ }
349
+ room.ready();
350
+ const roomId = room.saveMetadata();
351
+ this.setupRoomStateCallback(room);
352
+ return { roomId };
353
+ }
354
+ async editRoom(roomId, roomName, goal, baseRoomDir, agentIds = []) {
355
+ const room = await this.roomStore.getRoom(roomId);
356
+ if (!room) {
357
+ throw new errors_1.NotFoundError('Room not found');
358
+ }
359
+ if (room.getIsPublished() && room.getTemplateRoomId()) {
360
+ throw new errors_1.OperationFailedError('Cannot edit published room instances');
361
+ }
362
+ room.setName(roomName);
363
+ room.setGoal(goal);
364
+ room.setBaseRoomDir(baseRoomDir || '');
365
+ const newAgents = [];
366
+ for (const agentId of agentIds) {
367
+ const agent = await this.agentStore.getAgent(agentId);
368
+ if (agent) {
369
+ newAgents.push(agent);
370
+ }
371
+ else {
372
+ console.warn(`Agent ${agentId} not found when editing room ${roomName}`);
373
+ }
374
+ }
375
+ room.setAgents(newAgents);
376
+ room.saveMetadata();
377
+ }
378
+ async listRooms() {
379
+ return await this.roomStore.getAllRooms();
380
+ }
381
+ async getRoomDetails(roomId) {
382
+ const room = await this.roomStore.getRoom(roomId);
383
+ if (!room) {
384
+ return null;
385
+ }
386
+ const roomAgents = room.getAgents();
387
+ const agents = [];
388
+ for (const agent of roomAgents) {
389
+ const agentDetails = await this.getAgentDetails(agent.id);
390
+ if (agentDetails) {
391
+ agents.push(agentDetails);
392
+ }
393
+ }
394
+ return {
395
+ id: roomId,
396
+ name: room.getName(),
397
+ goal: room.getGoal(),
398
+ agentIds: roomAgents.map((agent) => agent.id),
399
+ agents,
400
+ baseRoomDir: room.getBaseRoomDir(),
401
+ isPublished: room.getIsPublished(),
402
+ };
403
+ }
404
+ async getRoomById(roomId) {
405
+ return await this.roomStore.getRoom(roomId);
406
+ }
407
+ async getRoomMessages(roomId, fromIndex = 0, includeThoughts = false) {
408
+ const room = await this.roomStore.getRoom(roomId);
409
+ if (!room) {
410
+ return {
411
+ messages: [],
412
+ totalCost: 0,
413
+ };
414
+ }
415
+ const indexedMessages = room.getLatestRoomMessages(fromIndex, includeThoughts);
416
+ const totalCost = room
417
+ .getAgents()
418
+ .map((a) => a.totalCost)
419
+ .reduce((acc, v) => acc + v, 0);
420
+ return {
421
+ messages: indexedMessages,
422
+ totalCost: totalCost,
423
+ };
424
+ }
425
+ async getAgentMessages(agentId, fromIndex = 0) {
426
+ const agent = await this.agentStore.getAgent(agentId);
427
+ if (!agent) {
428
+ return {
429
+ messages: [],
430
+ totalOutputTokens: 0,
431
+ totalInputTokens: 0,
432
+ totalCost: 0,
433
+ };
434
+ }
435
+ this.setupAgentStateCallback(agent);
436
+ const formattedMessages = agent.getFormattedMessages(fromIndex);
437
+ return {
438
+ messages: formattedMessages,
439
+ totalOutputTokens: agent.totalOutputTokens,
440
+ totalInputTokens: agent.totalInputTokens,
441
+ totalCost: agent.totalCost,
442
+ };
443
+ }
444
+ async getStoryMessages(storyId, fromIndex) {
445
+ const story = this.storyStore.getStory(storyId);
446
+ if (!story) {
447
+ return { messages: [], totalCost: 0 };
448
+ }
449
+ const room = await this.roomStore.getRoom(story.roomId);
450
+ if (!room) {
451
+ return { messages: [], totalCost: 0 };
452
+ }
453
+ const messages = room.getLatestRoomMessages(fromIndex, true);
454
+ const totalCost = story.totalCost || 0;
455
+ return { messages, totalCost };
456
+ }
457
+ async sendRoomMessage(roomId, content, sender, action = 'moderate', targets = [], clearQueue = false) {
458
+ const room = await this.roomStore.getRoom(roomId);
459
+ if (!room) {
460
+ throw new errors_1.NotFoundError('Room not found');
461
+ }
462
+ let messageAction;
463
+ switch (action.toLowerCase()) {
464
+ case 'moderate':
465
+ messageAction = app_types_1.MessageAction.MODERATE;
466
+ break;
467
+ case 'whisper':
468
+ messageAction = app_types_1.MessageAction.WHISPER;
469
+ break;
470
+ case 'shout':
471
+ messageAction = app_types_1.MessageAction.SHOUT;
472
+ break;
473
+ case 'think':
474
+ messageAction = app_types_1.MessageAction.THINK;
475
+ break;
476
+ default:
477
+ messageAction = app_types_1.MessageAction.SPEAK;
478
+ }
479
+ room.ready();
480
+ room.addPendingMessage(new message_1.RoomMessage(sender, messageAction, content, targets), clearQueue);
481
+ }
482
+ async pauseRoom(roomId) {
483
+ const room = await this.roomStore.getRoom(roomId);
484
+ if (!room) {
485
+ throw new errors_1.NotFoundError('Room not found');
486
+ }
487
+ room.pause();
488
+ }
489
+ async resumeRoom(roomId) {
490
+ const room = await this.roomStore.getRoom(roomId);
491
+ if (!room) {
492
+ throw new errors_1.NotFoundError('Room not found');
493
+ }
494
+ room.resume();
495
+ }
496
+ async deleteAgent(agentId) {
497
+ const agent = await this.agentStore.getAgent(agentId);
498
+ if (!agent) {
499
+ throw new errors_1.NotFoundError('Agent not found');
500
+ }
501
+ if (agent.isPublished) {
502
+ this.publishedAgentsService.removePublishedAgent(agentId);
503
+ }
504
+ await agent.deleteAgent();
505
+ }
506
+ async publishAgentInstance(templateId, instanceName) {
507
+ const template = await this.agentStore.getAgent(templateId);
508
+ if (!template) {
509
+ throw new errors_1.NotFoundError('Template agent not found');
510
+ }
511
+ const userId = this.configService.getUserId();
512
+ const instanceId = await this.agentStore.cloneAgentAsPublished(templateId, instanceName, userId);
513
+ this.publishedAgentsService.addPublishedAgent(instanceId, userId);
514
+ return {
515
+ instanceId,
516
+ publicUrl: `/public/agents/${instanceId}`,
517
+ };
518
+ }
519
+ async getPublishedInstances(templateId) {
520
+ const instances = await this.agentStore.getPublishedInstances(templateId);
521
+ return instances.map((agent) => ({
522
+ id: agent.id,
523
+ name: agent.agentName,
524
+ agentNickname: agent.agentNickname,
525
+ description: agent.description,
526
+ aiService: agent.serviceName,
527
+ aiModel: agent.modelName,
528
+ promptFolder: agent.promptFolder,
529
+ reasoningEffort: agent.reasoningEffort,
530
+ allowSearch: agent.allowSearch,
531
+ maxOutputTokens: agent.maxOutputTokens,
532
+ controlledByHuman: agent.isControlledByHuman,
533
+ totalInputTokens: agent.totalInputTokens,
534
+ totalOutputTokens: agent.totalOutputTokens,
535
+ totalCost: agent.totalCost,
536
+ isPublished: agent.isPublished,
537
+ beginInstruction: agent.beginInstruction,
538
+ }));
539
+ }
540
+ async resetPublishedInstance(instanceId) {
541
+ const instance = await this.agentStore.getAgent(instanceId);
542
+ if (!instance) {
543
+ throw new errors_1.NotFoundError('Instance agent not found');
544
+ }
545
+ if (!instance.templateAgentId) {
546
+ throw new errors_1.OperationFailedError('Agent is not a published instance');
547
+ }
548
+ await this.agentStore.resetPublishedInstance(instanceId, instance.templateAgentId);
549
+ }
550
+ async listPublishedAgents() {
551
+ const agentIds = await this.agentStore.getAllAgentIds();
552
+ const agents = [];
553
+ for (const id of agentIds) {
554
+ const agent = await this.agentStore.getAgent(id);
555
+ if (agent && agent.isPublished && !agent.ownerRoomId) {
556
+ agents.push({
557
+ id: agent.id,
558
+ name: agent.agentName,
559
+ agentNickname: agent.agentNickname,
560
+ description: agent.description,
561
+ aiService: agent.serviceName,
562
+ aiModel: agent.modelName,
563
+ promptFolder: agent.promptFolder,
564
+ reasoningEffort: agent.reasoningEffort,
565
+ allowSearch: agent.allowSearch,
566
+ maxOutputTokens: agent.maxOutputTokens,
567
+ controlledByHuman: agent.isControlledByHuman,
568
+ totalInputTokens: agent.totalInputTokens,
569
+ totalOutputTokens: agent.totalOutputTokens,
570
+ totalCost: agent.totalCost,
571
+ isPublished: agent.isPublished,
572
+ beginInstruction: agent.beginInstruction,
573
+ });
574
+ }
575
+ }
576
+ return agents;
577
+ }
578
+ async deleteRoom(roomId) {
579
+ const room = await this.roomStore.getRoom(roomId);
580
+ if (!room) {
581
+ throw new errors_1.NotFoundError('Room not found');
582
+ }
583
+ const isPublishedInstance = !!(room.getIsPublished() && room.getTemplateRoomId());
584
+ const isTemplate = !room.getTemplateRoomId();
585
+ if (isTemplate) {
586
+ const instances = await this.roomStore.getPublishedInstances(roomId);
587
+ for (const instance of instances) {
588
+ await this.deleteRoom(instance.getId());
589
+ }
590
+ }
591
+ this.attachedFileService.deleteAllFiles(roomId);
592
+ if (room.getIsPublished()) {
593
+ this.publishedRoomsService.removePublishedRoom(roomId);
594
+ }
595
+ const removed = this.roomStore.removeRoom(roomId, undefined, isPublishedInstance);
596
+ if (!removed) {
597
+ throw new errors_1.OperationFailedError('Failed to delete room');
598
+ }
599
+ }
600
+ async publishRoom(templateId, publishedName, userId) {
601
+ const template = await this.roomStore.getRoom(templateId);
602
+ if (!template) {
603
+ throw new errors_1.NotFoundError('Template room not found');
604
+ }
605
+ const instanceId = await this.roomStore.cloneRoomAsPublished(templateId, publishedName || template.getName(), userId);
606
+ this.publishedRoomsService.addPublishedRoom(instanceId, userId);
607
+ return instanceId;
608
+ }
609
+ async getPublishedRoomInstances(templateId) {
610
+ const instances = await this.roomStore.getPublishedInstances(templateId);
611
+ return instances.map((room) => ({
612
+ id: room.getId(),
613
+ name: room.getName(),
614
+ goal: room.getGoal(),
615
+ agentCount: room.getAgentCount(),
616
+ }));
617
+ }
618
+ async resetPublishedRoomInstance(instanceId) {
619
+ const instance = await this.roomStore.getRoom(instanceId);
620
+ if (!instance) {
621
+ throw new errors_1.NotFoundError('Instance not found');
622
+ }
623
+ const templateId = instance.getTemplateRoomId();
624
+ if (!templateId) {
625
+ throw new errors_1.OperationFailedError('Not a published instance');
626
+ }
627
+ this.roomStore.clearRoomMessages(instanceId);
628
+ const storageDir = this.roomStore.getDefaultStorageDir();
629
+ const roomDir = path.join(storageDir, instanceId);
630
+ if (fs.existsSync(roomDir)) {
631
+ const artifacts = instance.getArtifacts();
632
+ for (const artifact of artifacts) {
633
+ try {
634
+ const artifactPath = path.join(roomDir, `${artifact.name}.artifact`);
635
+ if (fs.existsSync(artifactPath)) {
636
+ fs.unlinkSync(artifactPath);
637
+ }
638
+ }
639
+ catch (err) {
640
+ console.error(`Failed to delete artifact ${artifact.name}:`, err);
641
+ }
642
+ }
643
+ }
644
+ instance.setArtifacts([]);
645
+ const instanceAgents = instance.getAgents();
646
+ for (const agent of instanceAgents) {
647
+ if (agent.templateAgentId) {
648
+ await this.agentStore.resetPublishedInstance(agent.id, agent.templateAgentId);
649
+ }
650
+ }
651
+ instance.saveMetadata();
652
+ }
653
+ getUserPreferences() {
654
+ if (!this.configService.exists(this.userPreferencesFile)) {
655
+ return {};
656
+ }
657
+ const preferencesData = this.configService.load(this.userPreferencesFile);
658
+ return preferencesData ? JSON.parse(preferencesData) : {};
659
+ }
660
+ saveUserPreferences(preferences) {
661
+ this.configService.store(this.userPreferencesFile, JSON.stringify(preferences, null, 2));
662
+ }
663
+ listPromptFiles(folderName) {
664
+ const baseNames = new Set();
665
+ const scanDirectory = (baseDir) => {
666
+ let targetDir = baseDir;
667
+ if (folderName !== 'shared') {
668
+ targetDir = path.join(baseDir, folderName);
669
+ }
670
+ if (!fs.existsSync(targetDir)) {
671
+ return;
672
+ }
673
+ const allFiles = fs.readdirSync(targetDir);
674
+ const promptFiles = allFiles.filter((file) => file.endsWith('.prompt') || file.endsWith('.json'));
675
+ promptFiles.forEach((file) => {
676
+ const baseName = file.replace(/\.(prompt|json)$/, '');
677
+ baseNames.add(baseName);
678
+ });
679
+ };
680
+ scanDirectory(this.configService.getCommonPromptsDir());
681
+ scanDirectory(this.configService.getUserPromptsDir());
682
+ return { files: Array.from(baseNames).sort() };
683
+ }
684
+ listPromptFilesWithScope(folderName) {
685
+ const fileMap = new Map();
686
+ const scanDirectory = (baseDir, scope) => {
687
+ let targetDir = baseDir;
688
+ if (folderName !== 'shared') {
689
+ targetDir = path.join(baseDir, folderName);
690
+ }
691
+ if (!fs.existsSync(targetDir)) {
692
+ return;
693
+ }
694
+ const allFiles = fs.readdirSync(targetDir);
695
+ const promptFiles = allFiles.filter((file) => file.endsWith('.prompt') || file.endsWith('.json'));
696
+ promptFiles.forEach((file) => {
697
+ const baseName = file.replace(/\.(prompt|json)$/, '');
698
+ fileMap.set(baseName, scope);
699
+ });
700
+ };
701
+ scanDirectory(this.configService.getCommonPromptsDir(), 'common');
702
+ scanDirectory(this.configService.getUserPromptsDir(), 'user');
703
+ const files = [];
704
+ fileMap.forEach((scope, name) => {
705
+ files.push({ name, scope });
706
+ });
707
+ files.sort((a, b) => a.name.localeCompare(b.name));
708
+ return { files };
709
+ }
710
+ getPromptFile(folderName, fileName) {
711
+ const fileExtension = fileName.endsWith('.prompt') || fileName.endsWith('.json') ? '' : '.prompt';
712
+ const fullFileName = fileName + fileExtension;
713
+ const userDir = this.configService.getUserPromptsDir();
714
+ const commonDir = this.configService.getCommonPromptsDir();
715
+ const searchPaths = [];
716
+ if (folderName === 'shared') {
717
+ searchPaths.push({ path: path.join(userDir, fullFileName), scope: 'user' }, { path: path.join(commonDir, fullFileName), scope: 'common' });
718
+ }
719
+ else {
720
+ searchPaths.push({ path: path.join(userDir, folderName, fullFileName), scope: 'user' }, { path: path.join(userDir, fullFileName), scope: 'user' }, {
721
+ path: path.join(commonDir, folderName, fullFileName),
722
+ scope: 'common',
723
+ }, { path: path.join(commonDir, fullFileName), scope: 'common' });
724
+ }
725
+ for (const { path: filePath, scope } of searchPaths) {
726
+ if (fs.existsSync(filePath)) {
727
+ const content = fs.readFileSync(filePath, 'utf8');
728
+ return { content, scope };
729
+ }
730
+ }
731
+ return { content: '' };
732
+ }
733
+ savePromptFile(folderName, fileName, content, fileType) {
734
+ let targetDir = this.configService.getUserPromptsDir();
735
+ if (folderName !== 'shared') {
736
+ targetDir = path.join(this.configService.getUserPromptsDir(), folderName);
737
+ }
738
+ if (!fs.existsSync(targetDir)) {
739
+ fs.mkdirSync(targetDir, { recursive: true });
740
+ }
741
+ const fileExtension = fileType === 'json' ? '.json' : '.prompt';
742
+ const filePath = path.join(targetDir, fileName + fileExtension);
743
+ if (content.trim() === '' && fileType === 'json') {
744
+ if (fs.existsSync(filePath)) {
745
+ fs.unlinkSync(filePath);
746
+ }
747
+ return;
748
+ }
749
+ fs.writeFileSync(filePath, content);
750
+ }
751
+ deletePromptFile(folderName, fileName) {
752
+ let targetDir = this.configService.getPromptsDir();
753
+ if (folderName !== 'shared') {
754
+ targetDir = path.join(this.configService.getPromptsDir(), folderName);
755
+ }
756
+ const promptPath = path.join(targetDir, fileName + '.prompt');
757
+ if (fs.existsSync(promptPath)) {
758
+ fs.unlinkSync(promptPath);
759
+ }
760
+ const jsonPath = path.join(targetDir, fileName + '.json');
761
+ if (fs.existsSync(jsonPath)) {
762
+ fs.unlinkSync(jsonPath);
763
+ }
764
+ }
765
+ async getRoomArtifacts(roomId) {
766
+ const room = await this.roomStore.getRoom(roomId);
767
+ if (!room) {
768
+ return { artifacts: [] };
769
+ }
770
+ const artifacts = room.getArtifacts();
771
+ return { artifacts };
772
+ }
773
+ async publishArtifact(roomId, name, creator, body, viewers = []) {
774
+ const room = await this.roomStore.getRoom(roomId);
775
+ if (!room)
776
+ throw new errors_1.NotFoundError('Room not found');
777
+ if (!name)
778
+ throw new errors_1.OperationFailedError('Artifact name is required');
779
+ room.publishArtifact(name, creator, body, viewers);
780
+ }
781
+ createPromptFolder(folderName) {
782
+ const targetDir = path.join(this.configService.getUserPromptsDir(), folderName);
783
+ if (fs.existsSync(targetDir)) {
784
+ throw new errors_1.OperationFailedError(`Folder ${folderName} already exists`);
785
+ }
786
+ fs.mkdirSync(targetDir, { recursive: true });
787
+ const systemInstructionPath = path.join(targetDir, 'system_instruction.prompt');
788
+ fs.writeFileSync(systemInstructionPath, '');
789
+ }
790
+ deletePromptFolder(folderName) {
791
+ if (folderName === 'shared') {
792
+ throw new errors_1.OperationFailedError('Cannot delete the shared folder');
793
+ }
794
+ const targetDir = path.join(this.configService.getUserPromptsDir(), folderName);
795
+ if (!fs.existsSync(targetDir)) {
796
+ throw new errors_1.NotFoundError(`Folder ${folderName} does not exist`);
797
+ }
798
+ fs.rmSync(targetDir, { recursive: true, force: true });
799
+ }
800
+ async updateAgent(agentId, updates) {
801
+ const agent = await this.agentStore.getAgent(agentId);
802
+ if (!agent) {
803
+ throw new errors_1.NotFoundError('Agent not found');
804
+ }
805
+ if (updates.agentNickname !== undefined)
806
+ agent.agentNickname = updates.agentNickname;
807
+ if (updates.description !== undefined)
808
+ agent.description = updates.description;
809
+ if (updates.modelName !== undefined)
810
+ agent.modelName = updates.modelName;
811
+ if (updates.reasoningEffort !== undefined)
812
+ agent.reasoningEffort = updates.reasoningEffort;
813
+ if (updates.isControlledByHuman !== undefined)
814
+ agent.isControlledByHuman = updates.isControlledByHuman;
815
+ if (updates.maxOutputTokens !== undefined)
816
+ agent.maxOutputTokens = updates.maxOutputTokens;
817
+ if (updates.allowSearch !== undefined)
818
+ agent.allowSearch = updates.allowSearch;
819
+ if (updates.beginInstruction !== undefined)
820
+ agent.beginInstruction = updates.beginInstruction;
821
+ agent.save();
822
+ }
823
+ async listAttachedFiles(agentId) {
824
+ const agent = await this.agentStore.getAgent(agentId);
825
+ if (!agent) {
826
+ return { files: [] };
827
+ }
828
+ const files = this.attachedFileService.listFiles(agentId);
829
+ return { files };
830
+ }
831
+ async deleteAttachedFile(agentId, fileName) {
832
+ const agent = await this.agentStore.getAgent(agentId);
833
+ if (!agent) {
834
+ throw new errors_1.NotFoundError('Agent not found');
835
+ }
836
+ const deleted = this.attachedFileService.deleteFileByName(agentId, fileName);
837
+ if (!deleted) {
838
+ throw new errors_1.NotFoundError(`File ${fileName} not found`);
839
+ }
840
+ agent.attachedFiles = agent.attachedFiles.filter((file) => file.fileName !== fileName);
841
+ agent.save();
842
+ }
843
+ async deleteAttachedFileById(documentId) {
844
+ const allAgentIds = await this.agentStore.getAllAgentIds();
845
+ let ownerAgent = null;
846
+ let fileMetadata = null;
847
+ for (const agentId of allAgentIds) {
848
+ const agent = await this.agentStore.getAgent(agentId);
849
+ if (agent) {
850
+ const file = agent.attachedFiles.find((f) => f.fileId === documentId);
851
+ if (file) {
852
+ ownerAgent = agent;
853
+ fileMetadata = file;
854
+ break;
855
+ }
856
+ }
857
+ }
858
+ if (!ownerAgent || !fileMetadata) {
859
+ throw new errors_1.NotFoundError('File not found');
860
+ }
861
+ const deleted = this.attachedFileService.deleteFile(ownerAgent.id, documentId);
862
+ if (!deleted) {
863
+ throw new errors_1.OperationFailedError('Failed to delete file');
864
+ }
865
+ ownerAgent.attachedFiles = ownerAgent.attachedFiles.filter((file) => file.fileId !== documentId);
866
+ ownerAgent.save();
867
+ }
868
+ async reloadAgent(agentId) {
869
+ const agent = await this.agentStore.getAgent(agentId);
870
+ if (!agent) {
871
+ throw new errors_1.NotFoundError('Agent not found');
872
+ }
873
+ const serviceName = agent.serviceName;
874
+ const aiService = this.getAiServiceFromServiceName(serviceName);
875
+ if (agent.history &&
876
+ agent.history.length > 0 &&
877
+ agent.history[0].content &&
878
+ agent.history[0].content.includes('[CONVERSATION HISTORY SUMMARY]'))
879
+ agent.history.splice(1);
880
+ else
881
+ agent.history = [];
882
+ const fileMetadataList = agent.attachedFiles;
883
+ for (const metadata of fileMetadataList) {
884
+ const fileData = this.attachedFileService.getFile(agent.id, metadata.fileId);
885
+ if (fileData) {
886
+ aiService.attachDocument(agent, metadata.fileName, fileData);
887
+ }
888
+ }
889
+ agent.save();
890
+ }
891
+ async resetRoom(roomId) {
892
+ const room = await this.roomStore.getRoom(roomId);
893
+ if (!room) {
894
+ throw new errors_1.NotFoundError('Room not found');
895
+ }
896
+ const roomName = room.getName();
897
+ const storageDir = room.getStorageDir() || this.roomStore.getDefaultStorageDir();
898
+ this.roomStore.clearRoomMessages(roomId, storageDir);
899
+ this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
900
+ room.setArtifacts([]);
901
+ const warnings = [];
902
+ for (const agent of room.getAgents()) {
903
+ try {
904
+ this.reloadAgent(agent.id);
905
+ }
906
+ catch (agentError) {
907
+ warnings.push(`Failed to reset agent ${agent.agentName}: ${agentError.message}`);
908
+ }
909
+ }
910
+ if (warnings.length > 0) {
911
+ console.warn(`Room "${roomName}" reset with warnings:`, warnings);
912
+ }
913
+ }
914
+ async resetStory(storyId) {
915
+ const story = this.storyStore.getStory(storyId);
916
+ if (!story || !story.roomId) {
917
+ throw new errors_1.NotFoundError('Story not found');
918
+ }
919
+ const storyName = story.name;
920
+ const room = await this.roomStore.getRoom(story.roomId);
921
+ if (!room) {
922
+ throw new errors_1.NotFoundError('Story room not found');
923
+ }
924
+ const roomMessages = room.getLatestRoomMessages();
925
+ const openingSceneMessage = roomMessages.find((msg) => msg.sender === 'Opening Scene');
926
+ const openingSceneText = openingSceneMessage?.content || '';
927
+ const storageDir = room.getStorageDir() ||
928
+ path.join(this.configService.getUserDataDir(), 'stories', storyId, 'rooms');
929
+ this.roomStore.clearRoomMessages(story.roomId, storageDir);
930
+ room.setRoomMessages([]);
931
+ const chapters = this.storyStore.listChapters(storyId);
932
+ const warnings = [];
933
+ if (chapters.length > 0) {
934
+ console.log(`Restoring agents from chapter 1 backup for story ${storyId}`);
935
+ const restoredAgentIds = await this.storyStore.restoreAgentsFromChapter(storyId, 1, this.agentStore);
936
+ console.log(`Restored ${restoredAgentIds.length} agents from chapter 1 backup`);
937
+ }
938
+ else {
939
+ console.warn(`No chapter 1 backup found for story ${storyId}, clearing agent histories`);
940
+ for (const agent of room.getAgents()) {
941
+ try {
942
+ this.reloadAgent(agent.id);
943
+ }
944
+ catch (agentError) {
945
+ warnings.push(`Failed to reset agent ${agent.agentName}: ${agentError.message}`);
946
+ }
947
+ }
948
+ }
949
+ if (openingSceneText) {
950
+ this.storyService.populateStoryHistory(room, openingSceneText);
951
+ }
952
+ if (story) {
953
+ story.declinedCharacters = [];
954
+ this.storyStore.updateStoryMetadata(storyId, story);
955
+ }
956
+ if (warnings.length > 0) {
957
+ console.warn(`Story "${storyName}" reset with warnings:`, warnings);
958
+ }
959
+ }
960
+ async createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel, isImport, imageModelName) {
961
+ return this.storyService.createStory(name, idea, userCharacterDesc, otherCharactersDesc, storyModel, isImport, imageModelName);
962
+ }
963
+ async importStoryFromZip(zipBuffer) {
964
+ return this.storyService.importStoryFromZip(zipBuffer);
965
+ }
966
+ getStoryProgressEmitter(storyId) {
967
+ return this.storyService.getProgressEmitter(storyId);
968
+ }
969
+ getStoryMessageEmitter(storyId) {
970
+ return this.storyService.getMessageEmitter(storyId);
971
+ }
972
+ getAgentMessageEmitter(agentId) {
973
+ return this.agentMessageService.getOrCreateEmitter(agentId);
974
+ }
975
+ async ensureAgentStateCallback(agentId) {
976
+ try {
977
+ const agent = await this.agentStore.getAgent(agentId);
978
+ if (agent) {
979
+ this.setupAgentStateCallback(agent);
980
+ }
981
+ }
982
+ catch (error) {
983
+ console.warn(`Could not set up SSE callback for agent ${agentId}:`, error.message);
984
+ }
985
+ }
986
+ setupAgentStateCallback(agent) {
987
+ if (!agent.id) {
988
+ console.warn('Cannot set up SSE callback for agent without ID');
989
+ return;
990
+ }
991
+ agent.setOnStateChange(() => {
992
+ const messages = agent.getFormattedMessages();
993
+ const agentState = {
994
+ agentId: agent.id,
995
+ latestMessage: messages.length > 0 ? messages[messages.length - 1] : undefined,
996
+ messageIndex: messages.length > 0 ? messages.length - 1 : undefined,
997
+ totalInputTokens: agent.totalInputTokens,
998
+ totalOutputTokens: agent.totalOutputTokens,
999
+ totalCost: agent.totalCost,
1000
+ };
1001
+ this.agentMessageService.emitUpdate(agent.id, agentState);
1002
+ });
1003
+ }
1004
+ getRoomMessageEmitter(roomId) {
1005
+ return this.roomMessageService.getOrCreateEmitter(roomId);
1006
+ }
1007
+ getBalanceMessageEmitter(userId) {
1008
+ return this.balanceMessageService.getOrCreateEmitter(userId);
1009
+ }
1010
+ async ensureRoomStateCallback(roomId) {
1011
+ try {
1012
+ const room = await this.roomStore.getRoom(roomId);
1013
+ if (room) {
1014
+ this.setupRoomStateCallback(room);
1015
+ }
1016
+ }
1017
+ catch (error) {
1018
+ console.warn(`Could not set up SSE callback for room ${roomId}:`, error.message);
1019
+ }
1020
+ }
1021
+ setupRoomStateCallback(room) {
1022
+ const roomId = room.getId();
1023
+ if (!roomId) {
1024
+ console.warn('Cannot set up SSE callback for room without ID');
1025
+ return;
1026
+ }
1027
+ room.setOnStateChange(() => {
1028
+ const messages = room.getLatestRoomMessages(0, false);
1029
+ const latestMessage = messages.length > 0 ? messages[messages.length - 1] : undefined;
1030
+ const totalCost = room
1031
+ .getAgents()
1032
+ .map((a) => a.totalCost)
1033
+ .reduce((acc, v) => acc + v, 0);
1034
+ const roomState = {
1035
+ roomId: roomId,
1036
+ latestMessage: latestMessage,
1037
+ messageIndex: messages.length > 0 ? messages.length - 1 : undefined,
1038
+ totalCost: totalCost,
1039
+ isPaused: room.getPaused(),
1040
+ currentSpeaker: room.getCurrentSpeaker(),
1041
+ processingInProgress: room.isProcessingInProgress(),
1042
+ };
1043
+ this.roomMessageService.emitUpdate(roomId, roomState);
1044
+ });
1045
+ }
1046
+ listStories() {
1047
+ return this.storyStore.getAllStories();
1048
+ }
1049
+ async resumePausedStories() {
1050
+ const stories = this.storyStore.getAllStories();
1051
+ let resumedCount = 0;
1052
+ for (const story of stories) {
1053
+ if (!story.roomId)
1054
+ continue;
1055
+ try {
1056
+ const room = await this.roomStore.getRoom(story.roomId);
1057
+ if (!room)
1058
+ continue;
1059
+ const isPaused = !room.isProcessingInProgress() && room['pendingMessages']?.length > 0;
1060
+ if (isPaused) {
1061
+ console.log(`Resuming paused story: ${story.name} (${story.id})`);
1062
+ const resumeMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, 'Balance added. Conversation resumed.', [], null, null);
1063
+ room.addRoomMessage(resumeMessage);
1064
+ room['processPendingMessages']();
1065
+ resumedCount++;
1066
+ }
1067
+ }
1068
+ catch (error) {
1069
+ console.error(`Error resuming story ${story.id}:`, error);
1070
+ }
1071
+ }
1072
+ if (resumedCount > 0) {
1073
+ console.log(`Resumed ${resumedCount} paused story/stories`);
1074
+ }
1075
+ return resumedCount;
1076
+ }
1077
+ async deleteStory(storyId) {
1078
+ await this.storyService.deleteStory(storyId);
1079
+ }
1080
+ async compactStory(storyId) {
1081
+ return this.storyService.compactStory(storyId);
1082
+ }
1083
+ async progressStory(storyId) {
1084
+ return this.storyService.progressStoryToNextChapter(storyId);
1085
+ }
1086
+ async getStoryState(storyId) {
1087
+ return this.storyService.getStoryState(storyId);
1088
+ }
1089
+ async getStoryInfo(storyId) {
1090
+ return this.storyStore.getStory(storyId);
1091
+ }
1092
+ async respondToStory(storyId, content) {
1093
+ return this.storyService.respondToStory(storyId, content);
1094
+ }
1095
+ async introduceCharacterToStory(storyId, name, description, storyModel, fromNarratorSuggestion) {
1096
+ await this.storyService.introduceCharacter(storyId, name, description, storyModel, fromNarratorSuggestion);
1097
+ }
1098
+ async declineCharacter(storyId, characterName) {
1099
+ await this.storyService.declineCharacter(storyId, characterName);
1100
+ }
1101
+ async deleteCharacterFromStory(storyId, characterName) {
1102
+ await this.storyService.deleteCharacter(storyId, characterName);
1103
+ }
1104
+ listChapters(storyId) {
1105
+ const chapters = this.storyStore.listChapters(storyId);
1106
+ return { chapters };
1107
+ }
1108
+ async getChapter(storyId, chapterIndex) {
1109
+ return await this.storyStore.getChapterContent(storyId, chapterIndex);
1110
+ }
1111
+ saveChapter(storyId, chapterIndex, content) {
1112
+ const saved = this.storyStore.saveChapterContent(storyId, chapterIndex, content);
1113
+ if (!saved) {
1114
+ throw new errors_1.OperationFailedError('Failed to save chapter');
1115
+ }
1116
+ }
1117
+ deleteChapter(storyId, chapterIndex) {
1118
+ const deleted = this.storyStore.deleteChapter(storyId, chapterIndex);
1119
+ if (!deleted) {
1120
+ throw new errors_1.NotFoundError('Chapter not found');
1121
+ }
1122
+ }
1123
+ async listCharacters(storyId) {
1124
+ return await this.storyService.listCharacters(storyId);
1125
+ }
1126
+ async getCharacter(storyId, characterName) {
1127
+ const content = await this.storyService.getCharacter(storyId, characterName);
1128
+ return { content: content || '' };
1129
+ }
1130
+ saveCharacter(storyId, characterName, content) {
1131
+ this.storyService.saveCharacter(storyId, characterName, content);
1132
+ }
1133
+ async getPlotPlan(storyId) {
1134
+ const content = await this.storyService.getPlotPlan(storyId);
1135
+ return { content: content || '' };
1136
+ }
1137
+ async downloadStoryMarkdown(storyId) {
1138
+ return await this.storyService.generateStoryMarkdown(storyId);
1139
+ }
1140
+ async exportStoryData(storyId) {
1141
+ return await this.storyService.exportStoryData(storyId);
1142
+ }
1143
+ async getAgentHistory(storyId, agentId) {
1144
+ const history = await this.storyService.getAgentHistory(storyId, agentId);
1145
+ return { content: history };
1146
+ }
1147
+ async savePlotPlan(storyId, content) {
1148
+ await this.storyService.savePlotPlan(storyId, content);
1149
+ }
1150
+ getBalance() {
1151
+ return this.balanceService.getBalance();
1152
+ }
1153
+ addBalance(amount) {
1154
+ return this.balanceService.addBalance(amount);
1155
+ }
1156
+ getTransactionService() {
1157
+ return this.transactionService;
1158
+ }
1159
+ listUserArtifacts() {
1160
+ return this.artifactService.listArtifacts();
1161
+ }
1162
+ getUserArtifact(artifactId) {
1163
+ return this.artifactService.getArtifact(artifactId);
1164
+ }
1165
+ createUserArtifact(name, content) {
1166
+ return this.artifactService.storeArtifact(name, content);
1167
+ }
1168
+ updateUserArtifact(artifactId, content) {
1169
+ return this.artifactService.updateArtifact(artifactId, content);
1170
+ }
1171
+ convertUserArtifact(name, pdfBuffer) {
1172
+ const placeholderContent = 'Converting PDF. This text will be replaced when the conversion is finished.';
1173
+ const artifactId = this.artifactService.storeArtifact(name, placeholderContent);
1174
+ this.convertPdfInBackground(artifactId, name, pdfBuffer).catch((error) => {
1175
+ console.error(`Background PDF conversion failed for ${artifactId}:`, error);
1176
+ const errorContent = `# Conversion Failed\n\nThe PDF conversion failed with the following error:\n\n${error.message}\n\nPlease try uploading the file again.`;
1177
+ this.artifactService.updateArtifact(artifactId, errorContent);
1178
+ });
1179
+ return artifactId;
1180
+ }
1181
+ async convertSinglePagePDF(pdfDoc, pageIndex) {
1182
+ const pageNum = pageIndex + 1;
1183
+ const agent = this.agentFactory.createAgent(process.env.DOC_CONVERSION_AI_SERVICE, 'PDF Converter', '', `Single page (#${pageNum}) PDF to Markdown conversion`, 'pdf_converter', process.env.DOC_CONVERSION_AI_MODEL);
1184
+ const singlePageDoc = await pdf_lib_1.PDFDocument.create();
1185
+ const [copiedPage] = await singlePageDoc.copyPages(pdfDoc, [pageIndex]);
1186
+ singlePageDoc.addPage(copiedPage);
1187
+ const singlePageBuffer = await singlePageDoc.save();
1188
+ const fileName = `Page${pageNum}.pdf`;
1189
+ await agent.attachDocument(fileName, singlePageBuffer);
1190
+ let response = null;
1191
+ try {
1192
+ let markdownContent = await agent.preparedPrompt('convert_pdf_page', {
1193
+ fileName: fileName,
1194
+ pageNum: pageNum,
1195
+ targetFormat: 'markdown',
1196
+ }, false);
1197
+ response = { markdownContent, cost: agent.totalCost };
1198
+ }
1199
+ finally {
1200
+ await agent.finishAgent();
1201
+ }
1202
+ return response;
1203
+ }
1204
+ async convertLargePdfInBackground(artifactId, name, pdfDoc) {
1205
+ const pageCount = pdfDoc.getPageCount();
1206
+ console.log(`Converting large PDF with ${pageCount} pages concurrently for artifact ${artifactId}`);
1207
+ try {
1208
+ const conversionPromises = Array.from({ length: pageCount }, (_, pageIndex) => {
1209
+ const pageNum = pageIndex + 1;
1210
+ console.log(`Starting conversion for page ${pageNum}/${pageCount} for artifact ${artifactId}`);
1211
+ return this.convertSinglePagePDF(pdfDoc, pageIndex)
1212
+ .then((pageResponse) => ({
1213
+ pageNum,
1214
+ success: true,
1215
+ cost: pageResponse.cost,
1216
+ content: `**[Page ${pageNum}]** \n${pageResponse.markdownContent} \n`,
1217
+ }))
1218
+ .catch((pageError) => {
1219
+ console.error(`Error converting page ${pageNum}:`, pageError);
1220
+ return {
1221
+ pageNum,
1222
+ success: false,
1223
+ cost: 0,
1224
+ content: `\n\n---\n**[Error converting page ${pageNum}: ${pageError.message}]**\n---\n\n`,
1225
+ };
1226
+ });
1227
+ });
1228
+ console.log(`Waiting for ${pageCount} concurrent page conversions...`);
1229
+ const results = await Promise.all(conversionPromises);
1230
+ const pageMarkdowns = results.map((result) => result.content);
1231
+ const totalCost = results.map((result) => result.cost).reduce((acc, v) => acc + v, 0);
1232
+ const markdownContent = pageMarkdowns.join('\n\n');
1233
+ if (!markdownContent || markdownContent.trim().length === 0) {
1234
+ throw new Error('PDF conversion produced empty content');
1235
+ }
1236
+ this.artifactService.updateArtifact(artifactId, markdownContent);
1237
+ const successCount = results.filter((r) => r.success).length;
1238
+ const failureCount = pageCount - successCount;
1239
+ console.log(`Large PDF conversion complete: ${artifactId}. ` +
1240
+ `Pages: ${pageCount} (${successCount} succeeded, ${failureCount} failed), ` +
1241
+ `Output: ${markdownContent.length} chars (total cost: ${totalCost})`);
1242
+ }
1243
+ catch (error) {
1244
+ console.error(`Error in large PDF conversion for ${artifactId}:`, error);
1245
+ const errorContent = `# Conversion Failed\n\nThe PDF conversion failed with the following error:\n\n${error.message}\n\nPlease try uploading the file again.`;
1246
+ this.artifactService.updateArtifact(artifactId, errorContent);
1247
+ throw error;
1248
+ }
1249
+ }
1250
+ async convertPdfInBackground(artifactId, name, pdfBuffer) {
1251
+ console.log(`Starting background PDF conversion for artifact ${artifactId}`);
1252
+ let agent = null;
1253
+ if (!process.env.DOC_CONVERSION_AI_SERVICE)
1254
+ throw new Error('DOC_CONVERSION_AI_SERVICE environment variable not set');
1255
+ if (!process.env.DOC_CONVERSION_AI_MODEL)
1256
+ throw new Error('DOC_CONVERSION_AI_MODEL environment variable not set');
1257
+ try {
1258
+ const pdfData = new Uint8Array(pdfBuffer);
1259
+ const pdfDoc = await pdf_lib_1.PDFDocument.load(pdfBuffer);
1260
+ const pageCount = pdfDoc.getPageCount();
1261
+ if (pageCount > 10) {
1262
+ return this.convertLargePdfInBackground(artifactId, name, pdfDoc);
1263
+ }
1264
+ agent = this.agentFactory.createAgent(process.env.DOC_CONVERSION_AI_SERVICE, 'PDF Converter', '', 'Small PDF to Markdown conversion', 'pdf_converter', process.env.DOC_CONVERSION_AI_MODEL);
1265
+ await agent.attachDocument(`${name}.pdf`, pdfData);
1266
+ let markdownContent = await agent.preparedPrompt('convert_pdf', {
1267
+ fileName: `${name}.pdf`,
1268
+ targetFormat: 'markdown',
1269
+ }, false);
1270
+ if (!markdownContent || markdownContent.trim().length === 0) {
1271
+ throw new Error('PDF conversion produced empty content');
1272
+ }
1273
+ this.artifactService.updateArtifact(artifactId, markdownContent);
1274
+ console.log(`PDF conversion complete: ${artifactId}. ` +
1275
+ `Input: ${pdfBuffer.length} bytes, Output: ${markdownContent.length} chars, ` +
1276
+ `Cost: $${agent.totalCost.toFixed(4)}`);
1277
+ }
1278
+ finally {
1279
+ try {
1280
+ await agent?.finishAgent();
1281
+ }
1282
+ catch (cleanupError) {
1283
+ console.error('Agent cleanup error:', cleanupError);
1284
+ }
1285
+ }
1286
+ }
1287
+ renameUserArtifact(artifactId, newName) {
1288
+ return this.artifactService.renameArtifact(artifactId, newName);
1289
+ }
1290
+ deleteUserArtifact(artifactId) {
1291
+ return this.artifactService.deleteArtifact(artifactId);
1292
+ }
1293
+ getStoryArtifactService(storyId) {
1294
+ return this.storyService.getStoryArtifactService(storyId);
1295
+ }
1296
+ listStoryArtifacts(storyId) {
1297
+ const storyArtifactService = this.getStoryArtifactService(storyId);
1298
+ return storyArtifactService.listArtifacts();
1299
+ }
1300
+ getStoryArtifact(storyId, artifactId) {
1301
+ const storyArtifactService = this.getStoryArtifactService(storyId);
1302
+ return storyArtifactService.getArtifact(artifactId);
1303
+ }
1304
+ async listAgentArtifacts(agentId) {
1305
+ const agent = await this.agentStore.getAgent(agentId);
1306
+ if (!agent) {
1307
+ throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
1308
+ }
1309
+ const artifactIds = agent.getAttachedArtifacts();
1310
+ const allArtifacts = this.artifactService.listArtifacts();
1311
+ return allArtifacts.filter((a) => artifactIds.includes(a.artifactId));
1312
+ }
1313
+ async attachArtifactToAgent(agentId, artifactId) {
1314
+ const agent = await this.agentStore.getAgent(agentId);
1315
+ if (!agent) {
1316
+ throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
1317
+ }
1318
+ const artifact = this.artifactService.getArtifactMetadata(artifactId);
1319
+ if (!artifact) {
1320
+ throw new errors_1.NotFoundError(`Artifact ${artifactId} not found`);
1321
+ }
1322
+ agent.attachArtifact(artifactId);
1323
+ agent.save();
1324
+ }
1325
+ async detachArtifactFromAgent(agentId, artifactId) {
1326
+ const agent = await this.agentStore.getAgent(agentId);
1327
+ if (!agent) {
1328
+ throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
1329
+ }
1330
+ agent.detachArtifact(artifactId);
1331
+ agent.save();
1332
+ }
1333
+ }
1334
+ exports.AppService = AppService;