@happyvertical/smrt-chat 0.45.1 → 0.45.2

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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.45.1",
5
+ "packageVersion": "0.45.2",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-chat:AgentSessionCollection": {
8
8
  "name": "agentsessioncollection",
@@ -1357,7 +1357,9 @@
1357
1357
  "get"
1358
1358
  ]
1359
1359
  },
1360
- "cli": true,
1360
+ "cli": {
1361
+ "skipApiCheck": true
1362
+ },
1361
1363
  "tenantScoped": {
1362
1364
  "mode": "optional"
1363
1365
  },
@@ -1804,7 +1806,9 @@
1804
1806
  "get"
1805
1807
  ]
1806
1808
  },
1807
- "cli": true,
1809
+ "cli": {
1810
+ "skipApiCheck": true
1811
+ },
1808
1812
  "tenantScoped": {
1809
1813
  "mode": "required"
1810
1814
  },
@@ -2199,7 +2203,9 @@
2199
2203
  "get"
2200
2204
  ]
2201
2205
  },
2202
- "cli": true,
2206
+ "cli": {
2207
+ "skipApiCheck": true
2208
+ },
2203
2209
  "tenantScoped": {
2204
2210
  "mode": "required"
2205
2211
  },
@@ -2759,7 +2765,9 @@
2759
2765
  "get"
2760
2766
  ]
2761
2767
  },
2762
- "cli": true,
2768
+ "cli": {
2769
+ "skipApiCheck": true
2770
+ },
2763
2771
  "tenantScoped": {
2764
2772
  "mode": "required"
2765
2773
  },
@@ -3010,7 +3018,9 @@
3010
3018
  "get"
3011
3019
  ]
3012
3020
  },
3013
- "cli": true,
3021
+ "cli": {
3022
+ "skipApiCheck": true
3023
+ },
3014
3024
  "tenantScoped": {
3015
3025
  "mode": "required"
3016
3026
  },
@@ -3682,7 +3692,9 @@
3682
3692
  "get"
3683
3693
  ]
3684
3694
  },
3685
- "cli": true,
3695
+ "cli": {
3696
+ "skipApiCheck": true
3697
+ },
3686
3698
  "tenantScoped": {
3687
3699
  "mode": "required"
3688
3700
  },
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-chat",
6
- "packageVersion": "0.45.1",
6
+ "packageVersion": "0.45.2",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "debdc685d046d39661671a7f59afc65561ce2aefadd31729c29ffe9d5797e377",
11
- "packageJson": "c234dde48416b48a7f8abfb7dcf9e7d09a9e7dfb068d6b7da3e01ecdb35aebe7",
12
- "agents": "0b73f5655366eb0aaee625ce18bccb56425a0720534f9248691a2950f6c68573"
10
+ "manifest": "8399345ae21a131e0785d725c8dbf28a4f79cbade8f7030e410fae099d31564e",
11
+ "packageJson": "295666cf292d6fc6ebbfc69bebe85d8d489424f4e6c5669d497c3e3c599b73c0",
12
+ "agents": "8d016963502a7cb53247cc366c5265c6b4d3240bc9c352242485b24a3644677c"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -4753,5 +4753,5 @@
4753
4753
  "polymorphicAssociations": 0,
4754
4754
  "uuidColumns": 46
4755
4755
  },
4756
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute is an interactive chat surface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root workbench also has a dev-only voice conversation mode. It reads voice\ngateway connection details through `/api/dev-voice/config`, streams browser mic\naudio to `WS /ws/voice` as PCM16 mono, appends gateway transcripts/responses to\nthe chat, and plays returned TTS audio. Exposing\n`SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN` to the browser requires\n`SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true`; keep that local-only.\n\n## Models\n\nInternal models — all mutations go through the membership/owner-checked `ChatService` (S5 #1392) or the voice adapter's binding-checked flow. EVERY `@smrt()` model in this package (ChatRoom, ChatMessage, ChatParticipant, ChatThread, ChatReaction, AgentSession, VoiceSession) has a READ-ONLY generated REST/MCP surface (`list`/`get` only); `create`/`update`/`delete` are intentionally NOT generated so the raw collection routes cannot skip the service-layer authorization. A structural regression test enumerates the registry to assert no chat model exposes a mutating op.\n\n`ChatService` is a CLOSED FACADE (S5 #1392). The raw collections (`rooms`, `messages`, `participants`, `threads`, `agentSessions`, `reactions`, `voiceSessions`) are ES `#private` fields — they are NOT on the public `ChatService` type and the package index does NOT export the collection classes, so a consumer cannot do `chat.messages.create({senderProfileId, role})` / `new ChatParticipantCollection(...)` to mutate around the authorization. The security-sensitive internals (`#writeMessage`, `#emitAgentReply`, `#enrollParticipant`, `#loadActiveSession`, `#requireActiveMembership`, `#requireRoomAdmin`, `#extractToolName`) are ES `#private` too, so they are unreachable at runtime — TypeScript `private` alone is erased and would leave them callable on the prototype. The agent-reply bridge is a `Symbol`-keyed static (not the old enumerable `_runAgentReply`), reachable only by the module-local `sendAgentReply` that holds the non-exported symbol.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (string ref, not FK), `allowedTools` (JSON string array), `sessionContext` (JSON), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nEvery public write takes an explicit server-supplied `actorProfileId` (the authenticated principal the route injects) — never a caller-controlled `senderProfileId`/`role` (S5 #1392).\n\nFacade: `sendMessage()` (authors as the actor with `role: 'user'`; room-membership-checked; no caller-supplied sender/role and no public membership-skip), `createRoom()` (acting actor becomes owner — no caller-supplied `createdByProfileId`), `startThread()` (member-checked; optional `rootMessageId` bound to the same room+tenant), `addParticipant()`/`removeParticipant()` (owner/admin-checked; self-leave allowed), `updateRoom()` (owner/admin-checked), `addReaction()`/`removeReaction()` (member-checked, self-keyed), `getOrCreateDM()` (actor must be a DM participant), `createAgentSession()` (acting actor becomes the session participant — no caller-supplied `participantProfileId`; the existing-session room lookup is tenant-bound; optional `sessionKey` scopes session identity to a conversation subject so distinct keys get distinct sessions/rooms and a session opened for one subject is never reused/rewritten for another). Tenant-bound read facade (replaces raw-collection reach-ins; consumers apply their own ownership/context checks on the returned rows): `getAgentSession({agentSessionId, tenantId})`, `findActiveAgentSessions({tenantId, agentId, participantProfileId})`, `getThread({threadId, tenantId})`, `listRoomThreads({roomId, actorProfileId, tenantId})` (membership-gated), `getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (membership-gated, chronological), `getRoomMessages({roomId, actorProfileId, tenantId})`/`getRoomForMember(roomId, actorProfileId, tenantId)` (membership-checked reads gated on the server-supplied `actorProfileId`, never a caller-controlled subject id — confused-deputy avoidance; `tenantId` required), `updateAgentSessionConfig()` (owner-checked; `tenantId` mandatory and bound into the lookup). Agent session messaging is split by authority: `sendAgentUserMessage()` (caller `actorProfileId` must be the session participant; always authored as the participant). The agent-authored reply path `sendAgentReply(service, params)` is an exported **function — NOT a `ChatService` method and NOT on the package index**; it is reachable only via the dedicated `@happyvertical/smrt-chat/internal/agent-runtime` subpath (S5 #1392), so only trusted in-process agent-runtime code that explicitly opts into that subpath can author as the agent. It authors as `session.agentId`, accepts an optional same-room/tenant `threadId`, and gates tool calls fail-closed against `allowedTools`. The shared internal persistence path (`writeMessage`) is private — it alone may author an arbitrary profile/role or skip the membership check, and is unreachable from any route; it also validates every supplied `threadId`/`agentSessionId`/`replyToMessageId` belongs to the SAME room AND tenant (tenant/room-bound lookups) before use, rejecting cross-room/cross-tenant references. Auto-creates rooms/sessions/participants via an internal `enrollParticipant`.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Conversational Harness (L3, #1891)\n\nThe \"chat with your learning agent\" surface — the real agentic runtime for `AgentSession` (the only shipping chat runtime before this was a single-shot completion). This is the new **acyclic `chat → personas` / `chat → agents` / `chat → users` edge**; keep it that way (personas/agents/users never depend back on chat).\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by a max-steps ceiling (`DEFAULT_MAX_STEPS = 8`): on the ceiling it disables tools for one final completion so the turn always terminates with text.\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge.\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token Streaming (SSE, #1936)\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n"
4756
+ "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Dev Server\n\n`pnpm --dir packages/chat dev` runs a package-local SvelteKit workbench. The root\nroute is an interactive chat surface with a dev-only `/api/dev-chat` endpoint:\nit uses `@happyvertical/ai` when local provider credentials are present and\nfalls back to a deterministic local assistant otherwise. `/api/dev-chat-stream`\nis its SSE companion (#1936) — the same provider/local-fallback resolution wired\nthrough `createChatStreamHandler` in plain mode, so an embedded `SmrtChatBackend`\nclient can exercise token streaming locally. `/previews` hosts the shared\ncomponent playground entries from `src/svelte/playground.ts`.\n\nThe root workbench also has a dev-only voice conversation mode. It reads voice\ngateway connection details through `/api/dev-voice/config`, streams browser mic\naudio to `WS /ws/voice` as PCM16 mono, appends gateway transcripts/responses to\nthe chat, and plays returned TTS audio. Exposing\n`SMRT_CHAT_DEV_VOICE_GATEWAY_TOKEN` to the browser requires\n`SMRT_CHAT_DEV_VOICE_GATEWAY_EXPOSE_TOKEN=true`; keep that local-only.\n\n## Models\n\nAll seven models expose only generated REST/MCP `list`/`get`; structural tests\ncheck the registry for accidental mutating operations. Writes go through\nmembership/owner-checked `ChatService` or the binding-checked voice adapter.\n\n`ChatService` is a closed facade. Its collections and security-sensitive\nhelpers use ES `#private` fields/methods (TypeScript `private` is erased).\nCollection classes are not exported from the package index. The agent-reply\nbridge is a Symbol-keyed static accessible through a non-exported symbol held\nby the module-local `sendAgentReply` function.\n\n- **ChatRoom**: `roomType` (public/private/dm/agent), `status`, `topic`, `maxParticipants`, `lastMessageAt`. Tenant-scoped (required).\n- **ChatMessage**: shared by users + agents. `role` (user/assistant/system/tool), `messageType` (text/system/action/file/tool_call/tool_result), `toolCallData` JSON. Unified model — no separate agent message type. Tenant-scoped (required).\n- **ChatParticipant**: `role` (owner/admin/member/viewer), `onlineStatus`, `lastReadMessageId`, `isMuted`. Tenant-scoped (required).\n- **ChatThread**: `rootMessageId`, `isResolved`, `messageCount`. Created via `ChatService.startThread()` (member-checked). Tenant-scoped (required).\n- **ChatReaction**: `messageId`, `profileId`, `emoji`. Added/removed via `ChatService.addReaction()`/`removeReaction()` (member-checked, self-keyed). Tenant-scoped (required).\n- **AgentSession**: `agentId` (string ref, not FK), `allowedTools` (JSON string array), `sessionContext` (JSON), `systemPrompt`, limits (`maxTokens`/`maxMessages`/`expiresAt`). Optional tenancy.\n- **VoiceSession**: short-lived voice-gateway binding over `(tenant, actorProfileId, personaId, room/thread/agentSession)` plus a persona snapshot, gateway `session_id`, expiry, replay tracking, and metadata. Tenant-scoped (required). Generated surface is read-only; creation and turns go through `createVoiceChatSession()` / `handleVoiceGatewayTurn()`.\n\n## ChatService\n\nPublic writes take server-supplied `actorProfileId`; never trust a request's\n`senderProfileId`, `role`, owner id, or participant id as authority.\n\n| Operation | Authorization and behavior |\n|---|---|\n| `sendMessage()` | Room member; authors as actor with `role: 'user'`; no public membership bypass |\n| `createRoom()` | Actor becomes owner |\n| `startThread()` | Member; optional root message bound to room and tenant |\n| `addParticipant()` / `removeParticipant()` | Owner/admin; self-leave allowed |\n| `updateRoom()` | Owner/admin |\n| `addReaction()` / `removeReaction()` | Member; self-keyed |\n| `getOrCreateDM()` | Actor must be a DM participant |\n| `createAgentSession()` | Actor becomes session participant; existing-session lookup tenant-bound; optional `sessionKey` isolates conversation subjects |\n| `updateAgentSessionConfig()` | Owner; mandatory tenant-bound lookup |\n| `sendAgentUserMessage()` | Actor must be session participant; authored as participant |\n\nRead facade: `getAgentSession({agentSessionId, tenantId})`,\n`findActiveAgentSessions({tenantId, agentId, participantProfileId})`, and\n`getThread({threadId, tenantId})` are tenant-bound; consumers still check\nownership/context. `listRoomThreads({roomId, actorProfileId, tenantId})`,\n`getThreadMessages({threadId, actorProfileId, tenantId, limit?})` (chronological),\n`getRoomMessages({roomId, actorProfileId, tenantId})`, and\n`getRoomForMember(roomId, actorProfileId, tenantId)` additionally require\nmembership of the server-supplied actor, not a caller-selected subject.\n\nTrusted agent runtime imports `sendAgentReply(service, params)` only from\n`@happyvertical/smrt-chat/internal/agent-runtime`. It is not a `ChatService`\nmethod or package-index export. It authors as `session.agentId`, accepts a\nsame-room/tenant thread, and enforces `allowedTools` fail-closed.\n\nPrivate `#writeMessage` alone can select arbitrary authors/roles or bypass\nmembership. It binds every supplied `threadId`, `agentSessionId`, and\n`replyToMessageId` to the same room **and** tenant. Internal enrollment supports\nautomatically created rooms, sessions, and participants.\n\n## Agent Tool Whitelisting\n\n`allowedTools` is a JSON array controlled by the consuming app. Fail-closed: an empty/unparseable whitelist permits NO tools. The internal `sendAgentReply(service, params)` function enforces the whitelist before emitting any `tool`/`tool_call` message; a caller cannot supply a `senderProfileId`/`role` to post as the agent, and the function is not reachable from the package index.\n\nPrincipal-bound data discovery and reads are available as `PrincipalTool[]` via\n`createDataSurfaceTools()` (re-exported by the chat package). Pass the tools as\n`extraTools` to the persona conversation/tool loop. They use the same\nfail-closed `allowedTools` offer/execution gates; RBAC, tenant, redaction,\nbounded query results, and audit authority remain in the authenticated\n`PrincipalRun` supplied by `@happyvertical/smrt-agents`.\n\n## Conversational Harness (L3, #1891)\n\nThe `AgentSession` runtime depends on personas, agents, and users. Keep those\nedges acyclic: none of those packages may depend back on chat.\n\n- **`runToolLoop(options)`** (`tool-loop.ts`) — a bounded `tool_call → observe → respond` loop. Tools are **manifest operations** of installed packages: `buildManifestToolCatalog({ allowedTools })` reads the `PermissionCatalogService` catalog and keeps only the `(collection, action)` entries named in the persona's allow-list (the **offer gate**; absent/empty ⇒ NO tools). The loop runs inside one `executeAsPrincipal` context, and `invokeManifestTool` executes each op **in-process (\"side door\")** against `run.context.database` (the RLS tx when Postgres RLS is on), after re-asserting the fail-closed allow-list (`run.assertToolAllowed`) AND the catalog permission (`run.assertOperation`) — the **execution gate**. Bounded by a max-steps ceiling (`DEFAULT_MAX_STEPS = 8`): on the ceiling it disables tools for one final completion so the turn always terminates with text.\n- **`runPersonaConversationTurn(options)`** (`persona-conversation.ts`) — binds a conversation to an `AgentPersona`/`ResolvedPersona`: runs as its principal (`runAsUserId`), offers only its `allowedTools`, speaks its instructions (`resolvePersonaInstructions`, layering approved learned directives), and injects its **recalled learning memory** (`personaLearningMemory`, isolated per `memoryScope`) into the system prompt. `bindPersonaToSession()` mirrors the persona's `allowedTools`/instructions onto the `AgentSession` so the chat authoring gate agrees with the loop's offer gate. Authors the reply (and each executed tool) via the internal `sendAgentReply` bridge.\n- **Agent orchestration** (L3, #1892) — the loop accepts non-manifest **`extraTools`** (`PrincipalTool[]`, from `@happyvertical/smrt-agents`), gated by the *same* fail-closed allow-list. The standard **`invoke-agent`** tool (`createInvokeAgentTool`, slug `agents.invoke`) lets a conversational agent delegate to a **worker agent under its own principal** — the worker runs via `executeAsPrincipal` as the originating user (never its own authority), the principal is immutable along the chain, and its completion is surfaced back into the conversation. `runPersonaConversationTurn` filters `extraTools` by the persona's `allowedTools` (offer gate); the tool's `execute` re-asserts `assertToolAllowed` (execution gate). See `@happyvertical/smrt-agents` for the delegation envelope + transports.\n- **Chat feedback capture** (`chat-feedback.ts`) — `captureChatFeedback()` + `acceptAppliedChange`/`rejectAppliedChange`/`correctResponse`/`rateResponse`/`thumbsUp`/`thumbsDown` write a `Feedback` row (personas) carrying the conversation's **correlation-id**, and (by default) reinforce the persona's learning memory (`reinforceFromFeedback`). So an in-chat reject decays a strategy below the reuse floor and it stops being recalled; a correction supersedes its stored value.\n\n## Voice Gateway Turns (#1910)\n\nVoice is an input mode for the existing persona chat harness, not a separate chat runtime. `createVoiceChatSession()` creates a short-lived `VoiceSession` for an authenticated actor/profile, binding tenant, persona, agent session, room, and optional thread. `handleVoiceGatewayTurn()` resolves that binding from `metadata.voiceSessionId`, checks the gateway's `session_id` and any supplied tenant/profile/persona/session/thread metadata against the server-side binding, persists the transcript through `ChatService.sendAgentUserMessage()`, runs `runPersonaConversationTurn()`, stamps voice/correlation metadata onto the persisted user/assistant/tool messages, records the gateway `turn_id`, and returns the gateway response contract. The Fetch-compatible `createVoiceGatewayTurnHandler()` adds the coarse gateway bearer-token check.\n\nThe gateway bearer token proves only \"this request came from the gateway\"; it never authorizes the end user. The short-lived `VoiceSession` binding is the user/session proof, and untrusted gateway metadata must be validated against that binding before any chat write or tool loop. Tool execution remains fail-closed through the persona allow-list mirrored onto `AgentSession` by `bindPersonaToSession()`.\n\n## Token Streaming (SSE, #1936)\n\n`chat-stream.ts` is the SSE seam for embeddable conversational UIs (first consumer: the Happy chat widget, `animation#5`): a client POSTs the conversation so far and receives a `text/event-stream` of `data: <json>` frames — `token` deltas as the model generates, then a final `done` frame with the message. The wire `ChatStreamEvent` union also declares `emotion` and `control` (#1921 host-page control commands) lanes for forward compatibility; the v1 engine emits `token`/`done`/`error`.\n\n- **`runChatConversationStream({ context, messages })`** — the transport-agnostic engine (an `AsyncGenerator<ChatStreamEvent>`). Dispatches on `context.binding`: **persona-bound** runs the full `runPersonaConversationTurn` with a token sink wired through the tool loop (`onToken` → `ai.chat({ stream: true, onProgress })`), then persists via `ChatService` and emits the persisted message as `done`; **plain/unbound** streams `ai.stream()` directly and emits a synthesized (unpersisted) `done`. Streamed tokens are a live PREVIEW (a tool-call round may narrate before acting); the `done` message is authoritative. Failures surface as an in-band `error` event, never a throw (the 200 has already committed once streaming starts).\n- **`createChatStreamHandler({ authorize, allowedOrigins?, allowCredentials? })`** — a Fetch-compatible handler returning `text/event-stream` (mirrors `createVoiceGatewayTurnHandler`). `authorize(request, body)` is the SOLE trust boundary and works exactly like the voice gateway: this module NEVER authorizes from the request's `session` metadata — the app validates the caller (bearer session id / cookie / same-origin) and the claimed ids against the authenticated principal, and returns an already-authorized `ChatStreamContext`. Generation caps (`model`/`maxTokens`/`maxSteps`) live on the context (server-resolved), never on the request. Cross-origin embedding uses the same fail-closed CORS posture as core `_events` (#1861): the `Origin` is echoed only when allow-listed (never `*`), credentials only when opted in.\n- **`SmrtChatBackend` (`@happyvertical/smrt-chat/client`)** — the consume side of the same contract: a browser SSE client (`src/client.ts`) that POSTs the conversation and dispatches `token`/`emotion`/`done`/`error` frames to streaming handlers, tolerating heartbeat comments and frames split across chunks. The subpath is BROWSER-SAFE and dependency-free (no server runtime, no workspace imports — keep it that way), and its widget-facing types are structurally identical to `@happyvertical/animation`'s `ChatBackend` contract so an instance plugs straight into the floating chat widget. `src/client.contract.ts` carries the compile-time locks pinning it to `chat-stream.ts`'s `ChatStreamEvent`/`ChatStreamSession` — a NON-test module precisely so `pnpm typecheck` actually enforces them (`tsconfig.typecheck.json` excludes `.test.ts` files, and Vitest transpiles without typechecking). A clean close without a `done` frame surfaces as an error (never an empty reply), and a settled turn cancels the reader so the connection is released promptly.\n- **Persona path reuses the harness's own gates unchanged** — persona principal, fail-closed `allowedTools` offer+execution gates, tenant binding. `onToken` is best-effort telemetry threaded through `runToolLoop`; it never changes what the loop persists or authorizes.\n- **Custom tools stream via `binding.extraTools`** — the persona binding threads an optional `extraTools?: PrincipalTool[]` down to `runPersonaConversationTurn`, so a *streamed* persona chat can offer non-manifest, service-backed tools (the persona messaging tool `messages.send`, or an assistance-request/lead-ticket tool wrapping a `@smrt({ api:false, mcp:false })` service) and thus *act*, not only answer — matching the non-streaming persona path. It is resolved server-side by `authorize` (trusted), never from request input, and stays fully gated: each tool is filtered by the persona's `allowedTools` (offer gate) and re-asserts the bound principal's authority in `execute` (execution gate). Offering a tool is not authorizing it.\n\n## Gotchas\n\n- **sessionContext, not context**: `context` is reserved for slug scoping. Use `getSessionContext()`/`updateSessionContext()` for agent memory.\n- **Agent rooms auto-created**: `roomType: 'agent'`, `maxParticipants` defaults to 2; the agent is enrolled as a member so its replies pass the membership check. `createAgentSession()` re-enrolls the participant AND the agent on the existing-session path, so legacy sessions created before the agent was enrolled self-heal.\n- **Per-subject sessions need `sessionKey`**: `createAgentSession()` reuses ANY active session for the same `(agentId, participantProfileId, tenantId)`. Callers that open separate conversations per subject (e.g. one content-editor session per content id) MUST pass a stable `sessionKey` (stored in `sessionContext.__sessionKey`, read via `AgentSession.getSessionKey()`); otherwise a session opened for one subject is reused and its context overwritten for another, surfacing the wrong room/threads (S5 #1392). A keyed create never reuses a keyless/legacy session.\n- **Session expiry**: check `isActive()` before allowing messages (expiresAt or limit-based)\n- **DM identity**: derived from the deterministic per-tenant `canonicalDmRoomId()` and the authoritative `chat_participants` join, not client metadata; concurrent creates upsert onto one row.\n- **Tenant-bound lookups**: membership/session/DM lookups REQUIRE `tenantId` and always bind it into the WHERE clause (`findActiveMembership`/`isActiveMember`/`findActiveSession` take a required `tenantId`; AgentSession's `null` tenant is an explicit bound scope, not \"any tenant\") so they can never resolve a row from another tenant.\n"
4757
4757
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-chat",
3
- "version": "0.45.1",
3
+ "version": "0.45.2",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Chat rooms, DMs, threads, and agent conversations for the SMRT framework",
6
6
  "type": "module",
