@happyvertical/smrt-chat 0.60.18 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/AGENTS.md +16 -22
  2. package/README.md +78 -0
  3. package/agents/owner-approvals.md +161 -0
  4. package/agents/runtime-exposure.md +28 -0
  5. package/agents/runtime-report-tools.md +26 -0
  6. package/agents/token-streaming.md +6 -0
  7. package/agents/tool-loop.md +13 -0
  8. package/agents/tool-summaries.md +155 -0
  9. package/agents/turn-drivers.md +293 -0
  10. package/dist/assistant-approvals.d.ts +45 -0
  11. package/dist/assistant-approvals.d.ts.map +1 -0
  12. package/dist/assistant-approvals.js +83 -0
  13. package/dist/assistant-approvals.js.map +1 -0
  14. package/dist/assistant-turn-driver.d.ts +73 -0
  15. package/dist/assistant-turn-driver.d.ts.map +1 -0
  16. package/dist/assistant-turn-events.d.ts +28 -1
  17. package/dist/assistant-turn-events.d.ts.map +1 -1
  18. package/dist/assistant-turn-events.js +2 -2
  19. package/dist/assistant-turn.d.ts +24 -37
  20. package/dist/assistant-turn.d.ts.map +1 -1
  21. package/dist/chunks/{ChatService-BGBAqmZq.js → ChatService-C1UBz0MR.js} +684 -657
  22. package/dist/chunks/ChatService-C1UBz0MR.js.map +1 -0
  23. package/dist/chunks/{assistant-turn-events-BbZUf-Ju.js → assistant-turn-events-DwdCZzQ0.js} +15 -2
  24. package/dist/chunks/assistant-turn-events-DwdCZzQ0.js.map +1 -0
  25. package/dist/chunks/chat-stream-mTbNV3kt.js +3571 -0
  26. package/dist/chunks/chat-stream-mTbNV3kt.js.map +1 -0
  27. package/dist/engines.d.ts +34 -0
  28. package/dist/engines.d.ts.map +1 -0
  29. package/dist/engines.js +260 -0
  30. package/dist/engines.js.map +1 -0
  31. package/dist/index.d.ts +4 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +8 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/internal/agent-runtime.js +1 -1
  36. package/dist/manifest.json +3 -1
  37. package/dist/persona-conversation.d.ts.map +1 -1
  38. package/dist/runtime-report-tools.d.ts.map +1 -1
  39. package/dist/services/ChatService.d.ts +3 -13
  40. package/dist/services/ChatService.d.ts.map +1 -1
  41. package/dist/smrt-knowledge.json +46 -9
  42. package/dist/smrt-knowledge.okf.md +29 -4
  43. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte +198 -0
  44. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts +34 -0
  45. package/dist/svelte/components/assistant/AssistantApprovalCard.svelte.d.ts.map +1 -0
  46. package/dist/svelte/components/assistant/AssistantComposer.svelte +6 -3
  47. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts +2 -0
  48. package/dist/svelte/components/assistant/AssistantComposer.svelte.d.ts.map +1 -1
  49. package/dist/svelte/components/assistant/AssistantDock.svelte +66 -17
  50. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts +2 -0
  51. package/dist/svelte/components/assistant/AssistantDock.svelte.d.ts.map +1 -1
  52. package/dist/svelte/components/assistant/assistant-http-client.d.ts +2 -0
  53. package/dist/svelte/components/assistant/assistant-http-client.d.ts.map +1 -1
  54. package/dist/svelte/components/assistant/assistant-http-client.js +28 -1
  55. package/dist/svelte/components/assistant/assistant-transport.d.ts +18 -1
  56. package/dist/svelte/components/assistant/assistant-transport.d.ts.map +1 -1
  57. package/dist/svelte/components/assistant/assistant-transport.js +2 -0
  58. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts +5 -1
  59. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.d.ts.map +1 -1
  60. package/dist/svelte/components/assistant/create-assistant-dock-controller.svelte.js +80 -4
  61. package/dist/svelte/i18n.d.ts +14 -0
  62. package/dist/svelte/i18n.d.ts.map +1 -1
  63. package/dist/svelte/i18n.js +14 -0
  64. package/dist/svelte/i18n.messages.d.ts +13 -0
  65. package/dist/svelte/i18n.messages.d.ts.map +1 -1
  66. package/dist/svelte/i18n.messages.js +13 -0
  67. package/dist/svelte/index.d.ts +2 -1
  68. package/dist/svelte/index.d.ts.map +1 -1
  69. package/dist/svelte/index.js +1 -0
  70. package/dist/sveltekit.d.ts +72 -4
  71. package/dist/sveltekit.d.ts.map +1 -1
  72. package/dist/sveltekit.js +439 -21
  73. package/dist/sveltekit.js.map +1 -1
  74. package/dist/tool-loop.d.ts +36 -3
  75. package/dist/tool-loop.d.ts.map +1 -1
  76. package/dist/tool-summary.d.ts +15 -0
  77. package/dist/tool-summary.d.ts.map +1 -0
  78. package/dist/tool-summary.js +95 -0
  79. package/dist/tool-summary.js.map +1 -0
  80. package/dist/work-profile.d.ts +64 -0
  81. package/dist/work-profile.d.ts.map +1 -0
  82. package/package.json +36 -22
  83. package/dist/chunks/ChatService-BGBAqmZq.js.map +0 -1
  84. package/dist/chunks/assistant-turn-events-BbZUf-Ju.js.map +0 -1
  85. package/dist/chunks/chat-stream-Blri3lj0.js +0 -2743
  86. package/dist/chunks/chat-stream-Blri3lj0.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { ObjectRegistry, SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, isPostgresDatabase, smrt } from "@happyvertical/smrt-core";
2
- import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
3
- import { ProfileCollection, resolveAgentProfileId } from "@happyvertical/smrt-profiles";
1
+ import { ObjectRegistry, SmrtCollection, SmrtObject, crossPackageRef, field, foreignKey, isPostgresDatabase, resolveListLimit, smrt } from "@happyvertical/smrt-core";
4
2
  import { createHash } from "node:crypto";
3
+ import { ProfileCollection, resolveAgentProfileId } from "@happyvertical/smrt-profiles";
4
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy";
5
5
  //#region \0rolldown/runtime.js
6
6
  var __defProp$7 = Object.defineProperty;
