@happyvertical/smrt-chat 0.53.2 → 0.53.4

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.
@@ -1,2 +1,2 @@
1
- import { r as sendAgentReply } from "../chunks/ChatService-jJi2JJJi.js";
1
+ import { a as sendAgentReply } from "../chunks/ChatService-Dl5tsK_F.js";
2
2
  export { sendAgentReply };
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.53.2",
5
+ "packageVersion": "0.53.4",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-chat:AgentSessionCollection": {
8
8
  "name": "agentsessioncollection",
@@ -19,7 +19,51 @@ export interface AgentReplyParams {
19
19
  * room/tenant as the session (validated in {@link ChatService.writeMessage}).
20
20
  */
21
21
  threadId?: string | null;
22
+ /**
23
+ * The message this reply answers (e.g. the user send that started the
24
+ * turn). Validated to the same room/tenant like `threadId`.
25
+ */
26
+ replyToMessageId?: string | null;
27
+ }
28
+ /**
29
+ * A file reference stored on a user message (`ChatMessage.attachments`). The
30
+ * caller must have verified the reference belongs to the actor (for example,
31
+ * an upload it just stored) — the service stores it as given.
32
+ */
33
+ export interface ChatMessageAttachment {
34
+ id: string;
35
+ filename: string;
36
+ contentType: string;
37
+ size: number;
38
+ url?: string;
22
39
  }
40
+ /**
41
+ * The deterministic id of the user message a client request stores (#3368):
42
+ * a UUIDv5 over tenant, room, thread, actor and `clientRequestId`. The same
43
+ * request always maps to the same primary key, so the database's primary-key
44
+ * uniqueness is the atomic, durable reservation: a second insert conflicts
45
+ * and is answered as a duplicate, on any replica. A valid UUID, so it fits
46
+ * native UUID id columns on PostgreSQL/DuckDB and text ids on SQLite. Not a
47
+ * secret: reads stay membership-gated.
48
+ */
49
+ export declare function clientRequestMessageId(params: {
50
+ tenantId: string;
51
+ roomId: string;
52
+ threadId?: string | null;
53
+ actorProfileId: string;
54
+ clientRequestId: string;
55
+ }): string;
56
+ /**
57
+ * Thrown by {@link ChatService.sendMessage} when a message for the same
58
+ * `clientRequestId` (same tenant, room, thread and actor) is already stored.
59
+ */
60
+ export declare class ChatClientRequestConflictError extends Error {
61
+ readonly messageId: string;
62
+ readonly code = "CHAT_CLIENT_REQUEST_CONFLICT";
63
+ constructor(messageId: string);
64
+ }
65
+ /** Where the turn answering a client request stands (`metadata.turnOutcome`); `running` is a resumed leg in flight. */
66
+ export type ChatClientRequestOutcome = 'running' | 'completed' | 'cancelled' | 'suspended' | 'failed';
23
67
  /** Tenant-bound agent session lookup descriptor for the read facade. */
24
68
  export interface AgentSessionLookup {
25
69
  agentSessionId: string;
@@ -90,6 +134,16 @@ export declare class ChatService {
90
134
  threadId?: string | null;
91
135
  agentSessionId?: string | null;
92
136
  replyToMessageId?: string | null;
137
+ /**
138
+ * The sending client's idempotency key, stored as
139
+ * `metadata.clientRequestId`. The message then gets the deterministic id
140
+ * {@link clientRequestMessageId} and is inserted, never upserted: a second
141
+ * send with the same key throws {@link ChatClientRequestConflictError}.
142
+ * Untrusted data, never authority.
143
+ */
144
+ clientRequestId?: string | null;
145
+ /** Already-verified file references to store on the message. */
146
+ attachments?: ChatMessageAttachment[] | null;
93
147
  }): Promise<ChatMessage>;
