@happyvertical/smrt-chat 0.38.20 → 0.38.21

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n"],"mappings":""}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/__smrt-register__.ts","../src/chat-feedback.ts","../src/tool-loop.ts","../src/persona-conversation.ts"],"sourcesContent":["/**\n * Self-registers this package's build-time manifest before any @smrt() decorator\n * in the package fires. Fixes issue #1132: in consumer runtimes (tsx, SvelteKit\n * SSR, plain `vite dev`) the decorator's synchronous manifest lookup previously\n * missed because no step populated the global manifest cache — classes got\n * registered with zero fields and `save()` / `toJSON()` silently dropped every\n * declared property.\n *\n * Import this module as the first statement in `src/index.ts` so its top-level\n * side effect runs ahead of any class module's @smrt() decorator.\n *\n * Silent no-op in dev/test, where the vitest plugin already populates manifests\n * via a different path. Only needs to succeed in the published dist output.\n *\n * @see https://github.com/happyvertical/smrt/issues/1132\n */\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\n\n// During library builds, smrtPlugin replaces this entire module with generated\n// code that embeds the scanned manifest inline (#1506/#1507) — published dists\n// never resolve this URL, so downstream bundlers cannot break registration by\n// relocating the compiled module away from dist/manifest.json. The runtime\n// lookup below is the fallback for source-mode runs without that transform.\nObjectRegistry.registerPackageManifest(\n new URL('./manifest.json', import.meta.url),\n);\n","/**\n * Chat feedback capture — turn an in-conversation judgement into a first-class\n * learning signal (L3 of the learning-agents epic, #1891).\n *\n * A tenant end-user accepting or rejecting an applied change, giving a\n * thumbs-up/down, or typing an inline correction produces a {@link Feedback}\n * row — carrying the conversation's **correlation-id** back to the turn it\n * judges — and (by default) immediately reinforces the persona's learning\n * memory. Because recall draws on that same memory next turn, captured feedback\n * *influences subsequent behaviour*: a rejected strategy decays below the reuse\n * floor and stops resurfacing; a correction supersedes it with the corrected\n * value.\n *\n * This is the human-signal half of the loop the personas package already models\n * ({@link reinforceFromFeedback}); the gated half — rewriting a persona's\n * instructions — stays in the directive-proposal flow.\n *\n * @module\n */\n\nimport type {\n LearningMemoryRecord,\n LearningSemanticSearch,\n SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n type Feedback,\n FeedbackCollection,\n type FeedbackSignalType,\n feedbackSourceFor,\n personaLearningMemory,\n personaMemoryScope,\n reinforceFromFeedback,\n} from '@happyvertical/smrt-personas';\nimport { getDatabase } from '@happyvertical/sql';\n\n/** The minimal persona shape chat feedback needs to route the signal. */\nexport interface ChatFeedbackPersona {\n /** Persona id — required (a signal always judges a specific persona). */\n id?: string | null;\n /** Owning tenant. */\n tenantId?: string | null;\n /** Canonical agent class the persona configures (denormalised onto the row). */\n agentClass?: string;\n /** Learning memory partition key. */\n memoryScope?: string;\n}\n\n/**\n * Options for {@link captureChatFeedback}.\n */\nexport interface CaptureChatFeedbackOptions {\n /** Database handle. */\n db: SmrtClassOptions['db'];\n /** The persona the signal judges. */\n persona: ChatFeedbackPersona;\n /** The kind of signal. */\n signalType: FeedbackSignalType;\n /** Correlation-id of the conversation turn this signal judges. */\n correlationId: string;\n /** What {@link correlationId} names. Default `'chat_message'`. */\n correlationType?: string;\n /** Learning episode scope the signal reinforces (matches recall/capture). */\n scope: string;\n /** Learning episode key the signal reinforces. */\n key: string;\n /** The user id that authored the signal (null for autonomous). */\n actorId?: string | null;\n /** Numeric rating for a `rating` signal. */\n rating?: number | null;\n /** Corrected value for a `correction` signal. */\n correction?: string | null;\n /** Freeform note. */\n comment?: string | null;\n /** Structured metadata persisted on the row. */\n metadata?: Record<string, unknown>;\n /** Apply the signal to memory immediately. Default `true`. */\n reinforce?: boolean;\n /** Optional embedding search wired into the reinforced memory. */\n semanticSearch?: LearningSemanticSearch;\n /** Neutral point of a `rating` scale (see `FeedbackOutcomeOptions`). Default 0. */\n ratingNeutral?: number;\n}\n\n/** The outcome of capturing chat feedback. */\nexport interface ChatFeedbackResult {\n /** The persisted feedback row. */\n feedback: Feedback;\n /** The memory record the signal reinforced, or `null` when it carried none. */\n reinforced: LearningMemoryRecord | null;\n}\n\n/**\n * Capture one in-chat feedback signal as a {@link Feedback} row and (by default)\n * reinforce the persona's learning memory from it.\n *\n * @throws when the persona has no id (a signal must name a persisted persona).\n */\nexport async function captureChatFeedback(\n options: CaptureChatFeedbackOptions,\n): Promise<ChatFeedbackResult> {\n if (!options.persona.id) {\n throw new Error(\n 'captureChatFeedback requires a persisted persona (missing id)',\n );\n }\n const memoryScope = personaMemoryScope(options.persona);\n\n const feedbacks = await FeedbackCollection.create({ db: options.db });\n const feedback = await feedbacks.create({\n tenantId: options.persona.tenantId ?? null,\n personaId: options.persona.id,\n agentClass: options.persona.agentClass ?? '',\n memoryScope,\n scope: options.scope,\n key: options.key,\n signalType: options.signalType,\n source: feedbackSourceFor(options.signalType),\n correlationId: options.correlationId,\n correlationType: options.correlationType ?? 'chat_message',\n rating: options.rating ?? null,\n correction: options.correction ?? null,\n comment: options.comment ?? null,\n actorId: options.actorId ?? null,\n });\n if (options.metadata) {\n feedback.setMetadata(options.metadata);\n }\n await feedback.save();\n\n let reinforced: LearningMemoryRecord | null = null;\n if (options.reinforce !== false) {\n // LearningMemory operates on a resolved DB handle; `getDatabase` accepts a\n // config or a handle and returns a handle (idempotent for a handle).\n const memory = personaLearningMemory({\n db: await getDatabase(options.db as Parameters<typeof getDatabase>[0]),\n persona: options.persona,\n semanticSearch: options.semanticSearch,\n });\n reinforced = await reinforceFromFeedback(memory, feedback, {\n ratingNeutral: options.ratingNeutral,\n });\n // Gate exactly-once reinforcement so a later reflection pass never\n // re-applies this signal (mirrors the personas reflection runner).\n feedback.reinforcedAt = new Date();\n await feedback.save();\n }\n\n return { feedback, reinforced };\n}\n\n/** Shared options for the signal-typed convenience wrappers. */\nexport type ChatFeedbackBase = Omit<\n CaptureChatFeedbackOptions,\n 'signalType' | 'rating' | 'correction'\n>;\n\n/**\n * Accept an applied change — reinforces the judged strategy as a success.\n */\nexport function acceptAppliedChange(\n options: ChatFeedbackBase,\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({ ...options, signalType: 'accept' });\n}\n\n/**\n * Reject an applied change — decays the judged strategy toward the failure floor\n * so it stops being recalled.\n */\nexport function rejectAppliedChange(\n options: ChatFeedbackBase & { comment?: string | null },\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({ ...options, signalType: 'reject' });\n}\n\n/**\n * Record an inline correction — decays the wrong strategy AND supersedes its\n * stored value with the corrected one, so the next recall returns the fix.\n */\nexport function correctResponse(\n options: ChatFeedbackBase & { correction: string; comment?: string | null },\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({\n ...options,\n signalType: 'correction',\n correction: options.correction,\n });\n}\n\n/**\n * Record a numeric rating for a response (scale is caller-defined; pass\n * `ratingNeutral` for a mid-point).\n */\nexport function rateResponse(\n options: ChatFeedbackBase & { rating: number },\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({\n ...options,\n signalType: 'rating',\n rating: options.rating,\n });\n}\n\n/** Thumbs-up — a `+1` rating (reinforces as a success against neutral 0). */\nexport function thumbsUp(\n options: ChatFeedbackBase,\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({ ...options, signalType: 'rating', rating: 1 });\n}\n\n/** Thumbs-down — a `-1` rating (decays as a failure against neutral 0). */\nexport function thumbsDown(\n options: ChatFeedbackBase,\n): Promise<ChatFeedbackResult> {\n return captureChatFeedback({ ...options, signalType: 'rating', rating: -1 });\n}\n","/**\n * ToolLoop — a bounded `tool_call → observe → respond` agentic loop over the\n * SMRT manifest operation surface (L3 of the learning-agents epic, #1891).\n *\n * The universe of tools is **closed**: every tool is a manifest operation of an\n * installed SMRT package — an object's CRUD or *public custom action*, each a\n * `(collection, action)` in the manifest-derived permission catalog\n * ({@link PermissionCatalogService}). The loop invokes them **in-process\n * (\"side door\")** — no HTTP/MCP round-trip — inside the persona's\n * session-permission context ({@link executeAsPrincipal}), so tenant isolation\n * and per-operation authority (Postgres RLS, or the catalog assert when RLS is\n * off) apply through any door.\n *\n * Two independent gates make the loop fail-closed:\n *\n * 1. **Offer gate** — the available tools are exactly the manifest operations\n * filtered by the persona's `allowedTools`. A tool outside the allow-list is\n * never offered to the model, and a hallucinated tool name is rejected\n * without execution.\n * 2. **Execution gate** — every executed tool additionally re-asserts the\n * fail-closed allow-list ({@link PrincipalRun.assertToolAllowed}) and the\n * catalog permission for its `(collection, action)`\n * ({@link PrincipalRun.assertOperation}), so even a bug in the offer gate\n * cannot run an un-permitted operation.\n *\n * The loop is bounded by a max-steps ceiling: after `maxSteps` tool-executing\n * rounds it disables tools for one final completion, guaranteeing termination\n * with a text answer.\n *\n * @module\n */\n\nimport type {\n AIInterface,\n AIMessage,\n AIResponse,\n AITool,\n ChatOptions,\n} from '@happyvertical/ai';\nimport {\n executeAsPrincipal,\n type PrincipalAuditSink,\n type PrincipalBinding,\n type PrincipalRun,\n PrincipalToolNotAllowedError,\n} from '@happyvertical/smrt-agents';\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n OperationPermissionError,\n PermissionCatalogService,\n type PermissionDefinition,\n} from '@happyvertical/smrt-users';\n\n/** Default ceiling on tool-executing rounds before the loop force-terminates. */\nexport const DEFAULT_MAX_STEPS = 8;\n\n/**\n * A transcript message that may carry an OpenAI-style `tool_call_id` on a tool\n * observation. A structural superset of {@link AIMessage}, so the working\n * transcript stays assignable to `AIMessage[]` for `ai.chat()`.\n */\ntype LoopMessage = AIMessage & { tool_call_id?: string };\n\n/**\n * A single manifest operation the loop can offer and execute. Its {@link slug}\n * is simultaneously the tool's stable name AND its permission-catalog slug — one\n * source of truth for both what the model may call and what the principal must\n * be permitted to do.\n */\nexport interface ManifestTool {\n /** Catalog slug (`collection.action`) — the tool name and the permission slug. */\n slug: string;\n /** Collection (permission resource), e.g. `articles`. */\n collection: string;\n /** Registry class name used to resolve the backing collection, e.g. `Article`. */\n className: string;\n /** Catalog action: `read` / `create` / `update` / `delete`, or a public custom method name. */\n action: string;\n /** Qualified class name, when known. */\n qualifiedName?: string;\n /** Human-readable description surfaced to the model. */\n description?: string;\n}\n\n/**\n * The record of one tool invocation attempt in a loop turn.\n */\nexport interface ToolInvocation {\n /** The tool name the model asked for. */\n slug: string;\n /** Parsed arguments (best-effort JSON parse of the model's raw arguments). */\n args: Record<string, unknown>;\n /** Whether the operation executed successfully. */\n ok: boolean;\n /** The JSON-serializable observation fed back to the model. */\n observation: unknown;\n /** True when the call was denied (not on the allow-list / not permitted). */\n rejected: boolean;\n /** Error summary when `ok` is false. */\n error?: string;\n}\n\n/** Why {@link runToolLoop} returned. */\nexport type ToolLoopStopReason = 'stop' | 'max_steps' | 'no_tools';\n\n/** The outcome of a {@link runToolLoop} turn. */\nexport interface ToolLoopResult {\n /** The model's final assistant text. */\n content: string;\n /** Number of tool-executing rounds completed. */\n steps: number;\n /** Why the loop stopped. */\n stoppedReason: ToolLoopStopReason;\n /** Every tool invocation attempted this turn, in order. */\n invocations: ToolInvocation[];\n /** The full working transcript (input messages + assistant/tool turns). */\n messages: AIMessage[];\n /** Total tokens reported by the AI boundary, when available. */\n totalTokens: number;\n}\n\n/** Context handed to a custom {@link ToolLoopOptions.executeTool} implementation. */\nexport interface ToolExecutionContext {\n /** The principal run whose context bounds this execution. */\n run: PrincipalRun;\n /** The manifest operation to execute. */\n tool: ManifestTool;\n /** Parsed tool arguments. */\n args: Record<string, unknown>;\n /** The database handle to operate against (already the RLS-bound tx when on). */\n db?: SmrtClassOptions['db'];\n}\n\n/**\n * Options for {@link runToolLoop}.\n */\nexport interface ToolLoopOptions {\n /** The AI boundary (the only thing mocked in tests). */\n ai: AIInterface;\n /** The initial conversation messages (system / history / user). */\n messages: AIMessage[];\n /** The manifest operations available this turn (already allow-list-filtered). */\n tools: ManifestTool[];\n /** The persona principal every tool call runs as. */\n principal: PrincipalBinding;\n /** Database handle the side-door operations run against. */\n db?: SmrtClassOptions['db'];\n /** Max tool-executing rounds before force-termination. Default {@link DEFAULT_MAX_STEPS}. */\n maxSteps?: number;\n /** Model id passed to the AI boundary. */\n model?: string;\n /** Sampling temperature. */\n temperature?: number;\n /** Max tokens per completion. */\n maxTokens?: number;\n /** Tool-choice behaviour while tools are offered. Default `'auto'`. */\n toolChoice?: ChatOptions['toolChoice'];\n /**\n * Override the side-door executor. The default\n * ({@link invokeManifestTool}) enforces the allow-list + catalog gate and\n * dispatches through the ObjectRegistry. Tests inject a stub to exercise loop\n * mechanics without a backing object.\n */\n executeTool?: (ctx: ToolExecutionContext) => Promise<unknown>;\n /** Notified after each tool invocation (for streaming/telemetry). */\n onInvocation?: (invocation: ToolInvocation) => void | Promise<void>;\n /** The originating user the turn runs on behalf of (audited). */\n onBehalfOfUserId?: string | null;\n /** Canonical agent class, recorded in the audit entry. */\n agentClass?: string;\n /** Audit sink forwarded to {@link executeAsPrincipal}. */\n audit?: PrincipalAuditSink;\n /** Opt into Postgres RLS transaction wrapping. */\n postgresRls?: boolean;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\n/**\n * Best-effort parse of the model's raw tool-call arguments (a JSON string).\n * A non-object or malformed payload yields `{}` so a bad-argument call still\n * flows through the permission gate rather than throwing before it.\n */\nfunction parseToolArguments(raw: string | undefined): Record<string, unknown> {\n if (!raw) {\n return {};\n }\n try {\n return asRecord(JSON.parse(raw));\n } catch {\n return {};\n }\n}\n\n/**\n * Derive the catalog action for a permission definition — the slug segment(s)\n * after the `collection.` prefix. Catalog slugs are built as\n * `${collection}.${action}`, so this recovers `read` / `create` / a custom\n * method name unambiguously.\n */\nfunction actionFromDefinition(def: PermissionDefinition): string | null {\n const collection = def.collection;\n if (!collection || !def.slug.startsWith(`${collection}.`)) {\n return null;\n }\n const action = def.slug.slice(collection.length + 1);\n return action.length > 0 ? action : null;\n}\n\n/**\n * Build the closed catalog of manifest operations available as tools.\n *\n * Reads the manifest-derived {@link PermissionCatalog} and keeps only the\n * entries that name a dispatchable operation (a `(collection, action)` with a\n * resolvable backing class). Pass `allowedTools` to narrow the catalog to a\n * persona's least-privilege allow-list — this is the **offer gate**: a slug not\n * in `allowedTools` is never returned, so it is neither offered to the model nor\n * executed. A missing, `null`, or empty `allowedTools` yields **no tools**\n * (fail-closed) — the same whitelist semantics as `AgentSession`/\n * `PrincipalBinding` (S5 #1392), so forgetting the allow-list can only tighten,\n * never widen, the offered surface. Pass `all: true` to deliberately enumerate\n * the full manifest operation surface (e.g. an admin tool picker) — that is the\n * one explicit escape hatch, never the default.\n */\nexport function buildManifestToolCatalog(\n options: SmrtClassOptions & {\n /** Least-privilege allow-list to narrow the catalog by (fail-closed). */\n allowedTools?: string[] | null;\n /** Explicitly enumerate the ENTIRE manifest operation surface (no narrowing). */\n all?: boolean;\n /** Supply a pre-built catalog (skips the manifest walk). */\n catalog?: PermissionDefinition[];\n } = {},\n): ManifestTool[] {\n const definitions =\n options.catalog ??\n PermissionCatalogService.create(options).getCatalog().permissions;\n\n // Fail-closed: an absent / `null` / empty allow-list permits NOTHING. Only an\n // explicit `all: true` disables the narrowing and returns the full surface, so\n // a caller that forgets `allowedTools` gets zero tools rather than every one.\n const filter =\n options.all === true ? null : new Set(options.allowedTools ?? []);\n\n const tools: ManifestTool[] = [];\n for (const def of definitions) {\n if (!def.className || !def.collection) {\n continue;\n }\n if (filter && !filter.has(def.slug)) {\n continue;\n }\n const action = actionFromDefinition(def);\n if (!action) {\n continue;\n }\n tools.push({\n slug: def.slug,\n collection: def.collection,\n className: def.className,\n action,\n qualifiedName: def.qualifiedName,\n description: def.description,\n });\n }\n return tools;\n}\n\n/**\n * JSON-schema parameters for a manifest operation, keyed off its action. Create\n * / update schemas are enriched with the object's declared field names (tool arg\n * schemas come from field metadata) when the registry can supply them.\n */\nfunction toolParameters(tool: ManifestTool): Record<string, unknown> {\n const fieldProps = (): Record<string, unknown> => {\n const props: Record<string, unknown> = {};\n try {\n for (const [name] of ObjectRegistry.getFields(tool.className)) {\n if (typeof name === 'string') {\n props[name] = { type: 'string' };\n }\n }\n } catch {\n // No field metadata available — fall back to a free-form object.\n }\n return props;\n };\n\n switch (tool.action) {\n case 'read':\n return {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Fetch one row by id (omit to list).',\n },\n where: {\n type: 'object',\n description: 'Equality filters for a list.',\n },\n limit: { type: 'number' },\n offset: { type: 'number' },\n },\n };\n case 'create':\n return { type: 'object', properties: fieldProps() };\n case 'update':\n return {\n type: 'object',\n required: ['id'],\n properties: { id: { type: 'string' }, ...fieldProps() },\n };\n case 'delete':\n return {\n type: 'object',\n required: ['id'],\n properties: { id: { type: 'string' } },\n };\n default:\n return {\n type: 'object',\n required: ['id'],\n properties: {\n id: { type: 'string', description: 'Target row id for the action.' },\n },\n };\n }\n}\n\n/**\n * A provider-safe function name for a catalog slug.\n *\n * Catalog slugs are `collection.action` and routinely contain a `.`, but many\n * providers (OpenAI) restrict function names to `[A-Za-z0-9_-]{1,64}`. This maps\n * the slug into that charset (dots → `-`) for the wire; {@link runToolLoop} maps\n * the returned name back to the tool, and `tool.slug` remains the internal\n * permission id. Distinct slugs stay distinct (the only substituted char is the\n * single `.` separator).\n */\nexport function toolFunctionName(slug: string): string {\n return slug.replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 64);\n}\n\n/**\n * Project a manifest operation into an AI function-tool definition. The function\n * name is the provider-safe rendering of the catalog slug\n * ({@link toolFunctionName}), so the model can only ever name a real operation.\n */\nexport function manifestToolToAITool(tool: ManifestTool): AITool {\n return {\n type: 'function',\n function: {\n name: toolFunctionName(tool.slug),\n description:\n tool.description ??\n `Manifest operation '${tool.action}' on '${tool.collection}'.`,\n parameters: toolParameters(tool),\n },\n };\n}\n\ninterface OperableItem {\n toJSON: () => Record<string, unknown>;\n save: () => Promise<unknown>;\n delete: () => Promise<unknown>;\n}\n\nfunction itemToObservation(item: unknown): unknown {\n const candidate = item as { toJSON?: () => unknown } | null;\n return typeof candidate?.toJSON === 'function' ? candidate.toJSON() : item;\n}\n\n/**\n * Execute a manifest operation in-process (\"side door\") under the principal.\n *\n * Enforces both authority dimensions before touching data: the fail-closed tool\n * allow-list ({@link PrincipalRun.assertToolAllowed}) and the catalog permission\n * for the `(collection, action)` ({@link PrincipalRun.assertOperation}) — the\n * door-agnostic teeth that hold on RLS-off adapters and are a redundant second\n * gate under Postgres RLS. Data operations run against the principal context's\n * database (the RLS-bound transaction when RLS is on), so tenant + per-operation\n * enforcement apply exactly as they would through REST or MCP.\n */\nexport async function invokeManifestTool(\n run: PrincipalRun,\n tool: ManifestTool,\n args: Record<string, unknown>,\n options: { db?: SmrtClassOptions['db'] } = {},\n): Promise<unknown> {\n // Gate 1: fail-closed allow-list (defense-in-depth behind the offer gate).\n run.assertToolAllowed(tool.slug);\n // Gate 2: door-agnostic catalog authority (the RLS-off teeth; redundant under RLS).\n await run.assertOperation(tool.collection, tool.action);\n\n // Operate against the principal context's database so RLS (when on) and tenant\n // auto-filtering bound the query; fall back to the supplied handle otherwise.\n const db = (run.context.database ?? options.db) as SmrtClassOptions['db'];\n const collection = await ObjectRegistry.getCollection(\n tool.className,\n db ? { db } : {},\n );\n\n switch (tool.action) {\n case 'read': {\n const id = typeof args.id === 'string' ? args.id : undefined;\n if (id) {\n const item = await collection.get(id);\n return item ? itemToObservation(item) : { found: false };\n }\n const items = await collection.list({\n where: asRecord(args.where),\n limit: typeof args.limit === 'number' ? args.limit : 50,\n offset: typeof args.offset === 'number' ? args.offset : 0,\n });\n return items.map(itemToObservation);\n }\n case 'create': {\n const item = (await collection.create(args)) as unknown as OperableItem;\n await item.save();\n return itemToObservation(item);\n }\n case 'update': {\n const { id, ...rest } = args;\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error(`'${tool.slug}' requires an 'id' to update.`);\n }\n const item = (await collection.get(id)) as unknown as OperableItem | null;\n if (!item) {\n return { found: false };\n }\n Object.assign(item, rest);\n await item.save();\n return itemToObservation(item);\n }\n case 'delete': {\n const id = typeof args.id === 'string' ? args.id : undefined;\n if (!id) {\n throw new Error(`'${tool.slug}' requires an 'id' to delete.`);\n }\n const item = (await collection.get(id)) as unknown as OperableItem | null;\n if (!item) {\n return { found: false };\n }\n await item.delete();\n return { success: true, id };\n }\n default: {\n // Public custom action: invoke the named method on the row.\n const { id, ...rest } = args;\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error(`'${tool.slug}' requires an 'id' for a custom action.`);\n }\n const item = await collection.get(id);\n if (!item) {\n return { found: false };\n }\n const method = (item as unknown as Record<string, unknown>)[tool.action];\n if (typeof method !== 'function') {\n throw new Error(\n `Method '${tool.action}' not found on '${tool.className}'.`,\n );\n }\n const result = await (\n method as (input: Record<string, unknown>) => Promise<unknown>\n ).call(item, rest);\n return result === undefined\n ? { success: true }\n : itemToObservation(result);\n }\n }\n}\n\n/**\n * Run a bounded `tool_call → observe → respond` loop over the manifest operation\n * surface, as the persona's bound principal.\n *\n * The whole turn runs inside a single {@link executeAsPrincipal} context, so\n * every tool call shares one published permission snapshot (matching what a\n * Postgres RLS session enforces) and the turn audits once as on-behalf-of the\n * originating user.\n *\n * @param options - The AI boundary, seed messages, allow-list-filtered tools,\n * principal, and ceiling.\n * @returns The final assistant text plus the invocation log and transcript.\n */\nexport async function runToolLoop(\n options: ToolLoopOptions,\n): Promise<ToolLoopResult> {\n const {\n ai,\n messages,\n tools,\n principal,\n db,\n maxSteps = DEFAULT_MAX_STEPS,\n model,\n temperature,\n maxTokens,\n toolChoice = 'auto',\n executeTool,\n onInvocation,\n onBehalfOfUserId,\n agentClass,\n audit,\n postgresRls,\n } = options;\n\n const aiTools = tools.map(manifestToolToAITool);\n // Resolve the tool by EITHER the internal slug (a mock/pass-through provider)\n // OR the provider-safe function name the model actually receives, so the offer\n // gate holds regardless of how the provider renders the name.\n const offered = new Map<string, ManifestTool>();\n for (const tool of tools) {\n offered.set(tool.slug, tool);\n offered.set(toolFunctionName(tool.slug), tool);\n }\n\n return executeAsPrincipal(\n {\n db,\n principal,\n onBehalfOfUserId,\n agentClass,\n action: 'chat.tool_loop',\n postgresRls,\n audit,\n },\n async (run): Promise<ToolLoopResult> => {\n // `LoopMessage` carries `tool_call_id` on tool observations (OpenAI's tool\n // message shape needs it to correlate an observation to its call); it is a\n // structural superset of `AIMessage`, so the transcript stays chat-compatible.\n const working: LoopMessage[] = [...messages];\n const invocations: ToolInvocation[] = [];\n let executedRounds = 0;\n let totalTokens = 0;\n let response: AIResponse;\n\n for (;;) {\n const offerTools = aiTools.length > 0 && executedRounds < maxSteps;\n response = await ai.chat(working, {\n model,\n temperature,\n maxTokens,\n tools: offerTools ? aiTools : undefined,\n toolChoice: offerTools ? toolChoice : 'none',\n });\n totalTokens += response.usage?.totalTokens ?? 0;\n\n const toolCalls = offerTools ? (response.toolCalls ?? []) : [];\n if (toolCalls.length === 0) {\n return {\n content: response.content ?? '',\n steps: executedRounds,\n stoppedReason:\n aiTools.length === 0\n ? 'no_tools'\n : offerTools\n ? 'stop'\n : 'max_steps',\n invocations,\n messages: working,\n totalTokens,\n };\n }\n\n // Record the assistant's tool-call turn before appending observations.\n working.push({\n role: 'assistant',\n content: response.content ?? '',\n tool_calls: toolCalls,\n });\n\n for (const call of toolCalls) {\n const requestedName = call.function.name;\n const args = parseToolArguments(call.function.arguments);\n const tool = offered.get(requestedName);\n // Record the canonical slug (the permission id) for a resolved tool;\n // for a rejected/hallucinated call, echo whatever the model named.\n const slug = tool?.slug ?? requestedName;\n\n let invocation: ToolInvocation;\n if (!tool) {\n // Offer gate: a tool the persona was not offered (not on the\n // allow-list, or hallucinated) is rejected without execution.\n invocation = {\n slug,\n args,\n ok: false,\n rejected: true,\n observation: {\n error: `Tool '${slug}' is not permitted for this persona.`,\n },\n error: 'not_permitted',\n };\n } else {\n try {\n const observation = await (executeTool\n ? executeTool({ run, tool, args, db })\n : invokeManifestTool(run, tool, args, { db }));\n invocation = {\n slug,\n args,\n ok: true,\n rejected: false,\n observation,\n };\n } catch (error) {\n const rejected =\n error instanceof PrincipalToolNotAllowedError ||\n error instanceof OperationPermissionError;\n invocation = {\n slug,\n args,\n ok: false,\n rejected,\n observation: {\n error: error instanceof Error ? error.message : String(error),\n },\n error: rejected ? 'not_permitted' : 'execution_error',\n };\n }\n }\n\n invocations.push(invocation);\n await onInvocation?.(invocation);\n working.push({\n role: 'tool',\n name: requestedName,\n // Correlate the observation to the exact call the model made — many\n // providers (OpenAI) require `tool_call_id` on a tool message and\n // mis-associate observations without it when several calls occur.\n tool_call_id: call.id,\n content: JSON.stringify(invocation.observation),\n });\n }\n\n executedRounds += 1;\n }\n },\n );\n}\n","/**\n * Persona-bound conversation — the bridge from an {@link AgentSession} (a\n * conversation) to an `AgentPersona`/`TenantAgent` (a tenant-scoped, principal-\n * bound behavioural profile) (L3 of the learning-agents epic, #1891).\n *\n * This is the new, acyclic `chat → personas` edge. A conversation bound this way\n * runs under the persona's **principal** (its `runAsUserId`, via\n * {@link runToolLoop} → `executeAsPrincipal`), offers only the persona's\n * **tools** (its `allowedTools`, narrowing the manifest operation surface),\n * speaks with the persona's **instructions**, and draws on its **recalled\n * learning memory** — so the assistant behaves like it knows the tenant's job.\n *\n * The persona's `allowedTools` is mirrored onto the `AgentSession` so the chat\n * layer's own fail-closed tool gate (S5 #1392) agrees with the loop's — one\n * allow-list, enforced at both the loop's side door and the message-authoring\n * seam.\n *\n * @module\n */\n\nimport type { AIInterface, AIMessage } from '@happyvertical/ai';\nimport type {\n PrincipalAuditSink,\n PrincipalBinding,\n} from '@happyvertical/smrt-agents';\nimport type {\n LearningMemoryRecord,\n LearningSemanticSearch,\n SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n personaLearningMemory,\n resolvePersonaInstructions,\n} from '@happyvertical/smrt-personas';\nimport { getDatabase } from '@happyvertical/sql';\nimport type { AgentSession } from './models/AgentSession.js';\nimport {\n buildManifestToolCatalog,\n type ManifestTool,\n runToolLoop,\n type ToolLoopResult,\n} from './tool-loop.js';\n\n/**\n * The structural persona shape the conversation binding needs. Both a\n * `ResolvedPersona` (from `PersonaResolver.resolve()`) and a raw `AgentPersona`\n * satisfy it via the adapters below.\n */\nexport interface ConversationPersona {\n /** Persona id — required to scope learning memory and prompt overrides. */\n id?: string | null;\n /** Owning tenant. */\n tenantId: string | null;\n /** Canonical agent class the persona configures. */\n agentClass?: string;\n /** The user whose live permissions bound the conversation. */\n runAsUserId: string;\n /** Optional acting `Bot` profile id (identity/audit). */\n actsAsProfileId?: string | null;\n /** The persona's tool allow-list (already capped by the class ceiling). */\n allowedTools: string[];\n /** Behavioural instructions / system prompt. */\n instructions?: string;\n /** Learning memory partition key. */\n memoryScope?: string;\n}\n\n/** Adapt a `PersonaResolver.resolve()` result into a {@link ConversationPersona}. */\nexport function conversationPersonaFromResolved(resolved: {\n personaId?: string;\n tenantId: string;\n agentClass: string;\n runAsUserId?: string;\n actsAsProfileId?: string | null;\n allowedTools: string[];\n instructions: string;\n memoryScope: string;\n}): ConversationPersona {\n return {\n id: resolved.personaId ?? null,\n tenantId: resolved.tenantId,\n agentClass: resolved.agentClass,\n runAsUserId: resolved.runAsUserId ?? '',\n actsAsProfileId: resolved.actsAsProfileId ?? null,\n allowedTools: resolved.allowedTools,\n instructions: resolved.instructions,\n memoryScope: resolved.memoryScope,\n };\n}\n\n/** Adapt a raw `AgentPersona` row into a {@link ConversationPersona}. */\nexport function conversationPersonaFromAgentPersona(persona: {\n id?: string | null;\n tenantId: string;\n agentClass: string;\n runAsUserId: string;\n actsAsProfileId?: string | null;\n instructions: string;\n memoryScope?: string;\n getAllowedTools: () => string[];\n}): ConversationPersona {\n return {\n id: persona.id ?? null,\n tenantId: persona.tenantId,\n agentClass: persona.agentClass,\n runAsUserId: persona.runAsUserId,\n actsAsProfileId: persona.actsAsProfileId ?? null,\n allowedTools: persona.getAllowedTools(),\n instructions: persona.instructions,\n memoryScope: persona.memoryScope,\n };\n}\n\n/**\n * Project a {@link ConversationPersona} into the {@link PrincipalBinding} the\n * tool loop runs as. The persona's `allowedTools` is the fail-closed whitelist\n * (absent/empty ⇒ no tools).\n */\nexport function principalBindingFor(\n persona: ConversationPersona,\n): PrincipalBinding {\n return {\n runAsUserId: persona.runAsUserId,\n tenantId: persona.tenantId,\n allowedTools: persona.allowedTools,\n actsAsProfileId: persona.actsAsProfileId ?? null,\n };\n}\n\n/** How to recall a persona's learning memory into the conversation context. */\nexport interface PersonaRecallOptions {\n /** Learning scope to recall (defaults to `'chat'`). */\n scope?: string;\n /** Exact episode key within the scope (omit for a scope-wide recall). */\n key?: string;\n /** Free-text query for the semantic arm (needs a `semanticSearch`). */\n query?: string;\n /** Max recalled records injected into context. Default 5. */\n limit?: number;\n /** Override the reuse floor for this recall. */\n minConfidence?: number;\n /** Optional embedding search for the semantic recall arm. */\n semanticSearch?: LearningSemanticSearch;\n}\n\n/**\n * Recall the persona's confidence-filtered learning memory.\n *\n * Isolated per persona by `memoryScope`, so what the \"Support\" persona learned\n * never bleeds into \"Sales\". Returns `[]` for a persona with no memory scope /\n * id (nothing to partition on).\n */\nexport async function recallPersonaMemory(\n db: SmrtClassOptions['db'],\n persona: ConversationPersona,\n options: PersonaRecallOptions = {},\n): Promise<LearningMemoryRecord[]> {\n if (!persona.memoryScope && !persona.id) {\n return [];\n }\n // LearningMemory operates on a resolved DB handle; `getDatabase` accepts a\n // config or a handle and returns a handle (idempotent for a handle).\n const memory = personaLearningMemory({\n db: await getDatabase(db as Parameters<typeof getDatabase>[0]),\n persona,\n semanticSearch: options.semanticSearch,\n });\n return memory.recall(options.scope ?? 'chat', {\n key: options.key,\n query: options.query,\n limit: options.limit ?? 5,\n minConfidence: options.minConfidence,\n });\n}\n\n/**\n * Format recalled memory into a system-context block. Empty string when there\n * is nothing to inject (so it can be unconditionally concatenated).\n */\nexport function formatRecalledMemory(records: LearningMemoryRecord[]): string {\n if (records.length === 0) {\n return '';\n }\n const lines = records.map((record) => {\n const value =\n typeof record.value === 'string'\n ? record.value\n : JSON.stringify(record.value);\n return `- [confidence ${record.confidence.toFixed(2)}] ${record.key}: ${value}`;\n });\n return `What you have learned about this organisation:\\n${lines.join('\\n')}`;\n}\n\n/**\n * Resolve the persona's effective instructions.\n *\n * Prefers the prompt-system resolution (`resolvePersonaInstructions`, which\n * layers any approved learned-directive override) when the persona is persisted;\n * falls back to the inline `persona.instructions`. This is how a conversation\n * \"uses its instructions (`applyPersonaInstructions`)\".\n */\nexport async function resolveConversationInstructions(\n db: SmrtClassOptions['db'],\n persona: ConversationPersona,\n): Promise<string> {\n if (persona.id) {\n try {\n const resolved = await resolvePersonaInstructions({\n persona: { id: persona.id, tenantId: persona.tenantId },\n db: db as Parameters<typeof resolvePersonaInstructions>[0]['db'],\n });\n if (resolved) {\n return resolved;\n }\n } catch {\n // Fall through to the inline instructions.\n }\n }\n return persona.instructions ?? '';\n}\n\n/** The minimal AgentSession surface the turn needs. */\ntype SessionLike = Pick<AgentSession, 'id' | 'chatRoomId' | 'systemPrompt'>;\n\n/** The minimal ChatService surface the turn needs to author the reply. */\nexport interface ConversationReplyService {\n initialize(): Promise<void>;\n}\n\n/**\n * Options for {@link runPersonaConversationTurn}.\n */\nexport interface PersonaConversationTurnOptions {\n /** The AI boundary. */\n ai: AIInterface;\n /** The database handle side-door operations run against. */\n db: SmrtClassOptions['db'];\n /** The persona the conversation is bound to. */\n persona: ConversationPersona;\n /** The user's message this turn. */\n userMessage: string;\n /** Tenant the turn runs within. */\n tenantId: string;\n /** Prior conversation turns (assistant/user), oldest first. */\n history?: AIMessage[];\n /**\n * The bound agent session. When provided together with `chatService`, the\n * agent reply is authored into the session's room and each executed tool is\n * recorded as a `tool_result` message (gated by the session allow-list).\n */\n session?: SessionLike | null;\n /** Chat service used to author the agent reply. */\n chatService?: ConversationReplyService | null;\n /** Thread to attach authored messages to. */\n threadId?: string | null;\n /** Recall configuration, or `false` to skip memory recall. */\n recall?: PersonaRecallOptions | false;\n /** Pre-built tool catalog (else derived from the persona's `allowedTools`). */\n tools?: ManifestTool[];\n /** Max tool-executing rounds. */\n maxSteps?: number;\n /** Model id. */\n model?: string;\n /** Sampling temperature. */\n temperature?: number;\n /** Max tokens per completion. */\n maxTokens?: number;\n /** Originating user the turn runs on behalf of (audited). */\n onBehalfOfUserId?: string | null;\n /** Audit sink for the on-behalf-of entry (forwarded to `executeAsPrincipal`). */\n audit?: PrincipalAuditSink;\n /** Opt into Postgres RLS transaction wrapping. */\n postgresRls?: boolean;\n /** Correlation id for the turn (feedback ties back to it). Auto-generated when omitted. */\n correlationId?: string;\n}\n\n/** The outcome of a persona-bound conversation turn. */\nexport interface PersonaConversationTurnResult {\n /** The tool-loop result (final text, invocations, transcript). */\n result: ToolLoopResult;\n /** The correlation id feedback on this turn should reference. */\n correlationId: string;\n /** The memory recalled into the turn's context. */\n recalled: LearningMemoryRecord[];\n /** The system prompt assembled for the turn. */\n systemPrompt: string;\n}\n\nfunction assembleSystemPrompt(\n instructions: string,\n memoryBlock: string,\n sessionPrompt: string | undefined,\n): string {\n // De-duplicate identical blocks: `bindPersonaToSession()` sets\n // `session.systemPrompt` to the persona instructions, so without this the\n // instruction block would appear twice (wasted tokens + confusion) once a\n // conversation runs on a bound session.\n const blocks = [sessionPrompt, instructions, memoryBlock]\n .map((part) => part?.trim())\n .filter((part): part is string => Boolean(part));\n return [...new Set(blocks)].join('\\n\\n');\n}\n\n/**\n * Run one turn of a persona-bound conversation.\n *\n * Binds the conversation to the persona: recalls its learning memory, resolves\n * its instructions, offers only its allow-listed manifest operations, and runs\n * the bounded tool loop as its principal. When a `chatService` + `session` are\n * given the assistant reply (and each executed tool) is authored into the room,\n * exercising the chat layer's own fail-closed tool gate.\n *\n * @returns The loop result, the turn's correlation id, and the recalled memory.\n */\nexport async function runPersonaConversationTurn(\n options: PersonaConversationTurnOptions,\n): Promise<PersonaConversationTurnResult> {\n const { ai, db, persona, userMessage, tenantId } = options;\n // A conversation must run as a concrete principal. A default/unbound persona\n // (e.g. a `PersonaResolver` default fallback) has no `runAsUserId`; fail fast\n // with a clear error rather than building an empty-string PrincipalBinding\n // that would silently resolve to zero permissions downstream.\n if (!persona.runAsUserId) {\n throw new Error(\n 'runPersonaConversationTurn requires a persona bound to a run-as user ' +\n '(runAsUserId); an unbound/default persona cannot operate the app.',\n );\n }\n const correlationId = options.correlationId ?? crypto.randomUUID();\n\n const recalled =\n options.recall === false\n ? []\n : await recallPersonaMemory(db, persona, options.recall ?? {});\n\n const instructions = await resolveConversationInstructions(db, persona);\n const memoryBlock = formatRecalledMemory(recalled);\n const systemPrompt = assembleSystemPrompt(\n instructions,\n memoryBlock,\n options.session?.systemPrompt,\n );\n\n const messages: AIMessage[] = [];\n if (systemPrompt) {\n messages.push({ role: 'system', content: systemPrompt });\n }\n if (options.history) {\n messages.push(...options.history);\n }\n messages.push({ role: 'user', content: userMessage });\n\n const tools =\n options.tools ??\n buildManifestToolCatalog({ db, allowedTools: persona.allowedTools });\n\n const result = await runToolLoop({\n ai,\n messages,\n tools,\n principal: principalBindingFor(persona),\n db,\n maxSteps: options.maxSteps,\n model: options.model,\n temperature: options.temperature,\n maxTokens: options.maxTokens,\n onBehalfOfUserId: options.onBehalfOfUserId,\n agentClass: persona.agentClass,\n postgresRls: options.postgresRls,\n audit: options.audit,\n });\n\n if (options.chatService && options.session?.id) {\n await authorConversationReply({\n chatService: options.chatService,\n session: options.session,\n tenantId,\n threadId: options.threadId ?? null,\n result,\n });\n }\n\n return { result, correlationId, recalled, systemPrompt };\n}\n\n/**\n * Options for {@link bindPersonaToSession}.\n */\nexport interface BindPersonaToSessionOptions {\n /** Chat service exposing the owner-checked `updateAgentSessionConfig`. */\n chatService: {\n updateAgentSessionConfig(params: {\n agentSessionId: string;\n actorProfileId: string;\n tenantId: string | null;\n allowedTools?: string[];\n systemPrompt?: string;\n }): Promise<AgentSession>;\n };\n /** The session to bind. */\n session: Pick<AgentSession, 'id'>;\n /** The session owner (the update is owner-checked, S5 #1392). */\n actorProfileId: string;\n /** Tenant the session belongs to. */\n tenantId: string | null;\n /** The persona to bind the session to. */\n persona: ConversationPersona;\n /** Instructions to set as the session system prompt (else resolved). */\n instructions?: string;\n /** Database handle used to resolve instructions when not supplied. */\n db?: SmrtClassOptions['db'];\n}\n\n/**\n * Bind an {@link AgentSession} to a persona: mirror the persona's `allowedTools`\n * and instructions onto the session so the chat layer's own fail-closed tool\n * gate (S5 #1392) agrees with the loop's, and the session's system prompt speaks\n * the persona's voice. This is the durable side of the `chat → personas` bridge:\n * once bound, the session's authoring gate and the loop's offer gate share one\n * allow-list.\n */\nexport async function bindPersonaToSession(\n options: BindPersonaToSessionOptions,\n): Promise<AgentSession> {\n const instructions =\n options.instructions ??\n (options.db\n ? await resolveConversationInstructions(options.db, options.persona)\n : (options.persona.instructions ?? ''));\n return options.chatService.updateAgentSessionConfig({\n agentSessionId: options.session.id as string,\n actorProfileId: options.actorProfileId,\n tenantId: options.tenantId,\n allowedTools: options.persona.allowedTools,\n systemPrompt: instructions,\n });\n}\n\n/**\n * Author the agent's turn into the chat room: one `tool_result` message per\n * executed tool (gated fail-closed by the session allow-list), then the final\n * assistant text. Uses the trusted in-package agent-reply bridge, so messages\n * are authored AS the session's agent.\n */\nasync function authorConversationReply(input: {\n chatService: ConversationReplyService;\n session: SessionLike;\n tenantId: string;\n threadId: string | null;\n result: ToolLoopResult;\n}): Promise<void> {\n const { sendAgentReply } = await import('./services/ChatService.js');\n for (const invocation of input.result.invocations) {\n if (!invocation.ok) {\n continue;\n }\n await sendAgentReply(input.chatService, {\n tenantId: input.tenantId,\n agentSessionId: input.session.id as string,\n threadId: input.threadId,\n content: JSON.stringify(invocation.observation),\n kind: 'tool',\n messageType: 'tool_result',\n toolCallData: { name: invocation.slug, args: invocation.args },\n });\n }\n await sendAgentReply(input.chatService, {\n tenantId: input.tenantId,\n agentSessionId: input.session.id as string,\n threadId: input.threadId,\n content: input.result.content,\n kind: 'assistant',\n });\n}\n"],"mappings":";;;;;;;;;;;ACkGA,eAAsB,oBACpB,SAC6B;CAC7B,IAAI,CAAC,QAAQ,QAAQ,IACnB,MAAM,IAAI,MACR,+DACF;CAEF,MAAM,cAAc,mBAAmB,QAAQ,OAAO;CAGtD,MAAM,WAAW,OAAM,MADC,mBAAmB,OAAO,EAAE,IAAI,QAAQ,GAAG,CAAC,EAAA,CACnC,OAAO;EACtC,UAAU,QAAQ,QAAQ,YAAY;EACtC,WAAW,QAAQ,QAAQ;EAC3B,YAAY,QAAQ,QAAQ,cAAc;EAC1C;EACA,OAAO,QAAQ;EACf,KAAK,QAAQ;EACb,YAAY,QAAQ;EACpB,QAAQ,kBAAkB,QAAQ,UAAU;EAC5C,eAAe,QAAQ;EACvB,iBAAiB,QAAQ,mBAAmB;EAC5C,QAAQ,QAAQ,UAAU;EAC1B,YAAY,QAAQ,cAAc;EAClC,SAAS,QAAQ,WAAW;EAC5B,SAAS,QAAQ,WAAW;CAC9B,CAAC;CACD,IAAI,QAAQ,UACV,SAAS,YAAY,QAAQ,QAAQ;CAEvC,MAAM,SAAS,K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EAAE;EAAQ;EAAe;EAAU;CAAa;AACzD;AAsCA,eAAsB,qBACpB,SACuB;CACvB,MAAM,eACJ,QAAQ,iBACP,QAAQ,KACL,MAAM,gCAAgC,QAAQ,IAAI,QAAQ,OAAO,IAChE,QAAQ,QAAQ,gBAAgB;CACvC,OAAO,QAAQ,YAAY,yBAAyB;EAClD,gBAAgB,QAAQ,QAAQ;EAChC,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,cAAc,QAAQ,QAAQ;EAC9B,cAAc;CAChB,CAAC;AACH;AAQA,eAAe,wBAAwB,OAMrB;CAChB,MAAM,EAAE,mBAAmB,MAAM,OAAO,mCAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CACxC,KAAA,MAAW,cAAc,MAAM,OAAO,aAAa;EACjD,IAAI,CAAC,WAAW,IACd;EAEF,MAAM,eAAe,MAAM,aAAa;GACtC,UAAU,MAAM;GAChB,gBAAgB,MAAM,QAAQ;GAC9B,UAAU,MAAM;GAChB,SAAS,KAAK,UAAU,WAAW,WAAW;GAC9C,MAAM;GACN,aAAa;GACb,cAAc;IAAE,MAAM,WAAW;IAAM,MAAM,WAAW;GAAK;EAC/D,CAAC;CACH;CACA,MAAM,eAAe,MAAM,aAAa;EACtC,UAAU,MAAM;EAChB,gBAAgB,MAAM,QAAQ;EAC9B,UAAU,MAAM;EAChB,SAAS,MAAM,OAAO;EACtB,MAAM;CACR,CAAC;AACH"}
@@ -1,2 +1,2 @@
1
- import { n as sendAgentReply } from "../chunks/ChatService-hKK-GI17.js";
1
+ import { r as sendAgentReply } from "../chunks/ChatService-BRsE5HmY.js";
2
2
  export { sendAgentReply };
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "version": "1.0.0",
3
- "timestamp": 1783576238922,
3
+ "timestamp": 1783580655772,
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.38.20",
5
+ "packageVersion": "0.38.21",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-chat:AgentSessionCollection": {
8
8
  "name": "agentsessioncollection",