7
7
  var __exportAll = (all, no_symbols) => {
@@ -179,6 +179,99 @@ AgentSession = __decorateClass$6([TenantScoped({ mode: "optional" }), smrt({
179
179
  cli: { skipApiCheck: true }
180
180
  })], AgentSession);
181
181
  //#endregion
182
+ //#region src/collections/AgentSessionCollection.ts
183
+ var AgentSessionCollection = class extends SmrtCollection {
184
+ static _itemClass = AgentSession;
185
+ async findActiveByParticipant(participantProfileId) {
186
+ return (await this.list({ where: {
187
+ participantProfileId,
188
+ status: "active"
189
+ } })).filter((s) => s.isActive());
190
+ }
191
+ /**
192
+ * Resolve the active agent session for an (agent, participant) pair within a
193
+ * tenant (S5 #1392).
194
+ *
195
+ * `tenantId` is REQUIRED and always bound into the WHERE clause — including the
196
+ * `null` (untenanted) case — so the lookup can never silently drop its tenant
197
+ * predicate and resolve a session from another tenant. AgentSession uses
198
+ * optional tenancy, so `null` is a legitimate, explicitly-bound scope rather
199
+ * than "any tenant".
200
+ *
201
+ * When `sessionKey` is supplied the result is additionally narrowed to the
202
+ * session whose stored {@link AgentSession.getSessionKey} matches EXACTLY
203
+ * (S5 #1392). This binds session identity to a conversation subject (e.g. a
204
+ * content id) so a session opened for one subject is never reused for another;
205
+ * `sessionContext` is a JSON blob so the discriminator is matched in memory
206
+ * after the tenant-bound SQL filter.
207
+ */
208
+ async findActiveSession(agentId, participantProfileId, tenantId, sessionKey) {
209
+ const where = {
210
+ agentId,
211
+ participantProfileId,
212
+ status: "active",
213
+ tenantId
214
+ };
215
+ return (await this.list({ where })).find((s) => s.isActive() && (sessionKey === void 0 || s.getSessionKey() === (sessionKey ?? null))) ?? null;
216
+ }
217
+ async findOrCreate(params) {
218
+ const existing = await this.findActiveSession(params.agentId, params.participantProfileId, params.tenantId, params.sessionKey);
219
+ if (existing) return existing;
220
+ const sessionContext = params.sessionKey != null ? JSON.stringify({ [AgentSession.SESSION_KEY_CONTEXT_FIELD]: params.sessionKey }) : void 0;
221
+ return await this.create({
222
+ agentId: params.agentId,
223
+ agentProfileId: params.agentProfileId ?? null,
224
+ participantProfileId: params.participantProfileId,
225
+ tenantId: params.tenantId ?? null,
226
+ allowedTools: JSON.stringify(params.allowedTools ?? []),
227
+ chatRoomId: params.chatRoomId ?? null,
228
+ systemPrompt: params.systemPrompt ?? "",
229
+ status: "active",
230
+ ...sessionContext !== void 0 ? { sessionContext } : {}
231
+ });
232
+ }
233
+ async findByAgent(agentId) {
234
+ return this.list({ where: { agentId } });
235
+ }
236
+ /**
237
+ * Expire active sessions whose last activity predates `olderThan`.
238
+ *
239
+ * Caller-scoping (S5 #1392): pass `scope` to restrict the sweep to a single
240
+ * tenant and/or agent. Without a scope this expires stale sessions across the
241
+ * whole (tenant-filtered) collection — only safe for trusted maintenance
242
+ * callers, never for a per-tenant request handler.
243
+ *
244
+ * The candidate set is narrowed in SQL (status + activity timestamp) rather
245
+ * than loading every active session into memory and filtering in JS
246
+ * (DoS hardening). `lastMessageAt < olderThan` is applied server-side; rows
247
+ * that never recorded a message fall back to `created_at`.
248
+ */
249
+ async expireStale(olderThan, scope) {
250
+ const baseWhere = { status: "active" };
251
+ if (scope?.tenantId !== void 0) baseWhere.tenantId = scope.tenantId;
252
+ if (scope?.agentId !== void 0) baseWhere.agentId = scope.agentId;
253
+ const byLastMessage = await this.list({ where: {
254
+ ...baseWhere,
255
+ "lastMessageAt <": olderThan
256
+ } });
257
+ const neverMessaged = await this.list({ where: {
258
+ ...baseWhere,
259
+ lastMessageAt: null,
260
+ "created_at <": olderThan
261
+ } });
262
+ const seen = /* @__PURE__ */ new Set();
263
+ let expired = 0;
264
+ for (const session of [...byLastMessage, ...neverMessaged]) {
265
+ const id = session.id;
266
+ if (!id || seen.has(id)) continue;
267
+ seen.add(id);
268
+ await session.expire();
269
+ expired++;
270
+ }
271
+ return expired;
272
+ }
273
+ };
274
+ //#endregion
182
275
  //#region src/models/ChatMessage.ts
183
276
  var __defProp$5 = Object.defineProperty;
184
277
  var __getOwnPropDesc$5 = Object.getOwnPropertyDescriptor;
@@ -322,656 +415,117 @@ ChatMessage = __decorateClass$5([TenantScoped({ mode: "required" }), smrt({
322
415
  cli: { skipApiCheck: true }
323
416
  })], ChatMessage);
324
417
  //#endregion
325
- //#region src/models/ChatParticipant.ts
326
- var __defProp$4 = Object.defineProperty;
327
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
328
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
329
- enumerable: true,
330
- configurable: true,
331
- writable: true,
332
- value
333
- }) : obj[key] = value;
334
- var __decorateClass$4 = (decorators, target, key, kind) => {
335
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
336
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
337
- if (kind && result) __defProp$4(target, key, result);
338
- return result;
339
- };
340
- var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
341
- var ChatParticipant = class extends SmrtObject {
342
- tenantId = "";
343
- roomId = "";
344
- profileId = "";
345
- role = "member";
346
- status = "active";
347
- onlineStatus = "offline";
348
- lastReadMessageId = null;
349
- lastSeenAt = null;
350
- joinedAt = null;
351
- nickname = "";
352
- isMuted = false;
353
- isPinned = false;
354
- constructor(options = {}) {
355
- super(options);
356
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
357
- if (options.roomId !== void 0) this.roomId = options.roomId;
358
- if (options.profileId !== void 0) this.profileId = options.profileId;
359
- if (options.role !== void 0) this.role = options.role;
360
- if (options.status !== void 0) this.status = options.status;
361
- if (options.onlineStatus !== void 0) this.onlineStatus = options.onlineStatus;
362
- if (options.lastReadMessageId !== void 0) this.lastReadMessageId = options.lastReadMessageId;
363
- if (options.lastSeenAt !== void 0) this.lastSeenAt = options.lastSeenAt;
364
- if (options.joinedAt !== void 0) this.joinedAt = options.joinedAt;
365
- if (options.nickname !== void 0) this.nickname = options.nickname;
366
- if (options.isMuted !== void 0) this.isMuted = options.isMuted;
367
- if (options.isPinned !== void 0) this.isPinned = options.isPinned;
418
+ //#region src/collections/ChatMessageCollection.ts
419
+ var ChatMessageCollection = class extends SmrtCollection {
420
+ static _itemClass = ChatMessage;
421
+ /**
422
+ * Get messages for a room (newest first), excluding threads and deleted.
423
+ *
424
+ * Filtering, ordering and pagination are pushed into SQL rather than loading
425
+ * the full room history into memory (S5 #1392, DoS hardening). Thread replies
426
+ * are excluded via `threadId IS NULL` (the WHERE API maps a `null` value to
427
+ * `IS NULL`).
428
+ *
429
+ * `tenantId` is REQUIRED and bound into BOTH the message window AND the cursor
430
+ * lookup (S5 #1392): room ids are not globally unique, so a roomId-only read
431
+ * could surface another tenant's messages for a same-id room. The caller's
432
+ * membership gate is tenant-scoped, so the read MUST be too.
433
+ *
434
+ * `roles` (non-empty) keeps only those roles, in SQL, so `limit` counts
435
+ * them alone (#4458); omitted or empty reads every role.
436
+ */
437
+ async getByRoom(roomId, tenantId, options) {
438
+ const where = {
439
+ roomId,
440
+ tenantId,
441
+ isDeleted: false,
442
+ threadId: null
443
+ };
444
+ if (options?.roles?.length) where.role = [...options.roles];
445
+ if (options?.before) {
446
+ const cursorMsg = await this.get({
447
+ id: options.before,
448
+ roomId,
449
+ tenantId,
450
+ isDeleted: false,
451
+ threadId: null
452
+ });
453
+ if (cursorMsg?.created_at) where["created_at <"] = cursorMsg.created_at;
454
+ }
455
+ return this.list({
456
+ where,
457
+ orderBy: "created_at DESC",
458
+ limit: options?.limit
459
+ });
368
460
  }
369
- isActive() {
370
- return this.status === "active";
461
+ /**
462
+ * Get messages in a thread, tenant-bound (S5 #1392).
463
+ *
464
+ * `tenantId` is bound into the query so a thread id from another tenant can
465
+ * never surface that tenant's thread history.
466
+ */
467
+ async getByThread(threadId, tenantId) {
468
+ return this.list({ where: {
469
+ threadId,
470
+ tenantId,
471
+ isDeleted: false
472
+ } });
371
473
  }
372
- isOwner() {
373
- return this.role === "owner";
474
+ /**
475
+ * Get messages for an agent session, tenant-bound (S5 #1392).
476
+ *
477
+ * `tenantId` is bound into the query so a session id from another tenant can
478
+ * never surface that tenant's session messages.
479
+ */
480
+ async getByAgentSession(agentSessionId, tenantId) {
481
+ return this.list({ where: {
482
+ agentSessionId,
483
+ tenantId,
484
+ isDeleted: false
485
+ } });
374
486
  }
375
- isAdmin() {
376
- return this.role === "admin" || this.role === "owner";
377
- }
378
- async markRead(messageId) {
379
- this.lastReadMessageId = messageId;
380
- this.lastSeenAt = /* @__PURE__ */ new Date();
381
- await this.save();
382
- }
383
- async leave() {
384
- this.status = "left";
385
- await this.save();
386
- }
387
- async setOnline(status) {
388
- this.onlineStatus = status;
389
- this.lastSeenAt = /* @__PURE__ */ new Date();
390
- await this.save();
391
- }
392
- };
393
- __publicField$4(ChatParticipant, "__smrtPackage__", "@happyvertical/smrt-chat");
394
- __decorateClass$4([tenantId()], ChatParticipant.prototype, "tenantId", 2);
395
- __decorateClass$4([foreignKey("ChatRoom", { required: true }), field({ description: "The room to which this membership belongs." })], ChatParticipant.prototype, "roomId", 2);
396
- __decorateClass$4([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true }), field({ description: "The person or assistant participating in the room." })], ChatParticipant.prototype, "profileId", 2);
397
- __decorateClass$4([field({
398
- required: true,
399
- description: "The member role that determines what they can do in the room."
400
- })], ChatParticipant.prototype, "role", 2);
401
- __decorateClass$4([field({
402
- required: true,
403
- description: "Whether this member is active, has left, was removed, or is banned."
404
- })], ChatParticipant.prototype, "status", 2);
405
- __decorateClass$4([field({
406
- required: true,
407
- description: "The availability shown for this member, such as online or away."
408
- })], ChatParticipant.prototype, "onlineStatus", 2);
409
- __decorateClass$4([foreignKey("ChatMessage"), field({ description: "The most recent message this member has read." })], ChatParticipant.prototype, "lastReadMessageId", 2);
410
- __decorateClass$4([field({ description: "When this member was last seen in the conversation." })], ChatParticipant.prototype, "lastSeenAt", 2);
411
- __decorateClass$4([field({ description: "When this member joined the room." })], ChatParticipant.prototype, "joinedAt", 2);
412
- __decorateClass$4([field({ description: "The display name this member uses within the room." })], ChatParticipant.prototype, "nickname", 2);
413
- __decorateClass$4([field({ description: "Whether notifications for this room are muted for this member." })], ChatParticipant.prototype, "isMuted", 2);
414
- __decorateClass$4([field({ description: "Whether this room is pinned for this member." })], ChatParticipant.prototype, "isPinned", 2);
415
- ChatParticipant = __decorateClass$4([TenantScoped({ mode: "required" }), smrt({
416
- tableName: "chat_participants",
417
- api: { include: ["list", "get"] },
418
- mcp: { include: ["list", "get"] },
419
- cli: { skipApiCheck: true }
420
- })], ChatParticipant);
421
- //#endregion
422
- //#region src/models/ChatReaction.ts
423
- var __defProp$3 = Object.defineProperty;
424
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
425
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
426
- enumerable: true,
427
- configurable: true,
428
- writable: true,
429
- value
430
- }) : obj[key] = value;
431
- var __decorateClass$3 = (decorators, target, key, kind) => {
432
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
433
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
434
- if (kind && result) __defProp$3(target, key, result);
435
- return result;
436
- };
437
- var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
438
- var ChatReaction = class extends SmrtObject {
439
- tenantId = "";
440
- messageId = "";
441
- profileId = "";
442
- emoji = "";
443
- constructor(options = {}) {
444
- super(options);
445
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
446
- if (options.messageId !== void 0) this.messageId = options.messageId;
447
- if (options.profileId !== void 0) this.profileId = options.profileId;
448
- if (options.emoji !== void 0) this.emoji = options.emoji;
449
- }
450
- };
451
- __publicField$3(ChatReaction, "__smrtPackage__", "@happyvertical/smrt-chat");
452
- __decorateClass$3([tenantId()], ChatReaction.prototype, "tenantId", 2);
453
- __decorateClass$3([foreignKey("ChatMessage", { required: true }), field({ description: "The message to which this reaction was added." })], ChatReaction.prototype, "messageId", 2);
454
- __decorateClass$3([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true }), field({ description: "The person who added this reaction." })], ChatReaction.prototype, "profileId", 2);
455
- __decorateClass$3([field({
456
- required: true,
457
- description: "The symbol chosen to express a response to the message."
458
- })], ChatReaction.prototype, "emoji", 2);
459
- ChatReaction = __decorateClass$3([TenantScoped({ mode: "required" }), smrt({
460
- tableName: "chat_reactions",
461
- api: { include: ["list"] },
462
- mcp: { include: ["list"] },
463
- cli: false
464
- })], ChatReaction);
465
- //#endregion
466
- //#region src/models/ChatRoom.ts
467
- var __defProp$2 = Object.defineProperty;
468
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
469
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
470
- enumerable: true,
471
- configurable: true,
472
- writable: true,
473
- value
474
- }) : obj[key] = value;
475
- var __decorateClass$2 = (decorators, target, key, kind) => {
476
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
477
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
478
- if (kind && result) __defProp$2(target, key, result);
479
- return result;
480
- };
481
- var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
482
- var ChatRoom = class extends SmrtObject {
483
- tenantId = "";
484
- name = "";
485
- description = "";
486
- roomType = "public";
487
- status = "active";
488
- topic = "";
489
- avatarUrl = "";
490
- isArchived = false;
491
- maxParticipants = 0;
492
- metadata = "{}";
493
- createdByProfileId = "";
494
- lastMessageAt = null;
495
- constructor(options = {}) {
496
- super(options);
497
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
498
- if (options.name !== void 0) this.name = options.name;
499
- if (options.description !== void 0) this.description = options.description;
500
- if (options.roomType !== void 0) this.roomType = options.roomType;
501
- if (options.status !== void 0) this.status = options.status;
502
- if (options.topic !== void 0) this.topic = options.topic;
503
- if (options.avatarUrl !== void 0) this.avatarUrl = options.avatarUrl;
504
- if (options.isArchived !== void 0) this.isArchived = options.isArchived;
505
- if (options.maxParticipants !== void 0) this.maxParticipants = options.maxParticipants;
506
- if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
507
- if (options.createdByProfileId !== void 0) this.createdByProfileId = options.createdByProfileId;
508
- if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
509
- }
510
- getMetadata() {
511
- try {
512
- return JSON.parse(this.metadata);
513
- } catch {
514
- return {};
515
- }
516
- }
517
- setMetadata(data) {
518
- this.metadata = JSON.stringify(data);
519
- }
520
- updateMetadata(updates) {
521
- const current = this.getMetadata();
522
- this.metadata = JSON.stringify({
523
- ...current,
524
- ...updates
525
- });
526
- }
527
- isDM() {
528
- return this.roomType === "dm";
529
- }
530
- isAgentRoom() {
531
- return this.roomType === "agent";
532
- }
533
- isPublic() {
534
- return this.roomType === "public";
535
- }
536
- isActive() {
537
- return this.status === "active";
538
- }
539
- async archive() {
540
- this.isArchived = true;
541
- this.status = "archived";
542
- await this.save();
543
- }
544
- async unarchive() {
545
- this.isArchived = false;
546
- this.status = "active";
547
- await this.save();
548
- }
549
- };
550
- __publicField$2(ChatRoom, "__smrtPackage__", "@happyvertical/smrt-chat");
551
- __decorateClass$2([tenantId()], ChatRoom.prototype, "tenantId", 2);
552
- __decorateClass$2([field({ description: "A recognizable name that helps teammates find this room." })], ChatRoom.prototype, "name", 2);
553
- __decorateClass$2([field({ description: "Explain the purpose of the room and who should join." })], ChatRoom.prototype, "description", 2);
554
- __decorateClass$2([field({
555
- required: true,
556
- description: "Whether the room is public, private, a direct message, or an assistant conversation."
557
- })], ChatRoom.prototype, "roomType", 2);
558
- __decorateClass$2([field({
559
- required: true,
560
- description: "Whether this room is active, archived, or deleted."
561
- })], ChatRoom.prototype, "status", 2);
562
- __decorateClass$2([field({ description: "The current subject or focus of the room." })], ChatRoom.prototype, "topic", 2);
563
- __decorateClass$2([field({ description: "The address of the image used to represent this room." })], ChatRoom.prototype, "avatarUrl", 2);
564
- __decorateClass$2([field({ description: "Whether the room has been archived from active conversations." })], ChatRoom.prototype, "isArchived", 2);
565
- __decorateClass$2([field({ description: "The maximum number of members; zero means no configured limit." })], ChatRoom.prototype, "maxParticipants", 2);
566
- __decorateClass$2([field({ description: "Additional room details maintained by the application." })], ChatRoom.prototype, "metadata", 2);
567
- __decorateClass$2([crossPackageRef("@happyvertical/smrt-profiles:Profile"), field({ description: "The person who originally created this room." })], ChatRoom.prototype, "createdByProfileId", 2);
568
- __decorateClass$2([field({ description: "When the most recent message was sent in this room." })], ChatRoom.prototype, "lastMessageAt", 2);
569
- ChatRoom = __decorateClass$2([TenantScoped({ mode: "required" }), smrt({
570
- tableName: "chat_rooms",
571
- api: { include: ["list", "get"] },
572
- mcp: { include: ["list", "get"] },
573
- cli: { skipApiCheck: true }
574
- })], ChatRoom);
575
- //#endregion
576
- //#region src/models/ChatThread.ts
577
- var __defProp$1 = Object.defineProperty;
578
- var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
579
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
580
- enumerable: true,
581
- configurable: true,
582
- writable: true,
583
- value
584
- }) : obj[key] = value;
585
- var __decorateClass$1 = (decorators, target, key, kind) => {
586
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
587
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
588
- if (kind && result) __defProp$1(target, key, result);
589
- return result;
590
- };
591
- var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
592
- var ChatThread = class extends SmrtObject {
593
- tenantId = "";
594
- roomId = "";
595
- rootMessageId = null;
596
- title = "";
597
- isResolved = false;
598
- messageCount = 0;
599
- lastMessageAt = null;
600
- participantCount = 0;
601
- constructor(options = {}) {
602
- super(options);
603
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
604
- if (options.roomId !== void 0) this.roomId = options.roomId;
605
- if (options.rootMessageId !== void 0) this.rootMessageId = options.rootMessageId;
606
- if (options.title !== void 0) this.title = options.title;
607
- if (options.isResolved !== void 0) this.isResolved = options.isResolved;
608
- if (options.messageCount !== void 0) this.messageCount = options.messageCount;
609
- if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
610
- if (options.participantCount !== void 0) this.participantCount = options.participantCount;
611
- }
612
- async resolve() {
613
- this.isResolved = true;
614
- await this.save();
615
- }
616
- async reopen() {
617
- this.isResolved = false;
618
- await this.save();
619
- }
620
- };
621
- __publicField$1(ChatThread, "__smrtPackage__", "@happyvertical/smrt-chat");
622
- __decorateClass$1([tenantId()], ChatThread.prototype, "tenantId", 2);
623
- __decorateClass$1([foreignKey("ChatRoom", { required: true }), field({ description: "The room containing this discussion thread." })], ChatThread.prototype, "roomId", 2);
624
- __decorateClass$1([foreignKey("ChatMessage", { nullable: true }), field({ description: "The message that started this thread, when it began as a reply." })], ChatThread.prototype, "rootMessageId", 2);
625
- __decorateClass$1([field({ description: "A short title describing the subject of this thread." })], ChatThread.prototype, "title", 2);
626
- __decorateClass$1([field({ description: "Whether the discussion has reached a resolution." })], ChatThread.prototype, "isResolved", 2);
627
- __decorateClass$1([field({ description: "The number of messages in this thread." })], ChatThread.prototype, "messageCount", 2);
628
- __decorateClass$1([field({ description: "When the most recent message was sent in this thread." })], ChatThread.prototype, "lastMessageAt", 2);
629
- __decorateClass$1([field({ description: "The number of people participating in this thread." })], ChatThread.prototype, "participantCount", 2);
630
- ChatThread = __decorateClass$1([TenantScoped({ mode: "required" }), smrt({
631
- tableName: "chat_threads",
632
- api: { include: ["list", "get"] },
633
- mcp: { include: ["list", "get"] },
634
- cli: { skipApiCheck: true }
635
- })], ChatThread);
636
- //#endregion
637
- //#region src/models/VoiceSession.ts
638
- var __defProp = Object.defineProperty;
639
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
640
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
641
- enumerable: true,
642
- configurable: true,
643
- writable: true,
644
- value
645
- }) : obj[key] = value;
646
- var __decorateClass = (decorators, target, key, kind) => {
647
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
648
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
649
- if (kind && result) __defProp(target, key, result);
650
- return result;
651
- };
652
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
653
- var VoiceSession = class extends SmrtObject {
654
- tenantId = "";
655
- gatewaySessionId = "";
656
- actorProfileId = "";
657
- actorUserId = null;
658
- personaId = "";
659
- agentSessionId = "";
660
- chatRoomId = "";
661
- threadId = null;
662
- target = "smrt:chat";
663
- status = "active";
664
- expiresAt = new Date(Date.now() + 600 * 1e3);
665
- lastTurnAt = null;
666
- lastGatewayTurnId = null;
667
- personaSnapshot = "{}";
668
- metadata = "{}";
669
- processedTurnIds = "[]";
670
- constructor(options = {}) {
671
- super(options);
672
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
673
- if (options.gatewaySessionId !== void 0) this.gatewaySessionId = options.gatewaySessionId;
674
- if (options.actorProfileId !== void 0) this.actorProfileId = options.actorProfileId;
675
- if (options.actorUserId !== void 0) this.actorUserId = options.actorUserId;
676
- if (options.personaId !== void 0) this.personaId = options.personaId;
677
- if (options.agentSessionId !== void 0) this.agentSessionId = options.agentSessionId;
678
- if (options.chatRoomId !== void 0) this.chatRoomId = options.chatRoomId;
679
- if (options.threadId !== void 0) this.threadId = options.threadId;
680
- if (options.target !== void 0) this.target = options.target;
681
- if (options.status !== void 0) this.status = options.status;
682
- if (options.expiresAt !== void 0) this.expiresAt = options.expiresAt;
683
- if (options.lastTurnAt !== void 0) this.lastTurnAt = options.lastTurnAt;
684
- if (options.lastGatewayTurnId !== void 0) this.lastGatewayTurnId = options.lastGatewayTurnId;
685
- if (options.personaSnapshot !== void 0) this.personaSnapshot = typeof options.personaSnapshot === "string" ? options.personaSnapshot : JSON.stringify(options.personaSnapshot);
686
- if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
687
- if (options.processedTurnIds !== void 0) this.processedTurnIds = typeof options.processedTurnIds === "string" ? options.processedTurnIds : JSON.stringify(options.processedTurnIds);
688
- }
689
- isActive(now = /* @__PURE__ */ new Date()) {
690
- return this.status === "active" && now < this.expiresAt;
691
- }
692
- isExpired(now = /* @__PURE__ */ new Date()) {
693
- return now >= this.expiresAt;
694
- }
695
- async expire() {
696
- this.status = "expired";
697
- await this.save();
698
- }
699
- async revoke() {
700
- this.status = "revoked";
701
- await this.save();
702
- }
703
- getPersonaSnapshot() {
704
- try {
705
- return JSON.parse(this.personaSnapshot);
706
- } catch {
707
- return {
708
- id: this.personaId,
709
- tenantId: this.tenantId,
710
- runAsUserId: "",
711
- allowedTools: []
712
- };
713
- }
714
- }
715
- setPersonaSnapshot(persona) {
716
- this.personaSnapshot = JSON.stringify(persona);
717
- }
718
- getMetadata() {
719
- try {
720
- return JSON.parse(this.metadata);
721
- } catch {
722
- return {};
723
- }
724
- }
725
- setMetadata(metadata) {
726
- this.metadata = JSON.stringify(metadata);
727
- }
728
- getProcessedTurnIds() {
729
- try {
730
- const parsed = JSON.parse(this.processedTurnIds);
731
- return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
732
- } catch {
733
- return [];
734
- }
735
- }
736
- hasProcessedTurn(turnId) {
737
- return this.getProcessedTurnIds().includes(turnId);
738
- }
739
- recordGatewayTurn(turnId, maxRememberedTurns = 50) {
740
- const ids = this.getProcessedTurnIds().filter((id) => id !== turnId);
741
- ids.push(turnId);
742
- this.processedTurnIds = JSON.stringify(ids.slice(-maxRememberedTurns));
743
- this.lastGatewayTurnId = turnId;
744
- this.lastTurnAt = /* @__PURE__ */ new Date();
745
- }
746
- };
747
- __publicField(VoiceSession, "__smrtPackage__", "@happyvertical/smrt-chat");
748
- __decorateClass([tenantId()], VoiceSession.prototype, "tenantId", 2);
749
- __decorateClass([field({ required: true })], VoiceSession.prototype, "gatewaySessionId", 2);
750
- __decorateClass([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], VoiceSession.prototype, "actorProfileId", 2);
751
- __decorateClass([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], VoiceSession.prototype, "actorUserId", 2);
752
- __decorateClass([crossPackageRef("@happyvertical/smrt-personas:AgentPersona", { required: true })], VoiceSession.prototype, "personaId", 2);
753
- __decorateClass([foreignKey("AgentSession", { required: true })], VoiceSession.prototype, "agentSessionId", 2);
754
- __decorateClass([foreignKey("ChatRoom", { required: true })], VoiceSession.prototype, "chatRoomId", 2);
755
- __decorateClass([foreignKey("ChatThread")], VoiceSession.prototype, "threadId", 2);
756
- __decorateClass([field({ required: true })], VoiceSession.prototype, "target", 2);
757
- __decorateClass([field({ required: true })], VoiceSession.prototype, "status", 2);
758
- __decorateClass([field({ required: true })], VoiceSession.prototype, "expiresAt", 2);
759
- __decorateClass([field()], VoiceSession.prototype, "lastTurnAt", 2);
760
- __decorateClass([field()], VoiceSession.prototype, "lastGatewayTurnId", 2);
761
- __decorateClass([field()], VoiceSession.prototype, "personaSnapshot", 2);
762
- __decorateClass([field()], VoiceSession.prototype, "metadata", 2);
763
- __decorateClass([field()], VoiceSession.prototype, "processedTurnIds", 2);
764
- VoiceSession = __decorateClass([TenantScoped({ mode: "required" }), smrt({
765
- tableName: "voice_sessions",
766
- api: { include: ["list", "get"] },
767
- mcp: { include: ["list", "get"] },
768
- cli: { skipApiCheck: true }
769
- })], VoiceSession);
770
- //#endregion
771
- //#region src/collections/AgentSessionCollection.ts
772
- var AgentSessionCollection = class extends SmrtCollection {
773
- static _itemClass = AgentSession;
774
- async findActiveByParticipant(participantProfileId) {
775
- return (await this.list({ where: {
776
- participantProfileId,
777
- status: "active"
778
- } })).filter((s) => s.isActive());
779
- }
780
- /**
781
- * Resolve the active agent session for an (agent, participant) pair within a
782
- * tenant (S5 #1392).
783
- *
784
- * `tenantId` is REQUIRED and always bound into the WHERE clause — including the
785
- * `null` (untenanted) case — so the lookup can never silently drop its tenant
786
- * predicate and resolve a session from another tenant. AgentSession uses
787
- * optional tenancy, so `null` is a legitimate, explicitly-bound scope rather
788
- * than "any tenant".
789
- *
790
- * When `sessionKey` is supplied the result is additionally narrowed to the
791
- * session whose stored {@link AgentSession.getSessionKey} matches EXACTLY
792
- * (S5 #1392). This binds session identity to a conversation subject (e.g. a
793
- * content id) so a session opened for one subject is never reused for another;
794
- * `sessionContext` is a JSON blob so the discriminator is matched in memory
795
- * after the tenant-bound SQL filter.
796
- */
797
- async findActiveSession(agentId, participantProfileId, tenantId, sessionKey) {
798
- const where = {
799
- agentId,
800
- participantProfileId,
801
- status: "active",
802
- tenantId
803
- };
804
- return (await this.list({ where })).find((s) => s.isActive() && (sessionKey === void 0 || s.getSessionKey() === (sessionKey ?? null))) ?? null;
805
- }
806
- async findOrCreate(params) {
807
- const existing = await this.findActiveSession(params.agentId, params.participantProfileId, params.tenantId, params.sessionKey);
808
- if (existing) return existing;
809
- const sessionContext = params.sessionKey != null ? JSON.stringify({ [AgentSession.SESSION_KEY_CONTEXT_FIELD]: params.sessionKey }) : void 0;
810
- return await this.create({
811
- agentId: params.agentId,
812
- agentProfileId: params.agentProfileId ?? null,
813
- participantProfileId: params.participantProfileId,
814
- tenantId: params.tenantId ?? null,
815
- allowedTools: JSON.stringify(params.allowedTools ?? []),
816
- chatRoomId: params.chatRoomId ?? null,
817
- systemPrompt: params.systemPrompt ?? "",
818
- status: "active",
819
- ...sessionContext !== void 0 ? { sessionContext } : {}
820
- });
821
- }
822
- async findByAgent(agentId) {
823
- return this.list({ where: { agentId } });
824
- }
825
- /**
826
- * Expire active sessions whose last activity predates `olderThan`.
827
- *
828
- * Caller-scoping (S5 #1392): pass `scope` to restrict the sweep to a single
829
- * tenant and/or agent. Without a scope this expires stale sessions across the
830
- * whole (tenant-filtered) collection — only safe for trusted maintenance
831
- * callers, never for a per-tenant request handler.
832
- *
833
- * The candidate set is narrowed in SQL (status + activity timestamp) rather
834
- * than loading every active session into memory and filtering in JS
835
- * (DoS hardening). `lastMessageAt < olderThan` is applied server-side; rows
836
- * that never recorded a message fall back to `created_at`.
837
- */
838
- async expireStale(olderThan, scope) {
839
- const baseWhere = { status: "active" };
840
- if (scope?.tenantId !== void 0) baseWhere.tenantId = scope.tenantId;
841
- if (scope?.agentId !== void 0) baseWhere.agentId = scope.agentId;
842
- const byLastMessage = await this.list({ where: {
843
- ...baseWhere,
844
- "lastMessageAt <": olderThan
845
- } });
846
- const neverMessaged = await this.list({ where: {
847
- ...baseWhere,
848
- lastMessageAt: null,
849
- "created_at <": olderThan
850
- } });
851
- const seen = /* @__PURE__ */ new Set();
852
- let expired = 0;
853
- for (const session of [...byLastMessage, ...neverMessaged]) {
854
- const id = session.id;
855
- if (!id || seen.has(id)) continue;
856
- seen.add(id);
857
- await session.expire();
858
- expired++;
859
- }
860
- return expired;
861
- }
862
- };
863
- //#endregion
864
- //#region src/collections/ChatMessageCollection.ts
865
- var ChatMessageCollection = class extends SmrtCollection {
866
- static _itemClass = ChatMessage;
867
- /**
868
- * Get messages for a room (newest first), excluding threads and deleted.
869
- *
870
- * Filtering, ordering and pagination are pushed into SQL rather than loading
871
- * the full room history into memory (S5 #1392, DoS hardening). Thread replies
872
- * are excluded via `threadId IS NULL` (the WHERE API maps a `null` value to
873
- * `IS NULL`).
874
- *
875
- * `tenantId` is REQUIRED and bound into BOTH the message window AND the cursor
876
- * lookup (S5 #1392): room ids are not globally unique, so a roomId-only read
877
- * could surface another tenant's messages for a same-id room. The caller's
878
- * membership gate is tenant-scoped, so the read MUST be too.
879
- *
880
- * `roles` (non-empty) keeps only those roles, in SQL, so `limit` counts
881
- * them alone (#4458); omitted or empty reads every role.
882
- */
883
- async getByRoom(roomId, tenantId, options) {
884
- const where = {
885
- roomId,
886
- tenantId,
887
- isDeleted: false,
888
- threadId: null
889
- };
890
- if (options?.roles?.length) where.role = [...options.roles];
891
- if (options?.before) {
892
- const cursorMsg = await this.get({
893
- id: options.before,
894
- roomId,
895
- tenantId,
896
- isDeleted: false,
897
- threadId: null
898
- });
899
- if (cursorMsg?.created_at) where["created_at <"] = cursorMsg.created_at;
900
- }
901
- return this.list({
902
- where,
903
- orderBy: "created_at DESC",
904
- limit: options?.limit
905
- });
906
- }
907
- /**
908
- * Get messages in a thread, tenant-bound (S5 #1392).
909
- *
910
- * `tenantId` is bound into the query so a thread id from another tenant can
911
- * never surface that tenant's thread history.
912
- */
913
- async getByThread(threadId, tenantId) {
914
- return this.list({ where: {
915
- threadId,
916
- tenantId,
917
- isDeleted: false
918
- } });
919
- }
920
- /**
921
- * Get messages for an agent session, tenant-bound (S5 #1392).
922
- *
923
- * `tenantId` is bound into the query so a session id from another tenant can
924
- * never surface that tenant's session messages.
925
- */
926
- async getByAgentSession(agentSessionId, tenantId) {
927
- return this.list({ where: {
928
- agentSessionId,
929
- tenantId,
930
- isDeleted: false
931
- } });
932
- }
933
- /**
934
- * Search messages with filters.
935
- *
936
- * All structural filters (tenant/room/thread/sender/type/role/date/text) are
937
- * pushed into SQL instead of loading the full message set and filtering in JS
938
- * (S5 #1392, DoS hardening). `tenantId` is REQUIRED and always bound so the
939
- * search can never cross a tenant boundary.
940
- *
941
- * `hasAttachments` is derived from the stored `attachments` JSON column and is
942
- * pushed into SQL as a `!=`/`=` pre-filter against the empty-array sentinel
943
- * (`'[]'`, the column default) so the `LIMIT` applies to the ALREADY-FILTERED
944
- * set, not the raw window (S5 #1392). Previously the limit truncated the
945
- * newest-N window first and the JS filter ran afterwards, so a room whose
946
- * newest messages lacked attachments could return fewer (or zero)
947
- * attachment-bearing rows than existed. A precise JS pass on
948
- * `hasAttachments()` still runs to reject any malformed/empty column value the
949
- * coarse SQL sentinel can't distinguish, and the requested `limit` is enforced
950
- * on the filtered result.
951
- */
952
- async search(filters) {
953
- const where = {
954
- tenantId: filters.tenantId,
955
- isDeleted: false
956
- };
957
- if (filters.roomId) where.roomId = filters.roomId;
958
- if (filters.threadId) where.threadId = filters.threadId;
959
- if (filters.senderProfileId) where.senderProfileId = filters.senderProfileId;
960
- if (filters.messageType) where.messageType = filters.messageType;
961
- if (filters.role) where.role = filters.role;
962
- if (filters.query) where["content like"] = `%${filters.query}%`;
963
- if (filters.sinceDate) where["created_at >="] = filters.sinceDate;
964
- if (filters.beforeDate) where["created_at <"] = filters.beforeDate;
965
- const limit = filters.limit ?? 100;
966
- if (filters.hasAttachments === true) where["attachments !="] = "[]";
967
- else if (filters.hasAttachments === false) where.attachments = "[]";
968
- const messages = await this.list({
969
- where,
970
- orderBy: "created_at DESC",
971
- limit
972
- });
973
- if (filters.hasAttachments !== void 0) return messages.filter((m) => m.hasAttachments() === filters.hasAttachments).slice(0, limit);
974
- return messages;
487
+ /**
488
+ * Search messages with filters.
489
+ *
490
+ * All structural filters (tenant/room/thread/sender/type/role/date/text) are
491
+ * pushed into SQL instead of loading the full message set and filtering in JS
492
+ * (S5 #1392, DoS hardening). `tenantId` is REQUIRED and always bound so the
493
+ * search can never cross a tenant boundary.
494
+ *
495
+ * `hasAttachments` is derived from the stored `attachments` JSON column and is
496
+ * pushed into SQL as a `!=`/`=` pre-filter against the empty-array sentinel
497
+ * (`'[]'`, the column default) so the `LIMIT` applies to the ALREADY-FILTERED
498
+ * set, not the raw window (S5 #1392). Previously the limit truncated the
499
+ * newest-N window first and the JS filter ran afterwards, so a room whose
500
+ * newest messages lacked attachments could return fewer (or zero)
501
+ * attachment-bearing rows than existed. A precise JS pass on
502
+ * `hasAttachments()` still runs to reject any malformed/empty column value the
503
+ * coarse SQL sentinel can't distinguish, and the requested `limit` is enforced
504
+ * on the filtered result.
505
+ */
506
+ async search(filters) {
507
+ const where = {
508
+ tenantId: filters.tenantId,
509
+ isDeleted: false
510
+ };
511
+ if (filters.roomId) where.roomId = filters.roomId;
512
+ if (filters.threadId) where.threadId = filters.threadId;
513
+ if (filters.senderProfileId) where.senderProfileId = filters.senderProfileId;
514
+ if (filters.messageType) where.messageType = filters.messageType;
515
+ if (filters.role) where.role = filters.role;
516
+ if (filters.query) where["content like"] = `%${filters.query}%`;
517
+ if (filters.sinceDate) where["created_at >="] = filters.sinceDate;
518
+ if (filters.beforeDate) where["created_at <"] = filters.beforeDate;
519
+ const limit = filters.limit ?? 100;
520
+ if (filters.hasAttachments === true) where["attachments !="] = "[]";
521
+ else if (filters.hasAttachments === false) where.attachments = "[]";
522
+ const messages = await this.list({
523
+ where,
524
+ orderBy: "created_at DESC",
525
+ limit
526
+ });
527
+ if (filters.hasAttachments !== void 0) return messages.filter((m) => m.hasAttachments() === filters.hasAttachments).slice(0, limit);
528
+ return messages;
975
529
  }
976
530
  /**
977
531
  * Get unread count for a participant in a room (excludes thread replies).
@@ -1029,6 +583,103 @@ var ChatMessageCollection = class extends SmrtCollection {
1029
583
  }
1030
584
  };
1031
585
  //#endregion
586
+ //#region src/models/ChatParticipant.ts
587
+ var __defProp$4 = Object.defineProperty;
588
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
589
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, {
590
+ enumerable: true,
591
+ configurable: true,
592
+ writable: true,
593
+ value
594
+ }) : obj[key] = value;
595
+ var __decorateClass$4 = (decorators, target, key, kind) => {
596
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$4(target, key) : target;
597
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
598
+ if (kind && result) __defProp$4(target, key, result);
599
+ return result;
600
+ };
601
+ var __publicField$4 = (obj, key, value) => __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
602
+ var ChatParticipant = class extends SmrtObject {
603
+ tenantId = "";
604
+ roomId = "";
605
+ profileId = "";
606
+ role = "member";
607
+ status = "active";
608
+ onlineStatus = "offline";
609
+ lastReadMessageId = null;
610
+ lastSeenAt = null;
611
+ joinedAt = null;
612
+ nickname = "";
613
+ isMuted = false;
614
+ isPinned = false;
615
+ constructor(options = {}) {
616
+ super(options);
617
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
618
+ if (options.roomId !== void 0) this.roomId = options.roomId;
619
+ if (options.profileId !== void 0) this.profileId = options.profileId;
620
+ if (options.role !== void 0) this.role = options.role;
621
+ if (options.status !== void 0) this.status = options.status;
622
+ if (options.onlineStatus !== void 0) this.onlineStatus = options.onlineStatus;
623
+ if (options.lastReadMessageId !== void 0) this.lastReadMessageId = options.lastReadMessageId;
624
+ if (options.lastSeenAt !== void 0) this.lastSeenAt = options.lastSeenAt;
625
+ if (options.joinedAt !== void 0) this.joinedAt = options.joinedAt;
626
+ if (options.nickname !== void 0) this.nickname = options.nickname;
627
+ if (options.isMuted !== void 0) this.isMuted = options.isMuted;
628
+ if (options.isPinned !== void 0) this.isPinned = options.isPinned;
629
+ }
630
+ isActive() {
631
+ return this.status === "active";
632
+ }
633
+ isOwner() {
634
+ return this.role === "owner";
635
+ }
636
+ isAdmin() {
637
+ return this.role === "admin" || this.role === "owner";
638
+ }
639
+ async markRead(messageId) {
640
+ this.lastReadMessageId = messageId;
641
+ this.lastSeenAt = /* @__PURE__ */ new Date();
642
+ await this.save();
643
+ }
644
+ async leave() {
645
+ this.status = "left";
646
+ await this.save();
647
+ }
648
+ async setOnline(status) {
649
+ this.onlineStatus = status;
650
+ this.lastSeenAt = /* @__PURE__ */ new Date();
651
+ await this.save();
652
+ }
653
+ };
654
+ __publicField$4(ChatParticipant, "__smrtPackage__", "@happyvertical/smrt-chat");
655
+ __decorateClass$4([tenantId()], ChatParticipant.prototype, "tenantId", 2);
656
+ __decorateClass$4([foreignKey("ChatRoom", { required: true }), field({ description: "The room to which this membership belongs." })], ChatParticipant.prototype, "roomId", 2);
657
+ __decorateClass$4([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true }), field({ description: "The person or assistant participating in the room." })], ChatParticipant.prototype, "profileId", 2);
658
+ __decorateClass$4([field({
659
+ required: true,
660
+ description: "The member role that determines what they can do in the room."
661
+ })], ChatParticipant.prototype, "role", 2);
662
+ __decorateClass$4([field({
663
+ required: true,
664
+ description: "Whether this member is active, has left, was removed, or is banned."
665
+ })], ChatParticipant.prototype, "status", 2);
666
+ __decorateClass$4([field({
667
+ required: true,
668
+ description: "The availability shown for this member, such as online or away."
669
+ })], ChatParticipant.prototype, "onlineStatus", 2);
670
+ __decorateClass$4([foreignKey("ChatMessage"), field({ description: "The most recent message this member has read." })], ChatParticipant.prototype, "lastReadMessageId", 2);
671
+ __decorateClass$4([field({ description: "When this member was last seen in the conversation." })], ChatParticipant.prototype, "lastSeenAt", 2);
672
+ __decorateClass$4([field({ description: "When this member joined the room." })], ChatParticipant.prototype, "joinedAt", 2);
673
+ __decorateClass$4([field({ description: "The display name this member uses within the room." })], ChatParticipant.prototype, "nickname", 2);
674
+ __decorateClass$4([field({ description: "Whether notifications for this room are muted for this member." })], ChatParticipant.prototype, "isMuted", 2);
675
+ __decorateClass$4([field({ description: "Whether this room is pinned for this member." })], ChatParticipant.prototype, "isPinned", 2);
676
+ ChatParticipant = __decorateClass$4([TenantScoped({ mode: "required" }), smrt({
677
+ tableName: "chat_participants",
678
+ api: { include: ["list", "get"] },
679
+ mcp: { include: ["list", "get"] },
680
+ cli: { skipApiCheck: true }
681
+ })], ChatParticipant);
682
+ //#endregion
1032
683
  //#region src/collections/ChatParticipantCollection.ts