94
148
  /**
95
149
  * Start a thread in a room (S5 #1392).
@@ -348,6 +402,48 @@ export declare class ChatService {
348
402
  tenantId: string;
349
403
  limit?: number;
350
404
  }): Promise<ChatMessage[]>;
405
+ /**
406
+ * A stored message and the replies linked to it (`replyToMessageId`),
407
+ * oldest first (#3368), or `null` when the message is not in the thread.
408
+ * Tenant- and membership-bound like {@link ChatService.getThreadMessages}.
409
+ * Replies are found by their link, not by position, so overlapping turns
410
+ * in one thread never claim each other's replies.
411
+ */
412
+ getThreadMessageReplies(params: {
413
+ threadId: string;
414
+ messageId: string;
415
+ actorProfileId: string;
416
+ tenantId: string;
417
+ limit?: number;
418
+ }): Promise<{
419
+ message: ChatMessage;
420
+ replies: ChatMessage[];
421
+ } | null>;
422
+ /**
423
+ * Record where the turn answering a client request stands, on the actor's
424
+ * own user message (`metadata.turnOutcome`, #3368). Only the message's
425
+ * author, still a member of its room, can record it.
426
+ *
427
+ * Transitions only move forward, per leg, and are compare-and-set on the
428
+ * row's revision (a concurrent writer re-reads and is re-checked):
429
+ * `unset → running → suspended(c) → running(resumedFrom c) → … →
430
+ * completed | cancelled | failed`, plus `unset → suspended | terminal` for
431
+ * a first leg whose earlier write was lost. A write from a leg that is not
432
+ * the current one (its `resumedFrom` differs), a `running` that does not
433
+ * consume the waiting continuation, or anything after a terminal outcome
434
+ * is refused. Returns whether the write was applied.
435
+ */
436
+ recordClientRequestOutcome(params: {
437
+ tenantId: string;
438
+ threadId: string;
439
+ messageId: string;
440
+ actorProfileId: string;
441
+ outcome: ChatClientRequestOutcome;
442
+ /** The continuation the writing leg consumed; `null` for the first leg. */
443
+ resumedFrom?: string | null;
444
+ /** The continuation a `suspended` turn now waits on. */
445
+ continuationId?: string | null;
446
+ }): Promise<boolean>;
351
447
  /**
352
448
  * Update the per-session agent configuration (allowedTools / systemPrompt),
353
449
  * restricted to the session owner — the room owner participant (S5 #1392).
@@ -1 +1 @@
1
- {"version":3,"file":"ChatService.d.ts","sourceRoot":"","sources":["../../src/services/ChatService.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,0BAA0B,CAAC;AAYlC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAEV,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,YAAY,EACb,MAAM,aAAa,CAAC;AAuBrB;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,EA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MAAM,EAAE,gBAAgB;CAO3B;AAED;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;AAEhE;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,cAAc,CAC5B,OAAO,EAAE,iBAAiB,EAC1B,MAAM,EAAE,gBAAgB,wBAGzB"}
@@ -1,2 +1,2 @@
1
- export { ChatService } from './ChatService.js';
1
+ export { ChatClientRequestConflictError, type ChatClientRequestOutcome, type ChatMessageAttachment, ChatService, clientRequestMessageId, } from './ChatService.js';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/services/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,KAAK,wBAAwB,EAC7B,KAAK,qBAAqB,EAC1B,WAAW,EACX,sBAAsB,GACvB,MAAM,kBAAkB,CAAC"}
@@ -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.53.2",
6
+ "packageVersion": "0.53.4",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "3865dce9ea07670b543e39c56ddee4c2244cdb8f6bf3450340c880d3d43d87ac",
11
- "packageJson": "f6fc0cd19c3d9d6cfeb520da745cc9715e14f39f5fc0e2b8b45b5e05216433fc",
12
- "agents": "c50538672f9ba892ac0998b58c3a2b497e876df27eff7693c66f3103e730df3c",
10
+ "manifest": "cc8bebd32d96f3c1d1b986b1aa09752743dca2cf873b7b16a0a5b20d556da0bb",
11
+ "packageJson": "94e3131a3466666c6b6270f781b883598b4bb736474a51c422ef08543ae1b87d",
12
+ "agents": "7fcad47394e216ac75f597e6c0c32045807b75c97d87fd5d436160b6be29af9f",
13
13
  "moduleDoc:agents/dev-workbench.md": "69b6f827d25c8aeb0e7516c90303af23948803213b5d34bc334c1e3376c83a16",
14
14
  "agentSurface:src/routes/chat-dev.intents.ts": "ff8f7c19c7eb6e841a08f03c97773c53092ed208004666bfed372bd1ad456b35"
15
15
  },
@@ -24,11 +24,13 @@
24
24
  "./manifest.json",
25
25
  "./playground",
26
26
  "./svelte",
27
+ "./sveltekit",
27
28
  "./ui"
28
29
  ],
29
30
  "dependencies": {
30
31
  "@happyvertical/ai": "catalog:",
31
32
  "@happyvertical/smrt-agents": "workspace:*",
33
+ "@happyvertical/smrt-config": "workspace:*",
32
34
  "@happyvertical/smrt-core": "workspace:*",
33
35
  "@happyvertical/smrt-personas": "workspace:*",
34
36
  "@happyvertical/smrt-profiles": "workspace:*",
@@ -55,6 +57,7 @@
55
57
  },
56
58
  "smrtDependencies": [
57
59
  "@happyvertical/smrt-agents",
60
+ "@happyvertical/smrt-config",
58
61
  "@happyvertical/smrt-core",
59
62
  "@happyvertical/smrt-personas",
60
63
  "@happyvertical/smrt-playground",
@@ -5122,7 +5125,7 @@
5122
5125
  "polymorphicAssociations": 0,
5123
5126
  "uuidColumns": 78
5124
5127
  },
5125
- "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 route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\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` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `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.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — 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. A thrown tool error is classified (`classifyToolError`): permission denials and 401/403 are `not_permitted`; a `ValidationError` or 400/404/409/422 is `invalid_request` (observation: actionable message, `publicMessage` first, `code`, fix-and-retry hint); else (incl. 429) `execution_error`.\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. Tools run with the run-as user's **live** permissions unless the host passes a `permissions` snapshot (#2978), which `runToolLoop` forwards to `executeAsPrincipal` so a narrowed principal (e.g. a shared station) cannot reach grants — such as `readPermission`-gated data-surface fields — beyond that snapshot, including through `agents.invoke` delegation (the snapshot becomes the worker's permission ceiling).\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## Streamed assistant turns with browser tools (#2908)\n\n`runAssistantTurn()` (`assistant-turn.ts`) is the host-route engine for the\nAssistantDock: one turn over `runToolLoop` with server tools (offer-gated by\n`principal.allowedTools`), browser tools (validated by\n`sanitizeClientToolDeclarations` + a server allow-list), `maxSteps`, `signal`,\nand `onUsage`. A browser tool call SUSPENDS the turn (`stoppedReason:\n'client_tools'`); the transcript waits in an `AssistantContinuationStore`\n(single-use, 15-minute TTL; `createSessionContinuationStore` keeps it in the\nAgentSession's `sessionContext`) and the browser resumes it with results,\nwhich reach the model wrapped `untrusted`. `createAssistantTurnResponse`\nserves the events as SSE; `assistant-turn-events.ts` is the browser-safe wire\ncontract (`./assistant-turn` subpath, also a vite library entry because the\nSvelte dock imports it). The dock decides whether a browser call runs or waits\nfor the user from the page registry, never the server's echo; destructive\nalways waits. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`) is a\nshell-mounted, route-aware assistant surface: it discovers currently-mounted\n`DataSurfaceDescriptor`s from a host-supplied `DataSurfaceRegistry`\n(`@happyvertical/smrt-ui/data-surface`) and fails closed to plain chat when\nnone are mounted. Action proposals flow through\n`normalizeDataSurfaceActionRequest` → a host-supplied `AssistantActionClient`\n(preview/apply against a server-hosted `DataSurfaceActionAdapter`, not through\nthe `data-surface-bridge.ts` live-collaboration command channel) →\n`ToolCallDisplay`'s additive `actionResult` rendering. `AssistantTransport`\n(`assistant-transport.ts`) is a narrower, separate contract from\n`ChatClientBackend` (`client.ts`): `ChatThread`/`ChatMessage` only expose\ngenerated `list`/`get` REST (`api: { include: ['list', 'get'] }`,\n`models/ChatThread.ts:16`, `models/ChatMessage.ts:26`), so writes need a host-\nsupplied `writeEndpoint`. See [`docs/assistant-dock.md`](../../docs/assistant-dock.md)\nfor the full design, the anytown `PortalChatTool.svelte` polling/stale-send\nreconnaissance, and open gaps.\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- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\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",
5128
+ "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 route also drives the **browser inference path**\n(`@happyvertical/smrt-web/ai`: bitgpu, WebLLM, and route backends composed by\n`createInferencePath`) and an **agent-addressable draft form** (`useViewIntent`\nover `src/routes/chat-dev.intents.ts`, #2588). Their dev-config dependencies\n(static optional-peer imports, `workspace-aliases.js` prefix rules, the theme\nstylesheet import) and the stage→apply tool-call gotchas are in\n[agents/dev-workbench.md](agents/dev-workbench.md).\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` (application slug, string ref, not FK), `agentProfileId` (nullable `crossPackageRef` to `Profile` — the `bot` profile the agent AUTHORS as, #2995), `allowedTools` (JSON string array), `sessionContext` (JSON, sensitive), `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.agentProfileId` — the\nagent's resolved `bot` Profile, NEVER the `agentId` slug (#2995) — 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. A thrown tool error is classified (`classifyToolError`): permission denials and 401/403 are `not_permitted`; a `ValidationError` or 400/404/409/422 is `invalid_request` (observation: actionable message, `publicMessage` first, `code`, fix-and-retry hint); else (incl. 429) `execution_error`.\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. Tools run with the run-as user's **live** permissions unless the host passes a `permissions` snapshot (#2978), which `runToolLoop` forwards to `executeAsPrincipal` so a narrowed principal (e.g. a shared station) cannot reach grants — such as `readPermission`-gated data-surface fields — beyond that snapshot, including through `agents.invoke` delegation (the snapshot becomes the worker's permission ceiling).\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## Streamed assistant turns with browser tools (#2908)\n\n`runAssistantTurn()` (`assistant-turn.ts`) is the host-route engine for the\nAssistantDock: one turn over `runToolLoop` with server tools (offer-gated by\n`principal.allowedTools`), browser tools (validated by\n`sanitizeClientToolDeclarations` + a server allow-list), `maxSteps`, `signal`,\nand `onUsage`. A browser tool call SUSPENDS the turn (`stoppedReason:\n'client_tools'`); the transcript waits in an `AssistantContinuationStore`\n(single-use, 15-minute TTL; `createSessionContinuationStore` keeps it in the\nAgentSession's `sessionContext`) and the browser resumes it with results,\nwhich reach the model wrapped `untrusted`. `createAssistantTurnResponse`\nserves the events as SSE; `assistant-turn-events.ts` is the browser-safe wire\ncontract (`./assistant-turn` subpath, also a vite library entry because the\nSvelte dock imports it). The dock decides whether a browser call runs or waits\nfor the user from the page registry, never the server's echo; destructive\nalways waits. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\n\n## AssistantDock (#2904)\n\n`AssistantDock` (`svelte/components/assistant/`, exported from `./svelte`)\nuses a host `DataSurfaceRegistry`'s mounted descriptors (none: plain chat).\nActions: `normalizeDataSurfaceActionRequest` → `AssistantActionClient`\n(preview/apply over a server `DataSurfaceActionAdapter`, not the\n`data-surface-bridge.ts` channel). Generated `ChatThread`/`ChatMessage`\n`list`/`get` are tenant- not member-scoped; the dock never calls them.\n\n**Server routes (#3368).** `./sveltekit` `mountAssistantRoutes({ ai, ... })`\nserves the dock from one `[...path]` route; `createAssistantHttpTransport`\nand `createAssistantHttpActionClient` (`./svelte`) are its browser half.\nPrincipal from `event.locals` (`user.id`, `user.profileId`, `tenantId`) or\n`resolvePrincipal`; threads are served only from the actor's keyed assistant\nsession room in that tenant (else 404); `allowedTools` is fail-closed;\n`ai` is injected, never read from env. `sendMessage`'s `clientRequestId`\nmakes the row id a UUIDv5 (`clientRequestMessageId`): the PK is the retry\nreservation. Details: [`docs/assistant-dock.md`](../../docs/assistant-dock.md).\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- **The agent's author is a Profile, not `agentId` (#2995)**: `senderProfileId`/`profileId` are `crossPackageRef`s to `Profile` and therefore uuid columns on PostgreSQL, so the slug fails the cast (`22P02`) and no agent reply can persist. `createAgentSession()` resolves the agent's `bot` Profile through `resolveAgentProfile()` in `@happyvertical/smrt-profiles` (created on first use, tenant-bound) and records it as `AgentSession.agentProfileId`; both enrolment and `sendAgentReply` use that uuid. A consumer whose agent already has an acting identity passes `agentProfileId` to skip resolution — the voice path does this with the persona's `actsAsProfileId`, so persona replies stay attributed to the configured acting profile. Like `actorProfileId`, `agentProfileId` is SERVER-supplied, never request input: it selects the author of every later assistant message. It is validated (`#requireAgentProfile`) to exist and be visible in the tenant and to differ from the acting participant, and it can never re-point a session that already resolved one — only a pre-#2995 session with none is backfilled. **Migration**: `agent_profile_id` is an ordinary additive manifest field, so a consumer adopts it the same way as any other — `smrt db:migrate` generates and applies the column from the manifest, and `db:status --parity` verifies it; the framework never creates application schema at runtime. It is nullable and needs no offline DATA backfill — a session created before #2995 resolves and persists its `agentProfileId`, and re-enrols the agent, on its first agent turn after the upgrade. Two pre-#2995 cohorts: a session whose `agentId` is an ordinary slug never committed an author on PostgreSQL (the cast failed), so there is nothing to repair there, while SQLite/DuckDB may hold `chat_messages`/`chat_participants` rows whose id column holds the slug — readable, but not joinable to `profiles`. A session whose `agentId` is already a Profile uuid (the voice path used to collapse a persona's `actsAsProfileId` into it) DID commit on PostgreSQL; that profile is ADOPTED as the author, tenant-checked and never the participant, so the conversation's author does not change and the two-seat room gains no third identity. Known one-time effect: because `voice.ts` no longer derives `agentId` from `actsAsProfileId`, a keyless `createVoiceChatSession()` for such a persona opens a new session and room instead of reusing the legacy one; the old room and its messages stay intact and readable, and resuming with an explicit `agentSessionId` is unaffected.\n- **Only SQLite-backed tests would miss this class of bug**: uuid columns accept any text on SQLite. `src/__tests__/agent-reply-postgres.test.ts` (`pnpm --filter @happyvertical/smrt-chat test:postgres`) pins the agent-reply path against real PostgreSQL. That suite runs in `postgres-tests.yml` on every same-repository PR and merge group (#2659); keep a cheap SQLite assertion alongside it anyway, since the default lane is SQLite-only (`chat-service.test.ts` asserts the author is the profile uuid, not the slug).\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",
5126
5129
  "moduleDocs": [
5127
5130
  {
5128
5131
  "path": "agents/dev-workbench.md",
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Browser half of the AssistantDock's mounted routes (#3368).
3
+ *
4
+ * `createAssistantHttpTransport` is `createSmrtAssistantTransport` pointed at
5
+ * `mountAssistantRoutes` (`@happyvertical/smrt-chat/sveltekit`): reads use its
6
+ * member-scoped `readEndpoint` unchanged, and the writes it leaves to the host
7
+ * (`writeEndpoint`) are filled in here. `createAssistantHttpActionClient` is
8
+ * the HTTP `AssistantActionClient` for the same routes' `actions/*`.
9
+ *
10
+ * Browser-safe: no server imports. Authentication is the host's session
11
+ * cookie (same-origin `fetch`), or headers the host supplies.
12
+ */
13
+ import type { DataSurfaceActionRequest, DataSurfaceRegistry } from '@happyvertical/smrt-ui/data-surface';
14
+ import { type AssistantTransport, type ModelOption } from './assistant-transport.js';
15
+ import type { AssistantActionClient } from './create-assistant-dock-controller.svelte.js';
16
+ /** Options shared by the HTTP transport and action client. */
17
+ export interface AssistantHttpOptions {
18
+ /** Where `mountAssistantRoutes` is mounted, e.g. `/api/assistant`. */
19
+ endpoint: string;
20
+ fetchImpl?: typeof fetch;
21
+ /** Extra request headers (e.g. a bearer token for a non-cookie host). */
22
+ headers?: Record<string, string> | (() => Record<string, string>);
23
+ /** Default `same-origin`, so the session cookie is sent. */
24
+ credentials?: RequestCredentials;
25
+ }
26
+ /** Options for {@link createAssistantHttpTransport}. */
27
+ export interface AssistantHttpTransportOptions extends AssistantHttpOptions {
28
+ /** When set, the dock renders `ModelPicker`; the server checks the choice. */
29
+ models?: ModelOption[];
30
+ }
31
+ /** A non-2xx answer from the assistant routes. `message` is user-safe. */
32
+ export declare class AssistantHttpError extends Error {
33
+ readonly status: number;
34
+ readonly code: string | undefined;
35
+ constructor(message: string, status: number, code: string | undefined);
36
+ }
37
+ /**
38
+ * An {@link AssistantTransport} for routes served by `mountAssistantRoutes`.
39
+ * Reads go through `createSmrtAssistantTransport`'s `readEndpoint`; writes,
40
+ * streamed turns, resumes and uploads through the same endpoint.
41
+ */
42
+ export declare function createAssistantHttpTransport(options: AssistantHttpTransportOptions): AssistantTransport;
43
+ /** Options for {@link createAssistantHttpActionClient}. */
44
+ export interface AssistantHttpActionClientOptions extends AssistantHttpOptions {
45
+ /**
46
+ * The registry the dock reads surfaces from; each call sends the surface's
47
+ * current revision as `expectedRevision`, so a page that changed since the
48
+ * preview is refused as `stale_revision` by the server.
49
+ */
50
+ registry?: Pick<DataSurfaceRegistry, 'inspect'>;
51
+ /** Override for the revision; wins over `registry`. */
52
+ expectedRevision?: (request: DataSurfaceActionRequest) => number | undefined;
53
+ }
54
+ /**
55
+ * An HTTP {@link AssistantActionClient} for `mountAssistantRoutes`'
56
+ * `actions/preview` and `actions/apply` (#2990 outcome rules):
57
+ * - 200 → the server's own result (refusals included);
58
+ * - apply 4xx → a refusal `{ ok: false, reason }` (nothing ran);
59
+ * - apply 5xx or a network failure → rejects, which the dock treats as an
60
+ * unknown outcome and retries with the same idempotency key;
61
+ * - preview non-2xx → rejects.
62
+ */
63
+ export declare function createAssistantHttpActionClient(options: AssistantHttpActionClientOptions): AssistantActionClient;
64
+ //# sourceMappingURL=assistant-http-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assistant-http-client.d.ts","sourceRoot":"","sources":["../../../../src/svelte/components/assistant/assistant-http-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EACV,wBAAwB,EAExB,mBAAmB,EACpB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAOL,KAAK,kBAAkB,EAGvB,KAAK,WAAW,EAIjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8CAA8C,CAAC;AAE1F,8DAA8D;AAC9D,MAAM,WAAW,oBAAoB;IACnC,sEAAsE;IACtE,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAClE,4DAA4D;IAC5D,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAED,wDAAwD;AACxD,MAAM,WAAW,6BAA8B,SAAQ,oBAAoB;IACzE,8EAA8E;IAC9E,MAAM,CAAC,EAAE,WAAW,EAAE,CAAC;CACxB;AAED,0EAA0E;AAC1E,qBAAa,kBAAmB,SAAQ,KAAK;IAGzC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS;gBAFjC,OAAO,EAAE,MAAM,EACN,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GAAG,SAAS;CAKpC;AAiFD;;;;GAIG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,GACrC,kBAAkB,CAgFpB;AAED,2DAA2D;AAC3D,MAAM,WAAW,gCAAiC,SAAQ,oBAAoB;IAC5E;;;;OAIG;IACH,QAAQ,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,SAAS,CAAC,CAAC;IAChD,uDAAuD;IACvD,gBAAgB,CAAC,EAAE,CAAC,OAAO,EAAE,wBAAwB,KAAK,MAAM,GAAG,SAAS,CAAC;CAC9E;AAED;;;;;;;;GAQG;AACH,wBAAgB,+BAA+B,CAC7C,OAAO,EAAE,gCAAgC,GACxC,qBAAqB,CAkEvB"}
@@ -0,0 +1,212 @@
1
+ import { createSmrtAssistantTransport, normalizeAssistantMessage, normalizeAssistantThreadSummary, readAssistantTurnResult, } from './assistant-transport.js';
2
+ /** A non-2xx answer from the assistant routes. `message` is user-safe. */
3
+ export class AssistantHttpError extends Error {
4
+ status;
5
+ code;
6
+ constructor(message, status, code) {
7
+ super(message);
8
+ this.status = status;
9
+ this.code = code;
10
+ this.name = 'AssistantHttpError';
11
+ }
12
+ }
13
+ function trimEndpoint(endpoint) {
14
+ return endpoint.replace(/\/+$/, '');
15
+ }
16
+ function makeFetch(options) {
17
+ const fetchImpl = options.fetchImpl ?? fetch;
18
+ const credentials = options.credentials ?? 'same-origin';
19
+ return (url, init = {}) => {
20
+ const headers = new Headers(init.headers);
21
+ // `createSmrtAssistantTransport` always sends a bearer header; with no
22
+ // token it is empty noise, so drop it and rely on the session cookie.
23
+ if (/^Bearer\s*$/i.test(headers.get('authorization') ?? '')) {
24
+ headers.delete('authorization');
25
+ }
26
+ const extra = typeof options.headers === 'function'
27
+ ? options.headers()
28
+ : (options.headers ?? {});
29
+ for (const [name, value] of Object.entries(extra)) {
30
+ headers.set(name, value);
31
+ }
32
+ return fetchImpl(url, { ...init, headers, credentials });
33
+ };
34
+ }
35
+ async function failure(response) {
36
+ let message = `The assistant request failed (${response.status}).`;
37
+ let code;
38
+ try {
39
+ const body = (await response.json());
40
+ if (typeof body.error === 'string' && body.error)
41
+ message = body.error;
42
+ if (typeof body.code === 'string')
43
+ code = body.code;
44
+ }
45
+ catch {
46
+ // Not JSON: keep the generic message.
47
+ }
48
+ return new AssistantHttpError(message, response.status, code);
49
+ }
50
+ function isJson(response) {
51
+ return /^application\/json\b/i.test(response.headers.get('content-type') ?? '');
52
+ }
53
+ /** Turns a send/resume response (SSE turn, or the JSON duplicate answer)
54
+ * into the dock's result. */
55
+ async function readTurn(response, onEvent) {
56
+ if (!response.ok)
57
+ throw await failure(response);
58
+ if (isJson(response)) {
59
+ const body = (await response.json());
60
+ return {
61
+ inProgress: body.inProgress === true,
62
+ ...(body.userMessage
63
+ ? { userMessage: normalizeAssistantMessage(body.userMessage) }
64
+ : {}),
65
+ ...(body.assistantMessage
66
+ ? { assistantMessage: normalizeAssistantMessage(body.assistantMessage) }
67
+ : {}),
68
+ messages: (body.messages ?? []).map(normalizeAssistantMessage),
69
+ };
70
+ }
71
+ const result = await readAssistantTurnResult(response, {
72
+ mapMessage: normalizeAssistantMessage,
73
+ onEvent,
74
+ });
75
+ const userMessage = result.messages?.find((message) => message.role === 'user');
76
+ return userMessage ? { ...result, userMessage } : result;
77
+ }
78
+ /**
79
+ * An {@link AssistantTransport} for routes served by `mountAssistantRoutes`.
80
+ * Reads go through `createSmrtAssistantTransport`'s `readEndpoint`; writes,
81
+ * streamed turns, resumes and uploads through the same endpoint.
82
+ */
83
+ export function createAssistantHttpTransport(options) {
84
+ const base = trimEndpoint(options.endpoint);
85
+ const request = makeFetch(options);
86
+ const postJson = (path, body, signal) => request(`${base}${path}`, {
87
+ method: 'POST',
88
+ headers: {
89
+ 'content-type': 'application/json',
90
+ accept: 'text/event-stream, application/json',
91
+ },
92
+ body: JSON.stringify(body),
93
+ ...(signal ? { signal } : {}),
94
+ });
95
+ const threadPath = (threadId, leaf) => `/threads/${encodeURIComponent(threadId)}/${leaf}`;
96
+ return createSmrtAssistantTransport({
97
+ readEndpoint: base,
98
+ token: '',
99
+ fetchImpl: ((url, init) => request(String(url), init)),
100
+ ...(options.models ? { models: options.models } : {}),
101
+ writeEndpoint: {
102
+ async createThread(title) {
103
+ const response = await postJson('/threads', { title });
104
+ if (!response.ok)
105
+ throw await failure(response);
106
+ const body = (await response.json());
107
+ return normalizeAssistantThreadSummary(body.thread);
108
+ },
109
+ async sendMessage(input) {
110
+ const response = await postJson(threadPath(input.threadId, 'messages'), {
111
+ content: input.content,
112
+ clientRequestId: input.clientRequestId,
113
+ ...(input.attachments?.length
114
+ ? { attachments: input.attachments }
115
+ : {}),
116
+ ...(input.model ? { model: input.model } : {}),
117
+ ...(input.clientTools?.length
118
+ ? { clientTools: input.clientTools }
119
+ : {}),
120
+ }, input.signal);
121
+ return readTurn(response, input.onEvent);
122
+ },
123
+ async resumeTurn(input) {
124
+ const response = await postJson(threadPath(input.threadId, 'resume'), {
125
+ clientRequestId: input.clientRequestId,
126
+ continuationId: input.continuationId,
127
+ results: input.results,
128
+ ...(input.model ? { model: input.model } : {}),
129
+ ...(input.clientTools?.length
130
+ ? { clientTools: input.clientTools }
131
+ : {}),
132
+ }, input.signal);
133
+ return readTurn(response, input.onEvent);
134
+ },
135
+ async uploadAttachment(file) {
136
+ const form = new FormData();
137
+ form.set('file', file, file.name);
138
+ const response = await request(`${base}/attachments`, {
139
+ method: 'POST',
140
+ body: form,
141
+ });
142
+ if (!response.ok)
143
+ throw await failure(response);
144
+ const body = (await response.json());
145
+ return body.attachment;
146
+ },
147
+ },
148
+ });
149
+ }
150
+ /**
151
+ * An HTTP {@link AssistantActionClient} for `mountAssistantRoutes`'
152
+ * `actions/preview` and `actions/apply` (#2990 outcome rules):
153
+ * - 200 → the server's own result (refusals included);
154
+ * - apply 4xx → a refusal `{ ok: false, reason }` (nothing ran);
155
+ * - apply 5xx or a network failure → rejects, which the dock treats as an
156
+ * unknown outcome and retries with the same idempotency key;
157
+ * - preview non-2xx → rejects.
158
+ */
159
+ export function createAssistantHttpActionClient(options) {
160
+ const base = trimEndpoint(options.endpoint);
161
+ const request = makeFetch(options);
162
+ const revisionOf = (action) => {
163
+ const revision = options.expectedRevision?.(action) ??
164
+ options.registry?.inspect(action.identity)?.revision;
165
+ if (!Number.isSafeInteger(revision) || revision < 0) {
166
+ throw new Error('AssistantDock: the surface is not mounted, so the action has no revision.');
167
+ }
168
+ return revision;
169
+ };
170
+ const call = async (phase, action, idempotencyKey) => {
171
+ const body = {
172
+ ...action,
173
+ phase,
174
+ expectedRevision: revisionOf(action),
175
+ ...(idempotencyKey ? { idempotencyKey } : {}),
176
+ };
177
+ const response = await request(`${base}/actions/${phase}`, {
178
+ method: 'POST',
179
+ headers: {
180
+ 'content-type': 'application/json',
181
+ accept: 'application/json',
182
+ },
183
+ body: JSON.stringify(body),
184
+ });
185
+ if (response.ok) {
186
+ const payload = (await response.json());
187
+ if (!payload.result) {
188
+ throw new Error('AssistantDock: the action route sent no result.');
189
+ }
190
+ return payload.result;
191
+ }
192
+ const error = await failure(response);
193
+ if (phase === 'apply' && response.status >= 400 && response.status < 500) {
194
+ return {
195
+ version: 1,
196
+ requestId: action.requestId,
197
+ identity: action.identity,
198
+ actionId: action.actionId,
199
+ phase: 'apply',
200
+ ok: false,
201
+ reason: response.status === 401 || response.status === 403
202
+ ? 'denied'
203
+ : (error.code ?? 'invalid_request'),
204
+ };
205
+ }
206
+ throw error;
207
+ };
208
+ return {
209
+ preview: (action) => call('preview', action),
210
+ apply: (action, idempotencyKey) => call('apply', action, idempotencyKey),
211
+ };
212
+ }
@@ -28,6 +28,7 @@ export { default as AssistantComposer } from './components/assistant/AssistantCo
28
28
  export { default as AssistantDock } from './components/assistant/AssistantDock.svelte';
