@firstlovecenter/ai-chat 0.7.0 → 0.8.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 +24 -0
- package/dist/drizzle/index.cjs +1 -0
- package/dist/drizzle/index.cjs.map +1 -1
- package/dist/drizzle/index.js +1 -0
- package/dist/drizzle/index.js.map +1 -1
- package/dist/prisma/index.cjs +4 -0
- package/dist/prisma/index.cjs.map +1 -1
- package/dist/prisma/index.js +4 -0
- package/dist/prisma/index.js.map +1 -1
- package/dist/server/index.cjs +140 -5
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +20 -0
- package/dist/server/index.d.ts +20 -0
- package/dist/server/index.js +140 -5
- package/dist/server/index.js.map +1 -1
- package/dist/ui/index.cjs +137 -98
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.d.cts +15 -2
- package/dist/ui/index.d.ts +15 -2
- package/dist/ui/index.js +137 -98
- package/dist/ui/index.js.map +1 -1
- package/package.json +1 -1
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;AAAA,EACX,WAAW,GAAA,CAAI,SAAA;AAAA,EACf,WAAW,GAAA,CAAI;AACjB,CAAA,CAAA;AAEA,IAAM,SAAA,GAAY,CAAC,GAAA,MAAsC;AAAA,EACvD,EAAA,EAAI,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AAAA,EACjB,SA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;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;;;ACtRO,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 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/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,CA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EAAW,KAAA;AAAM,OAC7B,CAAA;AACD,MAAA,OAAO,IAAA,CAAK,IAAI,SAAS,CAAA;AAAA,IAC3B,CAAA;AAAA;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"]}
|
package/dist/server/index.cjs
CHANGED
|
@@ -25,7 +25,10 @@ async function runAgent(input) {
|
|
|
25
25
|
const maxOutputTokens = input.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
26
26
|
const transcript = [];
|
|
27
27
|
transcript.push({ kind: "user", text: input.question });
|
|
28
|
-
const messages = [
|
|
28
|
+
const messages = [
|
|
29
|
+
...input.priorMessages ?? [],
|
|
30
|
+
{ role: "user", text: input.question }
|
|
31
|
+
];
|
|
29
32
|
const system = input.systemBlocks;
|
|
30
33
|
const toolSchemas = Object.values(input.tools).map((t) => t.schema);
|
|
31
34
|
let toolCallCount = 0;
|
|
@@ -218,11 +221,28 @@ function toAnthropicMessages(messages) {
|
|
|
218
221
|
const out = [];
|
|
219
222
|
for (const msg of messages) {
|
|
220
223
|
if (msg.role === "user") {
|
|
221
|
-
|
|
224
|
+
if (msg.cached) {
|
|
225
|
+
out.push({
|
|
226
|
+
role: "user",
|
|
227
|
+
content: [
|
|
228
|
+
{
|
|
229
|
+
type: "text",
|
|
230
|
+
text: msg.text,
|
|
231
|
+
cache_control: { type: "ephemeral" }
|
|
232
|
+
}
|
|
233
|
+
]
|
|
234
|
+
});
|
|
235
|
+
} else {
|
|
236
|
+
out.push({ role: "user", content: msg.text });
|
|
237
|
+
}
|
|
222
238
|
} else if (msg.role === "assistant") {
|
|
223
239
|
const blocks = [];
|
|
224
240
|
if (msg.text) {
|
|
225
|
-
|
|
241
|
+
const textBlock = { type: "text", text: msg.text };
|
|
242
|
+
if (msg.cached && msg.toolCalls.length === 0) {
|
|
243
|
+
textBlock.cache_control = { type: "ephemeral" };
|
|
244
|
+
}
|
|
245
|
+
blocks.push(textBlock);
|
|
226
246
|
}
|
|
227
247
|
for (const tc of msg.toolCalls) {
|
|
228
248
|
blocks.push({
|
|
@@ -574,6 +594,87 @@ var toolProviders = [
|
|
|
574
594
|
function getToolProvider(id) {
|
|
575
595
|
return toolProviders.find((p) => p.id === id);
|
|
576
596
|
}
|
|
597
|
+
|
|
598
|
+
// src/server/history.ts
|
|
599
|
+
var DEFAULT_MAX_HISTORY_PAIRS = 20;
|
|
600
|
+
var DEFAULT_MAX_TEXT_CHARS = 4e3;
|
|
601
|
+
function historyToNormalizedMessages(rows, opts = {}) {
|
|
602
|
+
const maxPairs = opts.maxPairs ?? DEFAULT_MAX_HISTORY_PAIRS;
|
|
603
|
+
const maxTextChars = opts.maxTextChars ?? DEFAULT_MAX_TEXT_CHARS;
|
|
604
|
+
const pairs = [];
|
|
605
|
+
let i = 0;
|
|
606
|
+
while (i < rows.length) {
|
|
607
|
+
const row = rows[i];
|
|
608
|
+
if (row.role !== "user" || !row.question) {
|
|
609
|
+
i += 1;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const next = rows[i + 1];
|
|
613
|
+
if (next?.role !== "assistant") {
|
|
614
|
+
i += 1;
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
const assistantText = truncate(
|
|
618
|
+
assistantMessageToText(next),
|
|
619
|
+
maxTextChars
|
|
620
|
+
);
|
|
621
|
+
if (assistantText) {
|
|
622
|
+
pairs.push([
|
|
623
|
+
{ role: "user", text: truncate(row.question, maxTextChars) },
|
|
624
|
+
{ role: "assistant", text: assistantText, toolCalls: [] }
|
|
625
|
+
]);
|
|
626
|
+
}
|
|
627
|
+
i += 2;
|
|
628
|
+
}
|
|
629
|
+
const kept = maxPairs > 0 ? pairs.slice(-maxPairs) : pairs;
|
|
630
|
+
return kept.flat();
|
|
631
|
+
}
|
|
632
|
+
function truncate(text, max) {
|
|
633
|
+
if (max <= 0 || text.length <= max) return text;
|
|
634
|
+
return text.slice(0, max);
|
|
635
|
+
}
|
|
636
|
+
function assistantMessageToText(row) {
|
|
637
|
+
if (row.errorJson) return "";
|
|
638
|
+
const proseText = proseToText(row.prose);
|
|
639
|
+
if (proseText) return proseText;
|
|
640
|
+
const blockText = blocksToText(row.blocks);
|
|
641
|
+
return blockText;
|
|
642
|
+
}
|
|
643
|
+
function proseToText(prose) {
|
|
644
|
+
if (!prose || typeof prose !== "object") return "";
|
|
645
|
+
const entries = Object.entries(prose).map(([k, v]) => [Number(k), typeof v === "string" ? v : ""]).filter(([k, v]) => Number.isFinite(k) && v.length > 0).sort(([a], [b]) => a - b);
|
|
646
|
+
return entries.map(([, v]) => v).join("\n\n").trim();
|
|
647
|
+
}
|
|
648
|
+
function blocksToText(blocks) {
|
|
649
|
+
if (!Array.isArray(blocks)) return "";
|
|
650
|
+
const parts = [];
|
|
651
|
+
for (const raw of blocks) {
|
|
652
|
+
if (!raw || typeof raw !== "object") continue;
|
|
653
|
+
const b = raw;
|
|
654
|
+
switch (b.kind) {
|
|
655
|
+
case "paragraph_brief": {
|
|
656
|
+
const facts = (b.key_facts ?? []).filter((f) => f && f.trim());
|
|
657
|
+
if (b.topic) parts.push(b.topic);
|
|
658
|
+
if (facts.length) parts.push(facts.join("\n"));
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
case "list": {
|
|
662
|
+
const items = (b.items ?? []).filter((s) => s && s.trim());
|
|
663
|
+
if (b.title) parts.push(b.title);
|
|
664
|
+
if (items.length) parts.push(items.map((s) => `- ${s}`).join("\n"));
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
case "chart":
|
|
668
|
+
case "table":
|
|
669
|
+
if (b.title) parts.push(`[${b.title}]`);
|
|
670
|
+
break;
|
|
671
|
+
case "callout":
|
|
672
|
+
if (b.text) parts.push(b.text);
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
return parts.join("\n\n").trim();
|
|
677
|
+
}
|
|
577
678
|
function vertexHost2(location) {
|
|
578
679
|
return location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`;
|
|
579
680
|
}
|
|
@@ -916,12 +1017,23 @@ function createAgentCustomRoutes(ctx) {
|
|
|
916
1017
|
const aiSettings = await persistence.getAiSettings();
|
|
917
1018
|
const effectiveProjectId = aiSettings.gcpProjectId ?? vertex.projectId;
|
|
918
1019
|
let chatSessionId;
|
|
1020
|
+
let priorMessages = [];
|
|
919
1021
|
if (incomingChatSessionId !== null) {
|
|
920
1022
|
const owned = await persistence.getSession(incomingChatSessionId, userId);
|
|
921
1023
|
if (!owned) {
|
|
922
1024
|
return jsonError(404, "NOT_FOUND", "Chat session not found.");
|
|
923
1025
|
}
|
|
924
1026
|
chatSessionId = owned.id;
|
|
1027
|
+
const stored = await persistence.listMessagesForSession(chatSessionId, userId);
|
|
1028
|
+
priorMessages = historyToNormalizedMessages(stored);
|
|
1029
|
+
if (priorMessages.length > 0) {
|
|
1030
|
+
const last = priorMessages[priorMessages.length - 1];
|
|
1031
|
+
if (last.role === "assistant" && last.toolCalls.length === 0) {
|
|
1032
|
+
priorMessages[priorMessages.length - 1] = { ...last, cached: true };
|
|
1033
|
+
} else if (last.role === "user") {
|
|
1034
|
+
priorMessages[priorMessages.length - 1] = { ...last, cached: true };
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
925
1037
|
} else {
|
|
926
1038
|
const created = await persistence.createSession({
|
|
927
1039
|
userId,
|
|
@@ -1009,6 +1121,7 @@ data: ${JSON.stringify(data)}
|
|
|
1009
1121
|
send("meta", { chatSessionId, scopeLabel });
|
|
1010
1122
|
const agentResult = await runAgent({
|
|
1011
1123
|
question,
|
|
1124
|
+
priorMessages,
|
|
1012
1125
|
ctx: toolContext,
|
|
1013
1126
|
tools: tools.tools,
|
|
1014
1127
|
systemBlocks,
|
|
@@ -1227,7 +1340,17 @@ function createAgentVercelRoutes(ctx) {
|
|
|
1227
1340
|
if (short) return short;
|
|
1228
1341
|
}
|
|
1229
1342
|
const body = await req.json().catch(() => null);
|
|
1230
|
-
|
|
1343
|
+
let question = typeof body?.question === "string" ? body.question.trim() : "";
|
|
1344
|
+
if (!question && Array.isArray(body?.messages)) {
|
|
1345
|
+
const msgs = body.messages;
|
|
1346
|
+
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
|
1347
|
+
const m = msgs[i];
|
|
1348
|
+
if (m && m.role === "user" && typeof m.content === "string") {
|
|
1349
|
+
question = m.content.trim();
|
|
1350
|
+
break;
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1231
1354
|
if (!question) {
|
|
1232
1355
|
return jsonError2(
|
|
1233
1356
|
400,
|
|
@@ -1242,6 +1365,7 @@ function createAgentVercelRoutes(ctx) {
|
|
|
1242
1365
|
const aiSettings = await persistence.getAiSettings();
|
|
1243
1366
|
const effectiveProjectId = aiSettings.gcpProjectId ?? vertex.projectId;
|
|
1244
1367
|
let chatSessionId;
|
|
1368
|
+
let priorMessages = [];
|
|
1245
1369
|
if (incomingChatSessionId !== null) {
|
|
1246
1370
|
const owned = await persistence.getSession(
|
|
1247
1371
|
incomingChatSessionId,
|
|
@@ -1251,6 +1375,11 @@ function createAgentVercelRoutes(ctx) {
|
|
|
1251
1375
|
return jsonError2(404, "NOT_FOUND", "Chat session not found.");
|
|
1252
1376
|
}
|
|
1253
1377
|
chatSessionId = owned.id;
|
|
1378
|
+
const stored = await persistence.listMessagesForSession(
|
|
1379
|
+
chatSessionId,
|
|
1380
|
+
userId
|
|
1381
|
+
);
|
|
1382
|
+
priorMessages = historyToNormalizedMessages(stored);
|
|
1254
1383
|
} else {
|
|
1255
1384
|
const created = await persistence.createSession({
|
|
1256
1385
|
userId,
|
|
@@ -1320,10 +1449,16 @@ function createAgentVercelRoutes(ctx) {
|
|
|
1320
1449
|
location: aiSettings.gcpLocation,
|
|
1321
1450
|
googleAuthOptions: {}
|
|
1322
1451
|
})(vertex.modelIds.gemini);
|
|
1452
|
+
const priorCoreMessages = priorMessages.filter(
|
|
1453
|
+
(m) => m.role === "user" || m.role === "assistant"
|
|
1454
|
+
).map((m) => ({ role: m.role, content: m.text }));
|
|
1323
1455
|
const result = ai.streamText({
|
|
1324
1456
|
model,
|
|
1325
1457
|
system,
|
|
1326
|
-
messages: [
|
|
1458
|
+
messages: [
|
|
1459
|
+
...priorCoreMessages,
|
|
1460
|
+
{ role: "user", content: question }
|
|
1461
|
+
],
|
|
1327
1462
|
tools: vercelTools,
|
|
1328
1463
|
maxSteps: 12,
|
|
1329
1464
|
maxTokens: aiSettings.maxOutputTokens,
|