1033
684
  var ChatParticipantCollection = class extends SmrtCollection {
1034
685
  static _itemClass = ChatParticipant;
@@ -1099,6 +750,50 @@ var ChatParticipantCollection = class extends SmrtCollection {
1099
750
  }
1100
751
  };
1101
752
  //#endregion
753
+ //#region src/models/ChatReaction.ts
754
+ var __defProp$3 = Object.defineProperty;
755
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
756
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, {
757
+ enumerable: true,
758
+ configurable: true,
759
+ writable: true,
760
+ value
761
+ }) : obj[key] = value;
762
+ var __decorateClass$3 = (decorators, target, key, kind) => {
763
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$3(target, key) : target;
764
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
765
+ if (kind && result) __defProp$3(target, key, result);
766
+ return result;
767
+ };
768
+ var __publicField$3 = (obj, key, value) => __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
769
+ var ChatReaction = class extends SmrtObject {
770
+ tenantId = "";
771
+ messageId = "";
772
+ profileId = "";
773
+ emoji = "";
774
+ constructor(options = {}) {
775
+ super(options);
776
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
777
+ if (options.messageId !== void 0) this.messageId = options.messageId;
778
+ if (options.profileId !== void 0) this.profileId = options.profileId;
779
+ if (options.emoji !== void 0) this.emoji = options.emoji;
780
+ }
781
+ };
782
+ __publicField$3(ChatReaction, "__smrtPackage__", "@happyvertical/smrt-chat");
783
+ __decorateClass$3([tenantId()], ChatReaction.prototype, "tenantId", 2);
784
+ __decorateClass$3([foreignKey("ChatMessage", { required: true }), field({ description: "The message to which this reaction was added." })], ChatReaction.prototype, "messageId", 2);
785
+ __decorateClass$3([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true }), field({ description: "The person who added this reaction." })], ChatReaction.prototype, "profileId", 2);
786
+ __decorateClass$3([field({
787
+ required: true,
788
+ description: "The symbol chosen to express a response to the message."
789
+ })], ChatReaction.prototype, "emoji", 2);
790
+ ChatReaction = __decorateClass$3([TenantScoped({ mode: "required" }), smrt({
791
+ tableName: "chat_reactions",
792
+ api: { include: ["list"] },
793
+ mcp: { include: ["list"] },
794
+ cli: false
795
+ })], ChatReaction);
796
+ //#endregion
1102
797
  //#region src/collections/ChatReactionCollection.ts