29
29
  export { default as AssistantThreadList } from './components/assistant/AssistantThreadList.svelte';
30
30
  export { ASSISTANT_CHOICE_MAX_OPTIONS, ASSISTANT_CHOICE_TOOL_PREFIX, type AssistantChoiceOffer, type AssistantChoiceOption, type AssistantChoicePending, type AssistantChoicePendingUpdate, type AssistantChoiceSet, type AssistantChoiceSource, type AssistantChoiceSourceRegistry, AssistantChoices, choiceToolName, createAssistantChoiceSourceRegistry, normalizeChoiceOptions, safeChoiceImageUrl, } from './components/assistant/assistant-choices.svelte.js';
31
+ export { type AssistantHttpActionClientOptions, AssistantHttpError, type AssistantHttpOptions, type AssistantHttpTransportOptions, createAssistantHttpActionClient, createAssistantHttpTransport, } from './components/assistant/assistant-http-client.js';
31
32
  export { type AssistantAttachmentRef, type AssistantMessage, type AssistantResumeTurnInput, type AssistantSendMessageInput, type AssistantSendMessageResult, type AssistantThreadSummary, type AssistantTransport, type AssistantTransportEvent, type AssistantTurnStreamInput, createInMemoryAssistantTransport, createSmrtAssistantTransport, type InMemoryAssistantTransportOptions, readAssistantTurnResult, type SmrtAssistantTransportOptions, } from './components/assistant/assistant-transport.js';
32
33
  export { ASSISTANT_PROPOSE_ACTION_TOOL, type AssistantClientTool, type AssistantClientToolPolicy, type AssistantClientToolSource, type AssistantToolRequest, declareClientTools, defaultClientToolPolicy, resolveClientToolPolicy, } from './components/assistant/client-tools.js';
33
34
  export { ASSISTANT_ACTION_UNKNOWN_OUTCOME_REASONS, type AssistantActionClient, type AssistantActionOutcome, type AssistantActionState, type AssistantDockController, type AssistantDockControllerOptions, type AssistantPendingSend, type AssistantPendingSendStatus, type AssistantRun, type AssistantRunState, type AssistantRunStopReason, type AssistantRunWaiting, type AssistantUserHold, createAssistantDockController, } from './components/assistant/create-assistant-dock-controller.svelte.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/svelte/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AA8CH,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAI7E,OAAO,EACL,KAAK,uBAAuB,EAC5B,KAAK,8BAA8B,EACnC,KAAK,yBAAyB,EAC9B,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,wBAAwB,EACxB,o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