briyah 1.0.2 → 1.0.3

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 (177) hide show
  1. package/dist/server/src/ai/LLM/deepseek.service.js +1 -1
  2. package/package.json +2 -2
  3. package/dist/ai/LLM/anthropic.module.d.ts +0 -2
  4. package/dist/ai/LLM/anthropic.module.js +0 -21
  5. package/dist/ai/LLM/anthropic.service.d.ts +0 -27
  6. package/dist/ai/LLM/anthropic.service.js +0 -329
  7. package/dist/ai/LLM/base-ai.service.d.ts +0 -45
  8. package/dist/ai/LLM/base-ai.service.js +0 -409
  9. package/dist/ai/LLM/deepseek.module.d.ts +0 -2
  10. package/dist/ai/LLM/deepseek.module.js +0 -21
  11. package/dist/ai/LLM/deepseek.service.d.ts +0 -15
  12. package/dist/ai/LLM/deepseek.service.js +0 -279
  13. package/dist/ai/LLM/fal.module.d.ts +0 -2
  14. package/dist/ai/LLM/fal.module.js +0 -21
  15. package/dist/ai/LLM/fal.service.d.ts +0 -17
  16. package/dist/ai/LLM/fal.service.js +0 -314
  17. package/dist/ai/LLM/googleai.module.d.ts +0 -2
  18. package/dist/ai/LLM/googleai.module.js +0 -21
  19. package/dist/ai/LLM/googleai.service.d.ts +0 -20
  20. package/dist/ai/LLM/googleai.service.js +0 -271
  21. package/dist/ai/LLM/grok.module.d.ts +0 -2
  22. package/dist/ai/LLM/grok.module.js +0 -21
  23. package/dist/ai/LLM/grok.service.d.ts +0 -14
  24. package/dist/ai/LLM/grok.service.js +0 -263
  25. package/dist/ai/LLM/mock.module.d.ts +0 -2
  26. package/dist/ai/LLM/mock.module.js +0 -21
  27. package/dist/ai/LLM/mock.service.d.ts +0 -13
  28. package/dist/ai/LLM/mock.service.js +0 -194
  29. package/dist/ai/LLM/openai.module.d.ts +0 -2
  30. package/dist/ai/LLM/openai.module.js +0 -21
  31. package/dist/ai/LLM/openai.service.d.ts +0 -21
  32. package/dist/ai/LLM/openai.service.js +0 -421
  33. package/dist/ai/LLM/together.module.d.ts +0 -2
  34. package/dist/ai/LLM/together.module.js +0 -21
  35. package/dist/ai/LLM/together.service.d.ts +0 -18
  36. package/dist/ai/LLM/together.service.js +0 -285
  37. package/dist/ai/LLM/vertexai.module.d.ts +0 -2
  38. package/dist/ai/LLM/vertexai.module.js +0 -21
  39. package/dist/ai/LLM/vertexai.service.d.ts +0 -17
  40. package/dist/ai/LLM/vertexai.service.js +0 -323
  41. package/dist/ai/agent-config.d.ts +0 -32
  42. package/dist/ai/agent-config.js +0 -2
  43. package/dist/ai/agent-factory.d.ts +0 -15
  44. package/dist/ai/agent-factory.js +0 -24
  45. package/dist/ai/agent-message.service.d.ts +0 -9
  46. package/dist/ai/agent-message.service.js +0 -56
  47. package/dist/ai/agent-store.module.d.ts +0 -2
  48. package/dist/ai/agent-store.module.js +0 -21
  49. package/dist/ai/agent-store.service.d.ts +0 -31
  50. package/dist/ai/agent-store.service.js +0 -352
  51. package/dist/ai/agent.d.ts +0 -75
  52. package/dist/ai/agent.js +0 -174
  53. package/dist/ai/ai-factory.module.d.ts +0 -2
  54. package/dist/ai/ai-factory.module.js +0 -40
  55. package/dist/ai/ai-factory.service.d.ts +0 -24
  56. package/dist/ai/ai-factory.service.js +0 -94
  57. package/dist/ai/artifact.module.d.ts +0 -2
  58. package/dist/ai/artifact.module.js +0 -22
  59. package/dist/ai/artifact.service.d.ts +0 -21
  60. package/dist/ai/artifact.service.js +0 -239
  61. package/dist/ai/attached-file.module.d.ts +0 -2
  62. package/dist/ai/attached-file.module.js +0 -22
  63. package/dist/ai/attached-file.service.d.ts +0 -35
  64. package/dist/ai/attached-file.service.js +0 -253
  65. package/dist/ai/model_prices.d.ts +0 -2
  66. package/dist/ai/model_prices.js +0 -54
  67. package/dist/ai/published-agents.service.d.ts +0 -13
  68. package/dist/ai/published-agents.service.js +0 -118
  69. package/dist/app/balance-message.service.d.ts +0 -8
  70. package/dist/app/balance-message.service.js +0 -45
  71. package/dist/app/balance.module.d.ts +0 -2
  72. package/dist/app/balance.module.js +0 -20
  73. package/dist/app/balance.service.d.ts +0 -18
  74. package/dist/app/balance.service.js +0 -158
  75. package/dist/app/stripe.controller.d.ts +0 -31
  76. package/dist/app/stripe.controller.js +0 -150
  77. package/dist/app/stripe.module.d.ts +0 -2
  78. package/dist/app/stripe.module.js +0 -22
  79. package/dist/app/stripe.service.d.ts +0 -28
  80. package/dist/app/stripe.service.js +0 -198
  81. package/dist/app/transaction.service.d.ts +0 -15
  82. package/dist/app/transaction.service.js +0 -139
  83. package/dist/app/user-service-factory.d.ts +0 -21
  84. package/dist/app/user-service-factory.js +0 -81
  85. package/dist/app/user-service-manager.d.ts +0 -28
  86. package/dist/app/user-service-manager.js +0 -102
  87. package/dist/app.controller.d.ts +0 -232
  88. package/dist/app.controller.js +0 -2536
  89. package/dist/app.module.d.ts +0 -2
  90. package/dist/app.module.js +0 -45
  91. package/dist/app.service.d.ts +0 -186
  92. package/dist/app.service.js +0 -1334
  93. package/dist/auth/agent-access.decorator.d.ts +0 -2
  94. package/dist/auth/agent-access.decorator.js +0 -10
  95. package/dist/auth/auth.controller.d.ts +0 -38
  96. package/dist/auth/auth.controller.js +0 -356
  97. package/dist/auth/auth.module.d.ts +0 -2
  98. package/dist/auth/auth.module.js +0 -55
  99. package/dist/auth/auth.service.d.ts +0 -14
  100. package/dist/auth/auth.service.js +0 -84
  101. package/dist/auth/dto/bot-login.dto.d.ts +0 -4
  102. package/dist/auth/dto/bot-login.dto.js +0 -2
  103. package/dist/auth/dto/password-reset.dto.d.ts +0 -11
  104. package/dist/auth/dto/password-reset.dto.js +0 -2
  105. package/dist/auth/dto/phone-login.dto.d.ts +0 -8
  106. package/dist/auth/dto/phone-login.dto.js +0 -2
  107. package/dist/auth/dto/phone-verification.dto.d.ts +0 -9
  108. package/dist/auth/dto/phone-verification.dto.js +0 -2
  109. package/dist/auth/jwt-auth.guard.d.ts +0 -13
  110. package/dist/auth/jwt-auth.guard.js +0 -143
  111. package/dist/auth/jwt.strategy.d.ts +0 -17
  112. package/dist/auth/jwt.strategy.js +0 -45
  113. package/dist/auth/phone-validation.service.d.ts +0 -7
  114. package/dist/auth/phone-validation.service.js +0 -50
  115. package/dist/auth/public.decorator.d.ts +0 -2
  116. package/dist/auth/public.decorator.js +0 -7
  117. package/dist/auth/rate-limit.service.d.ts +0 -16
  118. package/dist/auth/rate-limit.service.js +0 -84
  119. package/dist/auth/room-access.decorator.d.ts +0 -2
  120. package/dist/auth/room-access.decorator.js +0 -10
  121. package/dist/auth/scopes.decorator.d.ts +0 -2
  122. package/dist/auth/scopes.decorator.js +0 -7
  123. package/dist/auth/scopes.guard.d.ts +0 -9
  124. package/dist/auth/scopes.guard.js +0 -82
  125. package/dist/auth/session.guard.d.ts +0 -7
  126. package/dist/auth/session.guard.js +0 -55
  127. package/dist/auth/twilio.service.d.ts +0 -15
  128. package/dist/auth/twilio.service.js +0 -139
  129. package/dist/auth/users.service.d.ts +0 -24
  130. package/dist/auth/users.service.js +0 -149
  131. package/dist/common/errors.d.ts +0 -12
  132. package/dist/common/errors.js +0 -43
  133. package/dist/config/configuration.module.d.ts +0 -2
  134. package/dist/config/configuration.module.js +0 -20
  135. package/dist/config/configuration.service.d.ts +0 -26
  136. package/dist/config/configuration.service.js +0 -131
  137. package/dist/main.js +0 -15749
  138. package/dist/room/artifact-store.service.d.ts +0 -15
  139. package/dist/room/artifact-store.service.js +0 -226
  140. package/dist/room/artifact.d.ts +0 -6
  141. package/dist/room/artifact.js +0 -2
  142. package/dist/room/message.d.ts +0 -19
  143. package/dist/room/message.js +0 -70
  144. package/dist/room/published-rooms.service.d.ts +0 -12
  145. package/dist/room/published-rooms.service.js +0 -108
  146. package/dist/room/room-config.d.ts +0 -12
  147. package/dist/room/room-config.js +0 -2
  148. package/dist/room/room-factory.d.ts +0 -7
  149. package/dist/room/room-factory.js +0 -16
  150. package/dist/room/room-message.module.d.ts +0 -2
  151. package/dist/room/room-message.module.js +0 -21
  152. package/dist/room/room-message.service.d.ts +0 -8
  153. package/dist/room/room-message.service.js +0 -44
  154. package/dist/room/room-store.module.d.ts +0 -2
  155. package/dist/room/room-store.module.js +0 -25
  156. package/dist/room/room-store.service.d.ts +0 -38
  157. package/dist/room/room-store.service.js +0 -353
  158. package/dist/room/room.d.ts +0 -107
  159. package/dist/room/room.js +0 -833
  160. package/dist/sdk/briyah-config.d.ts +0 -13
  161. package/dist/sdk/briyah-config.js +0 -32
  162. package/dist/sdk/briyah.d.ts +0 -36
  163. package/dist/sdk/briyah.js +0 -122
  164. package/dist/sdk/index.d.ts +0 -6
  165. package/dist/sdk/index.js +0 -11
  166. package/dist/shared/shared.module.d.ts +0 -2
  167. package/dist/shared/shared.module.js +0 -46
  168. package/dist/story/story-message.service.d.ts +0 -10
  169. package/dist/story/story-message.service.js +0 -57
  170. package/dist/story/story-progress.service.d.ts +0 -8
  171. package/dist/story/story-progress.service.js +0 -44
  172. package/dist/story/story-store.module.d.ts +0 -2
  173. package/dist/story/story-store.module.js +0 -22
  174. package/dist/story/story-store.service.d.ts +0 -23
  175. package/dist/story/story-store.service.js +0 -392
  176. package/dist/story/story.service.d.ts +0 -94
  177. package/dist/story/story.service.js +0 -1797