1103
798
  var ChatReactionCollection = class extends SmrtCollection {
1104
799
  static _itemClass = ChatReaction;
@@ -1146,9 +841,119 @@ var ChatReactionCollection = class extends SmrtCollection {
1146
841
  profileId,
1147
842
  emoji
1148
843
  });
1149
- return { added: true };
844
+ return { added: true };
845
+ }
846
+ };
847
+ //#endregion
848
+ //#region src/models/ChatRoom.ts
849
+ var __defProp$2 = Object.defineProperty;
850
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
851
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, {
852
+ enumerable: true,
853
+ configurable: true,
854
+ writable: true,
855
+ value
856
+ }) : obj[key] = value;
857
+ var __decorateClass$2 = (decorators, target, key, kind) => {
858
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$2(target, key) : target;
859
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
860
+ if (kind && result) __defProp$2(target, key, result);
861
+ return result;
862
+ };
863
+ var __publicField$2 = (obj, key, value) => __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
864
+ var ChatRoom = class extends SmrtObject {
865
+ tenantId = "";
866
+ name = "";
867
+ description = "";
868
+ roomType = "public";
869
+ status = "active";
870
+ topic = "";
871
+ avatarUrl = "";
872
+ isArchived = false;
873
+ maxParticipants = 0;
874
+ metadata = "{}";
875
+ createdByProfileId = "";
876
+ lastMessageAt = null;
877
+ constructor(options = {}) {
878
+ super(options);
879
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
880
+ if (options.name !== void 0) this.name = options.name;
881
+ if (options.description !== void 0) this.description = options.description;
882
+ if (options.roomType !== void 0) this.roomType = options.roomType;
883
+ if (options.status !== void 0) this.status = options.status;
884
+ if (options.topic !== void 0) this.topic = options.topic;
885
+ if (options.avatarUrl !== void 0) this.avatarUrl = options.avatarUrl;
886
+ if (options.isArchived !== void 0) this.isArchived = options.isArchived;
887
+ if (options.maxParticipants !== void 0) this.maxParticipants = options.maxParticipants;
888
+ if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
889
+ if (options.createdByProfileId !== void 0) this.createdByProfileId = options.createdByProfileId;
890
+ if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
891
+ }
892
+ getMetadata() {
893
+ try {
894
+ return JSON.parse(this.metadata);
895
+ } catch {
896
+ return {};
897
+ }
898
+ }
899
+ setMetadata(data) {
900
+ this.metadata = JSON.stringify(data);
901
+ }
902
+ updateMetadata(updates) {
903
+ const current = this.getMetadata();
904
+ this.metadata = JSON.stringify({
905
+ ...current,
906
+ ...updates
907
+ });
908
+ }
909
+ isDM() {
910
+ return this.roomType === "dm";
911
+ }
912
+ isAgentRoom() {
913
+ return this.roomType === "agent";
914
+ }
915
+ isPublic() {
916
+ return this.roomType === "public";
917
+ }
918
+ isActive() {
919
+ return this.status === "active";
920
+ }
921
+ async archive() {
922
+ this.isArchived = true;
923
+ this.status = "archived";
924
+ await this.save();
925
+ }
926
+ async unarchive() {
927
+ this.isArchived = false;
928
+ this.status = "active";
929
+ await this.save();
1150
930
  }
1151
931
  };