@@ -2805,7 +2805,9 @@
2805
2805
  "smrtDependencies": [
2806
2806
  "@happyvertical/smrt-agents",
2807
2807
  "@happyvertical/smrt-core",
2808
+ "@happyvertical/smrt-personas",
2808
2809
  "@happyvertical/smrt-profiles",
2809
- "@happyvertical/smrt-tenancy"
2810
+ "@happyvertical/smrt-tenancy",
2811
+ "@happyvertical/smrt-users"
2810
2812
  ]
2811
2813
  }
@@ -0,0 +1,207 @@
1
+ import { AIInterface, AIMessage } from '@happyvertical/ai';
2
+ import { PrincipalAuditSink, PrincipalBinding } from '@happyvertical/smrt-agents';
3
+ import { LearningMemoryRecord, LearningSemanticSearch, SmrtClassOptions } from '@happyvertical/smrt-core';
4
+ import { AgentSession } from './models/AgentSession.js';
5
+ import { ManifestTool, ToolLoopResult } from './tool-loop.js';
6
+ /**
7
+ * The structural persona shape the conversation binding needs. Both a
8
+ * `ResolvedPersona` (from `PersonaResolver.resolve()`) and a raw `AgentPersona`
9
+ * satisfy it via the adapters below.
10
+ */
11
+ export interface ConversationPersona {
12
+ /** Persona id — required to scope learning memory and prompt overrides. */
13
+ id?: string | null;
14
+ /** Owning tenant. */
15
+ tenantId: string | null;
16
+ /** Canonical agent class the persona configures. */
17
+ agentClass?: string;
18
+ /** The user whose live permissions bound the conversation. */
19
+ runAsUserId: string;
20
+ /** Optional acting `Bot` profile id (identity/audit). */
21
+ actsAsProfileId?: string | null;
22
+ /** The persona's tool allow-list (already capped by the class ceiling). */
23
+ allowedTools: string[];
24
+ /** Behavioural instructions / system prompt. */
25
+ instructions?: string;
26
+ /** Learning memory partition key. */
27
+ memoryScope?: string;
28
+ }
29
+ /** Adapt a `PersonaResolver.resolve()` result into a {@link ConversationPersona}. */
30
+ export declare function conversationPersonaFromResolved(resolved: {
31
+ personaId?: string;
32
+ tenantId: string;
33
+ agentClass: string;
34
+ runAsUserId?: string;
35
+ actsAsProfileId?: string | null;
36
+ allowedTools: string[];
37
+ instructions: string;
38
+ memoryScope: string;
39
+ }): ConversationPersona;
40
+ /** Adapt a raw `AgentPersona` row into a {@link ConversationPersona}. */
41
+ export declare function conversationPersonaFromAgentPersona(persona: {
42
+ id?: string | null;
43
+ tenantId: string;
44
+ agentClass: string;
45
+ runAsUserId: string;
46
+ actsAsProfileId?: string | null;
47
+ instructions: string;
48
+ memoryScope?: string;
49
+ getAllowedTools: () => string[];
50
+ }): ConversationPersona;
51
+ /**
52
+ * Project a {@link ConversationPersona} into the {@link PrincipalBinding} the
53
+ * tool loop runs as. The persona's `allowedTools` is the fail-closed whitelist
54
+ * (absent/empty ⇒ no tools).
55
+ */
56
+ export declare function principalBindingFor(persona: ConversationPersona): PrincipalBinding;
57
+ /** How to recall a persona's learning memory into the conversation context. */
58
+ export interface PersonaRecallOptions {
59
+ /** Learning scope to recall (defaults to `'chat'`). */
60
+ scope?: string;
61
+ /** Exact episode key within the scope (omit for a scope-wide recall). */
62
+ key?: string;
63
+ /** Free-text query for the semantic arm (needs a `semanticSearch`). */
64
+ query?: string;
65
+ /** Max recalled records injected into context. Default 5. */
66
+ limit?: number;
67
+ /** Override the reuse floor for this recall. */
68
+ minConfidence?: number;
69
+ /** Optional embedding search for the semantic recall arm. */
70
+ semanticSearch?: LearningSemanticSearch;
71
+ }
72
+ /**
73
+ * Recall the persona's confidence-filtered learning memory.
74
+ *
75
+ * Isolated per persona by `memoryScope`, so what the "Support" persona learned
76
+ * never bleeds into "Sales". Returns `[]` for a persona with no memory scope /
77
+ * id (nothing to partition on).
78
+ */
79
+ export declare function recallPersonaMemory(db: SmrtClassOptions['db'], persona: ConversationPersona, options?: PersonaRecallOptions): Promise<LearningMemoryRecord[]>;
80
+ /**
81
+ * Format recalled memory into a system-context block. Empty string when there
82
+ * is nothing to inject (so it can be unconditionally concatenated).
83
+ */
84
+ export declare function formatRecalledMemory(records: LearningMemoryRecord[]): string;
85
+ /**
86
+ * Resolve the persona's effective instructions.
87
+ *
88
+ * Prefers the prompt-system resolution (`resolvePersonaInstructions`, which
89
+ * layers any approved learned-directive override) when the persona is persisted;
90
+ * falls back to the inline `persona.instructions`. This is how a conversation
91
+ * "uses its instructions (`applyPersonaInstructions`)".
92
+ */
93
+ export declare function resolveConversationInstructions(db: SmrtClassOptions['db'], persona: ConversationPersona): Promise<string>;
94
+ /** The minimal AgentSession surface the turn needs. */
95
+ type SessionLike = Pick<AgentSession, 'id' | 'chatRoomId' | 'systemPrompt'>;
96
+ /** The minimal ChatService surface the turn needs to author the reply. */
97
+ export interface ConversationReplyService {
98
+ initialize(): Promise<void>;
99
+ }
100
+ /**
101
+ * Options for {@link runPersonaConversationTurn}.
102
+ */
103
+ export interface PersonaConversationTurnOptions {
104
+ /** The AI boundary. */
105
+ ai: AIInterface;
106
+ /** The database handle side-door operations run against. */
107
+ db: SmrtClassOptions['db'];
108
+ /** The persona the conversation is bound to. */
109
+ persona: ConversationPersona;
110
+ /** The user's message this turn. */
111
+ userMessage: string;
112
+ /** Tenant the turn runs within. */
113
+ tenantId: string;
114
+ /** Prior conversation turns (assistant/user), oldest first. */
115
+ history?: AIMessage[];
116
+ /**
117
+ * The bound agent session. When provided together with `chatService`, the
118
+ * agent reply is authored into the session's room and each executed tool is
119
+ * recorded as a `tool_result` message (gated by the session allow-list).
120
+ */
121
+ session?: SessionLike | null;
122
+ /** Chat service used to author the agent reply. */
123
+ chatService?: ConversationReplyService | null;
124
+ /** Thread to attach authored messages to. */
125
+ threadId?: string | null;
126
+ /** Recall configuration, or `false` to skip memory recall. */
127
+ recall?: PersonaRecallOptions | false;
128
+ /** Pre-built tool catalog (else derived from the persona's `allowedTools`). */
129
+ tools?: ManifestTool[];
130
+ /** Max tool-executing rounds. */
131
+ maxSteps?: number;
132
+ /** Model id. */
133
+ model?: string;
134
+ /** Sampling temperature. */
135
+ temperature?: number;
136
+ /** Max tokens per completion. */
137
+ maxTokens?: number;
138
+ /** Originating user the turn runs on behalf of (audited). */
139
+ onBehalfOfUserId?: string | null;
140
+ /** Audit sink for the on-behalf-of entry (forwarded to `executeAsPrincipal`). */
141
+ audit?: PrincipalAuditSink;
142
+ /** Opt into Postgres RLS transaction wrapping. */
143
+ postgresRls?: boolean;
144
+ /** Correlation id for the turn (feedback ties back to it). Auto-generated when omitted. */
145
+ correlationId?: string;
146
+ }
147
+ /** The outcome of a persona-bound conversation turn. */
148
+ export interface PersonaConversationTurnResult {
149
+ /** The tool-loop result (final text, invocations, transcript). */
150
+ result: ToolLoopResult;
151
+ /** The correlation id feedback on this turn should reference. */
152
+ correlationId: string;
153
+ /** The memory recalled into the turn's context. */
154
+ recalled: LearningMemoryRecord[];
155
+ /** The system prompt assembled for the turn. */
156
+ systemPrompt: string;
157
+ }
158
+ /**
159
+ * Run one turn of a persona-bound conversation.
160
+ *
161
+ * Binds the conversation to the persona: recalls its learning memory, resolves
162
+ * its instructions, offers only its allow-listed manifest operations, and runs
163
+ * the bounded tool loop as its principal. When a `chatService` + `session` are
164
+ * given the assistant reply (and each executed tool) is authored into the room,
165
+ * exercising the chat layer's own fail-closed tool gate.
166
+ *
167
+ * @returns The loop result, the turn's correlation id, and the recalled memory.
168
+ */
169
+ export declare function runPersonaConversationTurn(options: PersonaConversationTurnOptions): Promise<PersonaConversationTurnResult>;
170
+ /**
171
+ * Options for {@link bindPersonaToSession}.
172
+ */
173
+ export interface BindPersonaToSessionOptions {
174
+ /** Chat service exposing the owner-checked `updateAgentSessionConfig`. */
175
+ chatService: {
176
+ updateAgentSessionConfig(params: {
177
+ agentSessionId: string;
178
+ actorProfileId: string;
179
+ tenantId: string | null;
180
+ allowedTools?: string[];
181
+ systemPrompt?: string;
182
+ }): Promise<AgentSession>;
183
+ };
184
+ /** The session to bind. */
185
+ session: Pick<AgentSession, 'id'>;
186
+ /** The session owner (the update is owner-checked, S5 #1392). */
187
+ actorProfileId: string;
188
+ /** Tenant the session belongs to. */
189
+ tenantId: string | null;
190
+ /** The persona to bind the session to. */
191
+ persona: ConversationPersona;
192
+ /** Instructions to set as the session system prompt (else resolved). */
193
+ instructions?: string;
194
+ /** Database handle used to resolve instructions when not supplied. */
195
+ db?: SmrtClassOptions['db'];
196
+ }
197
+ /**
198
+ * Bind an {@link AgentSession} to a persona: mirror the persona's `allowedTools`
199
+ * and instructions onto the session so the chat layer's own fail-closed tool
200
+ * gate (S5 #1392) agrees with the loop's, and the session's system prompt speaks
201
+ * the persona's voice. This is the durable side of the `chat → personas` bridge:
202
+ * once bound, the session's authoring gate and the loop's offer gate share one
203
+ * allow-list.
204
+ */
205
+ export declare function bindPersonaToSession(options: BindPersonaToSessionOptions): Promise<AgentSession>;
206
+ export {};
207
+ //# sourceMappingURL=persona-conversation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persona-conversation.d.ts","sourceRoot":"","sources":["../src/persona-conversation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EACV,oBAAoB,EACpB,sBAAsB,EACtB,gBAAgB,EACjB,MAAM,0BAA0B,CAAC;AAMlC,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAEL,KAAK,YAAY,EAEjB,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAExB;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,2EAA2E;IAC3E,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,qBAAqB;IACrB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8DAA8D;IAC9D,WAAW,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,2EAA2E;IAC3E,YA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AAC,CAAC;KAC3B,CAAC;IACF,2BAA2B;IAC3B,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;IAClC,iEAAiE;IACjE,cAAc,EAAE,MAAM,CAAC;IACvB,qCAAqC;IACrC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,0CAA0C;IAC1C,OAAO,EAAE,mBAAmB,CAAC;IAC7B,wEAAwE;IACxE,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sEAAsE;IACtE,EAAE,CAAC,EAAE,gBAAgB,CAAC,IAAI,CAAC,CAAC;CAC7B;AAED;;;;;;;GAOG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,YAAY,CAAC,CAavB"}
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-07-09T05:50:39.842Z",
3
+ "generatedAt": "2026-07-09T07:04:16.391Z",
4
4
  "packageName": "@happyvertical/smrt-chat",
