@happyvertical/smrt-chat 0.37.1 → 0.37.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.
@@ -0,0 +1,1737 @@
1
+ import { ObjectRegistry, SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, smrt } from "@happyvertical/smrt-core";
2
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
3
+ import { createHash } from "node:crypto";
4
+ //#region src/models/AgentSession.ts
5
+ var __defProp$5 = Object.defineProperty;
6
+ var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp$5(obj, key, {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value
12
+ }) : obj[key] = value;
13
+ var __decorateClass$5 = (decorators, target, key, kind) => {
14
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$5(target, key) : target;
15
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
16
+ if (kind && result) __defProp$5(target, key, result);
17
+ return result;
18
+ };
19
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
20
+ var AgentSession = class extends SmrtObject {
21
+ tenantId = null;
22
+ agentId = "";
23
+ participantProfileId = "";
24
+ chatRoomId = null;
25
+ status = "active";
26
+ allowedTools = "[]";
27
+ sessionContext = "{}";
28
+ systemPrompt = "";
29
+ messageCount = 0;
30
+ totalTokensUsed = 0;
31
+ maxTokens = 0;
32
+ maxMessages = 0;
33
+ lastMessageAt = null;
34
+ expiresAt = null;
35
+ closedAt = null;
36
+ constructor(options = {}) {
37
+ super(options);
38
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
39
+ if (options.agentId !== void 0) this.agentId = options.agentId;
40
+ if (options.participantProfileId !== void 0) this.participantProfileId = options.participantProfileId;
41
+ if (options.chatRoomId !== void 0) this.chatRoomId = options.chatRoomId;
42
+ if (options.status !== void 0) this.status = options.status;
43
+ if (options.allowedTools !== void 0) this.allowedTools = options.allowedTools;
44
+ if (options.sessionContext !== void 0) this.sessionContext = options.sessionContext;
45
+ if (options.systemPrompt !== void 0) this.systemPrompt = options.systemPrompt;
46
+ if (options.messageCount !== void 0) this.messageCount = options.messageCount;
47
+ if (options.totalTokensUsed !== void 0) this.totalTokensUsed = options.totalTokensUsed;
48
+ if (options.maxTokens !== void 0) this.maxTokens = options.maxTokens;
49
+ if (options.maxMessages !== void 0) this.maxMessages = options.maxMessages;
50
+ if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
51
+ if (options.expiresAt !== void 0) this.expiresAt = options.expiresAt;
52
+ if (options.closedAt !== void 0) this.closedAt = options.closedAt;
53
+ }
54
+ getAllowedTools() {
55
+ try {
56
+ const parsed = JSON.parse(this.allowedTools);
57
+ return Array.isArray(parsed) ? parsed.filter((t) => typeof t === "string") : [];
58
+ } catch {
59
+ return [];
60
+ }
61
+ }
62
+ setAllowedTools(tools) {
63
+ this.allowedTools = JSON.stringify(tools);
64
+ }
65
+ /**
66
+ * Fail-closed authorization check for an agent tool call (S5 #1392).
67
+ *
68
+ * A tool may only be invoked when it appears in this session's allow-list.
69
+ * If the allow-list is empty or unparseable, NO tools are permitted. This is
70
+ * deliberately conservative: an empty whitelist means "no tools", never
71
+ * "all tools".
72
+ */
73
+ isToolAllowed(toolName) {
74
+ if (typeof toolName !== "string" || toolName.length === 0) return false;
75
+ return this.getAllowedTools().includes(toolName);
76
+ }
77
+ isActive() {
78
+ if (this.status !== "active") return false;
79
+ if (this.expiresAt && /* @__PURE__ */ new Date() >= this.expiresAt) return false;
80
+ if (this.maxMessages > 0 && this.messageCount >= this.maxMessages) return false;
81
+ if (this.maxTokens > 0 && this.totalTokensUsed >= this.maxTokens) return false;
82
+ return true;
83
+ }
84
+ isExpired() {
85
+ return this.expiresAt !== null && /* @__PURE__ */ new Date() >= this.expiresAt;
86
+ }
87
+ async close() {
88
+ this.status = "closed";
89
+ this.closedAt = /* @__PURE__ */ new Date();
90
+ await this.save();
91
+ }
92
+ async expire() {
93
+ this.status = "expired";
94
+ this.closedAt = /* @__PURE__ */ new Date();
95
+ await this.save();
96
+ }
97
+ getSessionContext() {
98
+ try {
99
+ return JSON.parse(this.sessionContext);
100
+ } catch {
101
+ return {};
102
+ }
103
+ }
104
+ setSessionContext(ctx) {
105
+ this.sessionContext = JSON.stringify(ctx);
106
+ }
107
+ /**
108
+ * Stable identity key that scopes this session to a conversation subject
109
+ * (S5 #1392). Returns `null` when the session is not subject-scoped. Used by
110
+ * the reuse lookup so a session opened for one subject is never reused for a
111
+ * request about a different subject.
112
+ */
113
+ getSessionKey() {
114
+ const value = this.getSessionContext()[AgentSession.SESSION_KEY_CONTEXT_FIELD];
115
+ return typeof value === "string" && value.length > 0 ? value : null;
116
+ }
117
+ async updateSessionContext(updates) {
118
+ const current = this.getSessionContext();
119
+ this.sessionContext = JSON.stringify({
120
+ ...current,
121
+ ...updates
122
+ });
123
+ await this.save();
124
+ }
125
+ async recordMessage(tokensUsed = 0) {
126
+ this.messageCount++;
127
+ this.totalTokensUsed += tokensUsed;
128
+ this.lastMessageAt = /* @__PURE__ */ new Date();
129
+ await this.save();
130
+ }
131
+ };
132
+ /**
133
+ * Reserved `sessionContext` key that scopes a session's identity to a caller-
134
+ * supplied conversation subject (e.g. a content id) (S5 #1392).
135
+ *
136
+ * `createAgentSession`'s reuse path keys on `(agentId, participantProfileId,
137
+ * tenantId)`; without a discriminator a session opened for subject A would be
138
+ * reused (and its context rewritten) for a request about subject B, returning
139
+ * A's room/threads on B's route. Storing the key here lets the reuse lookup
140
+ * require an exact match so distinct subjects get distinct sessions.
141
+ */
142
+ __publicField(AgentSession, "SESSION_KEY_CONTEXT_FIELD", "__sessionKey");
143
+ __decorateClass$5([tenantId({ nullable: true })], AgentSession.prototype, "tenantId", 2);
144
+ __decorateClass$5([field({ required: true })], AgentSession.prototype, "agentId", 2);
145
+ __decorateClass$5([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], AgentSession.prototype, "participantProfileId", 2);
146
+ __decorateClass$5([foreignKey("ChatRoom")], AgentSession.prototype, "chatRoomId", 2);
147
+ __decorateClass$5([field({ required: true })], AgentSession.prototype, "status", 2);
148
+ __decorateClass$5([field()], AgentSession.prototype, "allowedTools", 2);
149
+ __decorateClass$5([field()], AgentSession.prototype, "sessionContext", 2);
150
+ __decorateClass$5([field()], AgentSession.prototype, "systemPrompt", 2);
151
+ __decorateClass$5([field()], AgentSession.prototype, "messageCount", 2);
152
+ __decorateClass$5([field()], AgentSession.prototype, "totalTokensUsed", 2);
153
+ __decorateClass$5([field()], AgentSession.prototype, "maxTokens", 2);
154
+ __decorateClass$5([field()], AgentSession.prototype, "maxMessages", 2);
155
+ __decorateClass$5([field()], AgentSession.prototype, "lastMessageAt", 2);
156
+ __decorateClass$5([field()], AgentSession.prototype, "expiresAt", 2);
157
+ __decorateClass$5([field()], AgentSession.prototype, "closedAt", 2);
158
+ AgentSession = __decorateClass$5([TenantScoped({ mode: "optional" }), smrt({
159
+ tableName: "agent_sessions",
160
+ api: { include: ["list", "get"] },
161
+ mcp: { include: ["list", "get"] },
162
+ cli: true
163
+ })], AgentSession);
164
+ //#endregion
165
+ //#region src/models/ChatMessage.ts
166
+ var __defProp$4 = Object.defineProperty;
167
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
168
+ var __decorateClass$4 = (decorators, target, key, kind) => {
169
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
170
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
171
+ if (kind && result) __defProp$4(target, key, result);
172
+ return result;
173
+ };
174
+ var ChatMessage = class extends SmrtObject {
175
+ tenantId = "";
176
+ roomId = "";
177
+ threadId = null;
178
+ senderProfileId = "";
179
+ agentSessionId = null;
180
+ content = "";
181
+ messageType = "text";
182
+ role = "user";
183
+ isEdited = false;
184
+ editedAt = null;
185
+ isDeleted = false;
186
+ replyToMessageId = null;
187
+ metadata = "{}";
188
+ toolCallData = null;
189
+ attachments = "[]";
190
+ constructor(options = {}) {
191
+ super(options);
192
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
193
+ if (options.roomId !== void 0) this.roomId = options.roomId;
194
+ if (options.threadId !== void 0) this.threadId = options.threadId;
195
+ if (options.senderProfileId !== void 0) this.senderProfileId = options.senderProfileId;
196
+ if (options.agentSessionId !== void 0) this.agentSessionId = options.agentSessionId;
197
+ if (options.content !== void 0) this.content = options.content;
198
+ if (options.messageType !== void 0) this.messageType = options.messageType;
199
+ if (options.role !== void 0) this.role = options.role;
200
+ if (options.isEdited !== void 0) this.isEdited = options.isEdited;
201
+ if (options.editedAt !== void 0) this.editedAt = options.editedAt;
202
+ if (options.isDeleted !== void 0) this.isDeleted = options.isDeleted;
203
+ if (options.replyToMessageId !== void 0) this.replyToMessageId = options.replyToMessageId;
204
+ if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
205
+ if (options.toolCallData !== void 0) this.toolCallData = options.toolCallData === null ? null : typeof options.toolCallData === "string" ? options.toolCallData : JSON.stringify(options.toolCallData);
206
+ if (options.attachments !== void 0) this.attachments = options.attachments;
207
+ }
208
+ getAttachments() {
209
+ try {
210
+ return JSON.parse(this.attachments);
211
+ } catch {
212
+ return [];
213
+ }
214
+ }
215
+ setAttachments(items) {
216
+ this.attachments = JSON.stringify(items);
217
+ }
218
+ getMetadata() {
219
+ try {
220
+ return JSON.parse(this.metadata);
221
+ } catch {
222
+ return {};
223
+ }
224
+ }
225
+ setMetadata(data) {
226
+ this.metadata = JSON.stringify(data);
227
+ }
228
+ getToolCallData() {
229
+ if (!this.toolCallData) return null;
230
+ try {
231
+ return JSON.parse(this.toolCallData);
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+ setToolCallData(data) {
237
+ this.toolCallData = data ? JSON.stringify(data) : null;
238
+ }
239
+ hasAttachments() {
240
+ return this.getAttachments().length > 0;
241
+ }
242
+ isToolCall() {
243
+ return this.messageType === "tool_call";
244
+ }
245
+ isToolResult() {
246
+ return this.messageType === "tool_result";
247
+ }
248
+ isFromAgent() {
249
+ return this.role === "assistant";
250
+ }
251
+ isSystemMessage() {
252
+ return this.role === "system";
253
+ }
254
+ async edit(newContent) {
255
+ this.content = newContent;
256
+ this.isEdited = true;
257
+ this.editedAt = /* @__PURE__ */ new Date();
258
+ await this.save();
259
+ }
260
+ async softDelete() {
261
+ this.isDeleted = true;
262
+ this.content = "";
263
+ await this.save();
264
+ }
265
+ getPreview(maxLength = 100) {
266
+ if (this.isDeleted) return "(deleted)";
267
+ const text = this.content || "";
268
+ if (text.length <= maxLength) return text;
269
+ return `${text.slice(0, maxLength)}...`;
270
+ }
271
+ };
272
+ __decorateClass$4([tenantId()], ChatMessage.prototype, "tenantId", 2);
273
+ __decorateClass$4([foreignKey("ChatRoom", { required: true })], ChatMessage.prototype, "roomId", 2);
274
+ __decorateClass$4([foreignKey("ChatThread")], ChatMessage.prototype, "threadId", 2);
275
+ __decorateClass$4([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], ChatMessage.prototype, "senderProfileId", 2);
276
+ __decorateClass$4([foreignKey("AgentSession")], ChatMessage.prototype, "agentSessionId", 2);
277
+ __decorateClass$4([field()], ChatMessage.prototype, "content", 2);
278
+ __decorateClass$4([field({ required: true })], ChatMessage.prototype, "messageType", 2);
279
+ __decorateClass$4([field({ required: true })], ChatMessage.prototype, "role", 2);
280
+ __decorateClass$4([field()], ChatMessage.prototype, "isEdited", 2);
281
+ __decorateClass$4([field()], ChatMessage.prototype, "editedAt", 2);
282
+ __decorateClass$4([field()], ChatMessage.prototype, "isDeleted", 2);
283
+ __decorateClass$4([foreignKey("ChatMessage")], ChatMessage.prototype, "replyToMessageId", 2);
284
+ __decorateClass$4([field()], ChatMessage.prototype, "metadata", 2);
285
+ __decorateClass$4([field()], ChatMessage.prototype, "toolCallData", 2);
286
+ __decorateClass$4([field()], ChatMessage.prototype, "attachments", 2);
287
+ ChatMessage = __decorateClass$4([TenantScoped({ mode: "required" }), smrt({
288
+ tableName: "chat_messages",
289
+ api: { include: ["list", "get"] },
290
+ mcp: { include: ["list", "get"] },
291
+ cli: true
292
+ })], ChatMessage);
293
+ //#endregion
294
+ //#region src/models/ChatParticipant.ts
295
+ var __defProp$3 = Object.defineProperty;
296
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
297
+ var __decorateClass$3 = (decorators, target, key, kind) => {
298
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
299
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
300
+ if (kind && result) __defProp$3(target, key, result);
301
+ return result;
302
+ };
303
+ var ChatParticipant = class extends SmrtObject {
304
+ tenantId = "";
305
+ roomId = "";
306
+ profileId = "";
307
+ role = "member";
308
+ status = "active";
309
+ onlineStatus = "offline";
310
+ lastReadMessageId = null;
311
+ lastSeenAt = null;
312
+ joinedAt = null;
313
+ nickname = "";
314
+ isMuted = false;
315
+ isPinned = false;
316
+ constructor(options = {}) {
317
+ super(options);
318
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
319
+ if (options.roomId !== void 0) this.roomId = options.roomId;
320
+ if (options.profileId !== void 0) this.profileId = options.profileId;
321
+ if (options.role !== void 0) this.role = options.role;
322
+ if (options.status !== void 0) this.status = options.status;
323
+ if (options.onlineStatus !== void 0) this.onlineStatus = options.onlineStatus;
324
+ if (options.lastReadMessageId !== void 0) this.lastReadMessageId = options.lastReadMessageId;
325
+ if (options.lastSeenAt !== void 0) this.lastSeenAt = options.lastSeenAt;
326
+ if (options.joinedAt !== void 0) this.joinedAt = options.joinedAt;
327
+ if (options.nickname !== void 0) this.nickname = options.nickname;
328
+ if (options.isMuted !== void 0) this.isMuted = options.isMuted;
329
+ if (options.isPinned !== void 0) this.isPinned = options.isPinned;
330
+ }
331
+ isActive() {
332
+ return this.status === "active";
333
+ }
334
+ isOwner() {
335
+ return this.role === "owner";
336
+ }
337
+ isAdmin() {
338
+ return this.role === "admin" || this.role === "owner";
339
+ }
340
+ async markRead(messageId) {
341
+ this.lastReadMessageId = messageId;
342
+ this.lastSeenAt = /* @__PURE__ */ new Date();
343
+ await this.save();
344
+ }
345
+ async leave() {
346
+ this.status = "left";
347
+ await this.save();
348
+ }
349
+ async setOnline(status) {
350
+ this.onlineStatus = status;
351
+ this.lastSeenAt = /* @__PURE__ */ new Date();
352
+ await this.save();
353
+ }
354
+ };
355
+ __decorateClass$3([tenantId()], ChatParticipant.prototype, "tenantId", 2);
356
+ __decorateClass$3([foreignKey("ChatRoom", { required: true })], ChatParticipant.prototype, "roomId", 2);
357
+ __decorateClass$3([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], ChatParticipant.prototype, "profileId", 2);
358
+ __decorateClass$3([field({ required: true })], ChatParticipant.prototype, "role", 2);
359
+ __decorateClass$3([field({ required: true })], ChatParticipant.prototype, "status", 2);
360
+ __decorateClass$3([field({ required: true })], ChatParticipant.prototype, "onlineStatus", 2);
361
+ __decorateClass$3([foreignKey("ChatMessage")], ChatParticipant.prototype, "lastReadMessageId", 2);
362
+ __decorateClass$3([field()], ChatParticipant.prototype, "lastSeenAt", 2);
363
+ __decorateClass$3([field()], ChatParticipant.prototype, "joinedAt", 2);
364
+ __decorateClass$3([field()], ChatParticipant.prototype, "nickname", 2);
365
+ __decorateClass$3([field()], ChatParticipant.prototype, "isMuted", 2);
366
+ __decorateClass$3([field()], ChatParticipant.prototype, "isPinned", 2);
367
+ ChatParticipant = __decorateClass$3([TenantScoped({ mode: "required" }), smrt({
368
+ tableName: "chat_participants",
369
+ api: { include: ["list", "get"] },
370
+ mcp: { include: ["list", "get"] },
371
+ cli: true
372
+ })], ChatParticipant);
373
+ //#endregion
374
+ //#region src/models/ChatReaction.ts
375
+ var __defProp$2 = Object.defineProperty;
376
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
377
+ var __decorateClass$2 = (decorators, target, key, kind) => {
378
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
379
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
380
+ if (kind && result) __defProp$2(target, key, result);
381
+ return result;
382
+ };
383
+ var ChatReaction = class extends SmrtObject {
384
+ tenantId = "";
385
+ messageId = "";
386
+ profileId = "";
387
+ emoji = "";
388
+ constructor(options = {}) {
389
+ super(options);
390
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
391
+ if (options.messageId !== void 0) this.messageId = options.messageId;
392
+ if (options.profileId !== void 0) this.profileId = options.profileId;
393
+ if (options.emoji !== void 0) this.emoji = options.emoji;
394
+ }
395
+ };
396
+ __decorateClass$2([tenantId()], ChatReaction.prototype, "tenantId", 2);
397
+ __decorateClass$2([foreignKey("ChatMessage", { required: true })], ChatReaction.prototype, "messageId", 2);
398
+ __decorateClass$2([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], ChatReaction.prototype, "profileId", 2);
399
+ __decorateClass$2([field({ required: true })], ChatReaction.prototype, "emoji", 2);
400
+ ChatReaction = __decorateClass$2([TenantScoped({ mode: "required" }), smrt({
401
+ tableName: "chat_reactions",
402
+ api: { include: ["list"] },
403
+ mcp: { include: ["list"] },
404
+ cli: false
405
+ })], ChatReaction);
406
+ //#endregion
407
+ //#region src/models/ChatRoom.ts
408
+ var __defProp$1 = Object.defineProperty;
409
+ var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
410
+ var __decorateClass$1 = (decorators, target, key, kind) => {
411
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
412
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
413
+ if (kind && result) __defProp$1(target, key, result);
414
+ return result;
415
+ };
416
+ var ChatRoom = class extends SmrtObject {
417
+ tenantId = "";
418
+ name = "";
419
+ description = "";
420
+ roomType = "public";
421
+ status = "active";
422
+ topic = "";
423
+ avatarUrl = "";
424
+ isArchived = false;
425
+ maxParticipants = 0;
426
+ metadata = "{}";
427
+ createdByProfileId = "";
428
+ lastMessageAt = null;
429
+ constructor(options = {}) {
430
+ super(options);
431
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
432
+ if (options.name !== void 0) this.name = options.name;
433
+ if (options.description !== void 0) this.description = options.description;
434
+ if (options.roomType !== void 0) this.roomType = options.roomType;
435
+ if (options.status !== void 0) this.status = options.status;
436
+ if (options.topic !== void 0) this.topic = options.topic;
437
+ if (options.avatarUrl !== void 0) this.avatarUrl = options.avatarUrl;
438
+ if (options.isArchived !== void 0) this.isArchived = options.isArchived;
439
+ if (options.maxParticipants !== void 0) this.maxParticipants = options.maxParticipants;
440
+ if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
441
+ if (options.createdByProfileId !== void 0) this.createdByProfileId = options.createdByProfileId;
442
+ if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
443
+ }
444
+ getMetadata() {
445
+ try {
446
+ return JSON.parse(this.metadata);
447
+ } catch {
448
+ return {};
449
+ }
450
+ }
451
+ setMetadata(data) {
452
+ this.metadata = JSON.stringify(data);
453
+ }
454
+ updateMetadata(updates) {
455
+ const current = this.getMetadata();
456
+ this.metadata = JSON.stringify({
457
+ ...current,
458
+ ...updates
459
+ });
460
+ }
461
+ isDM() {
462
+ return this.roomType === "dm";
463
+ }
464
+ isAgentRoom() {
465
+ return this.roomType === "agent";
466
+ }
467
+ isPublic() {
468
+ return this.roomType === "public";
469
+ }
470
+ isActive() {
471
+ return this.status === "active";
472
+ }
473
+ async archive() {
474
+ this.isArchived = true;
475
+ this.status = "archived";
476
+ await this.save();
477
+ }
478
+ async unarchive() {
479
+ this.isArchived = false;
480
+ this.status = "active";
481
+ await this.save();
482
+ }
483
+ };
484
+ __decorateClass$1([tenantId()], ChatRoom.prototype, "tenantId", 2);
485
+ __decorateClass$1([field()], ChatRoom.prototype, "name", 2);
486
+ __decorateClass$1([field()], ChatRoom.prototype, "description", 2);
487
+ __decorateClass$1([field({ required: true })], ChatRoom.prototype, "roomType", 2);
488
+ __decorateClass$1([field({ required: true })], ChatRoom.prototype, "status", 2);
489
+ __decorateClass$1([field()], ChatRoom.prototype, "topic", 2);
490
+ __decorateClass$1([field()], ChatRoom.prototype, "avatarUrl", 2);
491
+ __decorateClass$1([field()], ChatRoom.prototype, "isArchived", 2);
492
+ __decorateClass$1([field()], ChatRoom.prototype, "maxParticipants", 2);
493
+ __decorateClass$1([field()], ChatRoom.prototype, "metadata", 2);
494
+ __decorateClass$1([crossPackageRef("@happyvertical/smrt-profiles:Profile")], ChatRoom.prototype, "createdByProfileId", 2);
495
+ __decorateClass$1([field()], ChatRoom.prototype, "lastMessageAt", 2);
496
+ ChatRoom = __decorateClass$1([TenantScoped({ mode: "required" }), smrt({
497
+ tableName: "chat_rooms",
498
+ api: { include: ["list", "get"] },
499
+ mcp: { include: ["list", "get"] },
500
+ cli: true
501
+ })], ChatRoom);
502
+ //#endregion
503
+ //#region src/models/ChatThread.ts
504
+ var __defProp = Object.defineProperty;
505
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
506
+ var __decorateClass = (decorators, target, key, kind) => {
507
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
508
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
509
+ if (kind && result) __defProp(target, key, result);
510
+ return result;
511
+ };
512
+ var ChatThread = class extends SmrtObject {
513
+ tenantId = "";
514
+ roomId = "";
515
+ rootMessageId = null;
516
+ title = "";
517
+ isResolved = false;
518
+ messageCount = 0;
519
+ lastMessageAt = null;
520
+ participantCount = 0;
521
+ constructor(options = {}) {
522
+ super(options);
523
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
524
+ if (options.roomId !== void 0) this.roomId = options.roomId;
525
+ if (options.rootMessageId !== void 0) this.rootMessageId = options.rootMessageId;
526
+ if (options.title !== void 0) this.title = options.title;
527
+ if (options.isResolved !== void 0) this.isResolved = options.isResolved;
528
+ if (options.messageCount !== void 0) this.messageCount = options.messageCount;
529
+ if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
530
+ if (options.participantCount !== void 0) this.participantCount = options.participantCount;
531
+ }
532
+ async resolve() {
533
+ this.isResolved = true;
534
+ await this.save();
535
+ }
536
+ async reopen() {
537
+ this.isResolved = false;
538
+ await this.save();
539
+ }
540
+ };
541
+ __decorateClass([tenantId()], ChatThread.prototype, "tenantId", 2);
542
+ __decorateClass([foreignKey("ChatRoom", { required: true })], ChatThread.prototype, "roomId", 2);
543
+ __decorateClass([foreignKey("ChatMessage", { nullable: true })], ChatThread.prototype, "rootMessageId", 2);
544
+ __decorateClass([field()], ChatThread.prototype, "title", 2);
545
+ __decorateClass([field()], ChatThread.prototype, "isResolved", 2);
546
+ __decorateClass([field()], ChatThread.prototype, "messageCount", 2);
547
+ __decorateClass([field()], ChatThread.prototype, "lastMessageAt", 2);
548
+ __decorateClass([field()], ChatThread.prototype, "participantCount", 2);
549
+ ChatThread = __decorateClass([TenantScoped({ mode: "required" }), smrt({
550
+ tableName: "chat_threads",
551
+ api: { include: ["list", "get"] },
552
+ mcp: { include: ["list", "get"] },
553
+ cli: true
554
+ })], ChatThread);
555
+ //#endregion
556
+ //#region src/collections/AgentSessionCollection.ts
557
+ var AgentSessionCollection = class extends SmrtCollection {
558
+ static _itemClass = AgentSession;
559
+ async findActiveByParticipant(participantProfileId) {
560
+ return (await this.list({ where: {
561
+ participantProfileId,
562
+ status: "active"
563
+ } })).filter((s) => s.isActive());
564
+ }
565
+ /**
566
+ * Resolve the active agent session for an (agent, participant) pair within a
567
+ * tenant (S5 #1392).
568
+ *
569
+ * `tenantId` is REQUIRED and always bound into the WHERE clause — including the
570
+ * `null` (untenanted) case — so the lookup can never silently drop its tenant
571
+ * predicate and resolve a session from another tenant. AgentSession uses
572
+ * optional tenancy, so `null` is a legitimate, explicitly-bound scope rather
573
+ * than "any tenant".
574
+ *
575
+ * When `sessionKey` is supplied the result is additionally narrowed to the
576
+ * session whose stored {@link AgentSession.getSessionKey} matches EXACTLY
577
+ * (S5 #1392). This binds session identity to a conversation subject (e.g. a
578
+ * content id) so a session opened for one subject is never reused for another;
579
+ * `sessionContext` is a JSON blob so the discriminator is matched in memory
580
+ * after the tenant-bound SQL filter.
581
+ */
582
+ async findActiveSession(agentId, participantProfileId, tenantId, sessionKey) {
583
+ const where = {
584
+ agentId,
585
+ participantProfileId,
586
+ status: "active",
587
+ tenantId
588
+ };
589
+ return (await this.list({ where })).find((s) => s.isActive() && (sessionKey === void 0 || s.getSessionKey() === (sessionKey ?? null))) ?? null;
590
+ }
591
+ async findOrCreate(params) {
592
+ const existing = await this.findActiveSession(params.agentId, params.participantProfileId, params.tenantId, params.sessionKey);
593
+ if (existing) return existing;
594
+ const sessionContext = params.sessionKey != null ? JSON.stringify({ [AgentSession.SESSION_KEY_CONTEXT_FIELD]: params.sessionKey }) : void 0;
595
+ return await this.create({
596
+ agentId: params.agentId,
597
+ participantProfileId: params.participantProfileId,
598
+ tenantId: params.tenantId ?? null,
599
+ allowedTools: JSON.stringify(params.allowedTools ?? []),
600
+ chatRoomId: params.chatRoomId ?? null,
601
+ systemPrompt: params.systemPrompt ?? "",
602
+ status: "active",
603
+ ...sessionContext !== void 0 ? { sessionContext } : {}
604
+ });
605
+ }
606
+ async findByAgent(agentId) {
607
+ return this.list({ where: { agentId } });
608
+ }
609
+ /**
610
+ * Expire active sessions whose last activity predates `olderThan`.
611
+ *
612
+ * Caller-scoping (S5 #1392): pass `scope` to restrict the sweep to a single
613
+ * tenant and/or agent. Without a scope this expires stale sessions across the
614
+ * whole (tenant-filtered) collection — only safe for trusted maintenance
615
+ * callers, never for a per-tenant request handler.
616
+ *
617
+ * The candidate set is narrowed in SQL (status + activity timestamp) rather
618
+ * than loading every active session into memory and filtering in JS
619
+ * (DoS hardening). `lastMessageAt < olderThan` is applied server-side; rows
620
+ * that never recorded a message fall back to `created_at`.
621
+ */
622
+ async expireStale(olderThan, scope) {
623
+ const baseWhere = { status: "active" };
624
+ if (scope?.tenantId !== void 0) baseWhere.tenantId = scope.tenantId;
625
+ if (scope?.agentId !== void 0) baseWhere.agentId = scope.agentId;
626
+ const byLastMessage = await this.list({ where: {
627
+ ...baseWhere,
628
+ "lastMessageAt <": olderThan
629
+ } });
630
+ const neverMessaged = await this.list({ where: {
631
+ ...baseWhere,
632
+ lastMessageAt: null,
633
+ "created_at <": olderThan
634
+ } });
635
+ const seen = /* @__PURE__ */ new Set();
636
+ let expired = 0;
637
+ for (const session of [...byLastMessage, ...neverMessaged]) {
638
+ const id = session.id;
639
+ if (!id || seen.has(id)) continue;
640
+ seen.add(id);
641
+ await session.expire();
642
+ expired++;
643
+ }
644
+ return expired;
645
+ }
646
+ };
647
+ //#endregion
648
+ //#region src/collections/ChatMessageCollection.ts
649
+ var ChatMessageCollection = class extends SmrtCollection {
650
+ static _itemClass = ChatMessage;
651
+ /**
652
+ * Get messages for a room (newest first), excluding threads and deleted.
653
+ *
654
+ * Filtering, ordering and pagination are pushed into SQL rather than loading
655
+ * the full room history into memory (S5 #1392, DoS hardening). Thread replies
656
+ * are excluded via `threadId IS NULL` (the WHERE API maps a `null` value to
657
+ * `IS NULL`).
658
+ *
659
+ * `tenantId` is REQUIRED and bound into BOTH the message window AND the cursor
660
+ * lookup (S5 #1392): room ids are not globally unique, so a roomId-only read
661
+ * could surface another tenant's messages for a same-id room. The caller's
662
+ * membership gate is tenant-scoped, so the read MUST be too.
663
+ */
664
+ async getByRoom(roomId, tenantId, options) {
665
+ const where = {
666
+ roomId,
667
+ tenantId,
668
+ isDeleted: false,
669
+ threadId: null
670
+ };
671
+ if (options?.before) {
672
+ const cursorMsg = await this.get({
673
+ id: options.before,
674
+ roomId,
675
+ tenantId,
676
+ isDeleted: false,
677
+ threadId: null
678
+ });
679
+ if (cursorMsg?.created_at) where["created_at <"] = cursorMsg.created_at;
680
+ }
681
+ return this.list({
682
+ where,
683
+ orderBy: "created_at DESC",
684
+ limit: options?.limit
685
+ });
686
+ }
687
+ /**
688
+ * Get messages in a thread, tenant-bound (S5 #1392).
689
+ *
690
+ * `tenantId` is bound into the query so a thread id from another tenant can
691
+ * never surface that tenant's thread history.
692
+ */
693
+ async getByThread(threadId, tenantId) {
694
+ return this.list({ where: {
695
+ threadId,
696
+ tenantId,
697
+ isDeleted: false
698
+ } });
699
+ }
700
+ /**
701
+ * Get messages for an agent session, tenant-bound (S5 #1392).
702
+ *
703
+ * `tenantId` is bound into the query so a session id from another tenant can
704
+ * never surface that tenant's session messages.
705
+ */
706
+ async getByAgentSession(agentSessionId, tenantId) {
707
+ return this.list({ where: {
708
+ agentSessionId,
709
+ tenantId,
710
+ isDeleted: false
711
+ } });
712
+ }
713
+ /**
714
+ * Search messages with filters.
715
+ *
716
+ * All structural filters (tenant/room/thread/sender/type/role/date/text) are
717
+ * pushed into SQL instead of loading the full message set and filtering in JS
718
+ * (S5 #1392, DoS hardening). `tenantId` is REQUIRED and always bound so the
719
+ * search can never cross a tenant boundary.
720
+ *
721
+ * `hasAttachments` is derived from the stored `attachments` JSON column and is
722
+ * pushed into SQL as a `!=`/`=` pre-filter against the empty-array sentinel
723
+ * (`'[]'`, the column default) so the `LIMIT` applies to the ALREADY-FILTERED
724
+ * set, not the raw window (S5 #1392). Previously the limit truncated the
725
+ * newest-N window first and the JS filter ran afterwards, so a room whose
726
+ * newest messages lacked attachments could return fewer (or zero)
727
+ * attachment-bearing rows than existed. A precise JS pass on
728
+ * `hasAttachments()` still runs to reject any malformed/empty column value the
729
+ * coarse SQL sentinel can't distinguish, and the requested `limit` is enforced
730
+ * on the filtered result.
731
+ */
732
+ async search(filters) {
733
+ const where = {
734
+ tenantId: filters.tenantId,
735
+ isDeleted: false
736
+ };
737
+ if (filters.roomId) where.roomId = filters.roomId;
738
+ if (filters.threadId) where.threadId = filters.threadId;
739
+ if (filters.senderProfileId) where.senderProfileId = filters.senderProfileId;
740
+ if (filters.messageType) where.messageType = filters.messageType;
741
+ if (filters.role) where.role = filters.role;
742
+ if (filters.query) where["content like"] = `%${filters.query}%`;
743
+ if (filters.sinceDate) where["created_at >="] = filters.sinceDate;
744
+ if (filters.beforeDate) where["created_at <"] = filters.beforeDate;
745
+ const limit = filters.limit ?? 100;
746
+ if (filters.hasAttachments === true) where["attachments !="] = "[]";
747
+ else if (filters.hasAttachments === false) where.attachments = "[]";
748
+ const messages = await this.list({
749
+ where,
750
+ orderBy: "created_at DESC",
751
+ limit
752
+ });
753
+ if (filters.hasAttachments !== void 0) return messages.filter((m) => m.hasAttachments() === filters.hasAttachments).slice(0, limit);
754
+ return messages;
755
+ }
756
+ /**
757
+ * Get unread count for a participant in a room (excludes thread replies).
758
+ *
759
+ * Counting is pushed into SQL via `count()` rather than loading the whole
760
+ * room history into memory (S5 #1392, DoS hardening). `tenantId` is REQUIRED
761
+ * and bound into both the count and the read-cursor lookup so the count can
762
+ * never include another tenant's messages for a same-id room.
763
+ */
764
+ async getUnreadCount(roomId, tenantId, lastReadMessageId) {
765
+ const base = {
766
+ roomId,
767
+ tenantId,
768
+ isDeleted: false,
769
+ threadId: null
770
+ };
771
+ if (!lastReadMessageId) return this.count({ where: base });
772
+ const lastReadMsg = await this.get({
773
+ id: lastReadMessageId,
774
+ roomId,
775
+ tenantId,
776
+ isDeleted: false,
777
+ threadId: null
778
+ });
779
+ if (!lastReadMsg?.created_at) return this.count({ where: base });
780
+ return this.count({ where: {
781
+ ...base,
782
+ "created_at >": lastReadMsg.created_at
783
+ } });
784
+ }
785
+ /**
786
+ * Get most recent root message for each room (for room list preview).
787
+ *
788
+ * Each room is fetched with `orderBy created_at DESC, limit 1` so we never
789
+ * load the full per-room history into memory (S5 #1392, DoS hardening).
790
+ * `tenantId` is REQUIRED and bound into each per-room read so a same-id room
791
+ * from another tenant can never leak a preview message.
792
+ */
793
+ async getLatestPerRoom(roomIds, tenantId) {
794
+ const result = /* @__PURE__ */ new Map();
795
+ for (const roomId of roomIds) {
796
+ const latest = await this.list({
797
+ where: {
798
+ roomId,
799
+ tenantId,
800
+ isDeleted: false,
801
+ threadId: null
802
+ },
803
+ orderBy: "created_at DESC",
804
+ limit: 1
805
+ });
806
+ if (latest.length > 0) result.set(roomId, latest[0]);
807
+ }
808
+ return result;
809
+ }
810
+ };
811
+ //#endregion
812
+ //#region src/collections/ChatParticipantCollection.ts
813
+ var ChatParticipantCollection = class extends SmrtCollection {
814
+ static _itemClass = ChatParticipant;
815
+ async getByRoom(roomId) {
816
+ return this.list({ where: {
817
+ roomId,
818
+ status: "active"
819
+ } });
820
+ }
821
+ async getByProfile(profileId) {
822
+ return this.list({ where: {
823
+ profileId,
824
+ status: "active"
825
+ } });
826
+ }
827
+ async findMembership(roomId, profileId, tenantId) {
828
+ const where = {
829
+ roomId,
830
+ profileId
831
+ };
832
+ if (tenantId !== void 0) where.tenantId = tenantId;
833
+ return (await this.list({ where }))[0] ?? null;
834
+ }
835
+ /**
836
+ * Returns the participant row only if the profile is an ACTIVE member of the
837
+ * room (not left/kicked/banned). Used by ChatService to gate sends and reads
838
+ * on room membership (S5 #1392, IDOR hardening).
839
+ *
840
+ * `tenantId` is REQUIRED and always bound into the WHERE clause so a membership
841
+ * lookup can never resolve a row belonging to another tenant, even when no ALS
842
+ * tenant context is active to drive the tenancy interceptor (defense in depth).
843
+ * Making it a required parameter (rather than optional) closes the hole where a
844
+ * caller could omit it and silently drop the tenant predicate from the query.
845
+ */
846
+ async findActiveMembership(roomId, profileId, tenantId) {
847
+ const where = {
848
+ roomId,
849
+ profileId,
850
+ status: "active",
851
+ tenantId
852
+ };
853
+ return (await this.list({
854
+ where,
855
+ limit: 1
856
+ }))[0] ?? null;
857
+ }
858
+ /** True when the profile is an active member of the room (tenant-bound). */
859
+ async isActiveMember(roomId, profileId, tenantId) {
860
+ return await this.findActiveMembership(roomId, profileId, tenantId) !== null;
861
+ }
862
+ async getOnlineInRoom(roomId) {
863
+ return (await this.list({ where: {
864
+ roomId,
865
+ status: "active"
866
+ } })).filter((p) => p.onlineStatus !== "offline");
867
+ }
868
+ async getAdminsInRoom(roomId) {
869
+ return (await this.list({ where: {
870
+ roomId,
871
+ status: "active"
872
+ } })).filter((p) => p.isAdmin());
873
+ }
874
+ async countInRoom(roomId) {
875
+ return (await this.list({ where: {
876
+ roomId,
877
+ status: "active"
878
+ } })).length;
879
+ }
880
+ };
881
+ //#endregion
882
+ //#region src/collections/ChatReactionCollection.ts
883
+ var ChatReactionCollection = class extends SmrtCollection {
884
+ static _itemClass = ChatReaction;
885
+ async getByMessage(messageId) {
886
+ return this.list({ where: { messageId } });
887
+ }
888
+ /** Get reaction counts grouped by emoji for a message */
889
+ async getReactionCounts(messageId) {
890
+ const reactions = await this.list({ where: { messageId } });
891
+ const counts = /* @__PURE__ */ new Map();
892
+ for (const reaction of reactions) {
893
+ const existing = counts.get(reaction.emoji);
894
+ if (existing) {
895
+ existing.count++;
896
+ existing.profileIds.push(reaction.profileId);
897
+ } else counts.set(reaction.emoji, {
898
+ count: 1,
899
+ profileIds: [reaction.profileId]
900
+ });
901
+ }
902
+ return counts;
903
+ }
904
+ /**
905
+ * Toggle a reaction: add if not present, remove if already reacted.
906
+ *
907
+ * `tenantId` is bound into the existence lookup (S5 #1392) so the toggle can
908
+ * never match or delete a reaction row belonging to another tenant. Prefer the
909
+ * membership-checked {@link ChatService.addReaction}/{@link ChatService.removeReaction}
910
+ * for request-driven flows; this low-level helper performs no membership check.
911
+ */
912
+ async toggle(messageId, profileId, emoji, tenantId) {
913
+ const existing = await this.list({ where: {
914
+ messageId,
915
+ profileId,
916
+ emoji,
917
+ tenantId
918
+ } });
919
+ if (existing.length > 0) {
920
+ await existing[0].delete();
921
+ return { added: false };
922
+ }
923
+ await this.create({
924
+ tenantId,
925
+ messageId,
926
+ profileId,
927
+ emoji
928
+ });
929
+ return { added: true };
930
+ }
931
+ };
932
+ //#endregion
933
+ //#region src/collections/ChatRoomCollection.ts
934
+ function canonicalDmRoomId(tenantId, profileId1, profileId2) {
935
+ const [a, b] = [profileId1, profileId2].sort();
936
+ const key = `dm ${tenantId} ${a} ${b}`;
937
+ const hash = createHash("sha1").update(key).digest("hex");
938
+ return [
939
+ hash.slice(0, 8),
940
+ hash.slice(8, 12),
941
+ `5${hash.slice(13, 16)}`,
942
+ (Number.parseInt(hash.slice(16, 18), 16) & 63 | 128).toString(16).padStart(2, "0") + hash.slice(18, 20),
943
+ hash.slice(20, 32)
944
+ ].join("-");
945
+ }
946
+ var ChatRoomCollection = class extends SmrtCollection {
947
+ static _itemClass = ChatRoom;
948
+ async findByType(roomType) {
949
+ return this.list({ where: {
950
+ roomType,
951
+ status: "active"
952
+ } });
953
+ }
954
+ async findPublic() {
955
+ return this.list({ where: {
956
+ roomType: "public",
957
+ status: "active"
958
+ } });
959
+ }
960
+ async findDMs() {
961
+ return this.list({ where: {
962
+ roomType: "dm",
963
+ status: "active"
964
+ } });
965
+ }
966
+ async findAgentRooms() {
967
+ return this.list({ where: {
968
+ roomType: "agent",
969
+ status: "active"
970
+ } });
971
+ }
972
+ /**
973
+ * Search rooms by name/description/topic.
974
+ *
975
+ * Filtering and limiting are pushed into SQL via `LIKE` instead of loading
976
+ * the entire tenant room set and filtering in JS (S5 #1392, DoS hardening).
977
+ * The WHERE API does not support OR, so we issue one bounded query per
978
+ * searchable column and merge the results, capping the total returned.
979
+ */
980
+ async search(query, options) {
981
+ const limit = options?.limit ?? 50;
982
+ const like = `%${query}%`;
983
+ const columns = [
984
+ "name",
985
+ "description",
986
+ "topic"
987
+ ];
988
+ const merged = /* @__PURE__ */ new Map();
989
+ for (const column of columns) {
990
+ const matches = await this.list({
991
+ where: {
992
+ status: "active",
993
+ [`${column} like`]: like
994
+ },
995
+ orderBy: "created_at DESC",
996
+ limit
997
+ });
998
+ for (const room of matches) if (room.id) merged.set(room.id, room);
999
+ if (merged.size >= limit) break;
1000
+ }
1001
+ return Array.from(merged.values()).slice(0, limit);
1002
+ }
1003
+ /**
1004
+ * Find an existing 1:1 DM room between two profiles, or create one.
1005
+ *
1006
+ * DM identity is derived from the authoritative `chat_participants` join
1007
+ * (server-controlled) rather than client-mutable room metadata (S5 #1392).
1008
+ * Callers are responsible for attaching both profiles as participants after
1009
+ * creation; {@link ChatService.getOrCreateDM} does this.
1010
+ */
1011
+ async findOrCreateDM(profileId1, profileId2, tenantId, participants) {
1012
+ const dmId = canonicalDmRoomId(tenantId, profileId1, profileId2);
1013
+ const canonical = await this.get({
1014
+ id: dmId,
1015
+ tenantId
1016
+ });
1017
+ if (canonical && canonical.roomType === "dm") return canonical;
1018
+ const candidateRoomIds = (await participants.list({ where: {
1019
+ profileId: profileId1,
1020
+ status: "active",
1021
+ tenantId
1022
+ } })).map((m) => m.roomId);
1023
+ for (const roomId of candidateRoomIds) {
1024
+ const dm = await this.get({
1025
+ id: roomId,
1026
+ tenantId
1027
+ });
1028
+ if (!dm || dm.roomType !== "dm" || dm.status !== "active") continue;
1029
+ if ((await participants.list({ where: {
1030
+ roomId,
1031
+ profileId: profileId2,
1032
+ status: "active",
1033
+ tenantId
1034
+ } })).length > 0) return dm;
1035
+ }
1036
+ return await this.create({
1037
+ id: dmId,
1038
+ tenantId,
1039
+ name: "",
1040
+ roomType: "dm",
1041
+ status: "active",
1042
+ maxParticipants: 2
1043
+ });
1044
+ }
1045
+ };
1046
+ //#endregion
1047
+ //#region src/collections/ChatThreadCollection.ts
1048
+ var ChatThreadCollection = class extends SmrtCollection {
1049
+ static _itemClass = ChatThread;
1050
+ async getByRoom(roomId) {
1051
+ return this.list({ where: { roomId } });
1052
+ }
1053
+ async getActive(roomId) {
1054
+ return (await this.list({ where: { roomId } })).filter((t) => !t.isResolved);
1055
+ }
1056
+ async getUnresolved() {
1057
+ return (await this.list({})).filter((t) => !t.isResolved);
1058
+ }
1059
+ };
1060
+ //#endregion
1061
+ //#region src/services/ChatService.ts
1062
+ var RUN_AGENT_REPLY = /* @__PURE__ */ Symbol("smrt-chat.runAgentReply");
1063
+ var ChatService = class ChatService {
1064
+ #rooms;
1065
+ #messages;
1066
+ #participants;
1067
+ #threads;
1068
+ #agentSessions;
1069
+ #reactions;
1070
+ constructor(rooms, messages, participants, threads, agentSessions, reactions) {
1071
+ this.#rooms = rooms;
1072
+ this.#messages = messages;
1073
+ this.#participants = participants;
1074
+ this.#threads = threads;
1075
+ this.#agentSessions = agentSessions;
1076
+ this.#reactions = reactions;
1077
+ }
1078
+ static async create(options) {
1079
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:ChatRoom", ChatRoomCollection);
1080
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:ChatMessage", ChatMessageCollection);
1081
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:ChatParticipant", ChatParticipantCollection);
1082
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:ChatThread", ChatThreadCollection);
1083
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:AgentSession", AgentSessionCollection);
1084
+ ObjectRegistry.registerCollection("@happyvertical/smrt-chat:ChatReaction", ChatReactionCollection);
1085
+ return new ChatService(await ObjectRegistry.getCollection("@happyvertical/smrt-chat:ChatRoom", options), await ObjectRegistry.getCollection("@happyvertical/smrt-chat:ChatMessage", options), await ObjectRegistry.getCollection("@happyvertical/smrt-chat:ChatParticipant", options), await ObjectRegistry.getCollection("@happyvertical/smrt-chat:ChatThread", options), await ObjectRegistry.getCollection("@happyvertical/smrt-chat:AgentSession", options), await ObjectRegistry.getCollection("@happyvertical/smrt-chat:ChatReaction", options));
1086
+ }
1087
+ /** Initialize all underlying collections (table creation) */
1088
+ async initialize() {
1089
+ await this.#rooms.initialize();
1090
+ await this.#messages.initialize();
1091
+ await this.#participants.initialize();
1092
+ await this.#threads.initialize();
1093
+ await this.#agentSessions.initialize();
1094
+ await this.#reactions.initialize();
1095
+ }
1096
+ /**
1097
+ * Create a room and add the creating actor as owner (S5 #1392).
1098
+ *
1099
+ * The acting identity is the server-supplied `actorProfileId` (the
1100
+ * authenticated principal the route injects). The creator/owner is ALWAYS the
1101
+ * actor — a caller cannot supply a `createdByProfileId` to attribute the room
1102
+ * to (and enroll as owner) some other profile.
1103
+ */
1104
+ async createRoom(params) {
1105
+ const room = await this.#rooms.create({
1106
+ tenantId: params.tenantId,
1107
+ name: params.name,
1108
+ roomType: params.roomType,
1109
+ createdByProfileId: params.actorProfileId,
1110
+ description: params.description ?? "",
1111
+ topic: params.topic ?? "",
1112
+ status: "active"
1113
+ });
1114
+ await this.#enrollParticipant({
1115
+ tenantId: params.tenantId,
1116
+ roomId: room.id,
1117
+ profileId: params.actorProfileId,
1118
+ role: "owner"
1119
+ });
1120
+ return room;
1121
+ }
1122
+ /**
1123
+ * Send a USER message to a room as the authenticated caller (S5 #1392).
1124
+ *
1125
+ * The acting identity is the server-supplied `actorProfileId` (the
1126
+ * authenticated principal the route injects). The message is ALWAYS authored
1127
+ * as `actorProfileId` with `role: 'user'` — the caller cannot supply a
1128
+ * `senderProfileId` to impersonate another profile or the agent, and cannot
1129
+ * supply a privileged `role` (assistant/system/tool). Agent-authored messages
1130
+ * go exclusively through the internal {@link ChatService.sendAgentReply}.
1131
+ *
1132
+ * Authorization: `actorProfileId` must be an ACTIVE participant of the target
1133
+ * room, preventing cross-room IDOR within a tenant. There is no public
1134
+ * membership-skip parameter; system-authored writes use the internal
1135
+ * {@link ChatService.writeMessage} path.
1136
+ */
1137
+ async sendMessage(params) {
1138
+ return this.#writeMessage({
1139
+ tenantId: params.tenantId,
1140
+ roomId: params.roomId,
1141
+ senderProfileId: params.actorProfileId,
1142
+ content: params.content,
1143
+ role: "user",
1144
+ messageType: params.messageType ?? "text",
1145
+ threadId: params.threadId ?? null,
1146
+ agentSessionId: params.agentSessionId ?? null,
1147
+ replyToMessageId: params.replyToMessageId ?? null
1148
+ });
1149
+ }
1150
+ /**
1151
+ * INTERNAL persistence path for all message writes. Not exposed publicly: it
1152
+ * accepts an arbitrary author/role and an internal-only `skipMembershipCheck`
1153
+ * (S5 #1392). Every public entry point (`sendMessage`, `sendAgentUserMessage`,
1154
+ * `sendAgentReply`) funnels through here with a server-derived author/role.
1155
+ *
1156
+ * Membership is enforced unless `skipMembershipCheck` is set, which only the
1157
+ * in-class system-authored callers may do.
1158
+ */
1159
+ async #writeMessage(write) {
1160
+ if (!write.skipMembershipCheck) {
1161
+ if (!await this.#participants.isActiveMember(write.roomId, write.senderProfileId, write.tenantId)) throw new Error("Sender is not an active member of the room (authorization denied)");
1162
+ }
1163
+ const thread = write.threadId ? await this.#threads.get({
1164
+ id: write.threadId,
1165
+ roomId: write.roomId,
1166
+ tenantId: write.tenantId
1167
+ }) : null;
1168
+ if (write.threadId && !thread) throw new Error("threadId does not belong to this room/tenant (authorization denied)");
1169
+ const session = write.agentSessionId ? await this.#agentSessions.get({
1170
+ id: write.agentSessionId,
1171
+ chatRoomId: write.roomId,
1172
+ tenantId: write.tenantId
1173
+ }) : null;
1174
+ if (write.agentSessionId && !session) throw new Error("agentSessionId does not belong to this room/tenant (authorization denied)");
1175
+ if (write.replyToMessageId) {
1176
+ if (!await this.#messages.get({
1177
+ id: write.replyToMessageId,
1178
+ roomId: write.roomId,
1179
+ tenantId: write.tenantId
1180
+ })) throw new Error("replyToMessageId does not belong to this room/tenant (authorization denied)");
1181
+ }
1182
+ const message = await this.#messages.create({
1183
+ tenantId: write.tenantId,
1184
+ roomId: write.roomId,
1185
+ senderProfileId: write.senderProfileId,
1186
+ content: write.content,
1187
+ messageType: write.messageType ?? "text",
1188
+ role: write.role,
1189
+ threadId: write.threadId ?? null,
1190
+ agentSessionId: write.agentSessionId ?? null,
1191
+ replyToMessageId: write.replyToMessageId ?? null,
1192
+ toolCallData: write.toolCallData ? JSON.stringify(write.toolCallData) : null
1193
+ });
1194
+ const room = await this.#rooms.get({
1195
+ id: write.roomId,
1196
+ tenantId: write.tenantId
1197
+ });
1198
+ if (room) {
1199
+ room.lastMessageAt = /* @__PURE__ */ new Date();
1200
+ await room.save();
1201
+ }
1202
+ if (thread) {
1203
+ thread.messageCount++;
1204
+ thread.lastMessageAt = /* @__PURE__ */ new Date();
1205
+ await thread.save();
1206
+ }
1207
+ if (session) await session.recordMessage();
1208
+ return message;
1209
+ }
1210
+ /**
1211
+ * Start a thread in a room (S5 #1392).
1212
+ *
1213
+ * The acting identity is the server-supplied `actorProfileId`, which must be
1214
+ * an active member of the room. Generated thread `create` is disabled, so this
1215
+ * is the only path to create a thread.
1216
+ *
1217
+ * When a `rootMessageId` is supplied it is bound to `{ id, roomId, tenantId }`
1218
+ * and rejected unless it belongs to the SAME room and tenant — without this a
1219
+ * member of one room could anchor a thread to a message from another
1220
+ * room/tenant. `rootMessageId` is optional (a thread can be opened without a
1221
+ * root message, e.g. an agent-editor thread).
1222
+ */
1223
+ async startThread(params) {
1224
+ await this.#requireActiveMembership(params.roomId, params.actorProfileId, params.tenantId);
1225
+ if (params.rootMessageId) {
1226
+ if (!await this.#messages.get({
1227
+ id: params.rootMessageId,
1228
+ roomId: params.roomId,
1229
+ tenantId: params.tenantId
1230
+ })) throw new Error("rootMessageId does not belong to this room/tenant (authorization denied)");
1231
+ }
1232
+ return await this.#threads.create({
1233
+ tenantId: params.tenantId,
1234
+ roomId: params.roomId,
1235
+ rootMessageId: params.rootMessageId ?? null,
1236
+ title: params.title ?? "",
1237
+ messageCount: 0
1238
+ });
1239
+ }
1240
+ /**
1241
+ * Add a participant to a room (S5 #1392).
1242
+ *
1243
+ * Authorization: the acting identity is the server-supplied `actorProfileId`,
1244
+ * which MUST be an owner/admin of the target room. This prevents an arbitrary
1245
+ * tenant member from adding anyone (or themselves) to any room with any role —
1246
+ * a privilege-escalation / IDOR. System-bootstrap enrollment (room creation,
1247
+ * DM/agent-session setup) uses the internal {@link ChatService.enrollParticipant}.
1248
+ */
1249
+ async addParticipant(params) {
1250
+ await this.#requireRoomAdmin(params.roomId, params.actorProfileId, params.tenantId);
1251
+ return this.#enrollParticipant({
1252
+ tenantId: params.tenantId,
1253
+ roomId: params.roomId,
1254
+ profileId: params.profileId,
1255
+ role: params.role
1256
+ });
1257
+ }
1258
+ /**
1259
+ * INTERNAL participant enrollment (S5 #1392). No authorization check — only
1260
+ * the trusted in-class bootstrap paths (room creation, DM/agent-session setup)
1261
+ * and the owner-checked {@link ChatService.addParticipant} call this. Not
1262
+ * exposed publicly so a route cannot enroll an arbitrary profile.
1263
+ */
1264
+ async #enrollParticipant(params) {
1265
+ const existing = await this.#participants.findMembership(params.roomId, params.profileId, params.tenantId);
1266
+ if (existing) {
1267
+ if (existing.status !== "active") {
1268
+ existing.status = "active";
1269
+ existing.joinedAt = /* @__PURE__ */ new Date();
1270
+ await existing.save();
1271
+ }
1272
+ return existing;
1273
+ }
1274
+ return await this.#participants.create({
1275
+ tenantId: params.tenantId,
1276
+ roomId: params.roomId,
1277
+ profileId: params.profileId,
1278
+ role: params.role ?? "member",
1279
+ status: "active",
1280
+ joinedAt: /* @__PURE__ */ new Date()
1281
+ });
1282
+ }
1283
+ /**
1284
+ * Remove (soft-leave) a participant from a room (S5 #1392).
1285
+ *
1286
+ * Authorization: the server-supplied `actorProfileId` may remove THEMSELVES
1287
+ * (leave) at any time; removing ANOTHER profile requires the actor to be an
1288
+ * owner/admin of the room. An admin who is not an owner cannot remove an owner.
1289
+ */
1290
+ async removeParticipant(params) {
1291
+ const target = await this.#participants.findMembership(params.roomId, params.profileId, params.tenantId);
1292
+ if (!target) return;
1293
+ if (!(params.actorProfileId === params.profileId)) {
1294
+ const actor = await this.#participants.findActiveMembership(params.roomId, params.actorProfileId, params.tenantId);
1295
+ if (!actor || !actor.isAdmin()) throw new Error("Only a room owner/admin may remove another participant (authorization denied)");
1296
+ if (target.isOwner() && !actor.isOwner()) throw new Error("Only a room owner may remove an owner (authorization denied)");
1297
+ }
1298
+ target.status = "left";
1299
+ await target.save();
1300
+ }
1301
+ /**
1302
+ * Update mutable room fields, restricted to a room owner/admin (S5 #1392).
1303
+ *
1304
+ * Generated `update` on ChatRoom is disabled, so this owner-checked path is the
1305
+ * only way to mutate room state. The acting identity is the server-supplied
1306
+ * `actorProfileId`.
1307
+ */
1308
+ async updateRoom(params) {
1309
+ await this.#requireRoomAdmin(params.roomId, params.actorProfileId, params.tenantId);
1310
+ const room = await this.#rooms.get({
1311
+ id: params.roomId,
1312
+ tenantId: params.tenantId
1313
+ });
1314
+ if (!room) throw new Error("Room not found");
1315
+ if (params.name !== void 0) room.name = params.name;
1316
+ if (params.description !== void 0) room.description = params.description;
1317
+ if (params.topic !== void 0) room.topic = params.topic;
1318
+ if (params.avatarUrl !== void 0) room.avatarUrl = params.avatarUrl;
1319
+ if (params.status !== void 0) room.status = params.status;
1320
+ await room.save();
1321
+ return room;
1322
+ }
1323
+ /**
1324
+ * Add a reaction to a message as the authenticated caller (S5 #1392).
1325
+ *
1326
+ * Generated `create` on ChatReaction is disabled. The reaction is always
1327
+ * authored as the server-supplied `actorProfileId` (no caller-supplied
1328
+ * `profileId`), and the actor must be an active member of the room that owns
1329
+ * the message. Idempotent: re-reacting with the same emoji returns the
1330
+ * existing row.
1331
+ */
1332
+ async addReaction(params) {
1333
+ const message = await this.#messages.get({
1334
+ id: params.messageId,
1335
+ tenantId: params.tenantId
1336
+ });
1337
+ if (!message) throw new Error("Message not found");
1338
+ await this.#requireActiveMembership(message.roomId, params.actorProfileId, params.tenantId);
1339
+ const existing = await this.#reactions.list({
1340
+ where: {
1341
+ tenantId: params.tenantId,
1342
+ messageId: params.messageId,
1343
+ profileId: params.actorProfileId,
1344
+ emoji: params.emoji
1345
+ },
1346
+ limit: 1
1347
+ });
1348
+ if (existing[0]) return existing[0];
1349
+ return this.#reactions.create({
1350
+ tenantId: params.tenantId,
1351
+ messageId: params.messageId,
1352
+ profileId: params.actorProfileId,
1353
+ emoji: params.emoji
1354
+ });
1355
+ }
1356
+ /**
1357
+ * Remove the caller's own reaction from a message (S5 #1392).
1358
+ *
1359
+ * Generated `delete` on ChatReaction is disabled. A caller may only delete
1360
+ * THEIR OWN reaction (keyed on `actorProfileId`), so the route cannot remove
1361
+ * another member's reaction.
1362
+ */
1363
+ async removeReaction(params) {
1364
+ const existing = await this.#reactions.list({
1365
+ where: {
1366
+ tenantId: params.tenantId,
1367
+ messageId: params.messageId,
1368
+ profileId: params.actorProfileId,
1369
+ emoji: params.emoji
1370
+ },
1371
+ limit: 1
1372
+ });
1373
+ if (existing[0]) {
1374
+ await existing[0].delete();
1375
+ return true;
1376
+ }
1377
+ return false;
1378
+ }
1379
+ /**
1380
+ * Get or create a DM room with auto-participant setup.
1381
+ *
1382
+ * The acting identity is the server-supplied `actorProfileId`, which must be
1383
+ * one of the two DM participants — a caller cannot open a DM between two other
1384
+ * profiles on their behalf (S5 #1392). Enrollment uses the internal system
1385
+ * path (no owner check needed for a DM the actor is part of).
1386
+ */
1387
+ async getOrCreateDM(params) {
1388
+ if (params.actorProfileId !== params.profileId1 && params.actorProfileId !== params.profileId2) throw new Error("Caller must be a participant of the DM (authorization denied)");
1389
+ const room = await this.#rooms.findOrCreateDM(params.profileId1, params.profileId2, params.tenantId, this.#participants);
1390
+ await this.#enrollParticipant({
1391
+ tenantId: params.tenantId,
1392
+ roomId: room.id,
1393
+ profileId: params.profileId1
1394
+ });
1395
+ await this.#enrollParticipant({
1396
+ tenantId: params.tenantId,
1397
+ roomId: room.id,
1398
+ profileId: params.profileId2
1399
+ });
1400
+ return room;
1401
+ }
1402
+ /**
1403
+ * Create an agent conversation session with a linked chat room (S5 #1392).
1404
+ *
1405
+ * The acting identity is the server-supplied `actorProfileId`; the session is
1406
+ * ALWAYS created for that actor as the owning participant. A caller cannot
1407
+ * supply a `participantProfileId` to open (and own) a session on behalf of
1408
+ * another profile.
1409
+ *
1410
+ * `sessionKey` scopes the session's identity to a conversation subject (e.g. a
1411
+ * content id) (S5 #1392). The reuse lookup keys on `(agentId,
1412
+ * participantProfileId, tenantId)`, which is too coarse for callers that open
1413
+ * separate conversations for distinct subjects under one agent/profile/tenant:
1414
+ * without a key, a session opened for subject A would be reused for a request
1415
+ * about subject B, returning A's room/threads on B's route. When `sessionKey`
1416
+ * is set, an existing session is reused ONLY if its key matches exactly, and a
1417
+ * newly created session records the key; distinct keys therefore get distinct
1418
+ * sessions and rooms. When omitted, behavior is unchanged (single session per
1419
+ * agent/profile/tenant).
1420
+ */
1421
+ async createAgentSession(params) {
1422
+ const participantProfileId = params.actorProfileId;
1423
+ const sessionKey = params.sessionKey ?? null;
1424
+ const existingSession = await this.#agentSessions.findActiveSession(params.agentId, participantProfileId, params.tenantId, sessionKey);
1425
+ if (existingSession && existingSession.tenantId === params.tenantId) {
1426
+ if (existingSession.chatRoomId) {
1427
+ const existingRoom = await this.#rooms.get({
1428
+ id: existingSession.chatRoomId,
1429
+ tenantId: params.tenantId
1430
+ });
1431
+ if (existingRoom) {
1432
+ await this.#enrollParticipant({
1433
+ tenantId: params.tenantId,
1434
+ roomId: existingRoom.id,
1435
+ profileId: participantProfileId,
1436
+ role: "owner"
1437
+ });
1438
+ await this.#enrollParticipant({
1439
+ tenantId: params.tenantId,
1440
+ roomId: existingRoom.id,
1441
+ profileId: params.agentId,
1442
+ role: "member"
1443
+ });
1444
+ return {
1445
+ session: existingSession,
1446
+ room: existingRoom
1447
+ };
1448
+ }
1449
+ }
1450
+ await existingSession.expire();
1451
+ }
1452
+ const room = await this.#rooms.create({
1453
+ tenantId: params.tenantId,
1454
+ name: "",
1455
+ roomType: "agent",
1456
+ createdByProfileId: participantProfileId,
1457
+ status: "active",
1458
+ maxParticipants: 2
1459
+ });
1460
+ await this.#enrollParticipant({
1461
+ tenantId: params.tenantId,
1462
+ roomId: room.id,
1463
+ profileId: participantProfileId,
1464
+ role: "owner"
1465
+ });
1466
+ await this.#enrollParticipant({
1467
+ tenantId: params.tenantId,
1468
+ roomId: room.id,
1469
+ profileId: params.agentId,
1470
+ role: "member"
1471
+ });
1472
+ const session = await this.#agentSessions.findOrCreate({
1473
+ agentId: params.agentId,
1474
+ participantProfileId,
1475
+ tenantId: params.tenantId,
1476
+ allowedTools: params.allowedTools,
1477
+ chatRoomId: room.id,
1478
+ systemPrompt: params.systemPrompt,
1479
+ sessionKey
1480
+ });
1481
+ if (params.maxTokens) session.maxTokens = params.maxTokens;
1482
+ if (params.maxMessages) session.maxMessages = params.maxMessages;
1483
+ await session.save();
1484
+ return {
1485
+ session,
1486
+ room
1487
+ };
1488
+ }
1489
+ /**
1490
+ * Send a USER message within an agent session (S5 #1392).
1491
+ *
1492
+ * The authenticated caller (`actorProfileId`) must be the session's owning
1493
+ * participant. The message is always authored as `session.participantProfileId`
1494
+ * — the caller cannot supply a `senderProfileId`, a `role`, or tool-call data,
1495
+ * so this path can never be used to post as the agent (`assistant`/`tool`) or
1496
+ * to impersonate another profile. Agent replies go through the internal
1497
+ * {@link ChatService.sendAgentReply}.
1498
+ */
1499
+ async sendAgentUserMessage(params) {
1500
+ const session = await this.#loadActiveSession(params.agentSessionId, params.tenantId);
1501
+ if (params.actorProfileId !== session.participantProfileId) throw new Error("Only the session participant may post user messages in this agent session (authorization denied)");
1502
+ return this.#writeMessage({
1503
+ tenantId: params.tenantId,
1504
+ roomId: session.chatRoomId,
1505
+ senderProfileId: session.participantProfileId,
1506
+ content: params.content,
1507
+ role: "user",
1508
+ messageType: params.messageType ?? "text",
1509
+ agentSessionId: params.agentSessionId
1510
+ });
1511
+ }
1512
+ /**
1513
+ * Emit an ASSISTANT or TOOL message authored by the agent (S5 #1392).
1514
+ *
1515
+ * INTERNAL authority: this is the only path that authors a message as the
1516
+ * agent, and it is not reachable with a caller-supplied `senderProfileId`/
1517
+ * `role`. The author is always `session.agentId`. Tool calls are gated
1518
+ * fail-closed against the session's allow-list. Intended for the trusted
1519
+ * agent-runtime, never a per-tenant request handler driven by client-supplied
1520
+ * role/sender.
1521
+ *
1522
+ * This is a `private` method and is NOT exported from the package index. The
1523
+ * in-process agent runtime reaches it through the {@link sendAgentReply}
1524
+ * bridge in this module, which is deliberately not re-exported from
1525
+ * `src/index.ts`, so a route/consumer can never author a message as the agent.
1526
+ */
1527
+ async #emitAgentReply(params) {
1528
+ const session = await this.#loadActiveSession(params.agentSessionId, params.tenantId);
1529
+ const role = params.kind === "tool" ? "tool" : "assistant";
1530
+ if (params.messageType === "tool_call" || params.messageType === "tool_result" || role === "tool" || params.toolCallData) {
1531
+ const toolName = ChatService.#extractToolName(params.toolCallData);
1532
+ if (!toolName) throw new Error("Tool call is missing a tool name");
1533
+ if (!session.isToolAllowed(toolName)) throw new Error(`Tool '${toolName}' is not allowed for this agent session (authorization denied)`);
1534
+ }
1535
+ return this.#writeMessage({
1536
+ tenantId: params.tenantId,
1537
+ roomId: session.chatRoomId,
1538
+ senderProfileId: session.agentId,
1539
+ content: params.content,
1540
+ role,
1541
+ messageType: params.messageType ?? "text",
1542
+ threadId: params.threadId ?? null,
1543
+ agentSessionId: params.agentSessionId,
1544
+ toolCallData: params.toolCallData ?? null
1545
+ });
1546
+ }
1547
+ /** Load an active agent session by id, tenant-bound, or throw. */
1548
+ async #loadActiveSession(agentSessionId, tenantId) {
1549
+ const session = await this.#agentSessions.get({
1550
+ id: agentSessionId,
1551
+ tenantId
1552
+ });
1553
+ if (!session) throw new Error("Agent session not found");
1554
+ if (!session.isActive()) throw new Error("Agent session is not active");
1555
+ if (!session.chatRoomId) throw new Error("Agent session has no chat room");
1556
+ return session;
1557
+ }
1558
+ /**
1559
+ * Read messages in a room, gated on the AUTHENTICATED CALLER's active
1560
+ * membership (S5 #1392).
1561
+ *
1562
+ * The acting identity is the server-supplied `actorProfileId` (the
1563
+ * authenticated principal the route injects), NOT a caller-controlled
1564
+ * `profileId`. Authorizing a supplied `profileId` would make a route a
1565
+ * confused deputy: any caller could read a room by smuggling some member's
1566
+ * profile id. Throws if `actorProfileId` is not an active participant of
1567
+ * `roomId`. `tenantId` is required so the membership gate is always
1568
+ * tenant-scoped.
1569
+ */
1570
+ async getRoomMessages(params) {
1571
+ await this.#requireActiveMembership(params.roomId, params.actorProfileId, params.tenantId);
1572
+ return this.#messages.getByRoom(params.roomId, params.tenantId, {
1573
+ limit: params.limit,
1574
+ before: params.before
1575
+ });
1576
+ }
1577
+ /**
1578
+ * Load a room only if the AUTHENTICATED CALLER is an active member (S5 #1392).
1579
+ *
1580
+ * The acting identity is the server-supplied `actorProfileId`, never a
1581
+ * caller-controlled `profileId` (confused-deputy avoidance — see
1582
+ * {@link ChatService.getRoomMessages}). Returns null when the room does not
1583
+ * exist; throws when the actor is not an active participant. `tenantId` is
1584
+ * required so the lookup and the membership gate are always tenant-scoped.
1585
+ */
1586
+ async getRoomForMember(roomId, actorProfileId, tenantId) {
1587
+ const room = await this.#rooms.get({
1588
+ id: roomId,
1589
+ tenantId
1590
+ });
1591
+ if (!room) return null;
1592
+ await this.#requireActiveMembership(roomId, actorProfileId, tenantId);
1593
+ return room;
1594
+ }
1595
+ /**
1596
+ * Tenant-bound read of a single agent session (S5 #1392).
1597
+ *
1598
+ * The lookup ALWAYS binds `tenantId` (including the `null`/untenanted scope),
1599
+ * so a caller can never resolve a session belonging to another tenant by id.
1600
+ * Returns `null` when no session matches the id within the tenant. Replaces
1601
+ * direct `agentSessions.get(id)` reach-ins in package consumers; consumers
1602
+ * still apply their own ownership/context authorization on the returned row.
1603
+ */
1604
+ async getAgentSession(lookup) {
1605
+ return await this.#agentSessions.get({
1606
+ id: lookup.agentSessionId,
1607
+ tenantId: lookup.tenantId
1608
+ }) ?? null;
1609
+ }
1610
+ /**
1611
+ * Tenant-bound list of ACTIVE agent sessions for an (agent, participant) pair
1612
+ * (S5 #1392).
1613
+ *
1614
+ * Binds `tenantId` into the query so the result can never include a session
1615
+ * from another tenant. Replaces direct `agentSessions.list({ where })`
1616
+ * reach-ins; consumers apply their own per-session context authorization.
1617
+ */
1618
+ async findActiveAgentSessions(params) {
1619
+ return (await this.#agentSessions.list({ where: {
1620
+ tenantId: params.tenantId,
1621
+ agentId: params.agentId,
1622
+ participantProfileId: params.participantProfileId,
1623
+ status: "active"
1624
+ } })).filter((s) => s.isActive());
1625
+ }
1626
+ /**
1627
+ * Tenant-bound read of a single thread (S5 #1392).
1628
+ *
1629
+ * Binds `tenantId` into the lookup so a thread from another tenant can never
1630
+ * be resolved by id. Returns `null` when no thread matches within the tenant.
1631
+ * Replaces direct `threads.get(id)` reach-ins.
1632
+ */
1633
+ async getThread(lookup) {
1634
+ return await this.#threads.get({
1635
+ id: lookup.threadId,
1636
+ tenantId: lookup.tenantId
1637
+ }) ?? null;
1638
+ }
1639
+ /**
1640
+ * List a room's threads, gated on the caller's active membership (S5 #1392).
1641
+ *
1642
+ * Tenant- and membership-scoped: throws if `actorProfileId` is not an active
1643
+ * participant of `roomId`. Replaces direct `threads.list({ where: { roomId } })`
1644
+ * reach-ins that returned threads without a membership/tenant gate.
1645
+ */
1646
+ async listRoomThreads(params) {
1647
+ await this.#requireActiveMembership(params.roomId, params.actorProfileId, params.tenantId);
1648
+ return this.#threads.list({
1649
+ where: {
1650
+ tenantId: params.tenantId,
1651
+ roomId: params.roomId
1652
+ },
1653
+ orderBy: "createdAt DESC"
1654
+ });
1655
+ }
1656
+ /**
1657
+ * Read messages within a thread, tenant- and membership-bound (S5 #1392).
1658
+ *
1659
+ * The thread is resolved tenant-bound; the caller must be an active member of
1660
+ * the thread's room. Messages are returned oldest-first (chronological).
1661
+ * Replaces direct `messages.list({ where: { threadId } })` reach-ins that
1662
+ * could read another tenant's/room's thread history by raw id.
1663
+ */
1664
+ async getThreadMessages(params) {
1665
+ const thread = await this.#threads.get({
1666
+ id: params.threadId,
1667
+ tenantId: params.tenantId
1668
+ });
1669
+ if (!thread) throw new Error("Thread not found");
1670
+ await this.#requireActiveMembership(thread.roomId, params.actorProfileId, params.tenantId);
1671
+ return (await this.#messages.list({
1672
+ where: {
1673
+ tenantId: params.tenantId,
1674
+ threadId: params.threadId,
1675
+ isDeleted: false
1676
+ },
1677
+ orderBy: "created_at DESC",
1678
+ limit: params.limit
1679
+ })).reverse();
1680
+ }
1681
+ /**
1682
+ * Update the per-session agent configuration (allowedTools / systemPrompt),
1683
+ * restricted to the session owner — the room owner participant (S5 #1392).
1684
+ *
1685
+ * Tool whitelist and system prompt govern what the agent may do, so only the
1686
+ * owning participant (not arbitrary tenant members or the agent itself) may
1687
+ * mutate them.
1688
+ */
1689
+ async updateAgentSessionConfig(params) {
1690
+ const session = await this.#agentSessions.get({
1691
+ id: params.agentSessionId,
1692
+ tenantId: params.tenantId
1693
+ });
1694
+ if (!session) throw new Error("Agent session not found");
1695
+ if (!(params.actorProfileId === session.participantProfileId)) throw new Error("Only the session owner may update agent session configuration (authorization denied)");
1696
+ if (params.allowedTools !== void 0) session.setAllowedTools(params.allowedTools);
1697
+ if (params.systemPrompt !== void 0) session.systemPrompt = params.systemPrompt;
1698
+ await session.save();
1699
+ return session;
1700
+ }
1701
+ /** Throw unless the profile is an active participant of the room. */
1702
+ async #requireActiveMembership(roomId, profileId, tenantId) {
1703
+ if (!await this.#participants.isActiveMember(roomId, profileId, tenantId)) throw new Error("Caller is not an active member of the room (authorization denied)");
1704
+ }
1705
+ /** Throw unless the profile is an active owner/admin of the room. */
1706
+ async #requireRoomAdmin(roomId, profileId, tenantId) {
1707
+ const actor = await this.#participants.findActiveMembership(roomId, profileId, tenantId);
1708
+ if (!actor || !actor.isAdmin()) throw new Error("Caller must be a room owner/admin (authorization denied)");
1709
+ }
1710
+ /** Extract a tool name from tool-call payload data, if present. */
1711
+ static #extractToolName(data) {
1712
+ if (!data || typeof data !== "object") return null;
1713
+ const candidate = data.name ?? data.tool ?? data.toolName;
1714
+ return typeof candidate === "string" && candidate.length > 0 ? candidate : null;
1715
+ }
1716
+ /**
1717
+ * Symbol-keyed bridge to the `private` {@link ChatService.emitAgentReply} for
1718
+ * the module-local {@link sendAgentReply} function (S5 #1392). A static member
1719
+ * may reach a private instance member of its own class, so this is the
1720
+ * sanctioned "friend" access without widening the public instance surface.
1721
+ *
1722
+ * Keyed on the module-private {@link RUN_AGENT_REPLY} symbol — NOT a named
1723
+ * static — so it does not appear on the `ChatService` type, is not enumerable,
1724
+ * and is callable only by code holding the (non-exported) symbol. This is the
1725
+ * sole path the agent-runtime bridge uses to author a message as the agent.
1726
+ */
1727
+ static [RUN_AGENT_REPLY](service, params) {
1728
+ return service.#emitAgentReply(params);
1729
+ }
1730
+ };
1731
+ function sendAgentReply(service, params) {
1732
+ return ChatService[RUN_AGENT_REPLY](service, params);
1733
+ }
1734
+ //#endregion
1735
+ export { ChatReaction as a, AgentSession as c, ChatRoom as i, sendAgentReply as n, ChatParticipant as o, ChatThread as r, ChatMessage as s, ChatService as t };
1736
+
1737
+ //# sourceMappingURL=ChatService-DOBrZI3w.js.map