932
+ __publicField$2(ChatRoom, "__smrtPackage__", "@happyvertical/smrt-chat");
933
+ __decorateClass$2([tenantId()], ChatRoom.prototype, "tenantId", 2);
934
+ __decorateClass$2([field({ description: "A recognizable name that helps teammates find this room." })], ChatRoom.prototype, "name", 2);
935
+ __decorateClass$2([field({ description: "Explain the purpose of the room and who should join." })], ChatRoom.prototype, "description", 2);
936
+ __decorateClass$2([field({
937
+ required: true,
938
+ description: "Whether the room is public, private, a direct message, or an assistant conversation."
939
+ })], ChatRoom.prototype, "roomType", 2);
940
+ __decorateClass$2([field({
941
+ required: true,
942
+ description: "Whether this room is active, archived, or deleted."
943
+ })], ChatRoom.prototype, "status", 2);
944
+ __decorateClass$2([field({ description: "The current subject or focus of the room." })], ChatRoom.prototype, "topic", 2);
945
+ __decorateClass$2([field({ description: "The address of the image used to represent this room." })], ChatRoom.prototype, "avatarUrl", 2);
946
+ __decorateClass$2([field({ description: "Whether the room has been archived from active conversations." })], ChatRoom.prototype, "isArchived", 2);
947
+ __decorateClass$2([field({ description: "The maximum number of members; zero means no configured limit." })], ChatRoom.prototype, "maxParticipants", 2);
948
+ __decorateClass$2([field({ description: "Additional room details maintained by the application." })], ChatRoom.prototype, "metadata", 2);
949
+ __decorateClass$2([crossPackageRef("@happyvertical/smrt-profiles:Profile"), field({ description: "The person who originally created this room." })], ChatRoom.prototype, "createdByProfileId", 2);
950
+ __decorateClass$2([field({ description: "When the most recent message was sent in this room." })], ChatRoom.prototype, "lastMessageAt", 2);
951
+ ChatRoom = __decorateClass$2([TenantScoped({ mode: "required" }), smrt({
952
+ tableName: "chat_rooms",
953
+ api: { include: ["list", "get"] },
954
+ mcp: { include: ["list", "get"] },
955
+ cli: { skipApiCheck: true }
956
+ })], ChatRoom);
1152
957
  //#endregion
