@firstlovecenter/ai-chat 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/dist/drizzle/index.cjs +24 -16
- package/dist/drizzle/index.cjs.map +1 -1
- package/dist/drizzle/index.d.cts +17 -17
- package/dist/drizzle/index.d.ts +17 -17
- package/dist/drizzle/index.js +24 -16
- package/dist/drizzle/index.js.map +1 -1
- package/dist/prisma/index.cjs +20 -4
- package/dist/prisma/index.cjs.map +1 -1
- package/dist/prisma/index.d.cts +19 -10
- package/dist/prisma/index.d.ts +19 -10
- package/dist/prisma/index.js +20 -4
- package/dist/prisma/index.js.map +1 -1
- package/dist/server/index.cjs +5 -5
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +5 -5
- package/dist/server/index.js.map +1 -1
- package/dist/{types-BnwUkqKb.d.cts → types-BOgBJ7CD.d.cts} +14 -8
- package/dist/{types-BnwUkqKb.d.ts → types-BOgBJ7CD.d.ts} +14 -8
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.d.cts +3 -3
- package/dist/ui/index.d.ts +3 -3
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
- package/prisma/chat-models.prisma +7 -3
package/dist/prisma/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/ports/types.ts","../../src/adapters/prisma/adapter.ts","../../src/adapters/prisma/schema.ts"],"names":[],"mappings":";AAmFO,IAAM,4BAAA,GAA+B,IAAA;;;AC6D5C,IAAM,SAAA,GAAY,CAAC,GAAA,MAAsC;AAAA,EACvD,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AAAA,EACjB,MAAA,EAAQ,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AAAA,EACzB,OAAO,GAAA,CAAI,KAAA;A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;AAAA,IAIA,MAAM,aAAA,GAAqC;AACzC,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,UAAA,CAAW,UAAA,CAAW,EAAE,KAAA,EAAO,EAAE,EAAA,EAAI,CAAA,EAAE,EAAG,CAAA;AACnE,MAAA,OAAO,MAAM,YAAA,CAAa,GAAG,CAAA,GAAI,EAAE,GAAG,mBAAA,EAAoB;AAAA,IAC5D,CAAA;AAAA,IAEA,MAAM,gBAAA,CACJ,KAAA,EACA,QAAA,EACqB;AACrB,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,UAAA,CAAW,MAAA,CAAO;AAAA,QACzC,KAAA,EAAO,EAAE,EAAA,EAAI,CAAA,EAAE;AAAA,QACf,QAAQ,EAAE,EAAA,EAAI,GAAG,GAAG,KAAA,EAAO,iBAAiB,QAAA,EAAS;AAAA,QACrD,MAAA,EAAQ,EAAE,GAAG,KAAA,EAAO,iBAAiB,QAAA;AAAS,OAC/C,CAAA;AACD,MAAA,OAAO,aAAa,GAAG,CAAA;AAAA,IACzB;AAAA,GACF;AACF;;;AC9RO,IAAM,oBAAA,GAA+B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA","file":"index.js","sourcesContent":["/**\n * Ports — the contract between this package and any host that consumes it.\n *\n * Every project-specific concern (auth, scope, persistence, tools, credentials)\n * crosses the boundary as a typed port the host implements and passes into\n * `configureAiChat({...})`. The package itself has zero knowledge of the\n * host's database, RBAC model, or environment.\n *\n * Domain types (ChatSession, ChatMessage, AiSettings, PresentPayload, Block)\n * are pure TS — no ORM coupling. The Drizzle and Prisma adapters each map\n * their respective row types into these shapes so callers see one contract\n * regardless of the chosen ORM.\n */\nimport type { GoogleAuth } from 'google-auth-library';\nimport type { ToolDefinition, ToolContext, SystemBlock } from '../tools/types';\n\n// ---------------------------------------------------------------------------\n// Domain types — used by every port\n// ---------------------------------------------------------------------------\n\nexport type ChatSession = {\n id: number;\n userId: number;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type ChatMessageRole = 'user' | 'assistant';\n\n/**\n * One message turn. For 'user' rows, `question` carries the raw question text.\n * For 'assistant' rows, `blocks` holds the structured PresentPayload and\n * `prose` holds any paragraph_brief prose collected from the streamed\n * narrator. `errorJson` is set when an assistant turn failed mid-stream.\n */\nexport type ChatMessage = {\n id: number;\n sessionId: number;\n role: ChatMessageRole;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n createdAt: Date;\n};\n\n/**\n * Singleton row controlling global AI runtime settings. All open-string\n * fields are validated at runtime against the registries the host configures\n * — they are not enums in the package's types so consumers can register\n * additional providers / interfaces without a schema change.\n *\n * `maxOutputTokens` caps both the agent loop's per-turn output AND each\n * narrator's prose pass. Reasoning models (e.g. `xai/grok-4.1-fast-reasoning`)\n * charge internal thinking against this budget — set it generously when\n * those are in use.\n *\n * `rolePrompt` is the persona the assistant adopts. When non-null, it\n * takes precedence over the host's static `rolePrompt` configureAiChat\n * option, so admins can edit live in the settings UI.\n *\n * `gcpProjectId` is an admin-editable override for the GCP project that\n * every Vertex API call targets. When non-null, it takes precedence over\n * the host's static `VertexPort.projectId` so admins can flip projects\n * (staging ↔ prod, multi-tenant) without redeploying.\n */\nexport type AiSettings = {\n toolProvider: string;\n gcpLocation: string;\n chatInterface: string;\n maxOutputTokens: number;\n rolePrompt: string | null;\n gcpProjectId: string | null;\n updatedAt: Date | null;\n updatedByUserId: number | null;\n};\n\n/**\n * Default cap when nothing is persisted. Conservative so non-reasoning\n * models don't pay for headroom they don't need; admins bump it for\n * reasoning models via the settings UI.\n */\nexport const DEFAULT_AI_MAX_OUTPUT_TOKENS = 4096;\n\n// ---------------------------------------------------------------------------\n// AuthPort — the host tells us who's calling\n// ---------------------------------------------------------------------------\n\n/**\n * The host's resolved Scope (org/tenant/RBAC shape) is opaque to the package.\n * `S` is whatever the host wants — typically a discriminated union with at\n * least `userId: number` plus role/tenancy fields.\n */\nexport type AuthOk<S> = { ok: true; scope: S; userId: number };\nexport type AuthFail = { ok: false; response: Response };\nexport type AuthResult<S> = AuthOk<S> | AuthFail;\n\nexport type AuthPort<S = unknown> = {\n /**\n * Resolve the calling user from the request. Returning `{ ok: false }`\n * lets the route hand back the prepared 401/403 response untouched.\n */\n requireAuth(req: Request): Promise<AuthResult<S>>;\n /**\n * Predicate the admin-settings route uses to gate writes. Hosts that\n * don't model admins can return `() => true` if they trust their own\n * routing layer.\n */\n isSuperAdmin(scope: S): boolean;\n};\n\n// ---------------------------------------------------------------------------\n// ScopePort — human-readable scope description fed into the system prompt\n// ---------------------------------------------------------------------------\n\nexport type ScopePort<S = unknown> = {\n /** Short label rendered in the chat UI (e.g. \"Ghana\", \"All countries\"). */\n resolveScopeLabel(scope: S): Promise<string>;\n /** Longer narrative the system prompt uses to describe the data slice. */\n buildScopeSummary(scope: S): Promise<string>;\n};\n\n// ---------------------------------------------------------------------------\n// ToolsPort — host supplies its own tool registry + system prompts\n// ---------------------------------------------------------------------------\n\nexport type ToolsPort = {\n /**\n * Map of tool name → definition. Keys must match `definition.schema.name`.\n * Must include the terminal `present` tool — the agent loop refuses to\n * end a turn without it.\n */\n tools: Record<string, ToolDefinition>;\n /**\n * Build the ordered list of system blocks for one agent run. The host\n * decides how much of the prompt is project-specific (schema doc,\n * semantic-layer doc, scope summary, etc.). Blocks marked `cached: true`\n * become Anthropic ephemeral cache markers and Vertex prefix-cache hints.\n */\n buildSystemBlocks(ctx: ToolContext): Promise<SystemBlock[]>;\n};\n\n// ---------------------------------------------------------------------------\n// VertexPort — credentials are host-supplied; the package never reads env\n// ---------------------------------------------------------------------------\n\nexport type VertexPort = {\n projectId: string;\n /** e.g. 'us-east5' or 'global' — used unless `aiSettings.gcpLocation` overrides per-request. */\n defaultLocation: string;\n /**\n * A constructed `GoogleAuth` instance. Any auth scheme that yields one\n * works (ADC, Workload Identity Federation, split-key env vars,\n * Secret Manager, etc.). The package never reads `process.env.GCP_*`.\n */\n auth: GoogleAuth;\n /** Vertex model IDs pinned by the host (orgs pin their own versions). */\n modelIds: { claude: string; gemini: string };\n};\n\n// ---------------------------------------------------------------------------\n// LoggerPort — optional structured logging\n// ---------------------------------------------------------------------------\n\nexport type LoggerPort = {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n};\n\n// ---------------------------------------------------------------------------\n// PersistencePort — domain-shaped queries the package needs\n// ---------------------------------------------------------------------------\n\nexport type CreateSessionInput = {\n userId: number;\n title: string;\n};\n\nexport type AppendMessageInput = {\n sessionId: number;\n role: ChatMessageRole;\n question?: string | null;\n blocks?: unknown | null;\n prose?: unknown | null;\n errorJson?: unknown | null;\n};\n\nexport type ListSessionsOpts = {\n limit?: number;\n};\n\nexport type AiSettingsPatch = {\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n /** Pass `null` to clear back to the host's static fallback. */\n rolePrompt?: string | null;\n /** Pass `null` to clear back to the host's static VertexPort.projectId. */\n gcpProjectId?: string | null;\n};\n\n/**\n * The whole reason this package is ORM-agnostic. Implemented by:\n * - createDrizzlePersistence (src/adapters/drizzle/)\n * - createPrismaPersistence (src/adapters/prisma/)\n * - createMemoryPersistence (src/adapters/memory/, internal test use)\n *\n * Routes, agent loop, and UI never touch ORMs directly — they only call\n * methods on this port. A parameterized contract test runs the same\n * assertions against all three adapters to keep them in sync.\n */\nexport type PersistencePort = {\n // Sessions ---------------------------------------------------------------\n createSession(input: CreateSessionInput): Promise<ChatSession>;\n /** Returns null when the session doesn't exist OR doesn't belong to this user. */\n getSession(id: number, userId: number): Promise<ChatSession | null>;\n listSessionsForUser(userId: number, opts?: ListSessionsOpts): Promise<ChatSession[]>;\n /** No-op when session doesn't exist or doesn't belong to user — caller asserted authorisation. */\n updateSession(id: number, userId: number, patch: { title?: string }): Promise<void>;\n deleteSession(id: number, userId: number): Promise<void>;\n\n // Messages ---------------------------------------------------------------\n appendMessage(input: AppendMessageInput): Promise<ChatMessage>;\n listMessagesForSession(sessionId: number, userId: number): Promise<ChatMessage[]>;\n\n // AI settings (singleton row) -------------------------------------------\n /** Returns the singleton row, applying defaults if it's never been written. */\n getAiSettings(): Promise<AiSettings>;\n /**\n * Upsert. Validates `toolProvider` and `chatInterface` against the runtime\n * registries before writing — invalid values throw before SQL is issued.\n */\n updateAiSettings(patch: AiSettingsPatch, byUserId: number): Promise<AiSettings>;\n};\n","/**\n * Prisma `PersistencePort` adapter.\n *\n * Hosts call `createPrismaPersistence(prisma)` with their own configured\n * `PrismaClient` and pass the result to `configureAiChat({ persistence, ... })`.\n *\n * The concrete `PrismaClient` is an OPTIONAL peer dep, so this module never\n * imports a runtime value from `@prisma/client`. Instead it accepts a\n * structural duck-typed shape covering only the delegate methods the port\n * uses. Any object that satisfies `PrismaLike` works — including a real\n * `PrismaClient`, a Prisma extension proxy, or a hand-rolled fake in tests.\n *\n * BigInt note: Prisma returns row IDs as JavaScript `BigInt`. Domain types\n * use plain `number` (sessions/messages are nowhere near 2^53). The adapter\n * widens via `Number(row.id)` on every read; writes accept `number` and\n * Prisma narrows internally.\n */\nimport {\n DEFAULT_AI_MAX_OUTPUT_TOKENS,\n type AiSettings,\n type AiSettingsPatch,\n type AppendMessageInput,\n type ChatMessage,\n type ChatMessageRole,\n type ChatSession,\n type CreateSessionInput,\n type ListSessionsOpts,\n type PersistencePort\n} from '../../server/ports/types';\n\n// ---------------------------------------------------------------------------\n// Structural Prisma shape — covers exactly what this adapter touches.\n// Avoids a value-level dependency on `@prisma/client` (optional peer dep).\n// ---------------------------------------------------------------------------\n\ntype ChatSessionRow = {\n id: bigint | number;\n userId: bigint | number;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype ChatMessageRow = {\n id: bigint | number;\n sessionId: bigint | number;\n role: string;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n createdAt: Date;\n};\n\ntype AiSettingsRow = {\n id: number;\n toolProvider: string;\n gcpLocation: string;\n chatInterface: string;\n maxOutputTokens: number;\n rolePrompt: string | null;\n gcpProjectId: string | null;\n updatedAt: Date | null;\n updatedByUserId: bigint | number | null;\n};\n\ntype ChatSessionDelegate = {\n create(args: {\n data: { userId: number; title: string };\n }): Promise<ChatSessionRow>;\n findFirst(args: {\n where: { id: number; userId: number };\n }): Promise<ChatSessionRow | null>;\n findMany(args: {\n where: { userId: number };\n orderBy: { updatedAt: 'desc' };\n take?: number;\n }): Promise<ChatSessionRow[]>;\n update(args: {\n where: { id: number };\n data: { title?: string; updatedAt?: Date };\n }): Promise<ChatSessionRow>;\n updateMany(args: {\n where: { id: number; userId: number };\n data: { title?: string; updatedAt?: Date };\n }): Promise<{ count: number }>;\n deleteMany(args: {\n where: { id: number; userId: number };\n }): Promise<{ count: number }>;\n};\n\ntype ChatMessageDelegate = {\n create(args: {\n data: {\n sessionId: number;\n role: ChatMessageRole;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n };\n }): Promise<ChatMessageRow>;\n findMany(args: {\n where: { sessionId: number };\n orderBy: { createdAt: 'asc' };\n }): Promise<ChatMessageRow[]>;\n};\n\ntype AiSettingsDelegate = {\n findUnique(args: { where: { id: number } }): Promise<AiSettingsRow | null>;\n upsert(args: {\n where: { id: number };\n create: {\n id: number;\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n rolePrompt?: string | null;\n gcpProjectId?: string | null;\n updatedByUserId: number;\n };\n update: {\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n rolePrompt?: string | null;\n gcpProjectId?: string | null;\n updatedByUserId: number;\n };\n }): Promise<AiSettingsRow>;\n};\n\nexport type PrismaLike = {\n chatSession: ChatSessionDelegate;\n chatMessage: ChatMessageDelegate;\n aiSettings: AiSettingsDelegate;\n};\n\n// ---------------------------------------------------------------------------\n// Row -> domain mappers\n// ---------------------------------------------------------------------------\n\nconst toSession = (row: ChatSessionRow): ChatSession => ({\n id: Number(row.id),\n userId: Number(row.userId),\n title: row.title,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt\n});\n\nconst toMessage = (row: ChatMessageRow): ChatMessage => ({\n id: Number(row.id),\n sessionId: Number(row.sessionId),\n // Stored as VARCHAR(16) but constrained to ChatMessageRole at write time.\n role: row.role as ChatMessageRole,\n question: row.question,\n blocks: row.blocks,\n prose: row.prose,\n errorJson: row.errorJson,\n createdAt: row.createdAt\n});\n\nconst toAiSettings = (row: AiSettingsRow): AiSettings => ({\n toolProvider: row.toolProvider,\n gcpLocation: row.gcpLocation,\n chatInterface: row.chatInterface,\n maxOutputTokens: row.maxOutputTokens,\n rolePrompt: row.rolePrompt,\n gcpProjectId: row.gcpProjectId,\n updatedAt: row.updatedAt,\n updatedByUserId: row.updatedByUserId === null ? null : Number(row.updatedByUserId)\n});\n\nconst DEFAULT_AI_SETTINGS: AiSettings = {\n toolProvider: 'claude',\n gcpLocation: 'us-east5',\n chatInterface: 'custom',\n maxOutputTokens: DEFAULT_AI_MAX_OUTPUT_TOKENS,\n rolePrompt: null,\n gcpProjectId: null,\n updatedAt: null,\n updatedByUserId: null\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createPrismaPersistence(prisma: PrismaLike): PersistencePort {\n return {\n // Sessions ---------------------------------------------------------------\n\n async createSession(input: CreateSessionInput): Promise<ChatSession> {\n const row = await prisma.chatSession.create({\n data: { userId: input.userId, title: input.title }\n });\n return toSession(row);\n },\n\n async getSession(id: number, userId: number): Promise<ChatSession | null> {\n const row = await prisma.chatSession.findFirst({ where: { id, userId } });\n return row ? toSession(row) : null;\n },\n\n async listSessionsForUser(\n userId: number,\n opts?: ListSessionsOpts\n ): Promise<ChatSession[]> {\n const rows = await prisma.chatSession.findMany({\n where: { userId },\n orderBy: { updatedAt: 'desc' },\n take: opts?.limit\n });\n return rows.map(toSession);\n },\n\n async updateSession(\n id: number,\n userId: number,\n patch: { title?: string }\n ): Promise<void> {\n // updateMany so the userId scope filters; no-ops cleanly when the\n // session doesn't exist or belongs to another user.\n await prisma.chatSession.updateMany({\n where: { id, userId },\n data: { ...patch, updatedAt: new Date() }\n });\n },\n\n async deleteSession(id: number, userId: number): Promise<void> {\n await prisma.chatSession.deleteMany({ where: { id, userId } });\n },\n\n // Messages ---------------------------------------------------------------\n\n async appendMessage(input: AppendMessageInput): Promise<ChatMessage> {\n const row = await prisma.chatMessage.create({\n data: {\n sessionId: input.sessionId,\n role: input.role,\n question: input.question ?? null,\n blocks: input.blocks ?? null,\n prose: input.prose ?? null,\n errorJson: input.errorJson ?? null\n }\n });\n // Bump the parent session's `updatedAt` so `listSessionsForUser`\n // reflects \"most recent activity\" rather than creation time. Done\n // as a separate update so the message insert remains the source of\n // truth for ordering across replicas.\n await prisma.chatSession.update({\n where: { id: input.sessionId },\n data: { updatedAt: new Date() }\n });\n return toMessage(row);\n },\n\n async listMessagesForSession(\n sessionId: number,\n userId: number\n ): Promise<ChatMessage[]> {\n // Re-assert ownership before returning rows. A caller passing a\n // sessionId they don't own should get an empty list, not someone\n // else's transcript.\n const session = await prisma.chatSession.findFirst({\n where: { id: sessionId, userId }\n });\n if (!session) return [];\n const rows = await prisma.chatMessage.findMany({\n where: { sessionId },\n orderBy: { createdAt: 'asc' }\n });\n return rows.map(toMessage);\n },\n\n // AI settings (singleton row at id=1) -----------------------------------\n\n async getAiSettings(): Promise<AiSettings> {\n const row = await prisma.aiSettings.findUnique({ where: { id: 1 } });\n return row ? toAiSettings(row) : { ...DEFAULT_AI_SETTINGS };\n },\n\n async updateAiSettings(\n patch: AiSettingsPatch,\n byUserId: number\n ): Promise<AiSettings> {\n const row = await prisma.aiSettings.upsert({\n where: { id: 1 },\n create: { id: 1, ...patch, updatedByUserId: byUserId },\n update: { ...patch, updatedByUserId: byUserId }\n });\n return toAiSettings(row);\n }\n };\n}\n","/**\n * The Prisma schema fragment hosts paste into their own `schema.prisma`.\n *\n * Kept in lock-step with `prisma/chat-models.prisma` at the package root.\n * The fragment is inlined here (not read from disk) so consumer bundlers\n * never need to resolve a runtime fs path.\n *\n * Codegen tooling can import this constant and write it out, splice it into\n * a host's `schema.prisma`, etc.\n */\nexport const prismaSchemaFragment: string = `// =============================================================================\n// @firstlovecenter/ai-chat — Prisma schema fragment\n// =============================================================================\n//\n// HOSTS: copy the three models below into your own \\`schema.prisma\\`, then run\n//\n// pnpm prisma generate\n// pnpm prisma migrate dev --name flc_ai_chat\n//\n// Column names, SQL types, and indexes match the Drizzle adapter shipped at\n// \\`@firstlovecenter/ai-chat/server/drizzle\\` byte-for-byte, so the underlying MySQL schema\n// is identical regardless of which ORM your host picks. A host could swap\n// from one adapter to the other without touching data.\n// =============================================================================\n\nmodel ChatSession {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n userId BigInt @map(\"user_id\") @db.UnsignedBigInt\n title String @db.VarChar(200)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.DateTime(0)\n updatedAt DateTime @default(now()) @map(\"updated_at\") @db.DateTime(0)\n\n @@index([userId, updatedAt], map: \"idx_chat_session_user_updated\")\n @@map(\"chat_sessions\")\n}\n\nmodel ChatMessage {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n sessionId BigInt @map(\"session_id\") @db.UnsignedBigInt\n role String @db.VarChar(16)\n question String? @db.Text\n blocks Json?\n prose Json?\n errorJson Json? @map(\"error_json\")\n createdAt DateTime @default(now()) @map(\"created_at\") @db.DateTime(0)\n\n @@index([sessionId, createdAt], map: \"idx_chat_msg_session_created\")\n @@map(\"chat_messages\")\n}\n\nmodel AiSettings {\n id Int @id @default(1) @db.UnsignedTinyInt\n toolProvider String @default(\"claude\") @map(\"tool_provider\") @db.VarChar(32)\n gcpLocation String @default(\"us-east5\") @map(\"gcp_location\") @db.VarChar(32)\n chatInterface String @default(\"custom\") @map(\"chat_interface\") @db.VarChar(32)\n updatedAt DateTime @default(now()) @map(\"updated_at\") @db.DateTime(0)\n updatedByUserId BigInt? @map(\"updated_by_user_id\") @db.UnsignedBigInt\n\n @@map(\"ai_settings\")\n}\n`;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/ports/types.ts","../../src/server/uid.ts","../../src/adapters/prisma/adapter.ts","../../src/adapters/prisma/schema.ts"],"names":[],"mappings":";;;AAyFO,IAAM,4BAAA,GAA+B,IAAA;AC9E5C,IAAM,QAAA,GACJ,kEAAA;AAEK,IAAM,eAAA,GAAkB,EAAA;AAExB,SAAS,eAAA,CAAgB,OAAe,eAAA,EAAyB;AACtE,EAAA,MAAM,KAAA,GAAQ,YAAY,IAAI,CAAA;AAC9B,EAAA,IAAI,EAAA,GAAK,EAAA;AACT,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,EAAM,KAAK,CAAA,EAAG;AAEhC,IAAA,EAAA,IAAM,QAAA,CAAS,KAAA,CAAM,CAAC,CAAA,GAAI,EAAE,CAAA;AAAA,EAC9B;AACA,EAAA,OAAO,EAAA;AACT;;;AC6HA,IAAM,SAAA,GAAY,CAAC,GAAA,MAAsC;AAAA,EACvD,IAAI,GAAA,CAAI,EAAA;AAAA,EACR,MAAA,EAAQ,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AAAA,EACzB,OAAO,GAAA,CAAI,KAAA;AAAA,EACX,WAAW,GAAA,CAAI,SAAA;AAAA,EACf,WAAW,GAAA,CAAI;AACjB,CAAA,CAAA;AAEA,IAAM,SAAA,GAAY,CAAC,GAAA,MAAsC;AAAA,EACvD,IAAI,GAAA,CAAI,EAAA;AAAA,EACR,WAAW,GAAA,CA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AA,GAAqC;AACzC,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,UAAA,CAAW,UAAA,CAAW,EAAE,KAAA,EAAO,EAAE,EAAA,EAAI,CAAA,EAAE,EAAG,CAAA;AACnE,MAAA,OAAO,MAAM,YAAA,CAAa,GAAG,CAAA,GAAI,EAAE,GAAG,mBAAA,EAAoB;AAAA,IAC5D,CAAA;AAAA,IAEA,MAAM,gBAAA,CACJ,KAAA,EACA,QAAA,EACqB;AACrB,MAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,UAAA,CAAW,MAAA,CAAO;AAAA,QACzC,KAAA,EAAO,EAAE,EAAA,EAAI,CAAA,EAAE;AAAA,QACf,QAAQ,EAAE,EAAA,EAAI,GAAG,GAAG,KAAA,EAAO,iBAAiB,QAAA,EAAS;AAAA,QACrD,MAAA,EAAQ,EAAE,GAAG,KAAA,EAAO,iBAAiB,QAAA;AAAS,OAC/C,CAAA;AACD,MAAA,OAAO,aAAa,GAAG,CAAA;AAAA,IACzB;AAAA,GACF;AACF;;;ACxSO,IAAM,oBAAA,GAA+B,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA","file":"index.js","sourcesContent":["/**\n * Ports — the contract between this package and any host that consumes it.\n *\n * Every project-specific concern (auth, scope, persistence, tools, credentials)\n * crosses the boundary as a typed port the host implements and passes into\n * `configureAiChat({...})`. The package itself has zero knowledge of the\n * host's database, RBAC model, or environment.\n *\n * Domain types (ChatSession, ChatMessage, AiSettings, PresentPayload, Block)\n * are pure TS — no ORM coupling. The Drizzle and Prisma adapters each map\n * their respective row types into these shapes so callers see one contract\n * regardless of the chosen ORM.\n */\nimport type { GoogleAuth } from 'google-auth-library';\nimport type { ToolDefinition, ToolContext, SystemBlock } from '../tools/types';\n\n// ---------------------------------------------------------------------------\n// Domain types — used by every port\n// ---------------------------------------------------------------------------\n\n/**\n * Chat session and message identifiers are short URL-safe UIDs (12 chars,\n * ~72 bits of entropy, alphabet matches nanoid's URL-safe set). The\n * package generates them in `createSession`/`appendMessage` so adapters\n * never need to know about auto-increment vs UID.\n */\nexport type ChatSession = {\n id: string;\n userId: number;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type ChatMessageRole = 'user' | 'assistant';\n\n/**\n * One message turn. For 'user' rows, `question` carries the raw question text.\n * For 'assistant' rows, `blocks` holds the structured PresentPayload and\n * `prose` holds any paragraph_brief prose collected from the streamed\n * narrator. `errorJson` is set when an assistant turn failed mid-stream.\n */\nexport type ChatMessage = {\n id: string;\n sessionId: string;\n role: ChatMessageRole;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n createdAt: Date;\n};\n\n/**\n * Singleton row controlling global AI runtime settings. All open-string\n * fields are validated at runtime against the registries the host configures\n * — they are not enums in the package's types so consumers can register\n * additional providers / interfaces without a schema change.\n *\n * `maxOutputTokens` caps both the agent loop's per-turn output AND each\n * narrator's prose pass. Reasoning models (e.g. `xai/grok-4.1-fast-reasoning`)\n * charge internal thinking against this budget — set it generously when\n * those are in use.\n *\n * `rolePrompt` is the persona the assistant adopts. When non-null, it\n * takes precedence over the host's static `rolePrompt` configureAiChat\n * option, so admins can edit live in the settings UI.\n *\n * `gcpProjectId` is an admin-editable override for the GCP project that\n * every Vertex API call targets. When non-null, it takes precedence over\n * the host's static `VertexPort.projectId` so admins can flip projects\n * (staging ↔ prod, multi-tenant) without redeploying.\n */\nexport type AiSettings = {\n toolProvider: string;\n gcpLocation: string;\n chatInterface: string;\n maxOutputTokens: number;\n rolePrompt: string | null;\n gcpProjectId: string | null;\n updatedAt: Date | null;\n updatedByUserId: number | null;\n};\n\n/**\n * Default cap when nothing is persisted. Conservative so non-reasoning\n * models don't pay for headroom they don't need; admins bump it for\n * reasoning models via the settings UI.\n */\nexport const DEFAULT_AI_MAX_OUTPUT_TOKENS = 4096;\n\n// ---------------------------------------------------------------------------\n// AuthPort — the host tells us who's calling\n// ---------------------------------------------------------------------------\n\n/**\n * The host's resolved Scope (org/tenant/RBAC shape) is opaque to the package.\n * `S` is whatever the host wants — typically a discriminated union with at\n * least `userId: number` plus role/tenancy fields.\n */\nexport type AuthOk<S> = { ok: true; scope: S; userId: number };\nexport type AuthFail = { ok: false; response: Response };\nexport type AuthResult<S> = AuthOk<S> | AuthFail;\n\nexport type AuthPort<S = unknown> = {\n /**\n * Resolve the calling user from the request. Returning `{ ok: false }`\n * lets the route hand back the prepared 401/403 response untouched.\n */\n requireAuth(req: Request): Promise<AuthResult<S>>;\n /**\n * Predicate the admin-settings route uses to gate writes. Hosts that\n * don't model admins can return `() => true` if they trust their own\n * routing layer.\n */\n isSuperAdmin(scope: S): boolean;\n};\n\n// ---------------------------------------------------------------------------\n// ScopePort — human-readable scope description fed into the system prompt\n// ---------------------------------------------------------------------------\n\nexport type ScopePort<S = unknown> = {\n /** Short label rendered in the chat UI (e.g. \"Ghana\", \"All countries\"). */\n resolveScopeLabel(scope: S): Promise<string>;\n /** Longer narrative the system prompt uses to describe the data slice. */\n buildScopeSummary(scope: S): Promise<string>;\n};\n\n// ---------------------------------------------------------------------------\n// ToolsPort — host supplies its own tool registry + system prompts\n// ---------------------------------------------------------------------------\n\nexport type ToolsPort = {\n /**\n * Map of tool name → definition. Keys must match `definition.schema.name`.\n * Must include the terminal `present` tool — the agent loop refuses to\n * end a turn without it.\n */\n tools: Record<string, ToolDefinition>;\n /**\n * Build the ordered list of system blocks for one agent run. The host\n * decides how much of the prompt is project-specific (schema doc,\n * semantic-layer doc, scope summary, etc.). Blocks marked `cached: true`\n * become Anthropic ephemeral cache markers and Vertex prefix-cache hints.\n */\n buildSystemBlocks(ctx: ToolContext): Promise<SystemBlock[]>;\n};\n\n// ---------------------------------------------------------------------------\n// VertexPort — credentials are host-supplied; the package never reads env\n// ---------------------------------------------------------------------------\n\nexport type VertexPort = {\n projectId: string;\n /** e.g. 'us-east5' or 'global' — used unless `aiSettings.gcpLocation` overrides per-request. */\n defaultLocation: string;\n /**\n * A constructed `GoogleAuth` instance. Any auth scheme that yields one\n * works (ADC, Workload Identity Federation, split-key env vars,\n * Secret Manager, etc.). The package never reads `process.env.GCP_*`.\n */\n auth: GoogleAuth;\n /** Vertex model IDs pinned by the host (orgs pin their own versions). */\n modelIds: { claude: string; gemini: string };\n};\n\n// ---------------------------------------------------------------------------\n// LoggerPort — optional structured logging\n// ---------------------------------------------------------------------------\n\nexport type LoggerPort = {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n};\n\n// ---------------------------------------------------------------------------\n// PersistencePort — domain-shaped queries the package needs\n// ---------------------------------------------------------------------------\n\nexport type CreateSessionInput = {\n userId: number;\n title: string;\n};\n\nexport type AppendMessageInput = {\n sessionId: string;\n role: ChatMessageRole;\n question?: string | null;\n blocks?: unknown | null;\n prose?: unknown | null;\n errorJson?: unknown | null;\n};\n\nexport type ListSessionsOpts = {\n limit?: number;\n};\n\nexport type AiSettingsPatch = {\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n /** Pass `null` to clear back to the host's static fallback. */\n rolePrompt?: string | null;\n /** Pass `null` to clear back to the host's static VertexPort.projectId. */\n gcpProjectId?: string | null;\n};\n\n/**\n * The whole reason this package is ORM-agnostic. Implemented by:\n * - createDrizzlePersistence (src/adapters/drizzle/)\n * - createPrismaPersistence (src/adapters/prisma/)\n * - createMemoryPersistence (src/adapters/memory/, internal test use)\n *\n * Routes, agent loop, and UI never touch ORMs directly — they only call\n * methods on this port. A parameterized contract test runs the same\n * assertions against all three adapters to keep them in sync.\n */\nexport type PersistencePort = {\n // Sessions ---------------------------------------------------------------\n createSession(input: CreateSessionInput): Promise<ChatSession>;\n /** Returns null when the session doesn't exist OR doesn't belong to this user. */\n getSession(id: string, userId: number): Promise<ChatSession | null>;\n listSessionsForUser(userId: number, opts?: ListSessionsOpts): Promise<ChatSession[]>;\n /** No-op when session doesn't exist or doesn't belong to user — caller asserted authorisation. */\n updateSession(id: string, userId: number, patch: { title?: string }): Promise<void>;\n deleteSession(id: string, userId: number): Promise<void>;\n\n // Messages ---------------------------------------------------------------\n appendMessage(input: AppendMessageInput): Promise<ChatMessage>;\n listMessagesForSession(sessionId: string, userId: number): Promise<ChatMessage[]>;\n\n // AI settings (singleton row) -------------------------------------------\n /** Returns the singleton row, applying defaults if it's never been written. */\n getAiSettings(): Promise<AiSettings>;\n /**\n * Upsert. Validates `toolProvider` and `chatInterface` against the runtime\n * registries before writing — invalid values throw before SQL is issued.\n */\n updateAiSettings(patch: AiSettingsPatch, byUserId: number): Promise<AiSettings>;\n};\n","/**\n * Short URL-safe identifier generator for chat session and message rows.\n *\n * 12 chars from a 64-char URL-safe alphabet ≈ 72 bits of entropy. That's\n * collision-safe well past any per-user chat count and short enough to\n * appear unobtrusively in URLs (`/chat/V1StGXR8_Z5j`). The alphabet\n * matches nanoid's URL-safe set so the IDs round-trip cleanly through\n * URL paths, query strings, JSON, and SQL VARCHAR columns.\n */\nimport { randomBytes } from 'crypto';\n\nconst ALPHABET =\n 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW';\n\nexport const CHAT_UID_LENGTH = 12;\n\nexport function generateChatUid(size: number = CHAT_UID_LENGTH): string {\n const bytes = randomBytes(size);\n let id = '';\n for (let i = 0; i < size; i += 1) {\n // Mask to 6 bits → uniform index into the 64-char alphabet.\n id += ALPHABET[bytes[i] & 63];\n }\n return id;\n}\n","/**\n * Prisma `PersistencePort` adapter.\n *\n * Hosts call `createPrismaPersistence(prisma)` with their own configured\n * `PrismaClient` and pass the result to `configureAiChat({ persistence, ... })`.\n *\n * The concrete `PrismaClient` is an OPTIONAL peer dep, so this module never\n * imports a runtime value from `@prisma/client`. Instead it accepts a\n * structural duck-typed shape covering only the delegate methods the port\n * uses. Any object that satisfies `PrismaLike` works — including a real\n * `PrismaClient`, a Prisma extension proxy, or a hand-rolled fake in tests.\n *\n * BigInt note: Prisma returns row IDs as JavaScript `BigInt`. Domain types\n * use plain `number` (sessions/messages are nowhere near 2^53). The adapter\n * widens via `Number(row.id)` on every read; writes accept `number` and\n * Prisma narrows internally.\n */\nimport {\n DEFAULT_AI_MAX_OUTPUT_TOKENS,\n type AiSettings,\n type AiSettingsPatch,\n type AppendMessageInput,\n type ChatMessage,\n type ChatMessageRole,\n type ChatSession,\n type CreateSessionInput,\n type ListSessionsOpts,\n type PersistencePort\n} from '../../server/ports/types';\nimport { generateChatUid } from '../../server/uid';\n\n// ---------------------------------------------------------------------------\n// Structural Prisma shape — covers exactly what this adapter touches.\n// Avoids a value-level dependency on `@prisma/client` (optional peer dep).\n// ---------------------------------------------------------------------------\n\ntype ChatSessionRow = {\n id: string;\n userId: bigint | number;\n title: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype ChatMessageRow = {\n id: string;\n sessionId: string;\n role: string;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n createdAt: Date;\n};\n\ntype AiSettingsRow = {\n id: number;\n toolProvider: string;\n gcpLocation: string;\n chatInterface: string;\n maxOutputTokens: number;\n rolePrompt: string | null;\n gcpProjectId: string | null;\n updatedAt: Date | null;\n updatedByUserId: bigint | number | null;\n};\n\ntype ChatSessionDelegate = {\n create(args: {\n data: { id: string; userId: number; title: string };\n }): Promise<ChatSessionRow>;\n findFirst(args: {\n where: { id: string; userId: number };\n }): Promise<ChatSessionRow | null>;\n findMany(args: {\n where: { userId: number };\n orderBy: { updatedAt: 'desc' };\n take?: number;\n }): Promise<ChatSessionRow[]>;\n update(args: {\n where: { id: string };\n data: { title?: string; updatedAt?: Date };\n }): Promise<ChatSessionRow>;\n updateMany(args: {\n where: { id: string; userId: number };\n data: { title?: string; updatedAt?: Date };\n }): Promise<{ count: number }>;\n deleteMany(args: {\n where: { id: string; userId: number };\n }): Promise<{ count: number }>;\n};\n\ntype ChatMessageDelegate = {\n create(args: {\n data: {\n id: string;\n sessionId: string;\n role: ChatMessageRole;\n question: string | null;\n blocks: unknown | null;\n prose: unknown | null;\n errorJson: unknown | null;\n };\n }): Promise<ChatMessageRow>;\n findMany(args: {\n where: { sessionId: string };\n orderBy: { createdAt: 'asc' };\n }): Promise<ChatMessageRow[]>;\n deleteMany(args: {\n where: { sessionId: string };\n }): Promise<{ count: number }>;\n};\n\ntype AiSettingsDelegate = {\n findUnique(args: { where: { id: number } }): Promise<AiSettingsRow | null>;\n upsert(args: {\n where: { id: number };\n create: {\n id: number;\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n rolePrompt?: string | null;\n gcpProjectId?: string | null;\n updatedByUserId: number;\n };\n update: {\n toolProvider?: string;\n gcpLocation?: string;\n chatInterface?: string;\n maxOutputTokens?: number;\n rolePrompt?: string | null;\n gcpProjectId?: string | null;\n updatedByUserId: number;\n };\n }): Promise<AiSettingsRow>;\n};\n\nexport type PrismaLike = {\n chatSession: ChatSessionDelegate;\n chatMessage: ChatMessageDelegate;\n aiSettings: AiSettingsDelegate;\n};\n\n// ---------------------------------------------------------------------------\n// Row -> domain mappers\n// ---------------------------------------------------------------------------\n\nconst toSession = (row: ChatSessionRow): ChatSession => ({\n id: row.id,\n userId: Number(row.userId),\n title: row.title,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt\n});\n\nconst toMessage = (row: ChatMessageRow): ChatMessage => ({\n id: row.id,\n sessionId: row.sessionId,\n // Stored as VARCHAR(16) but constrained to ChatMessageRole at write time.\n role: row.role as ChatMessageRole,\n question: row.question,\n blocks: row.blocks,\n prose: row.prose,\n errorJson: row.errorJson,\n createdAt: row.createdAt\n});\n\nconst toAiSettings = (row: AiSettingsRow): AiSettings => ({\n toolProvider: row.toolProvider,\n gcpLocation: row.gcpLocation,\n chatInterface: row.chatInterface,\n maxOutputTokens: row.maxOutputTokens,\n rolePrompt: row.rolePrompt,\n gcpProjectId: row.gcpProjectId,\n updatedAt: row.updatedAt,\n updatedByUserId: row.updatedByUserId === null ? null : Number(row.updatedByUserId)\n});\n\nconst DEFAULT_AI_SETTINGS: AiSettings = {\n toolProvider: 'claude',\n gcpLocation: 'us-east5',\n chatInterface: 'custom',\n maxOutputTokens: DEFAULT_AI_MAX_OUTPUT_TOKENS,\n rolePrompt: null,\n gcpProjectId: null,\n updatedAt: null,\n updatedByUserId: null\n};\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport function createPrismaPersistence(prisma: PrismaLike): PersistencePort {\n return {\n // Sessions ---------------------------------------------------------------\n\n async createSession(input: CreateSessionInput): Promise<ChatSession> {\n const id = generateChatUid();\n const row = await prisma.chatSession.create({\n data: { id, userId: input.userId, title: input.title }\n });\n return toSession(row);\n },\n\n async getSession(id: string, userId: number): Promise<ChatSession | null> {\n const row = await prisma.chatSession.findFirst({ where: { id, userId } });\n return row ? toSession(row) : null;\n },\n\n async listSessionsForUser(\n userId: number,\n opts?: ListSessionsOpts\n ): Promise<ChatSession[]> {\n const rows = await prisma.chatSession.findMany({\n where: { userId },\n orderBy: { updatedAt: 'desc' },\n take: opts?.limit\n });\n return rows.map(toSession);\n },\n\n async updateSession(\n id: string,\n userId: number,\n patch: { title?: string }\n ): Promise<void> {\n // updateMany so the userId scope filters; no-ops cleanly when the\n // session doesn't exist or belongs to another user.\n await prisma.chatSession.updateMany({\n where: { id, userId },\n data: { ...patch, updatedAt: new Date() }\n });\n },\n\n async deleteSession(id: string, userId: number): Promise<void> {\n // Cascade-delete messages first (no ON DELETE CASCADE assumed).\n await prisma.chatMessage.deleteMany({ where: { sessionId: id } });\n await prisma.chatSession.deleteMany({ where: { id, userId } });\n },\n\n // Messages ---------------------------------------------------------------\n\n async appendMessage(input: AppendMessageInput): Promise<ChatMessage> {\n const id = generateChatUid();\n const row = await prisma.chatMessage.create({\n data: {\n id,\n sessionId: input.sessionId,\n role: input.role,\n question: input.question ?? null,\n blocks: input.blocks ?? null,\n prose: input.prose ?? null,\n errorJson: input.errorJson ?? null\n }\n });\n // Bump the parent session's `updatedAt` so `listSessionsForUser`\n // reflects \"most recent activity\" rather than creation time. Done\n // as a separate update so the message insert remains the source of\n // truth for ordering across replicas.\n await prisma.chatSession.update({\n where: { id: input.sessionId },\n data: { updatedAt: new Date() }\n });\n return toMessage(row);\n },\n\n async listMessagesForSession(\n sessionId: string,\n userId: number\n ): Promise<ChatMessage[]> {\n // Re-assert ownership before returning rows. A caller passing a\n // sessionId they don't own should get an empty list, not someone\n // else's transcript.\n const session = await prisma.chatSession.findFirst({\n where: { id: sessionId, userId }\n });\n if (!session) return [];\n const rows = await prisma.chatMessage.findMany({\n where: { sessionId },\n orderBy: { createdAt: 'asc' }\n });\n return rows.map(toMessage);\n },\n\n // AI settings (singleton row at id=1) -----------------------------------\n\n async getAiSettings(): Promise<AiSettings> {\n const row = await prisma.aiSettings.findUnique({ where: { id: 1 } });\n return row ? toAiSettings(row) : { ...DEFAULT_AI_SETTINGS };\n },\n\n async updateAiSettings(\n patch: AiSettingsPatch,\n byUserId: number\n ): Promise<AiSettings> {\n const row = await prisma.aiSettings.upsert({\n where: { id: 1 },\n create: { id: 1, ...patch, updatedByUserId: byUserId },\n update: { ...patch, updatedByUserId: byUserId }\n });\n return toAiSettings(row);\n }\n };\n}\n","/**\n * The Prisma schema fragment hosts paste into their own `schema.prisma`.\n *\n * Kept in lock-step with `prisma/chat-models.prisma` at the package root.\n * The fragment is inlined here (not read from disk) so consumer bundlers\n * never need to resolve a runtime fs path.\n *\n * Codegen tooling can import this constant and write it out, splice it into\n * a host's `schema.prisma`, etc.\n */\nexport const prismaSchemaFragment: string = `// =============================================================================\n// @firstlovecenter/ai-chat — Prisma schema fragment\n// =============================================================================\n//\n// HOSTS: copy the three models below into your own \\`schema.prisma\\`, then run\n//\n// pnpm prisma generate\n// pnpm prisma migrate dev --name flc_ai_chat\n//\n// Column names, SQL types, and indexes match the Drizzle adapter shipped at\n// \\`@firstlovecenter/ai-chat/server/drizzle\\` byte-for-byte, so the underlying MySQL schema\n// is identical regardless of which ORM your host picks. A host could swap\n// from one adapter to the other without touching data.\n// =============================================================================\n\nmodel ChatSession {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n userId BigInt @map(\"user_id\") @db.UnsignedBigInt\n title String @db.VarChar(200)\n createdAt DateTime @default(now()) @map(\"created_at\") @db.DateTime(0)\n updatedAt DateTime @default(now()) @map(\"updated_at\") @db.DateTime(0)\n\n @@index([userId, updatedAt], map: \"idx_chat_session_user_updated\")\n @@map(\"chat_sessions\")\n}\n\nmodel ChatMessage {\n id BigInt @id @default(autoincrement()) @db.UnsignedBigInt\n sessionId BigInt @map(\"session_id\") @db.UnsignedBigInt\n role String @db.VarChar(16)\n question String? @db.Text\n blocks Json?\n prose Json?\n errorJson Json? @map(\"error_json\")\n createdAt DateTime @default(now()) @map(\"created_at\") @db.DateTime(0)\n\n @@index([sessionId, createdAt], map: \"idx_chat_msg_session_created\")\n @@map(\"chat_messages\")\n}\n\nmodel AiSettings {\n id Int @id @default(1) @db.UnsignedTinyInt\n toolProvider String @default(\"claude\") @map(\"tool_provider\") @db.VarChar(32)\n gcpLocation String @default(\"us-east5\") @map(\"gcp_location\") @db.VarChar(32)\n chatInterface String @default(\"custom\") @map(\"chat_interface\") @db.VarChar(32)\n updatedAt DateTime @default(now()) @map(\"updated_at\") @db.DateTime(0)\n updatedByUserId BigInt? @map(\"updated_by_user_id\") @db.UnsignedBigInt\n\n @@map(\"ai_settings\")\n}\n`;\n"]}
|
package/dist/server/index.cjs
CHANGED
|
@@ -1013,7 +1013,7 @@ function createAgentCustomRoutes(ctx) {
|
|
|
1013
1013
|
);
|
|
1014
1014
|
}
|
|
1015
1015
|
const rawChatSessionId = body?.chatSessionId;
|
|
1016
|
-
const incomingChatSessionId = typeof rawChatSessionId === "
|
|
1016
|
+
const incomingChatSessionId = typeof rawChatSessionId === "string" && rawChatSessionId.length > 0 ? rawChatSessionId : null;
|
|
1017
1017
|
const aiSettings = await persistence.getAiSettings();
|
|
1018
1018
|
const effectiveProjectId = aiSettings.gcpProjectId ?? vertex.projectId;
|
|
1019
1019
|
let chatSessionId;
|
|
@@ -1359,7 +1359,7 @@ function createAgentVercelRoutes(ctx) {
|
|
|
1359
1359
|
);
|
|
1360
1360
|
}
|
|
1361
1361
|
const rawChatSessionId = body?.chatSessionId;
|
|
1362
|
-
const incomingChatSessionId = typeof rawChatSessionId === "
|
|
1362
|
+
const incomingChatSessionId = typeof rawChatSessionId === "string" && rawChatSessionId.length > 0 ? rawChatSessionId : null;
|
|
1363
1363
|
const rawModel = body?.model;
|
|
1364
1364
|
const requestedModel = typeof rawModel === "string" && VALID_MODELS.has(rawModel) ? rawModel : null;
|
|
1365
1365
|
const aiSettings = await persistence.getAiSettings();
|
|
@@ -1597,10 +1597,10 @@ function serializeSession(s) {
|
|
|
1597
1597
|
updatedAt: s.updatedAt ? s.updatedAt.toISOString() : null
|
|
1598
1598
|
};
|
|
1599
1599
|
}
|
|
1600
|
+
var SESSION_ID_RE = /^[A-Za-z0-9_-]{1,32}$/;
|
|
1600
1601
|
function parseSessionId(raw) {
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
return id;
|
|
1602
|
+
if (!raw || !SESSION_ID_RE.test(raw)) return null;
|
|
1603
|
+
return raw;
|
|
1604
1604
|
}
|
|
1605
1605
|
function createChatSessionsRoutes(ctx) {
|
|
1606
1606
|
const { persistence, auth, logger, hooks } = ctx;
|