@@ -71,13 +71,13 @@
71
71
  "dependencies": {
72
72
  "@happyvertical/ai": "^0.89.4",
73
73
  "@happyvertical/sql": "^0.89.4",
74
- "@happyvertical/smrt-agents": "0.45.1",
75
- "@happyvertical/smrt-personas": "0.45.1",
76
- "@happyvertical/smrt-core": "0.45.1",
77
- "@happyvertical/smrt-types": "0.45.1",
78
- "@happyvertical/smrt-tenancy": "0.45.1",
79
- "@happyvertical/smrt-ui": "0.45.1",
80
- "@happyvertical/smrt-users": "0.45.1"
74
+ "@happyvertical/smrt-core": "0.45.2",
75
+ "@happyvertical/smrt-personas": "0.45.2",
76
+ "@happyvertical/smrt-agents": "0.45.2",
77
+ "@happyvertical/smrt-ui": "0.45.2",
78
+ "@happyvertical/smrt-types": "0.45.2",
79
+ "@happyvertical/smrt-tenancy": "0.45.2",
80
+ "@happyvertical/smrt-users": "0.45.2"
81
81
  },
82
82
  "peerDependencies": {
83
83
  "svelte": "^5.56.4"
@@ -98,9 +98,9 @@
98
98
  "typescript": "5.9.3",
99
99
  "vite": "8.1.4",
100
100
  "vitest": "4.1.10",
101
- "@happyvertical/smrt-playground": "0.45.1",
102
- "@happyvertical/smrt-profiles": "0.45.1",
103
- "@happyvertical/smrt-vitest": "0.45.1"
101
+ "@happyvertical/smrt-playground": "0.45.2",
102
+ "@happyvertical/smrt-profiles": "0.45.2",
103
+ "@happyvertical/smrt-vitest": "0.45.2"
104
104
  },