1153
958
  //#region src/collections/ChatRoomCollection.ts
1154
959
  function canonicalDmRoomId(tenantId, profileId1, profileId2) {
@@ -1264,6 +1069,67 @@ var ChatRoomCollection = class extends SmrtCollection {
1264
1069
  }
1265
1070
  };
1266
1071
  //#endregion
1072
+ //#region src/models/ChatThread.ts
1073
+ var __defProp$1 = Object.defineProperty;
1074
+ var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
1075
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, {
1076
+ enumerable: true,
1077
+ configurable: true,
1078
+ writable: true,
1079
+ value
1080
+ }) : obj[key] = value;
1081
+ var __decorateClass$1 = (decorators, target, key, kind) => {
1082
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$1(target, key) : target;
1083
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1084
+ if (kind && result) __defProp$1(target, key, result);
1085
+ return result;
1086
+ };
1087
+ var __publicField$1 = (obj, key, value) => __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1088
+ var ChatThread = class extends SmrtObject {
1089
+ tenantId = "";
1090
+ roomId = "";
1091
+ rootMessageId = null;
1092
+ title = "";
1093
+ isResolved = false;
1094
+ messageCount = 0;
1095
+ lastMessageAt = null;
1096
+ participantCount = 0;
1097
+ constructor(options = {}) {
1098
+ super(options);
1099
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1100
+ if (options.roomId !== void 0) this.roomId = options.roomId;
1101
+ if (options.rootMessageId !== void 0) this.rootMessageId = options.rootMessageId;
1102
+ if (options.title !== void 0) this.title = options.title;
1103
+ if (options.isResolved !== void 0) this.isResolved = options.isResolved;
1104
+ if (options.messageCount !== void 0) this.messageCount = options.messageCount;
1105
+ if (options.lastMessageAt !== void 0) this.lastMessageAt = options.lastMessageAt;
1106
+ if (options.participantCount !== void 0) this.participantCount = options.participantCount;
1107
+ }
1108
+ async resolve() {
1109
+ this.isResolved = true;
1110
+ await this.save();
1111
+ }
1112
+ async reopen() {
1113
+ this.isResolved = false;
1114
+ await this.save();
1115
+ }
1116
+ };
1117
+ __publicField$1(ChatThread, "__smrtPackage__", "@happyvertical/smrt-chat");
1118
+ __decorateClass$1([tenantId()], ChatThread.prototype, "tenantId", 2);
1119
+ __decorateClass$1([foreignKey("ChatRoom", { required: true }), field({ description: "The room containing this discussion thread." })], ChatThread.prototype, "roomId", 2);
1120
+ __decorateClass$1([foreignKey("ChatMessage", { nullable: true }), field({ description: "The message that started this thread, when it began as a reply." })], ChatThread.prototype, "rootMessageId", 2);
1121
+ __decorateClass$1([field({ description: "A short title describing the subject of this thread." })], ChatThread.prototype, "title", 2);
1122
+ __decorateClass$1([field({ description: "Whether the discussion has reached a resolution." })], ChatThread.prototype, "isResolved", 2);
1123
+ __decorateClass$1([field({ description: "The number of messages in this thread." })], ChatThread.prototype, "messageCount", 2);
1124
+ __decorateClass$1([field({ description: "When the most recent message was sent in this thread." })], ChatThread.prototype, "lastMessageAt", 2);
1125
+ __decorateClass$1([field({ description: "The number of people participating in this thread." })], ChatThread.prototype, "participantCount", 2);
1126
+ ChatThread = __decorateClass$1([TenantScoped({ mode: "required" }), smrt({
1127
+ tableName: "chat_threads",
1128
+ api: { include: ["list", "get"] },
1129
+ mcp: { include: ["list", "get"] },
1130
+ cli: { skipApiCheck: true }
1131
+ })], ChatThread);
1132
+ //#endregion
1267
1133
  //#region src/collections/ChatThreadCollection.ts