package/dist/room/room.js DELETED
@@ -1,833 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Room = void 0;
4
- const app_types_1 = require("../shared/types/app.types");
5
- const message_1 = require("./message");
6
- const crypto_1 = require("crypto");
7
- const errors_1 = require("../common/errors");
8
- const child_process_1 = require("child_process");
9
- class Room {
10
- id;
11
- name;
12
- goal;
13
- baseRoomDir;
14
- agents = [];
15
- roomLeader;
16
- roomMessages = [];
17
- pendingMessages;
18
- nextMessageIndex = 0;
19
- createdAt;
20
- artifacts = [];
21
- isAdjourned = false;
22
- processingInProgress = true;
23
- isPaused = false;
24
- currentSpeaker = null;
25
- isPublished = false;
26
- isLoading = false;
27
- onStateChange;
28
- onError;
29
- currentSituation = '';
30
- onSituationUpdate;
31
- templateRoomId;
32
- storageDir;
33
- roomStoreService;
34
- constructor(id, name, goal, baseRoomDir = '', storageDir = '', roomStoreService = null) {
35
- this.name = name;
36
- this.goal = goal;
37
- this.baseRoomDir = baseRoomDir;
38
- this.storageDir = storageDir;
39
- this.roomStoreService = roomStoreService;
40
- this.createdAt = new Date();
41
- this.processingInProgress = true;
42
- this.id = id ? id : (0, crypto_1.randomUUID)();
43
- this.isLoading = false;
44
- }
45
- deleteRoom() {
46
- this.roomStoreService.removeRoom(this.id, this.storageDir);
47
- }
48
- setLoading(isLoading) {
49
- this.isLoading = isLoading;
50
- }
51
- getName() {
52
- return this.name;
53
- }
54
- setName(name) {
55
- this.name = name;
56
- }
57
- getGoal() {
58
- return this.goal;
59
- }
60
- setGoal(goal) {
61
- this.goal = goal;
62
- }
63
- getBaseRoomDir() {
64
- return this.baseRoomDir;
65
- }
66
- setBaseRoomDir(dir) {
67
- this.baseRoomDir = dir;
68
- }
69
- getIsPublished() {
70
- return this.isPublished;
71
- }
72
- setPublished(published) {
73
- this.isPublished = published;
74
- this.saveMetadata();
75
- }
76
- getPaused() {
77
- return this.isPaused;
78
- }
79
- getTemplateRoomId() {
80
- return this.templateRoomId;
81
- }
82
- setTemplateRoomId(templateId) {
83
- this.templateRoomId = templateId;
84
- }
85
- clearRoomMessages() {
86
- this.roomMessages = [];
87
- this.roomStoreService.clearRoomMessages(this.id, this.storageDir);
88
- }
89
- arrive(agent) {
90
- if (this.agents.some((a) => a.agentNickname === agent.agentNickname)) {
91
- return false;
92
- }
93
- this.agents.push(agent);
94
- return true;
95
- }
96
- getAgents() {
97
- return [...this.agents];
98
- }
99
- setAgents(newAgents) {
100
- this.agents = [];
101
- for (const agent of newAgents) {
102
- this.arrive(agent);
103
- }
104
- }
105
- describeAgentsInRoom() {
106
- return this.agents.map((a) => `${a.agentNickname}: ${a.description}`).join('\n');
107
- }
108
- setRoomLeader(agentNickname) {
109
- this.roomLeader = agentNickname;
110
- }
111
- getRoomLeader() {
112
- if (this.roomLeader)
113
- return this.roomLeader;
114
- if (this.agents.length > 0 && this.agents[0]) {
115
- return this.agents[0].agentNickname || '';
116
- }
117
- return '';
118
- }
119
- getAgentCount() {
120
- return this.agents.length;
121
- }
122
- ready() {
123
- if (this.isAdjourned || this.processingInProgress) {
124
- this.isAdjourned = false;
125
- this.processingInProgress = false;
126
- this.setCurrentSpeaker(this.getHumanAgentName());
127
- this.notifyStateChange();
128
- }
129
- }
130
- getCurrentSpeaker() {
131
- return this.currentSpeaker;
132
- }
133
- setCurrentSpeaker(agentNickname) {
134
- this.currentSpeaker = agentNickname;
135
- this.notifyStateChange();
136
- }
137
- isAgentsTurn(agentNickname) {
138
- return this.currentSpeaker === agentNickname;
139
- }
140
- getRoomMessageStats() {
141
- let numMessages = this.roomMessages.length;
142
- let numChars = this.roomMessages.map((m) => m.content?.length).reduce((a, b) => a + b, 0);
143
- return { numMessages, numChars };
144
- }
145
- getLatestRoomMessages(fromIndex = 0, includeThoughts = false) {
146
- const messages = this.roomMessages.filter((msg) => msg.index >= fromIndex);
147
- if (!includeThoughts) {
148
- return messages.filter((msg) => msg.action !== app_types_1.MessageAction.THINK);
149
- }
150
- return messages;
151
- }
152
- setRoomMessages(messages) {
153
- this.roomMessages = messages.map((m, idx) => {
154
- m.index = idx;
155
- return m;
156
- });
157
- this.nextMessageIndex = this.roomMessages.length;
158
- }
159
- addRoomMessage(message) {
160
- message.index = this.nextMessageIndex++;
161
- this.roomMessages.push(message);
162
- this.saveMessages([message]);
163
- if (message.situation) {
164
- this.handleSituationUpdate(message.situation);
165
- }
166
- this.notifyStateChange();
167
- }
168
- addRoomMessages(messages) {
169
- if (!messages || messages.length === 0)
170
- return;
171
- let indexedMessages = messages.map((m) => {
172
- m.index = this.nextMessageIndex++;
173
- return m;
174
- });
175
- this.roomMessages = this.roomMessages.concat(indexedMessages);
176
- this.saveMessages(indexedMessages);
177
- this.notifyStateChange();
178
- }
179
- getCreatedAt() {
180
- return this.createdAt;
181
- }
182
- setCreatedAt(date) {
183
- this.createdAt = date;
184
- }
185
- getArtifacts() {
186
- return [...this.artifacts];
187
- }
188
- isRoomAdjourned() {
189
- return this.isAdjourned;
190
- }
191
- setArtifacts(artifacts) {
192
- this.artifacts = [...artifacts];
193
- }
194
- parseAgentResponse(agent, response) {
195
- let needsModeration = false;
196
- let targets = [];
197
- let content = response;
198
- let situation;
199
- if (typeof response !== 'object') {
200
- needsModeration = true;
201
- const lines = response.split('\n');
202
- for (const line of lines) {
203
- const trimmedLine = line.trim();
204
- if (trimmedLine.startsWith('# Situation:')) {
205
- situation = trimmedLine.substring('# Situation:'.length).trim();
206
- content = lines
207
- .filter((l) => !l.startsWith('# Situation:'))
208
- .join('\n')
209
- .trimStart();
210
- break;
211
- }
212
- }
213
- situation = situation || undefined;
214
- }
215
- else if (!response.content) {
216
- needsModeration = true;
217
- }
218
- else if (!response.action) {
219
- needsModeration = true;
220
- }
221
- else if (response.targets) {
222
- targets = response.targets;
223
- if (targets.length === 0) {
224
- if (response.action === app_types_1.MessageAction.WHISPER) {
225
- needsModeration = true;
226
- }
227
- if (response.action === app_types_1.MessageAction.RELAY) {
228
- needsModeration = true;
229
- }
230
- }
231
- }
232
- if (needsModeration) {
233
- return new message_1.RoomMessage(agent.agentNickname, app_types_1.MessageAction.MODERATE, content, [], null, situation);
234
- }
235
- situation = response.situation || undefined;
236
- return new message_1.RoomMessage(agent.agentNickname, response.action, response.content, targets, response.name, situation);
237
- }
238
- async getAgentAiResponse(agent, onResponse) {
239
- let answer = null;
240
- try {
241
- const visibleArtifacts = this.getVisibleArtifacts(agent.agentNickname)
242
- .map((a) => `${a.name} (by ${a.creator}): ${a.body}`)
243
- .join('\n\n');
244
- const allArtifacts = this.getArtifacts();
245
- const invisibleArtifactNames = allArtifacts
246
- .filter((a) => !this.getVisibleArtifacts(agent.agentNickname).includes(a))
247
- .map((a) => a.name)
248
- .join(', ');
249
- const humanAgent = this.getAgents().find((a) => a.isControlledByHuman);
250
- const humanCharacterName = humanAgent ? humanAgent.agentNickname : 'Player';
251
- const maxOutputChars = 4096;
252
- const variables = {
253
- agentName: agent.agentName,
254
- agentNickname: agent.agentNickname,
255
- agentDescription: agent.description,
256
- otherAgents: this.agents.filter((a) => a.agentNickname !== agent.agentNickname),
257
- roomLeader: this.getRoomLeader(),
258
- roomGoal: this.getGoal(),
259
- scenario: this.getGoal(),
260
- situation: this.getSituation() || 'Story beginning',
261
- visibleArtifacts: visibleArtifacts,
262
- invisibleArtifactNames: invisibleArtifactNames,
263
- humanCharacterName: humanCharacterName,
264
- humanAgentName: humanCharacterName,
265
- maxOutputChars: maxOutputChars
266
- };
267
- let prompt = null;
268
- let situation = this.getSituation();
269
- if (situation)
270
- prompt = `Current Situation: ${situation}`;
271
- let response = await agent.instructedPrompt(prompt, 'perceive', variables, false, true, maxOutputChars);
272
- answer = this.parseAgentResponse(agent, response);
273
- agent.addToConversationHistory(response, true);
274
- }
275
- catch (e) {
276
- if (e instanceof errors_1.InsufficientBalanceError) {
277
- this.handleInsufficientBalance(e);
278
- }
279
- else {
280
- let internalizedError = `${agent.agentNickname} thinks: No one heard me because ${e.message}`;
281
- agent.addToConversationHistory(internalizedError, true);
282
- }
283
- }
284
- onResponse(answer);
285
- }
286
- perceive(agent, message, onResponse) {
287
- if (!message.canHear(agent.agentNickname)) {
288
- onResponse(null);
289
- return;
290
- }
291
- agent.addToConversationHistory(message, false);
292
- agent.save();
293
- if (!agent.canRespond(message)) {
294
- onResponse(null);
295
- return;
296
- }
297
- if (agent.isControlledByHuman) {
298
- return;
299
- }
300
- this.getAgentAiResponse(agent, onResponse);
301
- }
302
- async moderate(moderatorAgent, message, onResponse) {
303
- const humanAgent = this.getAgents().find((agent) => agent.isControlledByHuman);
304
- const humanAgentName = humanAgent ? humanAgent.agentNickname : 'Player';
305
- const variables = {
306
- agentName: moderatorAgent.agentName,
307
- agentNickname: moderatorAgent.agentNickname || moderatorAgent.agentName,
308
- agentDescription: moderatorAgent.description,
309
- otherAgents: this.agents.filter((a) => a.agentNickname !== moderatorAgent.agentNickname),
310
- agents: this.getAgents(),
311
- roomLeader: this.getRoomLeader(),
312
- roomGoal: this.getGoal(),
313
- scenario: this.getGoal(),
314
- humanAgent: humanAgent,
315
- humanAgentName: humanAgentName,
316
- };
317
- let prompt = `
318
- Current Situation: ${this.getSituation()}
319
- Sender: ${message.getSender()}
320
- Recent Message: ${message.getContent()}
321
- `;
322
- try {
323
- let response = await moderatorAgent.instructedPrompt(prompt, 'moderate', variables, false, true);
324
- let answer = this.parseAgentResponse(moderatorAgent, response);
325
- moderatorAgent.addToConversationHistory(message, false);
326
- moderatorAgent.addToConversationHistory(answer, true);
327
- moderatorAgent.save();
328
- onResponse(answer);
329
- }
330
- catch (e) {
331
- if (e instanceof errors_1.InsufficientBalanceError) {
332
- this.handleInsufficientBalance(e, onResponse);
333
- }
334
- else {
335
- throw e;
336
- }
337
- }
338
- }
339
- handleInsufficientBalance(error, onResponse) {
340
- this.notifyError(error);
341
- const balanceMessage = new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, `Conversation paused: ${error.message}`, [], null, null);
342
- this.addRoomMessage(balanceMessage);
343
- this.processingInProgress = false;
344
- this.notifyStateChange();
345
- if (onResponse) {
346
- onResponse(null);
347
- }
348
- }
349
- findArtifact(name) {
350
- return this.artifacts.find((a) => a.name === name);
351
- }
352
- publishArtifact(name, creator, body, viewers = []) {
353
- if (!body || body.trim().length === 0) {
354
- this.deleteArtifact(name);
355
- return null;
356
- }
357
- const existingIndex = this.artifacts.findIndex((a) => a.name === name);
358
- let returnedArtifact;
359
- if (existingIndex >= 0) {
360
- this.artifacts[existingIndex].body = body;
361
- this.artifacts[existingIndex].creator = creator;
362
- this.artifacts[existingIndex].viewers = viewers.length > 0 ? viewers : [creator];
363
- returnedArtifact = this.artifacts[existingIndex];
364
- }
365
- else {
366
- const newArtifact = {
367
- name,
368
- creator,
369
- body,
370
- viewers: viewers.length > 0 ? viewers : [creator],
371
- };
372
- this.artifacts.push(newArtifact);
373
- returnedArtifact = newArtifact;
374
- }
375
- if (this.roomStoreService && this.storageDir) {
376
- this.roomStoreService.saveArtifactFile(this.id, this.storageDir, returnedArtifact);
377
- }
378
- this.saveMetadata();
379
- return returnedArtifact;
380
- }
381
- deleteArtifact(name) {
382
- const index = this.artifacts.findIndex((a) => a.name === name);
383
- if (index === -1) {
384
- return false;
385
- }
386
- this.artifacts.splice(index, 1);
387
- if (this.roomStoreService && this.storageDir) {
388
- this.roomStoreService.deleteArtifactFile(this.id, this.storageDir, name);
389
- }
390
- return true;
391
- }
392
- getVisibleArtifacts(agentNickname) {
393
- return this.artifacts.filter((a) => a.creator === agentNickname ||
394
- (a.viewers && a.viewers.includes(agentNickname)) ||
395
- !a.viewers);
396
- }
397
- getId() {
398
- return this.id;
399
- }
400
- setId(id) {
401
- this.id = id;
402
- }
403
- getStorageDir() {
404
- return this.storageDir;
405
- }
406
- setStorageDir(dir) {
407
- this.storageDir = dir;
408
- }
409
- getRoomStoreService() {
410
- return this.roomStoreService;
411
- }
412
- setRoomStoreService(service) {
413
- this.roomStoreService = service;
414
- }
415
- saveMessages(messages) {
416
- if (!this.roomStoreService || !this.storageDir || !this.id) {
417
- return;
418
- }
419
- for (const message of messages) {
420
- this.roomStoreService.appendMessageToFile(this.id, message, this.storageDir);
421
- }
422
- }
423
- saveMetadata() {
424
- if (!this.roomStoreService || !this.storageDir) {
425
- return;
426
- }
427
- if (this.isLoading) {
428
- return;
429
- }
430
- let id = this.roomStoreService.storeRoom(this, this.storageDir);
431
- this.notifyStateChange();
432
- return id;
433
- }
434
- setOnStateChange(callback) {
435
- this.onStateChange = callback;
436
- }
437
- notifyStateChange() {
438
- if (this.onStateChange) {
439
- this.onStateChange();
440
- }
441
- }
442
- setOnError(callback) {
443
- this.onError = callback;
444
- }
445
- notifyError(error) {
446
- if (this.onError) {
447
- this.onError(error);
448
- }
449
- }
450
- getHumanAgentName() {
451
- const humanAgent = this.agents.find((agent) => agent.isControlledByHuman);
452
- return humanAgent ? humanAgent.agentNickname : '';
453
- }
454
- getModeratorAgent() {
455
- if (this.agents.length > 0)
456
- return this.agents[0];
457
- }
458
- getSituation() {
459
- return this.currentSituation;
460
- }
461
- setSituation(situation) {
462
- this.currentSituation = situation;
463
- }
464
- setOnSituationUpdate(callback) {
465
- this.onSituationUpdate = callback;
466
- }
467
- handleSituationUpdate(situation) {
468
- console.log(`Situation updated: ${situation}`);
469
- this.currentSituation = situation;
470
- if (this.onSituationUpdate) {
471
- this.onSituationUpdate(situation);
472
- }
473
- }
474
- handlePublishMessages(messages) {
475
- for (const message of messages) {
476
- if (message.name) {
477
- const artifactName = message.name;
478
- const creator = message.sender;
479
- const body = message.content;
480
- const viewers = message.targets;
481
- this.publishArtifact(artifactName, creator, body, viewers);
482
- }
483
- }
484
- }
485
- handleExecuteMessages(messages) {
486
- for (const message of messages) {
487
- if (message.content && message.content.trim()) {
488
- const command = message.content.trim();
489
- const creator = message.sender;
490
- const description = message.name || 'Command execution';
491
- const resultViewers = message.targets;
492
- this.executeCommand(command, creator, description, resultViewers);
493
- }
494
- }
495
- }
496
- executeCommand(command, creator, description, resultViewers = []) {
497
- const workingDir = this.baseRoomDir || process.cwd();
498
- console.log(`FEATURE DISABLED -- Executing command: ${command} in directory: ${workingDir} by agent: ${creator}`);
499
- return;
500
- (0, child_process_1.exec)(command, { cwd: workingDir }, (error, stdout, stderr) => {
501
- let result = '';
502
- if (error) {
503
- result = `Error: ${error.message}\n${stderr}`;
504
- console.error(`Command execution error: ${error.message}`);
505
- }
506
- else if (stderr) {
507
- result = `${stdout}\n\nStderr: ${stderr}`;
508
- }
509
- else {
510
- result = stdout;
511
- }
512
- const artifactBody = `Command: ${command}\nWorking Directory: ${workingDir}\n\n${result}`;
513
- this.publishArtifact(description, creator, artifactBody, resultViewers);
514
- });
515
- }
516
- handleAdjournMessages(messages) {
517
- if (messages.length === 0) {
518
- return;
519
- }
520
- const adjournedAgents = messages.map((m) => m.sender);
521
- const allAgentNames = this.agents.map((a) => a.agentNickname);
522
- const allAdjourned = allAgentNames.every((name) => adjournedAgents.includes(name));
523
- if (allAdjourned) {
524
- this.isAdjourned = true;
525
- this.notifyStateChange();
526
- this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, 'All agents have agreed to adjourn. The conversation has ended.'));
527
- this.pendingMessages = null;
528
- }
529
- if (adjournedAgents.includes('system')) {
530
- this.isAdjourned = true;
531
- this.notifyStateChange();
532
- this.addRoomMessage(new message_1.RoomMessage('system', app_types_1.MessageAction.SYSTEM, 'The conversation has been ended by the system.'));
533
- this.pendingMessages = null;
534
- }
535
- if (adjournedAgents.includes(this.getRoomLeader())) {
536
- this.addRoomMessage(messages[0]);
537
- }
538
- }
539
- addPendingMessage(message, clearQueue = false) {
540
- if (!this.pendingMessages) {
541
- this.pendingMessages = [];
542
- }
543
- if (!message.sender) {
544
- message.sender = this.getHumanAgentName();
545
- }
546
- if (!message.sender) {
547
- message.sender = 'system';
548
- }
549
- const humanAgent = this.agents.find((a) => a.isControlledByHuman);
550
- const isHumanMessage = humanAgent && message.sender === humanAgent.agentNickname;
551
- if (isHumanMessage && this.isPaused) {
552
- if (clearQueue) {
553
- this.pendingMessages = [];
554
- }
555
- humanAgent.addToConversationHistory(message, true);
556
- humanAgent.save();
557
- this.pendingMessages.push(message);
558
- this.resume();
559
- return;
560
- }
561
- if (isHumanMessage) {
562
- if (this.currentSpeaker !== null && this.currentSpeaker !== humanAgent.agentNickname) {
563
- console.warn(`Human agent ${humanAgent.agentNickname} tried to speak out of turn. Current speaker: ${this.currentSpeaker}`);
564
- return;
565
- }
566
- humanAgent.addToConversationHistory(message, true);
567
- humanAgent.save();
568
- this.setCurrentSpeaker(null);
569
- }
570
- this.pendingMessages.push(message);
571
- if (!this.processingInProgress) {
572
- this.processPendingMessages();
573
- }
574
- }
575
- isProcessingInProgress() {
576
- return this.processingInProgress;
577
- }
578
- pause() {
579
- this.isPaused = true;
580
- const humanAgent = this.agents.find(a => a.isControlledByHuman);
581
- if (humanAgent) {
582
- this.currentSpeaker = humanAgent.agentNickname;
583
- }
584
- this.notifyStateChange();
585
- }
586
- resume() {
587
- this.isPaused = false;
588
- this.notifyStateChange();
589
- if (this.pendingMessages && this.pendingMessages.length > 0) {
590
- this.processPendingMessages();
591
- }
592
- }
593
- checkAgentNicknameMatch(existingNickname, targetNickname) {
594
- if (existingNickname.toLowerCase() === targetNickname.toLowerCase())
595
- return true;
596
- const nicknameFirstWord = existingNickname.split(/\s+/)[0];
597
- if (nicknameFirstWord.toLowerCase() === targetNickname.toLowerCase())
598
- return true;
599
- return false;
600
- }
601
- handleModeratorResponse(moderatorMessage, originalMessage) {
602
- try {
603
- let responderNickname = moderatorMessage.name;
604
- const roomLeaderName = this.getRoomLeader();
605
- const targets = moderatorMessage.targets || [];
606
- if (!targets.includes(roomLeaderName))
607
- targets.push(roomLeaderName);
608
- let content = moderatorMessage.content;
609
- if (content && content.startsWith('relay'))
610
- content = originalMessage.getContent();
611
- if (originalMessage.content != content) {
612
- console.warn(`Moderator changed content:\n${originalMessage.content}\nto\n${content}`);
613
- originalMessage.content = content;
614
- }
615
- if (this.checkAgentNicknameMatch(originalMessage.sender, responderNickname)) {
616
- let responder = this.getHumanAgentName();
617
- if (!responder)
618
- responder = roomLeaderName;
619
- this.setCurrentSpeaker(responder);
620
- console.warn(`Moderator routed message to sender: ${originalMessage.sender}. Setting responder to room leader: ${responder}`);
621
- }
622
- console.log(`Moderator routing: sender=${originalMessage.sender} action=${moderatorMessage.action}, name=${responderNickname}, targets=${targets.join(', ')}`);
623
- if (moderatorMessage.action === app_types_1.MessageAction.RELAY) {
624
- this.addRoomMessage(new message_1.RoomMessage(originalMessage.sender, originalMessage.action, content, originalMessage.targets, originalMessage.name, originalMessage.situation));
625
- }
626
- for (const recipientName of targets) {
627
- if (recipientName === responderNickname)
628
- continue;
629
- if (recipientName === originalMessage.sender)
630
- continue;
631
- const recipient = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, recipientName));
632
- if (recipient) {
633
- recipient.addToConversationHistory(`From: ${originalMessage.sender}\n${content}`, false);
634
- recipient.save();
635
- }
636
- }
637
- let responderAgent = this.agents.find((a) => this.checkAgentNicknameMatch(a.agentNickname, responderNickname));
638
- if (!responderAgent) {
639
- let roomLeaderAgent = this.agents.find((a) => a.agentNickname === this.getRoomLeader());
640
- if (!roomLeaderAgent)
641
- throw new Error(`Room leader agent not found`);
642
- console.warn(`Responder agent not found: ${responderNickname}`);
643
- responderAgent = roomLeaderAgent;
644
- if (responderNickname) {
645
- if (this.onSituationUpdate && responderNickname.length > 0) {
646
- this.onSituationUpdate(`INTRODUCE: ${responderNickname}`);
647
- }
648
- }
649
- }
650
- if (responderAgent.isControlledByHuman) {
651
- console.log(`Waiting for human agent ${responderNickname} to respond`);
652
- responderAgent.addToConversationHistory(`From: ${originalMessage.sender}\n${content}`, false);
653
- responderAgent.save();
654
- this.processingInProgress = false;
655
- this.notifyStateChange();
656
- this.setCurrentSpeaker(responderNickname);
657
- return;
658
- }
659
- this.setCurrentSpeaker(responderNickname);
660
- this.perceive(responderAgent, originalMessage, (response) => {
661
- if (response !== null) {
662
- this.pendingMessages = [response, ...this.pendingMessages];
663
- }
664
- this.setCurrentSpeaker(null);
665
- this.processingInProgress = false;
666
- this.notifyStateChange();
667
- if (this.pendingMessages && this.pendingMessages.length > 0) {
668
- this.processPendingMessages();
669
- }
670
- });
671
- }
672
- catch (error) {
673
- console.error('Error parsing moderator response:', error);
674
- console.error('Moderator message content:', moderatorMessage.content);
675
- this.processingInProgress = false;
676
- this.notifyStateChange();
677
- if (this.pendingMessages && this.pendingMessages.length > 0) {
678
- this.processPendingMessages();
679
- }
680
- }
681
- }
682
- processPendingMessages() {
683
- if (this.isPaused ||
684
- this.processingInProgress ||
685
- !this.pendingMessages ||
686
- this.pendingMessages.length === 0) {
687
- return;
688
- }
689
- this.processingInProgress = true;
690
- this.notifyStateChange();
691
- const messages = [...this.pendingMessages];
692
- this.pendingMessages = [];
693
- this.handlePublishMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.PUBLISH));
694
- this.handleExecuteMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.EXECUTE));
695
- this.handleAdjournMessages(messages.filter((m) => m.getAction() === app_types_1.MessageAction.ADJOURN));
696
- if (this.isAdjourned) {
697
- console.log(`Room ${this.name} has been adjourned. Message processing stopped.`);
698
- this.pendingMessages = null;
699
- this.processingInProgress = false;
700
- this.notifyStateChange();
701
- return;
702
- }
703
- const moderateMessages = messages.filter((m) => m.getAction() === app_types_1.MessageAction.MODERATE);
704
- let regularMessages = messages.filter((m) => m.getAction() !== app_types_1.MessageAction.MODERATE &&
705
- m.getAction() !== app_types_1.MessageAction.PUBLISH &&
706
- m.getAction() !== app_types_1.MessageAction.EXECUTE &&
707
- m.getAction() !== app_types_1.MessageAction.ADJOURN);
708
- if (moderateMessages.length > 0) {
709
- const moderator = this.getModeratorAgent();
710
- if (!moderator) {
711
- console.warn('MODERATE messages found but no moderator agent in room');
712
- this.processingInProgress = false;
713
- this.notifyStateChange();
714
- return;
715
- }
716
- const originalMessage = moderateMessages[0];
717
- if (moderateMessages.length > 1) {
718
- this.pendingMessages = [...moderateMessages.slice(1), ...this.pendingMessages];
719
- }
720
- this.moderate(moderator, originalMessage, (response) => {
721
- if (response !== null) {
722
- this.handleModeratorResponse(response, originalMessage);
723
- }
724
- else {
725
- this.processingInProgress = false;
726
- this.notifyStateChange();
727
- if (this.pendingMessages && this.pendingMessages.length > 0) {
728
- this.processPendingMessages();
729
- }
730
- }
731
- });
732
- return;
733
- }
734
- if (regularMessages.length === 0)
735
- return;
736
- let nextMessage;
737
- if (regularMessages.length == 1)
738
- nextMessage = regularMessages[0];
739
- else if (regularMessages.length > 1) {
740
- let filteredMessage = this.filterConcurrentMessages(regularMessages);
741
- for (const m of regularMessages) {
742
- if (m.sender !== filteredMessage.sender) {
743
- let skippedAgent = this.agents.find((a) => a.agentNickname === m.sender);
744
- if (skippedAgent)
745
- skippedAgent.addToConversationHistory(`From system: Your most recent response was not heard in the room because you were interrupted by ${filteredMessage.sender}`, false);
746
- }
747
- }
748
- nextMessage = filteredMessage;
749
- }
750
- this.addRoomMessage(nextMessage);
751
- this.setCurrentSpeaker(nextMessage.targets[0]);
752
- let agentsRemaining = this.agents.length;
753
- for (const agent of this.agents) {
754
- this.perceive(agent, nextMessage, (message) => {
755
- agentsRemaining--;
756
- if (message !== null) {
757
- if (message.action === app_types_1.MessageAction.THINK) {
758
- this.addRoomMessage(message);
759
- }
760
- else if (message.action === app_types_1.MessageAction.SHOUT) {
761
- this.pendingMessages = [message, ...this.pendingMessages];
762
- }
763
- else {
764
- this.pendingMessages = [...this.pendingMessages, message];
765
- }
766
- }
767
- if (agentsRemaining === 0) {
768
- this.processingInProgress = false;
769
- this.notifyStateChange();
770
- if (this.pendingMessages && this.pendingMessages.length > 0) {
771
- this.processPendingMessages();
772
- }
773
- }
774
- });
775
- }
776
- this.processingInProgress = false;
777
- this.notifyStateChange();
778
- }
779
- filterConcurrentMessages(messages) {
780
- if (messages.length == 0)
781
- return null;
782
- if (messages.length == 1) {
783
- return messages[0];
784
- }
785
- let filtered = messages;
786
- const systemMessages = filtered.filter((m) => m.getSender() === 'system');
787
- if (systemMessages.length > 0) {
788
- return systemMessages[0];
789
- }
790
- const shoutMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SHOUT);
791
- if (shoutMessages.length > 0) {
792
- filtered = shoutMessages;
793
- }
794
- if (filtered.length > 1) {
795
- const speakMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.SPEAK);
796
- const whisperMessages = filtered.filter((m) => m.getAction() === app_types_1.MessageAction.WHISPER);
797
- if (speakMessages.length > 0) {
798
- filtered = speakMessages;
799
- }
800
- else {
801
- filtered = whisperMessages;
802
- }
803
- }
804
- if (filtered.length > 1) {
805
- const targetedMessages = filtered.filter((m) => m.getSender() === this.currentSpeaker);
806
- if (targetedMessages.length === 1) {
807
- filtered = targetedMessages;
808
- }
809
- }
810
- if (filtered.length > 1) {
811
- let earliestMessage = null;
812
- let earliestIndex = Infinity;
813
- for (const message of filtered) {
814
- const agentIndex = this.agents.findIndex((a) => a.agentNickname === message.getSender());
815
- if (agentIndex !== -1 && agentIndex < earliestIndex) {
816
- earliestIndex = agentIndex;
817
- earliestMessage = message;
818
- }
819
- }
820
- if (earliestMessage) {
821
- filtered = [earliestMessage];
822
- }
823
- else if (filtered.length > 0) {
824
- filtered = [filtered[0]];
825
- }
826
- }
827
- if (filtered.length > 0) {
828
- return filtered[0];
829
- }
830
- return null;
831
- }
832
- }
833
- exports.Room = Room;