105
105
  "scripts": {
106
106
  "build": "SMRT_PACKAGE_BUILD=1 vite build --mode library && SMRT_PACKAGE_BUILD=1 svelte-package -i src/svelte -o dist/svelte --tsconfig tsconfig.svelte.json",
@@ -1 +0,0 @@
1
- {"version":3,"file":"ChatService-B9rJuwtb.js","names":[],"sources":["../../src/models/AgentSession.ts","../../src/models/ChatMessage.ts","../../src/models/ChatParticipant.ts","../../src/models/ChatReaction.ts","../../src/models/ChatRoom.ts","../../src/models/ChatThread.ts","../../src/models/VoiceSession.ts","../../src/collections/AgentSessionCollection.ts","../../src/collections/ChatMessageCollection.ts","../../src/collections/ChatParticipantCollection.ts","../../src/collections/ChatReactionCollection.ts","../../src/collections/ChatRoomCollection.ts","../../src/collections/ChatThreadCollection.ts","../../src/collections/VoiceSessionCollection.ts","../../src/services/ChatService.ts"],"sourcesContent":["import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { AgentSessionOptions, AgentSessionStatus } from '../types.js';\n\n/**\n * Agent conversation session. Internal model — sessions must be created via\n * {@link ChatService.createAgentSession} and their security-relevant config\n * (`allowedTools` / `systemPrompt` / `chatRoomId` / `participantProfileId`)\n * mutated only via the owner-checked {@link ChatService.updateAgentSessionConfig}\n * (S5 #1392). The generated CRUD surface is read-only (`get`/`list`);\n * `create`/`update`/`delete` are NOT generated, otherwise a `PUT` could rewrite\n * the tool allow-list or system prompt and bypass the owner check.\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableName: 'agent_sessions',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class AgentSession extends SmrtObject {\n /**\n * Reserved `sessionContext` key that scopes a session's identity to a caller-\n * supplied conversation subject (e.g. a content id) (S5 #1392).\n *\n * `createAgentSession`'s reuse path keys on `(agentId, participantProfileId,\n * tenantId)`; without a discriminator a session opened for subject A would be\n * reused (and its context rewritten) for a request about subject B, returning\n * A's room/threads on B's route. Storing the key here lets the reuse lookup\n * require an exact match so distinct subjects get distinct sessions.\n */\n static readonly SESSION_KEY_CONTEXT_FIELD = '__sessionKey';\n\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @field({ required: true })\n agentId: string = '';\n\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { required: true })\n participantProfileId: string = '';\n\n @foreignKey('ChatRoom')\n chatRoomId: string | null = null;\n\n @field({ required: true })\n status: AgentSessionStatus = 'active';\n\n /** JSON array of tool names the consuming app has allowed for this session */\n @field()\n allowedTools: string = '[]';\n\n /** Conversation context/memory for multi-turn state (JSON string) */\n @field()\n sessionContext: string = '{}';\n\n /** System prompt override for this session */\n @field()\n systemPrompt: string = '';\n\n @field()\n messageCount: number = 0;\n @field()\n totalTokensUsed: number = 0;\n @field()\n maxTokens: number = 0;\n @field()\n maxMessages: number = 0;\n\n @field()\n lastMessageAt: Date | null = null;\n @field()\n expiresAt: Date | null = null;\n @field()\n closedAt: Date | null = null;\n\n constructor(options: AgentSessionOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.agentId !== undefined) this.agentId = options.agentId;\n if (options.participantProfileId !== undefined)\n this.participantProfileId = options.participantProfileId;\n if (options.chatRoomId !== undefined) this.chatRoomId = options.chatRoomId;\n if (options.status !== undefined) this.status = options.status;\n if (options.allowedTools !== undefined)\n this.allowedTools = options.allowedTools;\n if (options.sessionContext !== undefined)\n this.sessionContext = options.sessionContext;\n if (options.systemPrompt !== undefined)\n this.systemPrompt = options.systemPrompt;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.totalTokensUsed !== undefined)\n this.totalTokensUsed = options.totalTokensUsed;\n if (options.maxTokens !== undefined) this.maxTokens = options.maxTokens;\n if (options.maxMessages !== undefined)\n this.maxMessages = options.maxMessages;\n if (options.lastMessageAt !== undefined)\n this.lastMessageAt = options.lastMessageAt;\n if (options.expiresAt !== undefined) this.expiresAt = options.expiresAt;\n if (options.closedAt !== undefined) this.closedAt = options.closedAt;\n }\n\n getAllowedTools(): string[] {\n try {\n const parsed = JSON.parse(this.allowedTools);\n return Array.isArray(parsed)\n ? parsed.filter((t): t is string => typeof t === 'string')\n : [];\n } catch {\n return [];\n }\n }\n\n setAllowedTools(tools: string[]): void {\n this.allowedTools = JSON.stringify(tools);\n }\n\n /**\n * Fail-closed authorization check for an agent tool call (S5 #1392).\n *\n * A tool may only be invoked when it appears in this session's allow-list.\n * If the allow-list is empty or unparseable, NO tools are permitted. This is\n * deliberately conservative: an empty whitelist means \"no tools\", never\n * \"all tools\".\n */\n isToolAllowed(toolName: string): boolean {\n if (typeof toolName !== 'string' || toolName.length === 0) return false;\n return this.getAllowedTools().includes(toolName);\n }\n\n isActive(): boolean {\n if (this.status !== 'active') return false;\n if (this.expiresAt && new Date() >= this.expiresAt) return false;\n if (this.maxMessages > 0 && this.messageCount >= this.maxMessages)\n return false;\n if (this.maxTokens > 0 && this.totalTokensUsed >= this.maxTokens)\n return false;\n return true;\n }\n\n isExpired(): boolean {\n return this.expiresAt !== null && new Date() >= this.expiresAt;\n }\n\n async close(): Promise<void> {\n this.status = 'closed';\n this.closedAt = new Date();\n await this.save();\n }\n\n async expire(): Promise<void> {\n this.status = 'expired';\n this.closedAt = new Date();\n await this.save();\n }\n\n getSessionContext(): Record<string, unknown> {\n try {\n return JSON.parse(this.sessionContext);\n } catch {\n return {};\n }\n }\n\n setSessionContext(ctx: Record<string, unknown>): void {\n this.sessionContext = JSON.stringify(ctx);\n }\n\n /**\n * Stable identity key that scopes this session to a conversation subject\n * (S5 #1392). Returns `null` when the session is not subject-scoped. Used by\n * the reuse lookup so a session opened for one subject is never reused for a\n * request about a different subject.\n */\n getSessionKey(): string | null {\n const value =\n this.getSessionContext()[AgentSession.SESSION_KEY_CONTEXT_FIELD];\n return typeof value === 'string' && value.length > 0 ? value : null;\n }\n\n async updateSessionContext(updates: Record<string, unknown>): Promise<void> {\n const current = this.getSessionContext();\n this.sessionContext = JSON.stringify({ ...current, ...updates });\n await this.save();\n }\n\n async recordMessage(tokensUsed: number = 0): Promise<void> {\n this.messageCount++;\n this.totalTokensUsed += tokensUsed;\n this.lastMessageAt = new Date();\n await this.save();\n }\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type {\n ChatMessageOptions,\n ChatMessageRole,\n ChatMessageType,\n} from '../types.js';\n\n/**\n * Chat message. Internal model — all mutations must go through the\n * membership-checked {@link ChatService} (S5 #1392). The generated CRUD surface\n * is read-only (`get`/`list`); `create`/`update`/`delete` are intentionally NOT\n * generated so an authenticated caller cannot write into an arbitrary room via\n * the raw collection routes, bypassing the room-membership authorization in\n * {@link ChatService.sendMessage}.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'chat_messages',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class ChatMessage extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('ChatRoom', { required: true })\n roomId: string = '';\n @foreignKey('ChatThread')\n threadId: string | null = null;\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { required: true })\n senderProfileId: string = '';\n @foreignKey('AgentSession')\n agentSessionId: string | null = null;\n\n @field()\n content: string = '';\n @field({ required: true })\n messageType: ChatMessageType = 'text';\n @field({ required: true })\n role: ChatMessageRole = 'user';\n\n @field()\n isEdited: boolean = false;\n @field()\n editedAt: Date | null = null;\n @field()\n isDeleted: boolean = false;\n @foreignKey('ChatMessage')\n replyToMessageId: string | null = null;\n\n @field()\n metadata: string = '{}';\n @field()\n toolCallData: string | null = null;\n @field()\n attachments: string = '[]';\n\n constructor(options: ChatMessageOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.roomId !== undefined) this.roomId = options.roomId;\n if (options.threadId !== undefined) this.threadId = options.threadId;\n if (options.senderProfileId !== undefined)\n this.senderProfileId = options.senderProfileId;\n if (options.agentSessionId !== undefined)\n this.agentSessionId = options.agentSessionId;\n if (options.content !== undefined) this.content = options.content;\n if (options.messageType !== undefined)\n this.messageType = options.messageType;\n if (options.role !== undefined) this.role = options.role;\n if (options.isEdited !== undefined) this.isEdited = options.isEdited;\n if (options.editedAt !== undefined) this.editedAt = options.editedAt;\n if (options.isDeleted !== undefined) this.isDeleted = options.isDeleted;\n if (options.replyToMessageId !== undefined)\n this.replyToMessageId = options.replyToMessageId;\n if (options.metadata !== undefined)\n this.metadata =\n typeof options.metadata === 'string'\n ? options.metadata\n : JSON.stringify(options.metadata);\n if (options.toolCallData !== undefined)\n this.toolCallData =\n options.toolCallData === null\n ? null\n : typeof options.toolCallData === 'string'\n ? options.toolCallData\n : JSON.stringify(options.toolCallData);\n if (options.attachments !== undefined)\n this.attachments = options.attachments;\n }\n\n getAttachments(): Array<{\n id: string;\n filename: string;\n contentType: string;\n size: number;\n url?: string;\n }> {\n try {\n return JSON.parse(this.attachments);\n } catch {\n return [];\n }\n }\n\n setAttachments(\n items: Array<{\n id: string;\n filename: string;\n contentType: string;\n size: number;\n url?: string;\n }>,\n ): void {\n this.attachments = JSON.stringify(items);\n }\n\n getMetadata(): Record<string, unknown> {\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n setMetadata(data: Record<string, unknown>): void {\n this.metadata = JSON.stringify(data);\n }\n\n getToolCallData(): Record<string, unknown> | null {\n if (!this.toolCallData) return null;\n try {\n return JSON.parse(this.toolCallData);\n } catch {\n return null;\n }\n }\n\n setToolCallData(data: Record<string, unknown> | null): void {\n this.toolCallData = data ? JSON.stringify(data) : null;\n }\n\n hasAttachments(): boolean {\n return this.getAttachments().length > 0;\n }\n\n isToolCall(): boolean {\n return this.messageType === 'tool_call';\n }\n\n isToolResult(): boolean {\n return this.messageType === 'tool_result';\n }\n\n isFromAgent(): boolean {\n return this.role === 'assistant';\n }\n\n isSystemMessage(): boolean {\n return this.role === 'system';\n }\n\n async edit(newContent: string): Promise<void> {\n this.content = newContent;\n this.isEdited = true;\n this.editedAt = new Date();\n await this.save();\n }\n\n async softDelete(): Promise<void> {\n this.isDeleted = true;\n this.content = '';\n await this.save();\n }\n\n getPreview(maxLength = 100): string {\n if (this.isDeleted) return '(deleted)';\n const text = this.content || '';\n if (text.length <= maxLength) return text;\n return `${text.slice(0, maxLength)}...`;\n }\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type {\n ChatParticipantOptions,\n ChatParticipantRole,\n ChatParticipantStatus,\n OnlineStatus,\n} from '../types.js';\n\n/**\n * Room membership row. Internal model — membership must be established and\n * mutated only through the membership/owner-checked {@link ChatService}\n * (S5 #1392). The generated CRUD surface is read-only (`get`/`list`);\n * `create`/`update`/`delete` are NOT generated, otherwise an authenticated\n * caller could POST a ChatParticipant to forge their own membership of any room\n * (privilege escalation) and bypass every downstream membership check.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'chat_participants',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class ChatParticipant extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('ChatRoom', { required: true })\n roomId: string = '';\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { required: true })\n profileId: string = '';\n @field({ required: true })\n role: ChatParticipantRole = 'member';\n @field({ required: true })\n status: ChatParticipantStatus = 'active';\n @field({ required: true })\n onlineStatus: OnlineStatus = 'offline';\n @foreignKey('ChatMessage')\n lastReadMessageId: string | null = null;\n @field()\n lastSeenAt: Date | null = null;\n @field()\n joinedAt: Date | null = null;\n @field()\n nickname: string = '';\n @field()\n isMuted: boolean = false;\n @field()\n isPinned: boolean = false;\n\n constructor(options: ChatParticipantOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.roomId !== undefined) this.roomId = options.roomId;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n if (options.role !== undefined) this.role = options.role;\n if (options.status !== undefined) this.status = options.status;\n if (options.onlineStatus !== undefined)\n this.onlineStatus = options.onlineStatus;\n if (options.lastReadMessageId !== undefined)\n this.lastReadMessageId = options.lastReadMessageId;\n if (options.lastSeenAt !== undefined) this.lastSeenAt = options.lastSeenAt;\n if (options.joinedAt !== undefined) this.joinedAt = options.joinedAt;\n if (options.nickname !== undefined) this.nickname = options.nickname;\n if (options.isMuted !== undefined) this.isMuted = options.isMuted;\n if (options.isPinned !== undefined) this.isPinned = options.isPinned;\n }\n\n isActive(): boolean {\n return this.status === 'active';\n }\n\n isOwner(): boolean {\n return this.role === 'owner';\n }\n\n isAdmin(): boolean {\n return this.role === 'admin' || this.role === 'owner';\n }\n\n async markRead(messageId: string): Promise<void> {\n this.lastReadMessageId = messageId;\n this.lastSeenAt = new Date();\n await this.save();\n }\n\n async leave(): Promise<void> {\n this.status = 'left';\n await this.save();\n }\n\n async setOnline(status: OnlineStatus): Promise<void> {\n this.onlineStatus = status;\n this.lastSeenAt = new Date();\n await this.save();\n }\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { ChatReactionOptions } from '../types.js';\n\n/**\n * Message reaction. Internal model — reactions must be added/removed only\n * through the membership-checked {@link ChatService} (S5 #1392). The generated\n * CRUD surface is read-only (`list`); `create`/`update`/`delete` are NOT\n * generated, otherwise a caller could POST a reaction (forging a `profileId`)\n * onto a message in a room they do not belong to, or DELETE another member's\n * reaction, via the raw collection routes — bypassing the room-membership\n * authorization in {@link ChatService.addReaction}/{@link ChatService.removeReaction}.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'chat_reactions',\n api: { include: ['list'] },\n mcp: { include: ['list'] },\n cli: false,\n})\nexport class ChatReaction extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('ChatMessage', { required: true })\n messageId: string = '';\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { required: true })\n profileId: string = '';\n @field({ required: true })\n emoji: string = '';\n\n constructor(options: ChatReactionOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n if (options.emoji !== undefined) this.emoji = options.emoji;\n }\n}\n","import {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type {\n ChatRoomOptions,\n ChatRoomStatus,\n ChatRoomType,\n} from '../types.js';\n\ntype ChatRoomMetadata = Record<string, unknown>;\n\n/**\n * Chat room supporting public channels, private groups, DMs, and agent conversations.\n *\n * @remarks\n * Room types: `public`, `private`, `dm`, `agent`. Agent rooms are auto-created by\n * {@link ChatService.createAgentSession} with `maxParticipants: 2`. DM rooms are\n * found-or-created via {@link ChatService.getOrCreateDM}. Threads are tracked via\n * {@link ChatThread} linked by `roomId`. Tenant-scoped (required).\n *\n * Internal model — room creation and mutation must go through the\n * membership/owner-checked {@link ChatService} (S5 #1392). The generated CRUD\n * surface is read-only (`get`/`list`); `create`/`update`/`delete` are NOT\n * generated, so a caller cannot forge a room or mutate room state via the raw\n * collection routes, skipping the ChatService authorization paths.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'chat_rooms',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class ChatRoom extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @field()\n name: string = '';\n @field()\n description: string = '';\n @field({ required: true })\n roomType: ChatRoomType = 'public';\n @field({ required: true })\n status: ChatRoomStatus = 'active';\n @field()\n topic: string = '';\n @field()\n avatarUrl: string = '';\n @field()\n isArchived: boolean = false;\n @field()\n maxParticipants: number = 0;\n @field()\n metadata: string = '{}';\n @crossPackageRef('@happyvertical/smrt-profiles:Profile')\n createdByProfileId: string = '';\n @field()\n lastMessageAt: Date | null = null;\n\n constructor(options: ChatRoomOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.name !== undefined) this.name = options.name;\n if (options.description !== undefined)\n this.description = options.description;\n if (options.roomType !== undefined) this.roomType = options.roomType;\n if (options.status !== undefined) this.status = options.status;\n if (options.topic !== undefined) this.topic = options.topic;\n if (options.avatarUrl !== undefined) this.avatarUrl = options.avatarUrl;\n if (options.isArchived !== undefined) this.isArchived = options.isArchived;\n if (options.maxParticipants !== undefined)\n this.maxParticipants = options.maxParticipants;\n if (options.metadata !== undefined)\n this.metadata =\n typeof options.metadata === 'string'\n ? options.metadata\n : JSON.stringify(options.metadata);\n if (options.createdByProfileId !== undefined)\n this.createdByProfileId = options.createdByProfileId;\n if (options.lastMessageAt !== undefined)\n this.lastMessageAt = options.lastMessageAt;\n }\n\n getMetadata(): ChatRoomMetadata {\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n setMetadata(data: ChatRoomMetadata): void {\n this.metadata = JSON.stringify(data);\n }\n\n updateMetadata(updates: ChatRoomMetadata): void {\n const current = this.getMetadata();\n this.metadata = JSON.stringify({ ...current, ...updates });\n }\n\n isDM(): boolean {\n return this.roomType === 'dm';\n }\n\n isAgentRoom(): boolean {\n return this.roomType === 'agent';\n }\n\n isPublic(): boolean {\n return this.roomType === 'public';\n }\n\n isActive(): boolean {\n return this.status === 'active';\n }\n\n async archive(): Promise<void> {\n this.isArchived = true;\n this.status = 'archived';\n await this.save();\n }\n\n async unarchive(): Promise<void> {\n this.isArchived = false;\n this.status = 'active';\n await this.save();\n }\n}\n","import { field, foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { ChatThreadOptions } from '../types.js';\n\n/**\n * Conversation thread. Internal model — threads must be created/mutated only\n * through the membership-checked {@link ChatService} (S5 #1392). The generated\n * CRUD surface is read-only (`get`/`list`); `create`/`update`/`delete` are NOT\n * generated, otherwise a caller could POST a thread rooted in an arbitrary room\n * (or mutate `messageCount`/`isResolved`) via the raw collection routes,\n * bypassing the room-membership authorization in {@link ChatService.startThread}.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'chat_threads',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class ChatThread extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('ChatRoom', { required: true })\n roomId: string = '';\n // Nullable FK (S5 #1392): a thread can be opened WITHOUT a root message (e.g.\n // a content/agent-editor thread). The previous `= ''` default wrote an empty\n // string into this FK column, which breaks native-`uuid` DBs (Postgres/DuckDB\n // reject `''` as a uuid). `null` is the correct \"no root\" value.\n @foreignKey('ChatMessage', { nullable: true })\n rootMessageId: string | null = null;\n @field()\n title: string = '';\n @field()\n isResolved: boolean = false;\n @field()\n messageCount: number = 0;\n @field()\n lastMessageAt: Date | null = null;\n @field()\n participantCount: number = 0;\n\n constructor(options: ChatThreadOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.roomId !== undefined) this.roomId = options.roomId;\n if (options.rootMessageId !== undefined)\n this.rootMessageId = options.rootMessageId;\n if (options.title !== undefined) this.title = options.title;\n if (options.isResolved !== undefined) this.isResolved = options.isResolved;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.lastMessageAt !== undefined)\n this.lastMessageAt = options.lastMessageAt;\n if (options.participantCount !== undefined)\n this.participantCount = options.participantCount;\n }\n\n async resolve(): Promise<void> {\n this.isResolved = true;\n await this.save();\n }\n\n async reopen(): Promise<void> {\n this.isResolved = false;\n await this.save();\n }\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { ConversationPersona } from '../persona-conversation.js';\nimport type { VoiceSessionOptions, VoiceSessionStatus } from '../types.js';\n\n/**\n * Short-lived binding proving a voice gateway turn belongs to an authenticated\n * SMRT actor, persona, and chat session. Internal model: creation and turn\n * handling must go through the voice adapter, never raw generated mutations.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'voice_sessions',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: true,\n})\nexport class VoiceSession extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n /** Stable session id the gateway places in the top-level `session_id`. */\n @field({ required: true })\n gatewaySessionId: string = '';\n\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { required: true })\n actorProfileId: string = '';\n\n @crossPackageRef('@happyvertical/smrt-users:User', { nullable: true })\n actorUserId: string | null = null;\n\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n required: true,\n })\n personaId: string = '';\n\n @foreignKey('AgentSession', { required: true })\n agentSessionId: string = '';\n\n @foreignKey('ChatRoom', { required: true })\n chatRoomId: string = '';\n\n @foreignKey('ChatThread')\n threadId: string | null = null;\n\n @field({ required: true })\n target: string = 'smrt:chat';\n\n @field({ required: true })\n status: VoiceSessionStatus = 'active';\n\n @field({ required: true })\n expiresAt: Date = new Date(Date.now() + 10 * 60 * 1000);\n\n @field()\n lastTurnAt: Date | null = null;\n\n @field()\n lastGatewayTurnId: string | null = null;\n\n @field()\n personaSnapshot: string = '{}';\n\n @field()\n metadata: string = '{}';\n\n @field()\n processedTurnIds: string = '[]';\n\n constructor(options: VoiceSessionOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.gatewaySessionId !== undefined)\n this.gatewaySessionId = options.gatewaySessionId;\n if (options.actorProfileId !== undefined)\n this.actorProfileId = options.actorProfileId;\n if (options.actorUserId !== undefined)\n this.actorUserId = options.actorUserId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.agentSessionId !== undefined)\n this.agentSessionId = options.agentSessionId;\n if (options.chatRoomId !== undefined) this.chatRoomId = options.chatRoomId;\n if (options.threadId !== undefined) this.threadId = options.threadId;\n if (options.target !== undefined) this.target = options.target;\n if (options.status !== undefined) this.status = options.status;\n if (options.expiresAt !== undefined) this.expiresAt = options.expiresAt;\n if (options.lastTurnAt !== undefined) this.lastTurnAt = options.lastTurnAt;\n if (options.lastGatewayTurnId !== undefined)\n this.lastGatewayTurnId = options.lastGatewayTurnId;\n if (options.personaSnapshot !== undefined)\n this.personaSnapshot =\n typeof options.personaSnapshot === 'string'\n ? options.personaSnapshot\n : JSON.stringify(options.personaSnapshot);\n if (options.metadata !== undefined)\n this.metadata =\n typeof options.metadata === 'string'\n ? options.metadata\n : JSON.stringify(options.metadata);\n if (options.processedTurnIds !== undefined)\n this.processedTurnIds =\n typeof options.processedTurnIds === 'string'\n ? options.processedTurnIds\n : JSON.stringify(options.processedTurnIds);\n }\n\n isActive(now: Date = new Date()): boolean {\n return this.status === 'active' && now < this.expiresAt;\n }\n\n isExpired(now: Date = new Date()): boolean {\n return now >= this.expiresAt;\n }\n\n async expire(): Promise<void> {\n this.status = 'expired';\n await this.save();\n }\n\n async revoke(): Promise<void> {\n this.status = 'revoked';\n await this.save();\n }\n\n getPersonaSnapshot(): ConversationPersona {\n try {\n return JSON.parse(this.personaSnapshot) as ConversationPersona;\n } catch {\n return {\n id: this.personaId,\n tenantId: this.tenantId,\n runAsUserId: '',\n allowedTools: [],\n };\n }\n }\n\n setPersonaSnapshot(persona: ConversationPersona): void {\n this.personaSnapshot = JSON.stringify(persona);\n }\n\n getMetadata(): Record<string, unknown> {\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n setMetadata(metadata: Record<string, unknown>): void {\n this.metadata = JSON.stringify(metadata);\n }\n\n getProcessedTurnIds(): string[] {\n try {\n const parsed = JSON.parse(this.processedTurnIds);\n return Array.isArray(parsed)\n ? parsed.filter((id): id is string => typeof id === 'string')\n : [];\n } catch {\n return [];\n }\n }\n\n hasProcessedTurn(turnId: string): boolean {\n return this.getProcessedTurnIds().includes(turnId);\n }\n\n recordGatewayTurn(turnId: string, maxRememberedTurns = 50): void {\n const ids = this.getProcessedTurnIds().filter((id) => id !== turnId);\n ids.push(turnId);\n this.processedTurnIds = JSON.stringify(ids.slice(-maxRememberedTurns));\n this.lastGatewayTurnId = turnId;\n this.lastTurnAt = new Date();\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { AgentSession } from '../models/AgentSession.js';\n\nexport class AgentSessionCollection extends SmrtCollection<AgentSession> {\n static readonly _itemClass = AgentSession;\n\n async findActiveByParticipant(\n participantProfileId: string,\n ): Promise<AgentSession[]> {\n const sessions = await this.list({\n where: { participantProfileId, status: 'active' },\n });\n return sessions.filter((s) => s.isActive());\n }\n\n /**\n * Resolve the active agent session for an (agent, participant) pair within a\n * tenant (S5 #1392).\n *\n * `tenantId` is REQUIRED and always bound into the WHERE clause — including the\n * `null` (untenanted) case — so the lookup can never silently drop its tenant\n * predicate and resolve a session from another tenant. AgentSession uses\n * optional tenancy, so `null` is a legitimate, explicitly-bound scope rather\n * than \"any tenant\".\n *\n * When `sessionKey` is supplied the result is additionally narrowed to the\n * session whose stored {@link AgentSession.getSessionKey} matches EXACTLY\n * (S5 #1392). This binds session identity to a conversation subject (e.g. a\n * content id) so a session opened for one subject is never reused for another;\n * `sessionContext` is a JSON blob so the discriminator is matched in memory\n * after the tenant-bound SQL filter.\n */\n async findActiveSession(\n agentId: string,\n participantProfileId: string,\n tenantId: string | null,\n sessionKey?: string | null,\n ): Promise<AgentSession | null> {\n const where: Record<string, unknown> = {\n agentId,\n participantProfileId,\n status: 'active',\n tenantId,\n };\n const sessions = await this.list({ where });\n const active = sessions.find(\n (s) =>\n s.isActive() &&\n (sessionKey === undefined ||\n s.getSessionKey() === (sessionKey ?? null)),\n );\n return active ?? null;\n }\n\n async findOrCreate(params: {\n agentId: string;\n participantProfileId: string;\n tenantId: string | null;\n allowedTools?: string[];\n chatRoomId?: string | null;\n systemPrompt?: string;\n /**\n * Optional subject-scoping key (S5 #1392). When set, an existing active\n * session is reused only if its stored session key matches, and the created\n * session records the key so future lookups stay subject-scoped.\n */\n sessionKey?: string | null;\n }): Promise<AgentSession> {\n const existing = await this.findActiveSession(\n params.agentId,\n params.participantProfileId,\n params.tenantId,\n params.sessionKey,\n );\n if (existing) return existing;\n\n const sessionContext =\n params.sessionKey != null\n ? JSON.stringify({\n [AgentSession.SESSION_KEY_CONTEXT_FIELD]: params.sessionKey,\n })\n : undefined;\n\n const session = await this.create({\n agentId: params.agentId,\n participantProfileId: params.participantProfileId,\n tenantId: params.tenantId ?? null,\n allowedTools: JSON.stringify(params.allowedTools ?? []),\n chatRoomId: params.chatRoomId ?? null,\n systemPrompt: params.systemPrompt ?? '',\n status: 'active',\n ...(sessionContext !== undefined ? { sessionContext } : {}),\n });\n return session;\n }\n\n async findByAgent(agentId: string): Promise<AgentSession[]> {\n return this.list({ where: { agentId } });\n }\n\n /**\n * Expire active sessions whose last activity predates `olderThan`.\n *\n * Caller-scoping (S5 #1392): pass `scope` to restrict the sweep to a single\n * tenant and/or agent. Without a scope this expires stale sessions across the\n * whole (tenant-filtered) collection — only safe for trusted maintenance\n * callers, never for a per-tenant request handler.\n *\n * The candidate set is narrowed in SQL (status + activity timestamp) rather\n * than loading every active session into memory and filtering in JS\n * (DoS hardening). `lastMessageAt < olderThan` is applied server-side; rows\n * that never recorded a message fall back to `created_at`.\n */\n async expireStale(\n olderThan: Date,\n scope?: { tenantId?: string | null; agentId?: string },\n ): Promise<number> {\n const baseWhere: Record<string, unknown> = { status: 'active' };\n if (scope?.tenantId !== undefined) baseWhere.tenantId = scope.tenantId;\n if (scope?.agentId !== undefined) baseWhere.agentId = scope.agentId;\n\n // Sessions stale by their last message timestamp.\n const byLastMessage = await this.list({\n where: { ...baseWhere, 'lastMessageAt <': olderThan },\n });\n\n // Sessions that never recorded a message: judge by creation time.\n const neverMessaged = await this.list({\n where: { ...baseWhere, lastMessageAt: null, 'created_at <': olderThan },\n });\n\n const seen = new Set<string>();\n let expired = 0;\n for (const session of [...byLastMessage, ...neverMessaged]) {\n const id = session.id as string;\n if (!id || seen.has(id)) continue;\n seen.add(id);\n await session.expire();\n expired++;\n }\n return expired;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ChatMessage } from '../models/ChatMessage.js';\nimport type { ChatMessageSearchFilters } from '../types.js';\n\nexport class ChatMessageCollection extends SmrtCollection<ChatMessage> {\n static readonly _itemClass = ChatMessage;\n\n /**\n * Get messages for a room (newest first), excluding threads and deleted.\n *\n * Filtering, ordering and pagination are pushed into SQL rather than loading\n * the full room history into memory (S5 #1392, DoS hardening). Thread replies\n * are excluded via `threadId IS NULL` (the WHERE API maps a `null` value to\n * `IS NULL`).\n *\n * `tenantId` is REQUIRED and bound into BOTH the message window AND the cursor\n * lookup (S5 #1392): room ids are not globally unique, so a roomId-only read\n * could surface another tenant's messages for a same-id room. The caller's\n * membership gate is tenant-scoped, so the read MUST be too.\n */\n async getByRoom(\n roomId: string,\n tenantId: string,\n options?: { limit?: number; before?: string },\n ): Promise<ChatMessage[]> {\n const where: Record<string, unknown> = {\n roomId,\n tenantId,\n isDeleted: false,\n threadId: null,\n };\n\n // Cursor-based pagination: only messages older than the cursor message.\n // The cursor must belong to the SAME root-message set of the SAME room AND\n // tenant (S5 #1392); a cursor id from another room/thread/tenant is silently\n // ignored rather than allowing it to influence this room's window.\n if (options?.before) {\n const cursorMsg = await this.get({\n id: options.before,\n roomId,\n tenantId,\n isDeleted: false,\n threadId: null,\n });\n if (cursorMsg?.created_at) {\n where['created_at <'] = cursorMsg.created_at;\n }\n }\n\n return this.list({\n where,\n orderBy: 'created_at DESC',\n limit: options?.limit,\n });\n }\n\n /**\n * Get messages in a thread, tenant-bound (S5 #1392).\n *\n * `tenantId` is bound into the query so a thread id from another tenant can\n * never surface that tenant's thread history.\n */\n async getByThread(\n threadId: string,\n tenantId: string,\n ): Promise<ChatMessage[]> {\n return this.list({ where: { threadId, tenantId, isDeleted: false } });\n }\n\n /**\n * Get messages for an agent session, tenant-bound (S5 #1392).\n *\n * `tenantId` is bound into the query so a session id from another tenant can\n * never surface that tenant's session messages.\n */\n async getByAgentSession(\n agentSessionId: string,\n tenantId: string,\n ): Promise<ChatMessage[]> {\n return this.list({ where: { agentSessionId, tenantId, isDeleted: false } });\n }\n\n /**\n * Search messages with filters.\n *\n * All structural filters (tenant/room/thread/sender/type/role/date/text) are\n * pushed into SQL instead of loading the full message set and filtering in JS\n * (S5 #1392, DoS hardening). `tenantId` is REQUIRED and always bound so the\n * search can never cross a tenant boundary.\n *\n * `hasAttachments` is derived from the stored `attachments` JSON column and is\n * pushed into SQL as a `!=`/`=` pre-filter against the empty-array sentinel\n * (`'[]'`, the column default) so the `LIMIT` applies to the ALREADY-FILTERED\n * set, not the raw window (S5 #1392). Previously the limit truncated the\n * newest-N window first and the JS filter ran afterwards, so a room whose\n * newest messages lacked attachments could return fewer (or zero)\n * attachment-bearing rows than existed. A precise JS pass on\n * `hasAttachments()` still runs to reject any malformed/empty column value the\n * coarse SQL sentinel can't distinguish, and the requested `limit` is enforced\n * on the filtered result.\n */\n async search(\n filters: ChatMessageSearchFilters & { tenantId: string; limit?: number },\n ): Promise<ChatMessage[]> {\n const where: Record<string, unknown> = {\n tenantId: filters.tenantId,\n isDeleted: false,\n };\n if (filters.roomId) where.roomId = filters.roomId;\n if (filters.threadId) where.threadId = filters.threadId;\n if (filters.senderProfileId)\n where.senderProfileId = filters.senderProfileId;\n if (filters.messageType) where.messageType = filters.messageType;\n if (filters.role) where.role = filters.role;\n if (filters.query) where['content like'] = `%${filters.query}%`;\n if (filters.sinceDate) where['created_at >='] = filters.sinceDate;\n if (filters.beforeDate) where['created_at <'] = filters.beforeDate;\n\n const limit = filters.limit ?? 100;\n\n // Push the attachment predicate into SQL against the empty-array sentinel so\n // the LIMIT applies to the filtered set, not the raw window. `'[]'` is the\n // ChatMessage.attachments column default, so `!= '[]'` keeps rows carrying a\n // non-empty attachment array and `= '[]'` keeps the rest.\n if (filters.hasAttachments === true) {\n where['attachments !='] = '[]';\n } else if (filters.hasAttachments === false) {\n where.attachments = '[]';\n }\n\n const messages = await this.list({\n where,\n orderBy: 'created_at DESC',\n limit,\n });\n\n // The SQL sentinel can't tell a malformed/empty column (e.g. '', whitespace)\n // from a genuinely-empty array, so re-apply the precise computed predicate\n // and enforce the limit on the filtered result.\n if (filters.hasAttachments !== undefined) {\n return messages\n .filter((m) => m.hasAttachments() === filters.hasAttachments)\n .slice(0, limit);\n }\n\n return messages;\n }\n\n /**\n * Get unread count for a participant in a room (excludes thread replies).\n *\n * Counting is pushed into SQL via `count()` rather than loading the whole\n * room history into memory (S5 #1392, DoS hardening). `tenantId` is REQUIRED\n * and bound into both the count and the read-cursor lookup so the count can\n * never include another tenant's messages for a same-id room.\n */\n async getUnreadCount(\n roomId: string,\n tenantId: string,\n lastReadMessageId: string | null,\n ): Promise<number> {\n const base = { roomId, tenantId, isDeleted: false, threadId: null };\n\n if (!lastReadMessageId) return this.count({ where: base });\n\n // The read-cursor must belong to the same room's root-message set in the\n // same tenant; a cursor from another room/thread/tenant is ignored rather\n // than skewing the count (S5 #1392).\n const lastReadMsg = await this.get({\n id: lastReadMessageId,\n roomId,\n tenantId,\n isDeleted: false,\n threadId: null,\n });\n if (!lastReadMsg?.created_at) return this.count({ where: base });\n\n return this.count({\n where: { ...base, 'created_at >': lastReadMsg.created_at },\n });\n }\n\n /**\n * Get most recent root message for each room (for room list preview).\n *\n * Each room is fetched with `orderBy created_at DESC, limit 1` so we never\n * load the full per-room history into memory (S5 #1392, DoS hardening).\n * `tenantId` is REQUIRED and bound into each per-room read so a same-id room\n * from another tenant can never leak a preview message.\n */\n async getLatestPerRoom(\n roomIds: string[],\n tenantId: string,\n ): Promise<Map<string, ChatMessage>> {\n const result = new Map<string, ChatMessage>();\n for (const roomId of roomIds) {\n const latest = await this.list({\n where: { roomId, tenantId, isDeleted: false, threadId: null },\n orderBy: 'created_at DESC',\n limit: 1,\n });\n if (latest.length > 0) {\n result.set(roomId, latest[0]);\n }\n }\n return result;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ChatParticipant } from '../models/ChatParticipant.js';\n\nexport class ChatParticipantCollection extends SmrtCollection<ChatParticipant> {\n static readonly _itemClass = ChatParticipant;\n\n async getByRoom(roomId: string): Promise<ChatParticipant[]> {\n return this.list({ where: { roomId, status: 'active' } });\n }\n\n async getByProfile(profileId: string): Promise<ChatParticipant[]> {\n return this.list({ where: { profileId, status: 'active' } });\n }\n\n async findMembership(\n roomId: string,\n profileId: string,\n tenantId?: string,\n ): Promise<ChatParticipant | null> {\n const where: Record<string, unknown> = { roomId, profileId };\n if (tenantId !== undefined) where.tenantId = tenantId;\n const results = await this.list({ where });\n return results[0] ?? null;\n }\n\n /**\n * Returns the participant row only if the profile is an ACTIVE member of the\n * room (not left/kicked/banned). Used by ChatService to gate sends and reads\n * on room membership (S5 #1392, IDOR hardening).\n *\n * `tenantId` is REQUIRED and always bound into the WHERE clause so a membership\n * lookup can never resolve a row belonging to another tenant, even when no ALS\n * tenant context is active to drive the tenancy interceptor (defense in depth).\n * Making it a required parameter (rather than optional) closes the hole where a\n * caller could omit it and silently drop the tenant predicate from the query.\n */\n async findActiveMembership(\n roomId: string,\n profileId: string,\n tenantId: string,\n ): Promise<ChatParticipant | null> {\n const where: Record<string, unknown> = {\n roomId,\n profileId,\n status: 'active',\n tenantId,\n };\n const results = await this.list({ where, limit: 1 });\n return results[0] ?? null;\n }\n\n /** True when the profile is an active member of the room (tenant-bound). */\n async isActiveMember(\n roomId: string,\n profileId: string,\n tenantId: string,\n ): Promise<boolean> {\n return (\n (await this.findActiveMembership(roomId, profileId, tenantId)) !== null\n );\n }\n\n async getOnlineInRoom(roomId: string): Promise<ChatParticipant[]> {\n const participants = await this.list({\n where: { roomId, status: 'active' },\n });\n return participants.filter((p) => p.onlineStatus !== 'offline');\n }\n\n async getAdminsInRoom(roomId: string): Promise<ChatParticipant[]> {\n const participants = await this.list({\n where: { roomId, status: 'active' },\n });\n return participants.filter((p) => p.isAdmin());\n }\n\n async countInRoom(roomId: string): Promise<number> {\n const participants = await this.list({\n where: { roomId, status: 'active' },\n });\n return participants.length;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ChatReaction } from '../models/ChatReaction.js';\n\nexport class ChatReactionCollection extends SmrtCollection<ChatReaction> {\n static readonly _itemClass = ChatReaction;\n\n async getByMessage(messageId: string): Promise<ChatReaction[]> {\n return this.list({ where: { messageId } });\n }\n\n /** Get reaction counts grouped by emoji for a message */\n async getReactionCounts(\n messageId: string,\n ): Promise<Map<string, { count: number; profileIds: string[] }>> {\n const reactions = await this.list({ where: { messageId } });\n const counts = new Map<string, { count: number; profileIds: string[] }>();\n\n for (const reaction of reactions) {\n const existing = counts.get(reaction.emoji);\n if (existing) {\n existing.count++;\n existing.profileIds.push(reaction.profileId);\n } else {\n counts.set(reaction.emoji, {\n count: 1,\n profileIds: [reaction.profileId],\n });\n }\n }\n\n return counts;\n }\n\n /**\n * Toggle a reaction: add if not present, remove if already reacted.\n *\n * `tenantId` is bound into the existence lookup (S5 #1392) so the toggle can\n * never match or delete a reaction row belonging to another tenant. Prefer the\n * membership-checked {@link ChatService.addReaction}/{@link ChatService.removeReaction}\n * for request-driven flows; this low-level helper performs no membership check.\n */\n async toggle(\n messageId: string,\n profileId: string,\n emoji: string,\n tenantId: string,\n ): Promise<{ added: boolean }> {\n const existing = await this.list({\n where: { messageId, profileId, emoji, tenantId },\n });\n\n if (existing.length > 0) {\n await existing[0].delete();\n return { added: false };\n }\n\n await this.create({\n tenantId,\n messageId,\n profileId,\n emoji,\n });\n return { added: true };\n }\n}\n","import { createHash } from 'node:crypto';\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport type { ChatParticipantCollection } from '../collections/ChatParticipantCollection.js';\nimport { ChatRoom } from '../models/ChatRoom.js';\nimport type { ChatRoomType } from '../types.js';\n\n/**\n * Deterministic, order-independent room id for a 1:1 DM between two profiles\n * within a tenant (S5 #1392, DM race hardening).\n *\n * Concurrent {@link ChatRoomCollection.findOrCreateDM} calls for the same pair\n * compute the SAME id, so the underlying upsert (which conflicts on `id` for new\n * objects) collapses the racing inserts onto one row instead of creating\n * duplicate DM rooms. The id is a deterministic UUIDv5-shaped value derived from\n * the tenant and the sorted profile pair.\n */\nexport function canonicalDmRoomId(\n tenantId: string,\n profileId1: string,\n profileId2: string,\n): string {\n const [a, b] = [profileId1, profileId2].sort();\n const key = `dm ${tenantId} ${a} ${b}`;\n const hash = createHash('sha1').update(key).digest('hex');\n // Shape the digest as a v5 UUID (set version/variant nibbles).\n return [\n hash.slice(0, 8),\n hash.slice(8, 12),\n `5${hash.slice(13, 16)}`,\n ((Number.parseInt(hash.slice(16, 18), 16) & 0x3f) | 0x80)\n .toString(16)\n .padStart(2, '0') + hash.slice(18, 20),\n hash.slice(20, 32),\n ].join('-');\n}\n\nexport class ChatRoomCollection extends SmrtCollection<ChatRoom> {\n static readonly _itemClass = ChatRoom;\n\n async findByType(roomType: ChatRoomType): Promise<ChatRoom[]> {\n return this.list({ where: { roomType, status: 'active' } });\n }\n\n async findPublic(): Promise<ChatRoom[]> {\n return this.list({ where: { roomType: 'public', status: 'active' } });\n }\n\n async findDMs(): Promise<ChatRoom[]> {\n return this.list({ where: { roomType: 'dm', status: 'active' } });\n }\n\n async findAgentRooms(): Promise<ChatRoom[]> {\n return this.list({ where: { roomType: 'agent', status: 'active' } });\n }\n\n /**\n * Search rooms by name/description/topic.\n *\n * Filtering and limiting are pushed into SQL via `LIKE` instead of loading\n * the entire tenant room set and filtering in JS (S5 #1392, DoS hardening).\n * The WHERE API does not support OR, so we issue one bounded query per\n * searchable column and merge the results, capping the total returned.\n */\n async search(\n query: string,\n options?: { limit?: number },\n ): Promise<ChatRoom[]> {\n const limit = options?.limit ?? 50;\n const like = `%${query}%`;\n const columns = ['name', 'description', 'topic'] as const;\n\n const merged = new Map<string, ChatRoom>();\n for (const column of columns) {\n const matches = await this.list({\n where: { status: 'active', [`${column} like`]: like },\n orderBy: 'created_at DESC',\n limit,\n });\n for (const room of matches) {\n if (room.id) merged.set(room.id, room);\n }\n if (merged.size >= limit) break;\n }\n\n return Array.from(merged.values()).slice(0, limit);\n }\n\n /**\n * Find an existing 1:1 DM room between two profiles, or create one.\n *\n * DM identity is derived from the authoritative `chat_participants` join\n * (server-controlled) rather than client-mutable room metadata (S5 #1392).\n * Callers are responsible for attaching both profiles as participants after\n * creation; {@link ChatService.getOrCreateDM} does this.\n */\n async findOrCreateDM(\n profileId1: string,\n profileId2: string,\n tenantId: string,\n participants: ChatParticipantCollection,\n ): Promise<ChatRoom> {\n // Fast, race-safe path: a DM for a tenant + profile pair has a deterministic\n // id, so a prior (or concurrently-created) DM resolves directly (S5 #1392).\n const dmId = canonicalDmRoomId(tenantId, profileId1, profileId2);\n const canonical = await this.get({ id: dmId, tenantId });\n if (canonical && canonical.roomType === 'dm') {\n return canonical;\n }\n\n // Legacy fallback: DMs created before the deterministic-id scheme are still\n // discovered via the authoritative chat_participants join. tenantId is bound\n // into every lookup so a DM can never be resolved (or reused) across tenants,\n // even without an ALS tenant context.\n const memberships1 = await participants.list({\n where: { profileId: profileId1, status: 'active', tenantId },\n });\n const candidateRoomIds = memberships1.map((m) => m.roomId);\n\n for (const roomId of candidateRoomIds) {\n const dm = await this.get({ id: roomId, tenantId });\n if (dm?.roomType !== 'dm' || dm.status !== 'active') continue;\n\n // Confirm profile2 is also an active participant of this same room.\n const others = await participants.list({\n where: { roomId, profileId: profileId2, status: 'active', tenantId },\n });\n if (others.length > 0) {\n return dm;\n }\n }\n\n // Create new DM room with the deterministic id. Membership is established by\n // the caller via the chat_participants join — not via client metadata. The\n // deterministic id makes concurrent creates upsert onto a single row,\n // eliminating the former check-then-create duplicate-DM race.\n const room = await this.create({\n id: dmId,\n tenantId,\n name: '',\n roomType: 'dm',\n status: 'active',\n maxParticipants: 2,\n });\n return room;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ChatThread } from '../models/ChatThread.js';\n\nexport class ChatThreadCollection extends SmrtCollection<ChatThread> {\n static readonly _itemClass = ChatThread;\n\n async getByRoom(roomId: string): Promise<ChatThread[]> {\n return this.list({ where: { roomId } });\n }\n\n async getActive(roomId: string): Promise<ChatThread[]> {\n const threads = await this.list({ where: { roomId } });\n return threads.filter((t) => !t.isResolved);\n }\n\n async getUnresolved(): Promise<ChatThread[]> {\n const threads = await this.list({});\n return threads.filter((t) => !t.isResolved);\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { VoiceSession } from '../models/VoiceSession.js';\n\nexport class VoiceSessionCollection extends SmrtCollection<VoiceSession> {\n static readonly _itemClass = VoiceSession;\n\n async getActiveById(\n id: string,\n target = 'smrt:chat',\n ): Promise<VoiceSession | null> {\n const session = await this.get({ id, target });\n if (!session?.isActive()) return null;\n return session;\n }\n\n async expireStale(\n olderThan: Date = new Date(),\n scope?: { tenantId?: string; target?: string },\n ): Promise<number> {\n const where: Record<string, unknown> = {\n status: 'active',\n 'expiresAt <': olderThan,\n };\n if (scope?.tenantId !== undefined) where.tenantId = scope.tenantId;\n if (scope?.target !== undefined) where.target = scope.target;\n\n const stale = await this.list({ where });\n let expired = 0;\n for (const session of stale) {\n await session.expire();\n expired++;\n }\n return expired;\n }\n}\n","import {\n ObjectRegistry,\n type SmrtObjectOptions,\n} from '@happyvertical/smrt-core';\nimport { AgentSessionCollection } from '../collections/AgentSessionCollection.js';\nimport { ChatMessageCollection } from '../collections/ChatMessageCollection.js';\nimport { ChatParticipantCollection } from '../collections/ChatParticipantCollection.js';\nimport { ChatReactionCollection } from '../collections/ChatReactionCollection.js';\nimport { ChatRoomCollection } from '../collections/ChatRoomCollection.js';\nimport { ChatThreadCollection } from '../collections/ChatThreadCollection.js';\nimport { VoiceSessionCollection } from '../collections/VoiceSessionCollection.js';\nimport type { AgentSession } from '../models/AgentSession.js';\nimport type { ChatMessage } from '../models/ChatMessage.js';\nimport type { ChatThread } from '../models/ChatThread.js';\nimport type {\n ChatMessageRole,\n ChatMessageType,\n ChatParticipantRole,\n ChatRoomStatus,\n ChatRoomType,\n} from '../types.js';\n\n/**\n * Internal write descriptor for {@link ChatService.writeMessage}. This shape can\n * author a message as an arbitrary profile/role and may skip the membership\n * check, so it MUST NOT be reachable from any public/route-facing signature\n * (S5 #1392). Only the trusted in-class callers below construct it.\n */\ninterface InternalMessageWrite {\n tenantId: string;\n roomId: string;\n senderProfileId: string;\n content: string;\n role: ChatMessageRole;\n messageType?: ChatMessageType;\n threadId?: string | null;\n agentSessionId?: string | null;\n replyToMessageId?: string | null;\n toolCallData?: Record<string, unknown> | null;\n /** Internal-only escape hatch for system-authored writes. */\n skipMembershipCheck?: boolean;\n}\n\n/**\n * Parameters for emitting an agent-authored (assistant/tool) message. Used only\n * by the internal {@link sendAgentReply} bridge below — NOT a public surface.\n */\nexport interface AgentReplyParams {\n tenantId: string;\n agentSessionId: string;\n content: string;\n kind?: 'assistant' | 'tool';\n messageType?: ChatMessageType;\n toolCallData?: Record<string, unknown> | null;\n /**\n * Optional thread to attach the agent reply to. It MUST belong to the same\n * room/tenant as the session (validated in {@link ChatService.writeMessage}).\n */\n threadId?: string | null;\n}\n\n/** Tenant-bound agent session lookup descriptor for the read facade. */\nexport interface AgentSessionLookup {\n agentSessionId: string;\n tenantId: string | null;\n}\n\n/** Tenant-bound thread lookup descriptor for the read facade. */\nexport interface ThreadLookup {\n threadId: string;\n tenantId: string;\n}\n\n/**\n * Module-private bridge key for the agent-reply path (S5 #1392).\n *\n * The agent-authoring path is reachable only through the {@link sendAgentReply}\n * function (re-exported solely from `./internal/agent-runtime`). To let that\n * module-local function reach the `private` {@link ChatService.emitAgentReply}\n * without widening the class's PUBLIC surface, the class exposes a single\n * symbol-keyed static. A symbol key is not a named member: it does not appear on\n * the `ChatService` type, is not enumerable, and is callable only by code that\n * holds this non-exported symbol. This replaces the previous public\n * `_runAgentReply` static, which any consumer of the root-exported `ChatService`\n * could call to author messages as the agent.\n */\nconst RUN_AGENT_REPLY = Symbol('smrt-chat.runAgentReply');\n\nexport class ChatService {\n // Raw persistence collections are PRIVATE (S5 #1392). They can author/mutate\n // any row with no actor/membership check, so they must NOT appear on the\n // public `ChatService` type, and the package index no longer re-exports the\n // collection classes for direct construction around the service. Every\n // external read/write goes through the authorized facade methods below.\n readonly #rooms: ChatRoomCollection;\n readonly #messages: ChatMessageCollection;\n readonly #participants: ChatParticipantCollection;\n readonly #threads: ChatThreadCollection;\n readonly #agentSessions: AgentSessionCollection;\n readonly #reactions: ChatReactionCollection;\n readonly #voiceSessions: VoiceSessionCollection;\n\n private constructor(\n rooms: ChatRoomCollection,\n messages: ChatMessageCollection,\n participants: ChatParticipantCollection,\n threads: ChatThreadCollection,\n agentSessions: AgentSessionCollection,\n reactions: ChatReactionCollection,\n voiceSessions: VoiceSessionCollection,\n ) {\n this.#rooms = rooms;\n this.#messages = messages;\n this.#participants = participants;\n this.#threads = threads;\n this.#agentSessions = agentSessions;\n this.#reactions = reactions;\n this.#voiceSessions = voiceSessions;\n }\n\n static async create(options: SmrtObjectOptions): Promise<ChatService> {\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:ChatRoom',\n ChatRoomCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:ChatMessage',\n ChatMessageCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:ChatParticipant',\n ChatParticipantCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:ChatThread',\n ChatThreadCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:AgentSession',\n AgentSessionCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:ChatReaction',\n ChatReactionCollection,\n );\n ObjectRegistry.registerCollection(\n '@happyvertical/smrt-chat:VoiceSession',\n VoiceSessionCollection,\n );\n\n const rooms = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:ChatRoom',\n options,\n )) as ChatRoomCollection;\n const messages = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:ChatMessage',\n options,\n )) as ChatMessageCollection;\n const participants = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:ChatParticipant',\n options,\n )) as ChatParticipantCollection;\n const threads = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:ChatThread',\n options,\n )) as ChatThreadCollection;\n const agentSessions = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:AgentSession',\n options,\n )) as AgentSessionCollection;\n const reactions = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:ChatReaction',\n options,\n )) as ChatReactionCollection;\n const voiceSessions = (await ObjectRegistry.getCollection(\n '@happyvertical/smrt-chat:VoiceSession',\n options,\n )) as VoiceSessionCollection;\n\n return new ChatService(\n rooms,\n messages,\n participants,\n threads,\n agentSessions,\n reactions,\n voiceSessions,\n );\n }\n\n /** Initialize all underlying collections (table creation) */\n async initialize(): Promise<void> {\n await this.#rooms.initialize();\n await this.#messages.initialize();\n await this.#participants.initialize();\n await this.#threads.initialize();\n await this.#agentSessions.initialize();\n await this.#reactions.initialize();\n await this.#voiceSessions.initialize();\n }\n\n /**\n * Create a room and add the creating actor as owner (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId` (the\n * authenticated principal the route injects). The creator/owner is ALWAYS the\n * actor — a caller cannot supply a `createdByProfileId` to attribute the room\n * to (and enroll as owner) some other profile.\n */\n async createRoom(params: {\n tenantId: string;\n name: string;\n roomType: ChatRoomType;\n actorProfileId: string;\n description?: string;\n topic?: string;\n }) {\n const room = await this.#rooms.create({\n tenantId: params.tenantId,\n name: params.name,\n roomType: params.roomType,\n createdByProfileId: params.actorProfileId,\n description: params.description ?? '',\n topic: params.topic ?? '',\n status: 'active',\n });\n\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: room.id as string,\n profileId: params.actorProfileId,\n role: 'owner',\n });\n\n return room;\n }\n\n /**\n * Send a USER message to a room as the authenticated caller (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId` (the\n * authenticated principal the route injects). The message is ALWAYS authored\n * as `actorProfileId` with `role: 'user'` — the caller cannot supply a\n * `senderProfileId` to impersonate another profile or the agent, and cannot\n * supply a privileged `role` (assistant/system/tool). Agent-authored messages\n * go exclusively through the internal {@link ChatService.sendAgentReply}.\n *\n * Authorization: `actorProfileId` must be an ACTIVE participant of the target\n * room, preventing cross-room IDOR within a tenant. There is no public\n * membership-skip parameter; system-authored writes use the internal\n * {@link ChatService.writeMessage} path.\n */\n async sendMessage(params: {\n tenantId: string;\n roomId: string;\n actorProfileId: string;\n content: string;\n messageType?: ChatMessageType;\n threadId?: string | null;\n agentSessionId?: string | null;\n replyToMessageId?: string | null;\n }) {\n return this.#writeMessage({\n tenantId: params.tenantId,\n roomId: params.roomId,\n senderProfileId: params.actorProfileId,\n content: params.content,\n role: 'user',\n messageType: params.messageType ?? 'text',\n threadId: params.threadId ?? null,\n agentSessionId: params.agentSessionId ?? null,\n replyToMessageId: params.replyToMessageId ?? null,\n });\n }\n\n /**\n * INTERNAL persistence path for all message writes. Not exposed publicly: it\n * accepts an arbitrary author/role and an internal-only `skipMembershipCheck`\n * (S5 #1392). Every public entry point (`sendMessage`, `sendAgentUserMessage`,\n * `sendAgentReply`) funnels through here with a server-derived author/role.\n *\n * Membership is enforced unless `skipMembershipCheck` is set, which only the\n * in-class system-authored callers may do.\n */\n async #writeMessage(write: InternalMessageWrite) {\n if (!write.skipMembershipCheck) {\n const isMember = await this.#participants.isActiveMember(\n write.roomId,\n write.senderProfileId,\n write.tenantId,\n );\n if (!isMember) {\n throw new Error(\n 'Sender is not an active member of the room (authorization denied)',\n );\n }\n }\n\n // Every supplied reference (thread / agent session / reply-to message) MUST\n // belong to the SAME room AND tenant as the message being written (S5\n // #1392). Without this, an active member of one room could attach a message\n // to — or pull in/mutate the stats of — an unrelated thread/session/message\n // from another room or tenant. Bind roomId + tenantId into each lookup and\n // reject any mismatch. The validated rows are reused below for stat updates,\n // so there is no second, tenant-UNBOUND lookup.\n const thread = write.threadId\n ? await this.#threads.get({\n id: write.threadId,\n roomId: write.roomId,\n tenantId: write.tenantId,\n })\n : null;\n if (write.threadId && !thread) {\n throw new Error(\n 'threadId does not belong to this room/tenant (authorization denied)',\n );\n }\n\n const session = write.agentSessionId\n ? await this.#agentSessions.get({\n id: write.agentSessionId,\n chatRoomId: write.roomId,\n tenantId: write.tenantId,\n })\n : null;\n if (write.agentSessionId && !session) {\n throw new Error(\n 'agentSessionId does not belong to this room/tenant (authorization denied)',\n );\n }\n\n if (write.replyToMessageId) {\n const replyTo = await this.#messages.get({\n id: write.replyToMessageId,\n roomId: write.roomId,\n tenantId: write.tenantId,\n });\n if (!replyTo) {\n throw new Error(\n 'replyToMessageId does not belong to this room/tenant (authorization denied)',\n );\n }\n }\n\n const message = await this.#messages.create({\n tenantId: write.tenantId,\n roomId: write.roomId,\n senderProfileId: write.senderProfileId,\n content: write.content,\n messageType: write.messageType ?? 'text',\n role: write.role,\n threadId: write.threadId ?? null,\n agentSessionId: write.agentSessionId ?? null,\n replyToMessageId: write.replyToMessageId ?? null,\n toolCallData: write.toolCallData\n ? JSON.stringify(write.toolCallData)\n : null,\n });\n\n // Update room's lastMessageAt\n const room = await this.#rooms.get({\n id: write.roomId,\n tenantId: write.tenantId,\n });\n if (room) {\n room.lastMessageAt = new Date();\n await room.save();\n }\n\n // Update thread stats if threaded (reuse the validated row)\n if (thread) {\n thread.messageCount++;\n thread.lastMessageAt = new Date();\n await thread.save();\n }\n\n // Record on agent session if applicable (reuse the validated row)\n if (session) {\n await session.recordMessage();\n }\n\n return message;\n }\n\n /**\n * Start a thread in a room (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId`, which must be\n * an active member of the room. Generated thread `create` is disabled, so this\n * is the only path to create a thread.\n *\n * When a `rootMessageId` is supplied it is bound to `{ id, roomId, tenantId }`\n * and rejected unless it belongs to the SAME room and tenant — without this a\n * member of one room could anchor a thread to a message from another\n * room/tenant. `rootMessageId` is optional (a thread can be opened without a\n * root message, e.g. an agent-editor thread).\n */\n async startThread(params: {\n tenantId: string;\n roomId: string;\n actorProfileId: string;\n rootMessageId?: string | null;\n title?: string;\n }) {\n await this.#requireActiveMembership(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n if (params.rootMessageId) {\n const rootMessage = await this.#messages.get({\n id: params.rootMessageId,\n roomId: params.roomId,\n tenantId: params.tenantId,\n });\n if (!rootMessage) {\n throw new Error(\n 'rootMessageId does not belong to this room/tenant (authorization denied)',\n );\n }\n }\n const thread = await this.#threads.create({\n tenantId: params.tenantId,\n roomId: params.roomId,\n rootMessageId: params.rootMessageId ?? null,\n title: params.title ?? '',\n messageCount: 0,\n });\n return thread;\n }\n\n /**\n * Add a participant to a room (S5 #1392).\n *\n * Authorization: the acting identity is the server-supplied `actorProfileId`,\n * which MUST be an owner/admin of the target room. This prevents an arbitrary\n * tenant member from adding anyone (or themselves) to any room with any role —\n * a privilege-escalation / IDOR. System-bootstrap enrollment (room creation,\n * DM/agent-session setup) uses the internal {@link ChatService.enrollParticipant}.\n */\n async addParticipant(params: {\n tenantId: string;\n roomId: string;\n actorProfileId: string;\n profileId: string;\n role?: ChatParticipantRole;\n }) {\n await this.#requireRoomAdmin(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n return this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: params.roomId,\n profileId: params.profileId,\n role: params.role,\n });\n }\n\n /**\n * INTERNAL participant enrollment (S5 #1392). No authorization check — only\n * the trusted in-class bootstrap paths (room creation, DM/agent-session setup)\n * and the owner-checked {@link ChatService.addParticipant} call this. Not\n * exposed publicly so a route cannot enroll an arbitrary profile.\n */\n async #enrollParticipant(params: {\n tenantId: string;\n roomId: string;\n profileId: string;\n role?: ChatParticipantRole;\n }) {\n const existing = await this.#participants.findMembership(\n params.roomId,\n params.profileId,\n params.tenantId,\n );\n if (existing) {\n if (existing.status !== 'active') {\n existing.status = 'active';\n existing.joinedAt = new Date();\n await existing.save();\n }\n return existing;\n }\n\n const participant = await this.#participants.create({\n tenantId: params.tenantId,\n roomId: params.roomId,\n profileId: params.profileId,\n role: params.role ?? 'member',\n status: 'active',\n joinedAt: new Date(),\n });\n return participant;\n }\n\n /**\n * Remove (soft-leave) a participant from a room (S5 #1392).\n *\n * Authorization: the server-supplied `actorProfileId` may remove THEMSELVES\n * (leave) at any time; removing ANOTHER profile requires the actor to be an\n * owner/admin of the room. An admin who is not an owner cannot remove an owner.\n */\n async removeParticipant(params: {\n tenantId: string;\n roomId: string;\n actorProfileId: string;\n profileId: string;\n }) {\n const target = await this.#participants.findMembership(\n params.roomId,\n params.profileId,\n params.tenantId,\n );\n if (!target) return;\n\n const isSelf = params.actorProfileId === params.profileId;\n if (!isSelf) {\n const actor = await this.#participants.findActiveMembership(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n if (!actor?.isAdmin()) {\n throw new Error(\n 'Only a room owner/admin may remove another participant (authorization denied)',\n );\n }\n // An admin (non-owner) cannot remove an owner.\n if (target.isOwner() && !actor.isOwner()) {\n throw new Error(\n 'Only a room owner may remove an owner (authorization denied)',\n );\n }\n }\n\n target.status = 'left';\n await target.save();\n }\n\n /**\n * Update mutable room fields, restricted to a room owner/admin (S5 #1392).\n *\n * Generated `update` on ChatRoom is disabled, so this owner-checked path is the\n * only way to mutate room state. The acting identity is the server-supplied\n * `actorProfileId`.\n */\n async updateRoom(params: {\n tenantId: string;\n roomId: string;\n actorProfileId: string;\n name?: string;\n description?: string;\n topic?: string;\n avatarUrl?: string;\n status?: ChatRoomStatus;\n }) {\n await this.#requireRoomAdmin(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n const room = await this.#rooms.get({\n id: params.roomId,\n tenantId: params.tenantId,\n });\n if (!room) throw new Error('Room not found');\n\n if (params.name !== undefined) room.name = params.name;\n if (params.description !== undefined) room.description = params.description;\n if (params.topic !== undefined) room.topic = params.topic;\n if (params.avatarUrl !== undefined) room.avatarUrl = params.avatarUrl;\n if (params.status !== undefined) room.status = params.status;\n await room.save();\n return room;\n }\n\n /**\n * Add a reaction to a message as the authenticated caller (S5 #1392).\n *\n * Generated `create` on ChatReaction is disabled. The reaction is always\n * authored as the server-supplied `actorProfileId` (no caller-supplied\n * `profileId`), and the actor must be an active member of the room that owns\n * the message. Idempotent: re-reacting with the same emoji returns the\n * existing row.\n */\n async addReaction(params: {\n tenantId: string;\n messageId: string;\n actorProfileId: string;\n emoji: string;\n }) {\n const message = await this.#messages.get({\n id: params.messageId,\n tenantId: params.tenantId,\n });\n if (!message) throw new Error('Message not found');\n\n await this.#requireActiveMembership(\n message.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n\n const existing = await this.#reactions.list({\n where: {\n tenantId: params.tenantId,\n messageId: params.messageId,\n profileId: params.actorProfileId,\n emoji: params.emoji,\n },\n limit: 1,\n });\n if (existing[0]) return existing[0];\n\n return this.#reactions.create({\n tenantId: params.tenantId,\n messageId: params.messageId,\n profileId: params.actorProfileId,\n emoji: params.emoji,\n });\n }\n\n /**\n * Remove the caller's own reaction from a message (S5 #1392).\n *\n * Generated `delete` on ChatReaction is disabled. A caller may only delete\n * THEIR OWN reaction (keyed on `actorProfileId`), so the route cannot remove\n * another member's reaction.\n */\n async removeReaction(params: {\n tenantId: string;\n messageId: string;\n actorProfileId: string;\n emoji: string;\n }): Promise<boolean> {\n const existing = await this.#reactions.list({\n where: {\n tenantId: params.tenantId,\n messageId: params.messageId,\n profileId: params.actorProfileId,\n emoji: params.emoji,\n },\n limit: 1,\n });\n if (existing[0]) {\n await existing[0].delete();\n return true;\n }\n return false;\n }\n\n /**\n * Get or create a DM room with auto-participant setup.\n *\n * The acting identity is the server-supplied `actorProfileId`, which must be\n * one of the two DM participants — a caller cannot open a DM between two other\n * profiles on their behalf (S5 #1392). Enrollment uses the internal system\n * path (no owner check needed for a DM the actor is part of).\n */\n async getOrCreateDM(params: {\n tenantId: string;\n actorProfileId: string;\n profileId1: string;\n profileId2: string;\n }) {\n if (\n params.actorProfileId !== params.profileId1 &&\n params.actorProfileId !== params.profileId2\n ) {\n throw new Error(\n 'Caller must be a participant of the DM (authorization denied)',\n );\n }\n\n const room = await this.#rooms.findOrCreateDM(\n params.profileId1,\n params.profileId2,\n params.tenantId,\n this.#participants,\n );\n\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: room.id as string,\n profileId: params.profileId1,\n });\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: room.id as string,\n profileId: params.profileId2,\n });\n\n return room;\n }\n\n /**\n * Create an agent conversation session with a linked chat room (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId`; the session is\n * ALWAYS created for that actor as the owning participant. A caller cannot\n * supply a `participantProfileId` to open (and own) a session on behalf of\n * another profile.\n *\n * `sessionKey` scopes the session's identity to a conversation subject (e.g. a\n * content id) (S5 #1392). The reuse lookup keys on `(agentId,\n * participantProfileId, tenantId)`, which is too coarse for callers that open\n * separate conversations for distinct subjects under one agent/profile/tenant:\n * without a key, a session opened for subject A would be reused for a request\n * about subject B, returning A's room/threads on B's route. When `sessionKey`\n * is set, an existing session is reused ONLY if its key matches exactly, and a\n * newly created session records the key; distinct keys therefore get distinct\n * sessions and rooms. When omitted, behavior is unchanged (single session per\n * agent/profile/tenant).\n */\n async createAgentSession(params: {\n tenantId: string;\n agentId: string;\n actorProfileId: string;\n allowedTools?: string[];\n systemPrompt?: string;\n maxTokens?: number;\n maxMessages?: number;\n sessionKey?: string | null;\n }) {\n const participantProfileId = params.actorProfileId;\n const sessionKey = params.sessionKey ?? null;\n // Check for existing active session first to avoid orphaned rooms. When a\n // sessionKey is supplied the reuse lookup is narrowed to a matching key so a\n // session opened for a different subject is never reused/rewritten here.\n const existingSession = await this.#agentSessions.findActiveSession(\n params.agentId,\n participantProfileId,\n params.tenantId,\n sessionKey,\n );\n if (existingSession && existingSession.tenantId === params.tenantId) {\n if (existingSession.chatRoomId) {\n // Tenant-bind the room lookup (S5 #1392): the session's chatRoomId must\n // resolve a room within the SAME tenant, never one from another tenant.\n const existingRoom = await this.#rooms.get({\n id: existingSession.chatRoomId,\n tenantId: params.tenantId,\n });\n if (existingRoom) {\n // Ensure both the participant and the agent are enrolled even on the\n // existing-session path. Legacy sessions created before the agent was\n // enrolled as a member would otherwise fail sendAgentReply's\n // membership check (S5 #1392). enrollParticipant is idempotent.\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: existingRoom.id as string,\n profileId: participantProfileId,\n role: 'owner',\n });\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: existingRoom.id as string,\n profileId: params.agentId,\n role: 'member',\n });\n return { session: existingSession, room: existingRoom };\n }\n }\n // Session exists but room is missing/orphaned — expire it so we create fresh\n await existingSession.expire();\n }\n\n // Create an agent-type room for this session\n const room = await this.#rooms.create({\n tenantId: params.tenantId,\n name: '',\n roomType: 'agent',\n createdByProfileId: participantProfileId,\n status: 'active',\n maxParticipants: 2,\n });\n\n // Add participant\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: room.id as string,\n profileId: participantProfileId,\n role: 'owner',\n });\n\n // Add the agent itself as a member so its assistant/tool messages pass the\n // room-membership authorization check in sendMessage (S5 #1392).\n await this.#enrollParticipant({\n tenantId: params.tenantId,\n roomId: room.id as string,\n profileId: params.agentId,\n role: 'member',\n });\n\n // Create session (subject-scoped when a sessionKey is supplied, so the key\n // is persisted on the new session and future reuse lookups stay scoped).\n const session = await this.#agentSessions.findOrCreate({\n agentId: params.agentId,\n participantProfileId,\n tenantId: params.tenantId,\n allowedTools: params.allowedTools,\n chatRoomId: room.id as string,\n systemPrompt: params.systemPrompt,\n sessionKey,\n });\n\n if (params.maxTokens) session.maxTokens = params.maxTokens;\n if (params.maxMessages) session.maxMessages = params.maxMessages;\n await session.save();\n\n return { session, room };\n }\n\n /**\n * Send a USER message within an agent session (S5 #1392).\n *\n * The authenticated caller (`actorProfileId`) must be the session's owning\n * participant. The message is always authored as `session.participantProfileId`\n * — the caller cannot supply a `senderProfileId`, a `role`, or tool-call data,\n * so this path can never be used to post as the agent (`assistant`/`tool`) or\n * to impersonate another profile. Agent replies go through the internal\n * {@link ChatService.sendAgentReply}.\n */\n async sendAgentUserMessage(params: {\n tenantId: string;\n agentSessionId: string;\n actorProfileId: string;\n content: string;\n messageType?: ChatMessageType;\n }) {\n const session = await this.#loadActiveSession(\n params.agentSessionId,\n params.tenantId,\n );\n\n if (params.actorProfileId !== session.participantProfileId) {\n throw new Error(\n 'Only the session participant may post user messages in this agent session (authorization denied)',\n );\n }\n\n return this.#writeMessage({\n tenantId: params.tenantId,\n roomId: session.chatRoomId as string,\n senderProfileId: session.participantProfileId,\n content: params.content,\n role: 'user',\n messageType: params.messageType ?? 'text',\n agentSessionId: params.agentSessionId,\n });\n }\n\n /**\n * Emit an ASSISTANT or TOOL message authored by the agent (S5 #1392).\n *\n * INTERNAL authority: this is the only path that authors a message as the\n * agent, and it is not reachable with a caller-supplied `senderProfileId`/\n * `role`. The author is always `session.agentId`. Tool calls are gated\n * fail-closed against the session's allow-list. Intended for the trusted\n * agent-runtime, never a per-tenant request handler driven by client-supplied\n * role/sender.\n *\n * This is a `private` method and is NOT exported from the package index. The\n * in-process agent runtime reaches it through the {@link sendAgentReply}\n * bridge in this module, which is deliberately not re-exported from\n * `src/index.ts`, so a route/consumer can never author a message as the agent.\n */\n async #emitAgentReply(params: AgentReplyParams) {\n const session = await this.#loadActiveSession(\n params.agentSessionId,\n params.tenantId,\n );\n\n const role: ChatMessageRole = params.kind === 'tool' ? 'tool' : 'assistant';\n\n // Enforce the per-session tool allow-list, fail-closed (S5 #1392, broadened\n // T2 #1391). A tool message carries its tool name in toolCallData.name (or\n // .tool); any call to a tool not on the session's whitelist is rejected.\n // The gate covers every tool-shaped message — `tool_call` AND `tool_result`\n // message types, the `tool` role, and any payload that carries toolCallData\n // — so a `tool_result` emitted with the default `assistant` kind and no\n // toolCallData can never render a tool bubble for a non-whitelisted tool.\n if (\n params.messageType === 'tool_call' ||\n params.messageType === 'tool_result' ||\n role === 'tool' ||\n params.toolCallData\n ) {\n const toolName = ChatService.#extractToolName(params.toolCallData);\n if (!toolName) {\n throw new Error('Tool call is missing a tool name');\n }\n if (!session.isToolAllowed(toolName)) {\n throw new Error(\n `Tool '${toolName}' is not allowed for this agent session (authorization denied)`,\n );\n }\n }\n\n return this.#writeMessage({\n tenantId: params.tenantId,\n roomId: session.chatRoomId as string,\n senderProfileId: session.agentId,\n content: params.content,\n role,\n messageType: params.messageType ?? 'text',\n threadId: params.threadId ?? null,\n agentSessionId: params.agentSessionId,\n toolCallData: params.toolCallData ?? null,\n });\n }\n\n /** Load an active agent session by id, tenant-bound, or throw. */\n async #loadActiveSession(agentSessionId: string, tenantId: string) {\n const session = await this.#agentSessions.get({\n id: agentSessionId,\n tenantId,\n });\n if (!session) throw new Error('Agent session not found');\n if (!session.isActive()) throw new Error('Agent session is not active');\n if (!session.chatRoomId) throw new Error('Agent session has no chat room');\n return session;\n }\n\n /**\n * Read messages in a room, gated on the AUTHENTICATED CALLER's active\n * membership (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId` (the\n * authenticated principal the route injects), NOT a caller-controlled\n * `profileId`. Authorizing a supplied `profileId` would make a route a\n * confused deputy: any caller could read a room by smuggling some member's\n * profile id. Throws if `actorProfileId` is not an active participant of\n * `roomId`. `tenantId` is required so the membership gate is always\n * tenant-scoped.\n */\n async getRoomMessages(params: {\n roomId: string;\n actorProfileId: string;\n tenantId: string;\n limit?: number;\n before?: string;\n }) {\n await this.#requireActiveMembership(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n return this.#messages.getByRoom(params.roomId, params.tenantId, {\n limit: params.limit,\n before: params.before,\n });\n }\n\n /**\n * Load a room only if the AUTHENTICATED CALLER is an active member (S5 #1392).\n *\n * The acting identity is the server-supplied `actorProfileId`, never a\n * caller-controlled `profileId` (confused-deputy avoidance — see\n * {@link ChatService.getRoomMessages}). Returns null when the room does not\n * exist; throws when the actor is not an active participant. `tenantId` is\n * required so the lookup and the membership gate are always tenant-scoped.\n */\n async getRoomForMember(\n roomId: string,\n actorProfileId: string,\n tenantId: string,\n ) {\n const room = await this.#rooms.get({ id: roomId, tenantId });\n if (!room) return null;\n await this.#requireActiveMembership(roomId, actorProfileId, tenantId);\n return room;\n }\n\n /**\n * Tenant-bound read of a single agent session (S5 #1392).\n *\n * The lookup ALWAYS binds `tenantId` (including the `null`/untenanted scope),\n * so a caller can never resolve a session belonging to another tenant by id.\n * Returns `null` when no session matches the id within the tenant. Replaces\n * direct `agentSessions.get(id)` reach-ins in package consumers; consumers\n * still apply their own ownership/context authorization on the returned row.\n */\n async getAgentSession(\n lookup: AgentSessionLookup,\n ): Promise<AgentSession | null> {\n const session = await this.#agentSessions.get({\n id: lookup.agentSessionId,\n tenantId: lookup.tenantId,\n });\n return session ?? null;\n }\n\n /**\n * Tenant-bound list of ACTIVE agent sessions for an (agent, participant) pair\n * (S5 #1392).\n *\n * Binds `tenantId` into the query so the result can never include a session\n * from another tenant. Replaces direct `agentSessions.list({ where })`\n * reach-ins; consumers apply their own per-session context authorization.\n */\n async findActiveAgentSessions(params: {\n tenantId: string | null;\n agentId: string;\n participantProfileId: string;\n }): Promise<AgentSession[]> {\n const sessions = await this.#agentSessions.list({\n where: {\n tenantId: params.tenantId,\n agentId: params.agentId,\n participantProfileId: params.participantProfileId,\n status: 'active',\n },\n });\n return sessions.filter((s) => s.isActive());\n }\n\n /**\n * Tenant-bound read of a single thread (S5 #1392).\n *\n * Binds `tenantId` into the lookup so a thread from another tenant can never\n * be resolved by id. Returns `null` when no thread matches within the tenant.\n * Replaces direct `threads.get(id)` reach-ins.\n */\n async getThread(lookup: ThreadLookup): Promise<ChatThread | null> {\n const thread = await this.#threads.get({\n id: lookup.threadId,\n tenantId: lookup.tenantId,\n });\n return thread ?? null;\n }\n\n /**\n * List a room's threads, gated on the caller's active membership (S5 #1392).\n *\n * Tenant- and membership-scoped: throws if `actorProfileId` is not an active\n * participant of `roomId`. Replaces direct `threads.list({ where: { roomId } })`\n * reach-ins that returned threads without a membership/tenant gate.\n */\n async listRoomThreads(params: {\n roomId: string;\n actorProfileId: string;\n tenantId: string;\n }): Promise<ChatThread[]> {\n await this.#requireActiveMembership(\n params.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n return this.#threads.list({\n where: { tenantId: params.tenantId, roomId: params.roomId },\n orderBy: 'createdAt DESC',\n });\n }\n\n /**\n * Read messages within a thread, tenant- and membership-bound (S5 #1392).\n *\n * The thread is resolved tenant-bound; the caller must be an active member of\n * the thread's room. Messages are returned oldest-first (chronological).\n * Replaces direct `messages.list({ where: { threadId } })` reach-ins that\n * could read another tenant's/room's thread history by raw id.\n */\n async getThreadMessages(params: {\n threadId: string;\n actorProfileId: string;\n tenantId: string;\n limit?: number;\n }): Promise<ChatMessage[]> {\n const thread = await this.#threads.get({\n id: params.threadId,\n tenantId: params.tenantId,\n });\n if (!thread) {\n throw new Error('Thread not found');\n }\n await this.#requireActiveMembership(\n thread.roomId,\n params.actorProfileId,\n params.tenantId,\n );\n const messages = await this.#messages.list({\n where: {\n tenantId: params.tenantId,\n threadId: params.threadId,\n isDeleted: false,\n },\n orderBy: 'created_at DESC',\n limit: params.limit,\n });\n return messages.reverse();\n }\n\n /**\n * Update the per-session agent configuration (allowedTools / systemPrompt),\n * restricted to the session owner — the room owner participant (S5 #1392).\n *\n * Tool whitelist and system prompt govern what the agent may do, so only the\n * owning participant (not arbitrary tenant members or the agent itself) may\n * mutate them.\n */\n async updateAgentSessionConfig(params: {\n agentSessionId: string;\n actorProfileId: string;\n tenantId: string | null;\n allowedTools?: string[];\n systemPrompt?: string;\n }) {\n // `tenantId` is mandatory and ALWAYS bound into the lookup (S5 #1392).\n // AgentSession tenancy is optional, so `null` is the explicit \"no tenant\"\n // scope — never \"any tenant\". This prevents mutating allowedTools /\n // systemPrompt on a session belonging to another tenant via an unbound get.\n const session = await this.#agentSessions.get({\n id: params.agentSessionId,\n tenantId: params.tenantId,\n });\n if (!session) throw new Error('Agent session not found');\n\n const isOwner = params.actorProfileId === session.participantProfileId;\n if (!isOwner) {\n throw new Error(\n 'Only the session owner may update agent session configuration (authorization denied)',\n );\n }\n\n if (params.allowedTools !== undefined) {\n session.setAllowedTools(params.allowedTools);\n }\n if (params.systemPrompt !== undefined) {\n session.systemPrompt = params.systemPrompt;\n }\n await session.save();\n return session;\n }\n\n /** Throw unless the profile is an active participant of the room. */\n async #requireActiveMembership(\n roomId: string,\n profileId: string,\n tenantId: string,\n ): Promise<void> {\n const isMember = await this.#participants.isActiveMember(\n roomId,\n profileId,\n tenantId,\n );\n if (!isMember) {\n throw new Error(\n 'Caller is not an active member of the room (authorization denied)',\n );\n }\n }\n\n /** Throw unless the profile is an active owner/admin of the room. */\n async #requireRoomAdmin(\n roomId: string,\n profileId: string,\n tenantId: string,\n ): Promise<void> {\n const actor = await this.#participants.findActiveMembership(\n roomId,\n profileId,\n tenantId,\n );\n if (!actor?.isAdmin()) {\n throw new Error(\n 'Caller must be a room owner/admin (authorization denied)',\n );\n }\n }\n\n /** Extract a tool name from tool-call payload data, if present. */\n static #extractToolName(\n data: Record<string, unknown> | null | undefined,\n ): string | null {\n if (!data || typeof data !== 'object') return null;\n const candidate =\n (data.name as unknown) ??\n (data.tool as unknown) ??\n (data.toolName as unknown);\n return typeof candidate === 'string' && candidate.length > 0\n ? candidate\n : null;\n }\n\n /**\n * Symbol-keyed bridge to the `private` {@link ChatService.emitAgentReply} for\n * the module-local {@link sendAgentReply} function (S5 #1392). A static member\n * may reach a private instance member of its own class, so this is the\n * sanctioned \"friend\" access without widening the public instance surface.\n *\n * Keyed on the module-private {@link RUN_AGENT_REPLY} symbol — NOT a named\n * static — so it does not appear on the `ChatService` type, is not enumerable,\n * and is callable only by code holding the (non-exported) symbol. This is the\n * sole path the agent-runtime bridge uses to author a message as the agent.\n */\n static [RUN_AGENT_REPLY](\n service: AgentReplyService,\n params: AgentReplyParams,\n ) {\n // The structural param lets this bridge be called across pnpm\n // module-instance boundaries (src vs dist). Any real instance is a\n // ChatService, so reaching the private `emitAgentReply` here is safe.\n return (service as ChatService).#emitAgentReply(params);\n }\n}\n\n/**\n * Structural ChatService surface accepted by {@link sendAgentReply}. The chat\n * collections are `#private`, so they cannot appear in a `Pick`; this opaque\n * marker type keeps the agent-runtime bridge callable across module-instance\n * boundaries (in a pnpm workspace a consumer's `ChatService` type may resolve to\n * the package source while this function resolves to dist) without naming any\n * private member. Any real ChatService instance satisfies it.\n */\nexport type AgentReplyService = Pick<ChatService, 'initialize'>;\n\n/**\n * Internal agent-runtime entry point: emit an ASSISTANT/TOOL message authored\n * as the session's agent (S5 #1392).\n *\n * NOT re-exported from `src/index.ts`. Only in-process, trusted agent-runtime\n * code that imports this module path directly can author messages as the agent;\n * route handlers and package consumers (which import from the package index)\n * cannot. The author is always `session.agentId`, never a caller-supplied\n * sender/role, and tool calls are gated fail-closed against `allowedTools`.\n *\n * Because this lives in the same module as {@link ChatService}, reaching the\n * symbol-keyed bridge (and through it the `private` method) is the owning\n * module's sanctioned \"friend\" access, not an external private reach-in.\n */\nexport function sendAgentReply(\n service: AgentReplyService,\n params: AgentReplyParams,\n) {\n return ChatService[RUN_AGENT_REPLY](service, params);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BO,IAAM,eAAN,cAA2B,WAAW;CAc3C,WAA0B;CAG1B,UAAkB;CAGlB,uBAA+B;CAG/B,aAA4B;CAG5B,SAA6B;CAI7B,eAAuB;CAIvB,iBAAyB;CAIzB,eAAuB;CAGvB,eAAuB;CAEvB,kBAA0B;CAE1B,YAAoB;CAEpB,cAAsB;CAGtB,gBAA6B;CAE7B,YAAyB;CAEzB,WAAwB;CAExB,YAAY,UAA+B,CAAC,GAAG;EAC7C,MAAM,OAAO;EACb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,YAAY,KAAA,GAAW,KAAK,UAAU,QAAQ;EAC1D,IAAI,QAAQ,yBAAyB,KAAA,GACnC,KAAK,uBAAuB,QAAQ;EACtC,IAAI,QAAQ,eAAe,KAAA,GA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