1268
1134
  var ChatThreadCollection = class extends SmrtCollection {
1269
1135
  static _itemClass = ChatThread;
@@ -1278,6 +1144,140 @@ var ChatThreadCollection = class extends SmrtCollection {
1278
1144
  }
1279
1145
  };
1280
1146
  //#endregion
1147
+ //#region src/models/VoiceSession.ts
1148
+ var __defProp = Object.defineProperty;
1149
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1150
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
1151
+ enumerable: true,
1152
+ configurable: true,
1153
+ writable: true,
1154
+ value
1155
+ }) : obj[key] = value;
1156
+ var __decorateClass = (decorators, target, key, kind) => {
1157
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
1158
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
1159
+ if (kind && result) __defProp(target, key, result);
1160
+ return result;
1161
+ };
1162
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1163
+ var VoiceSession = class extends SmrtObject {
1164
+ tenantId = "";
1165
+ gatewaySessionId = "";
1166
+ actorProfileId = "";
1167
+ actorUserId = null;
1168
+ personaId = "";
1169
+ agentSessionId = "";
1170
+ chatRoomId = "";
1171
+ threadId = null;
1172
+ target = "smrt:chat";
1173
+ status = "active";
1174
+ expiresAt = new Date(Date.now() + 600 * 1e3);
1175
+ lastTurnAt = null;
1176
+ lastGatewayTurnId = null;
1177
+ personaSnapshot = "{}";
1178
+ metadata = "{}";
1179
+ processedTurnIds = "[]";
1180
+ constructor(options = {}) {
1181
+ super(options);
1182
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
1183
+ if (options.gatewaySessionId !== void 0) this.gatewaySessionId = options.gatewaySessionId;
1184
+ if (options.actorProfileId !== void 0) this.actorProfileId = options.actorProfileId;
1185
+ if (options.actorUserId !== void 0) this.actorUserId = options.actorUserId;
1186
+ if (options.personaId !== void 0) this.personaId = options.personaId;
1187
+ if (options.agentSessionId !== void 0) this.agentSessionId = options.agentSessionId;
1188
+ if (options.chatRoomId !== void 0) this.chatRoomId = options.chatRoomId;
1189
+ if (options.threadId !== void 0) this.threadId = options.threadId;
1190
+ if (options.target !== void 0) this.target = options.target;
1191
+ if (options.status !== void 0) this.status = options.status;
1192
+ if (options.expiresAt !== void 0) this.expiresAt = options.expiresAt;
1193
+ if (options.lastTurnAt !== void 0) this.lastTurnAt = options.lastTurnAt;
1194
+ if (options.lastGatewayTurnId !== void 0) this.lastGatewayTurnId = options.lastGatewayTurnId;
1195
+ if (options.personaSnapshot !== void 0) this.personaSnapshot = typeof options.personaSnapshot === "string" ? options.personaSnapshot : JSON.stringify(options.personaSnapshot);
1196
+ if (options.metadata !== void 0) this.metadata = typeof options.metadata === "string" ? options.metadata : JSON.stringify(options.metadata);
1197
+ if (options.processedTurnIds !== void 0) this.processedTurnIds = typeof options.processedTurnIds === "string" ? options.processedTurnIds : JSON.stringify(options.processedTurnIds);
1198
+ }
1199
+ isActive(now = /* @__PURE__ */ new Date()) {
1200
+ return this.status === "active" && now < this.expiresAt;
1201
+ }
1202
+ isExpired(now = /* @__PURE__ */ new Date()) {
1203
+ return now >= this.expiresAt;
1204
+ }
1205
+ async expire() {
1206
+ this.status = "expired";
1207
+ await this.save();
1208
+ }
1209
+ async revoke() {
1210
+ this.status = "revoked";
1211
+ await this.save();
1212
+ }
1213
+ getPersonaSnapshot() {
1214
+ try {
1215
+ return JSON.parse(this.personaSnapshot);
1216
+ } catch {
1217
+ return {
1218
+ id: this.personaId,
1219
+ tenantId: this.tenantId,
1220
+ runAsUserId: "",
1221
+ allowedTools: []
1222
+ };
1223
+ }
1224
+ }
1225
+ setPersonaSnapshot(persona) {
1226
+ this.personaSnapshot = JSON.stringify(persona);
1227
+ }
1228
+ getMetadata() {
1229
+ try {
1230
+ return JSON.parse(this.metadata);
1231
+ } catch {
1232
+ return {};
1233
+ }
1234
+ }
1235
+ setMetadata(metadata) {
1236
+ this.metadata = JSON.stringify(metadata);
1237
+ }
1238
+ getProcessedTurnIds() {
1239
+ try {
1240
+ const parsed = JSON.parse(this.processedTurnIds);
1241
+ return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
1242
+ } catch {
1243
+ return [];
1244
+ }
1245
+ }
1246
+ hasProcessedTurn(turnId) {
1247
+ return this.getProcessedTurnIds().includes(turnId);
1248
+ }
1249
+ recordGatewayTurn(turnId, maxRememberedTurns = 50) {
1250
+ const ids = this.getProcessedTurnIds().filter((id) => id !== turnId);
1251
+ ids.push(turnId);
1252
+ this.processedTurnIds = JSON.stringify(ids.slice(-maxRememberedTurns));
1253
+ this.lastGatewayTurnId = turnId;
1254
+ this.lastTurnAt = /* @__PURE__ */ new Date();
1255
+ }
1256
+ };
1257
+ __publicField(VoiceSession, "__smrtPackage__", "@happyvertical/smrt-chat");
1258
+ __decorateClass([tenantId()], VoiceSession.prototype, "tenantId", 2);
1259
+ __decorateClass([field({ required: true })], VoiceSession.prototype, "gatewaySessionId", 2);
1260
+ __decorateClass([crossPackageRef("@happyvertical/smrt-profiles:Profile", { required: true })], VoiceSession.prototype, "actorProfileId", 2);
1261
+ __decorateClass([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], VoiceSession.prototype, "actorUserId", 2);
1262
+ __decorateClass([crossPackageRef("@happyvertical/smrt-personas:AgentPersona", { required: true })], VoiceSession.prototype, "personaId", 2);
1263
+ __decorateClass([foreignKey("AgentSession", { required: true })], VoiceSession.prototype, "agentSessionId", 2);
1264
+ __decorateClass([foreignKey("ChatRoom", { required: true })], VoiceSession.prototype, "chatRoomId", 2);
1265
+ __decorateClass([foreignKey("ChatThread")], VoiceSession.prototype, "threadId", 2);
1266
+ __decorateClass([field({ required: true })], VoiceSession.prototype, "target", 2);
1267
+ __decorateClass([field({ required: true })], VoiceSession.prototype, "status", 2);
1268
+ __decorateClass([field({ required: true })], VoiceSession.prototype, "expiresAt", 2);
1269
+ __decorateClass([field()], VoiceSession.prototype, "lastTurnAt", 2);
1270
+ __decorateClass([field()], VoiceSession.prototype, "lastGatewayTurnId", 2);
1271
+ __decorateClass([field()], VoiceSession.prototype, "personaSnapshot", 2);
1272
+ __decorateClass([field()], VoiceSession.prototype, "metadata", 2);
1273
+ __decorateClass([field()], VoiceSession.prototype, "processedTurnIds", 2);
1274
+ VoiceSession = __decorateClass([TenantScoped({ mode: "required" }), smrt({
1275
+ tableName: "voice_sessions",
1276
+ api: { include: ["list", "get"] },
1277
+ mcp: { include: ["list", "get"] },
1278
+ cli: { skipApiCheck: true }
1279
+ })], VoiceSession);
1280
+ //#endregion
1281
1281
  //#region src/collections/VoiceSessionCollection.ts