5
- "packageVersion": "0.38.20",
5
+ "packageVersion": "0.38.21",
6
6
  "sourceManifestPath": "dist/manifest.json",
7
7
  "agentDocPath": "AGENTS.md",
8
8
  "sourceHashes": {
9
- "manifest": "b514d5d429a94461646e28d6a5627a27e4af2b5e661b814783693cc1775c4450",
10
- "packageJson": "8efa6696eeb471767d9029567fb3adf96922d0d9afe71c5f3c24f83f6c0310c6",
11
- "agents": "e0a8c6788fbd48c2619a353295d4538e9ff6863d483bcd354af522fb7c6a31bc"
9
+ "manifest": "29c7f2167abe85e4c49227122c589032e32d6249015a9e476e3a4aa00476fd5c",
10
+ "packageJson": "70e56d899d4f84a3c38147887467c9f4c9fe8a75d909f42a7ec2419a95bbe8a2",
11
+ "agents": "27d591888108d6145f939e2cb25069211b0411cffc6cc87e119965d9be982813"
12
12
  },
13
13
  "exports": [
14
14
  ".",
@@ -20,11 +20,15 @@
20
20
  "./ui"
21
21
  ],
22
22
  "dependencies": {
23
+ "@happyvertical/ai": "catalog:",
24
+ "@happyvertical/smrt-agents": "workspace:*",
23
25
  "@happyvertical/smrt-core": "workspace:*",
26
+ "@happyvertical/smrt-personas": "workspace:*",
24
27
  "@happyvertical/smrt-tenancy": "workspace:*",
25
28
  "@happyvertical/smrt-types": "workspace:*",
26
29
  "@happyvertical/smrt-ui": "workspace:*",
27
- "@happyvertical/smrt-agents": "workspace:*",
30
+ "@happyvertical/smrt-users": "workspace:*",
31
+ "@happyvertical/sql": "catalog:",
28
32
  "@happyvertical/smrt-profiles": "workspace:*",
29
33
  "@happyvertical/smrt-vitest": "workspace:*",
30
34
  "@sveltejs/package": "^2.5.8",
@@ -40,13 +44,18 @@
40
44
  "smrtDependencies": [
41
45
  "@happyvertical/smrt-agents",
42
46
  "@happyvertical/smrt-core",
47
+ "@happyvertical/smrt-personas",
43
48
  "@happyvertical/smrt-profiles",
44
49
  "@happyvertical/smrt-tenancy",
45
50
  "@happyvertical/smrt-types",
46
51
  "@happyvertical/smrt-ui",
52
+ "@happyvertical/smrt-users",
47
53
  "@happyvertical/smrt-vitest"
48
54
  ],
49
- "sdkDependencies": [],
55
+ "sdkDependencies": [
56
+ "@happyvertical/ai",
57
+ "@happyvertical/sql"
58
+ ],
50
59
  "tags": [],
51
60
  "risks": [],
52
61
  "objects": [
@@ -1503,5 +1512,5 @@
1503
1512
  "polymorphicAssociations": 0,
1504
1513
  "uuidColumns": 33
1505
1514
  },
1506
- "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Models\n\nInternal models — all mutations go through the membership/owner-checked `ChatService` (S5 #1392). EVERY `@smrt()` model in this package (ChatRoom, ChatMessage, ChatParticipant, ChatThread, ChatReaction, AgentSession) 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`) 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\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\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"
1515
+ "agentDoc": "# @happyvertical/smrt-chat\n\nChat rooms, threads, and agent sessions with app-controlled tool whitelisting.\n\n## Models\n\nInternal models — all mutations go through the membership/owner-checked `ChatService` (S5 #1392). EVERY `@smrt()` model in this package (ChatRoom, ChatMessage, ChatParticipant, ChatThread, ChatReaction, AgentSession) 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`) 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\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\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- **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## 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"
1507
1516
  }