1282
1282
  var VoiceSessionCollection = class extends SmrtCollection {
1283
1283
  static _itemClass = VoiceSession;
@@ -2105,6 +2105,33 @@ var ChatService = class ChatService {
2105
2105
  * newest `limit` of those, however many tool rows sit between (#4458).
2106
2106
  * Omitted or empty reads every role.
2107
2107
  */
2108
+ /** Filter trusted agent provenance only; user metadata never changes visibility. */
2109
+ #isConversationMessage(message) {
2110
+ if (message.role !== "assistant" && message.role !== "tool") return true;
2111
+ const metadata = message.getMetadata();
2112
+ return !(metadata && typeof metadata === "object" && (metadata.assistantInternalTurn === true || message.role === "assistant" && Object.hasOwn(metadata, "designOutput")));
2113
+ }
2114
+ async #listConversationMessages(options) {
2115
+ const visible = [];
2116
+ const limit = resolveListLimit(options.limit, { defaultValue: 200 });
2117
+ const pageSize = 200;
2118
+ const seen = /* @__PURE__ */ new Set();
2119
+ for (let offset = 0; visible.length < limit; offset += pageSize) {
2120
+ const page = await this.#messages.list({
2121
+ ...options,
2122
+ limit: pageSize,
2123
+ offset
2124
+ });
2125
+ for (const message of page) {
2126
+ if (seen.has(String(message.id))) continue;
2127
+ seen.add(String(message.id));
2128
+ if (this.#isConversationMessage(message)) visible.push(message);
2129
+ if (visible.length === limit) break;
2130
+ }
2131
+ if (page.length < pageSize) break;
2132
+ }
2133
+ return visible;
2134
+ }
2108
2135
  async getThreadMessages(params) {
2109
2136
  const thread = await this.#threads.get({
2110
2137
  id: params.threadId,
@@ -2112,14 +2139,14 @@ var ChatService = class ChatService {
2112
2139
  });
2113
2140
  if (!thread) throw new Error("Thread not found");
2114
2141
  await this.#requireActiveMembership(thread.roomId, params.actorProfileId, params.tenantId);
2115
- return (await this.#messages.list({
2142
+ return (await (params.visibility === "conversation" ? this.#listConversationMessages.bind(this) : this.#messages.list.bind(this.#messages))({
2116
2143
  where: {
2117
2144
  tenantId: params.tenantId,
2118
2145
  threadId: params.threadId,
2119
2146
  isDeleted: false,
2120
2147
  ...params.roles?.length ? { role: [...params.roles] } : {}
2121
2148
  },
2122
- orderBy: "created_at DESC",
2149
+ orderBy: params.visibility === "conversation" ? ["created_at DESC", "id DESC"] : "created_at DESC",
2123
2150
  limit: params.limit
2124
2151
  })).reverse();
2125
2152
  }
@@ -2142,17 +2169,17 @@ var ChatService = class ChatService {
2142
2169
  threadId: params.threadId,
2143
2170
  tenantId: params.tenantId
2144
2171
  });
2145
- if (!message || message.isDeleted) return null;
2172
+ if (!message || message.isDeleted || params.visibility === "conversation" && !this.#isConversationMessage(message)) return null;
2146
2173
  return {
2147
2174
  message,
2148
- replies: await this.#messages.list({
2175
+ replies: await (params.visibility === "conversation" ? this.#listConversationMessages.bind(this) : this.#messages.list.bind(this.#messages))({
2149
2176
  where: {
2150
2177
  tenantId: params.tenantId,
2151
2178
  threadId: params.threadId,
2152
2179
  replyToMessageId: params.messageId,
2153
2180
  isDeleted: false
2154
2181
  },
2155
- orderBy: "created_at ASC",
2182
+ orderBy: params.visibility === "conversation" ? ["created_at ASC", "id ASC"] : "created_at ASC",
2156
2183
  limit: params.limit ?? 100
2157
2184
  })
2158
2185
  };
@@ -2261,4 +2288,4 @@ function sendAgentReply(service, params) {
2261
2288
  //#endregion
2262
2289
  export { sendAgentReply as a, ChatThread as c, ChatParticipant as d, ChatMessage as f, clientRequestMessageId as i, ChatRoom as l, ChatService as n, VoiceSessionCollection as o, AgentSession as p, ChatService_exports as r, VoiceSession as s, ChatClientRequestConflictError as t, ChatReaction as u };
2263
2290
 
2264
- //# sourceMappingURL=ChatService-BGBAqmZq.js.map
2291
+ //# sourceMappingURL=ChatService-C1UBz0MR.js.map