@open-mercato/ai-assistant 0.10.1-develop.8182.1.0acd6a564c → 0.10.1-develop.8191.1.2563ac3bfc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- [build:ai-assistant] found 251 entry points
1
+ [build:ai-assistant] found 252 entry points
2
2
  [build:ai-assistant] built successfully
@@ -0,0 +1,61 @@
1
+ import { test, expect } from "@playwright/test";
2
+ import { randomUUID } from "node:crypto";
3
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
4
+ import { getTokenScope, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
5
+ import { deleteConversationCascadeInDb } from "./helpers/aiAssistantFixtures.js";
6
+ const CONVERSATIONS = "/api/ai_assistant/ai/conversations";
7
+ test.describe("TC-AI-CONVERSATIONS-002: conversation list cursor pagination", () => {
8
+ test("walking nextPageToken with limit=1 returns every conversation exactly once", async ({ request }) => {
9
+ test.slow();
10
+ const adminToken = await getAuthToken(request, "admin");
11
+ const { tenantId } = getTokenScope(adminToken);
12
+ const agentId = `it_conv.cursor_${randomUUID().slice(0, 8)}`;
13
+ const created = [];
14
+ try {
15
+ const activeId = `it-conv-active-${randomUUID()}`;
16
+ created.push(activeId);
17
+ const importRes = await apiRequest(request, "POST", `${CONVERSATIONS}/import`, {
18
+ token: adminToken,
19
+ data: {
20
+ conversation: { conversationId: activeId, agentId },
21
+ messages: [{ clientMessageId: `msg-${randomUUID()}`, role: "user", content: "hello" }]
22
+ }
23
+ });
24
+ expect(importRes.status(), "import with a message succeeds").toBe(200);
25
+ const emptyIds = [];
26
+ for (let index = 0; index < 3; index += 1) {
27
+ const conversationId = `it-conv-empty-${index}-${randomUUID()}`;
28
+ created.push(conversationId);
29
+ const createRes = await apiRequest(request, "POST", CONVERSATIONS, {
30
+ token: adminToken,
31
+ data: { agentId, conversationId }
32
+ });
33
+ expect(createRes.status(), "create returns 201").toBe(201);
34
+ emptyIds.push(conversationId);
35
+ }
36
+ const seen = [];
37
+ let cursor = null;
38
+ for (let page = 0; page < 10; page += 1) {
39
+ const query = new URLSearchParams({ agent: agentId, limit: "1" });
40
+ if (cursor) query.set("cursor", cursor);
41
+ const listRes = await apiRequest(request, "GET", `${CONVERSATIONS}?${query.toString()}`, {
42
+ token: adminToken
43
+ });
44
+ expect(listRes.status()).toBe(200);
45
+ const body = await readJsonSafe(listRes);
46
+ seen.push(...(body?.items ?? []).map((item) => item.conversationId));
47
+ if (body?.nextCursor) {
48
+ expect(new Date(body.nextCursor).toISOString(), "nextCursor stays an ISO timestamp").toBe(body.nextCursor);
49
+ }
50
+ cursor = body?.nextPageToken ?? null;
51
+ if (!cursor) break;
52
+ }
53
+ expect(seen).toEqual([...emptyIds].reverse().concat(activeId));
54
+ } finally {
55
+ for (const conversationId of created) {
56
+ await deleteConversationCascadeInDb({ tenantId, conversationId }).catch(() => void 0);
57
+ }
58
+ }
59
+ });
60
+ });
61
+ //# sourceMappingURL=TC-AI-CONVERSATIONS-002-list-cursor-pagination.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/ai_assistant/__integration__/TC-AI-CONVERSATIONS-002-list-cursor-pagination.spec.ts"],
4
+ "sourcesContent": ["import { test, expect } from '@playwright/test';\nimport { randomUUID } from 'node:crypto';\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';\nimport { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';\nimport { deleteConversationCascadeInDb } from './helpers/aiAssistantFixtures';\n\n/**\n * TC-AI-CONVERSATIONS-002 \u2014 Conversation list cursor pagination returns every row exactly once.\n *\n * Conversations without messages have a null `lastMessageAt` and sort first. Walking\n * `nextPageToken` page by page must still reach every one of them, then the conversations\n * that do have messages. `nextCursor` stays the ISO timestamp it was before.\n */\n\nconst CONVERSATIONS = '/api/ai_assistant/ai/conversations';\n\ninterface ListResponse {\n items: Array<{ conversationId: string }>;\n nextCursor: string | null;\n nextPageToken: string | null;\n}\n\ntest.describe('TC-AI-CONVERSATIONS-002: conversation list cursor pagination', () => {\n test('walking nextPageToken with limit=1 returns every conversation exactly once', async ({ request }) => {\n test.slow();\n const adminToken = await getAuthToken(request, 'admin');\n const { tenantId } = getTokenScope(adminToken);\n const agentId = `it_conv.cursor_${randomUUID().slice(0, 8)}`;\n const created: string[] = [];\n\n try {\n const activeId = `it-conv-active-${randomUUID()}`;\n created.push(activeId);\n const importRes = await apiRequest(request, 'POST', `${CONVERSATIONS}/import`, {\n token: adminToken,\n data: {\n conversation: { conversationId: activeId, agentId },\n messages: [{ clientMessageId: `msg-${randomUUID()}`, role: 'user', content: 'hello' }],\n },\n });\n expect(importRes.status(), 'import with a message succeeds').toBe(200);\n\n const emptyIds: string[] = [];\n for (let index = 0; index < 3; index += 1) {\n const conversationId = `it-conv-empty-${index}-${randomUUID()}`;\n created.push(conversationId);\n const createRes = await apiRequest(request, 'POST', CONVERSATIONS, {\n token: adminToken,\n data: { agentId, conversationId },\n });\n expect(createRes.status(), 'create returns 201').toBe(201);\n emptyIds.push(conversationId);\n }\n\n const seen: string[] = [];\n let cursor: string | null = null;\n for (let page = 0; page < 10; page += 1) {\n const query = new URLSearchParams({ agent: agentId, limit: '1' });\n if (cursor) query.set('cursor', cursor);\n const listRes = await apiRequest(request, 'GET', `${CONVERSATIONS}?${query.toString()}`, {\n token: adminToken,\n });\n expect(listRes.status()).toBe(200);\n const body = await readJsonSafe<ListResponse>(listRes);\n seen.push(...(body?.items ?? []).map((item) => item.conversationId));\n if (body?.nextCursor) {\n expect(new Date(body.nextCursor).toISOString(), 'nextCursor stays an ISO timestamp').toBe(body.nextCursor);\n }\n cursor = body?.nextPageToken ?? null;\n if (!cursor) break;\n }\n\n expect(seen).toEqual([...emptyIds].reverse().concat(activeId));\n } finally {\n for (const conversationId of created) {\n await deleteConversationCascadeInDb({ tenantId, conversationId }).catch(() => undefined);\n }\n }\n });\n});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ACxB,UAAI,SAAwB;AAC5B,eAAS,OAAO,GAAG,OAAO,IAAI,QAAQ,GAAG;AACvC,cAAM,QAAQ,IAAI,gBAAgB,EAAE,OAAO,SAAS,OAAO,IAAI,CAAC;AAChE,YAAI,OAAQ,OAAM,IAAI,UAAU,MAAM;AACtC,cAAM,UAAU,MAAM,WAAW,SAAS,OAAO,GAAG,aAAa,IAAI,MAAM,SAAS,CAAC,IAAI;AAAA,UACvF,OAAO;AAAA,QACT,CAAC;AACD,eAAO,QAAQ,OAAO,CAAC,EAAE,KAAK,GAAG;AACjC,cAAM,OAAO,MAAM,aAA2B,OAAO;AACrD,aAAK,KAAK,IAAI,MAAM,SAAS,CAAC,GAAG,IAAI,CAAC,SAAS,KAAK,cAAc,CAAC;AACnE,YAAI,MAAM,YAAY;AACpB,iBAAO,IAAI,KAAK,KAAK,UAAU,EAAE,YAAY,GAAG,mCAAmC,EAAE,KAAK,KAAK,UAAU;AAAA,QAC3G;AACA,iBAAS,MAAM,iBAAiB;AAChC,YAAI,CAAC,OAAQ;AAAA,MACf;AAEA,aAAO,IAAI,EAAE,QAAQ,CAAC,GAAG,QAAQ,EAAE,QAAQ,EAAE,OAAO,QAAQ,CAAC;AAAA,IAC/D,UAAE;AACA,iBAAW,kBAAkB,SAAS;AACpC,cAAM,8BAA8B,EAAE,UAAU,eAAe,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MACzF;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -21,7 +21,7 @@ const openApi = {
21
21
  GET: {
22
22
  operationId: "aiAssistantListConversations",
23
23
  summary: "List AI chat conversations visible to the caller.",
24
- description: "Returns `{ items, nextCursor }` for the authenticated caller, ordered by `lastMessageAt` descending. View-only callers receive only their own conversations. Callers with `ai_assistant.conversations.manage` may list conversations across users in the same tenant/organization. The `agent` and `status` filters are optional; `cursor` is the ISO timestamp returned by a previous response.",
24
+ description: "Returns `{ items, nextCursor, nextPageToken }` for the authenticated caller, ordered by `lastMessageAt` descending (conversations without messages first), then `createdAt` and `id`. View-only callers receive only their own conversations. Callers with `ai_assistant.conversations.manage` may list conversations across users in the same tenant/organization. The `agent` and `status` filters are optional; `cursor` accepts the ISO timestamp `nextCursor` or the opaque `nextPageToken` returned by a previous response. Follow `nextPageToken` to visit every conversation exactly once; the timestamp `nextCursor` keeps its earlier behaviour and can skip conversations without messages or sharing the boundary timestamp.",
25
25
  responses: [
26
26
  {
27
27
  status: 200,
@@ -102,7 +102,7 @@ async function GET(req) {
102
102
  return jsonError(403, `Caller lacks required feature "${REQUIRED_FEATURE}".`, "forbidden");
103
103
  }
104
104
  if (callerCtx.kind === "missing-tenant") {
105
- return NextResponse.json({ items: [], nextCursor: null });
105
+ return NextResponse.json({ items: [], nextCursor: null, nextPageToken: null });
106
106
  }
107
107
  const url = new URL(req.url);
108
108
  const parseResult = aiChatConversationListQuerySchema.safeParse({
@@ -135,7 +135,8 @@ async function GET(req) {
135
135
  );
136
136
  return NextResponse.json({
137
137
  items: result.items.map((row) => serializeAiChatConversation(row)),
138
- nextCursor: result.nextCursor
138
+ nextCursor: result.nextCursor,
139
+ nextPageToken: result.nextPageToken
139
140
  });
140
141
  } catch (error) {
141
142
  logger.error("AI Conversations GET \u2014 Failure", { err: error });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/ai_assistant/api/ai/conversations/route.ts"],
4
- "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { NextResponse, type NextRequest } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n aiChatConversationCreateSchema,\n aiChatConversationListQuerySchema,\n} from '../../../data/validators'\nimport { hasRequiredFeatures } from '../../../lib/auth'\nimport {\n createConversationStorage,\n serializeAiChatConversation,\n} from '../../../lib/conversation-storage'\n\nconst logger = createLogger('ai_assistant')\n\nconst REQUIRED_FEATURE = 'ai_assistant.view'\nconst MANAGE_CONVERSATIONS_FEATURE = 'ai_assistant.conversations.manage'\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'AI Assistant',\n summary: 'Server-side AI chat conversations',\n methods: {\n GET: {\n operationId: 'aiAssistantListConversations',\n summary: 'List AI chat conversations visible to the caller.',\n description:\n 'Returns `{ items, nextCursor }` for the authenticated caller, ordered by `lastMessageAt` ' +\n 'descending. View-only callers receive only their own conversations. Callers with ' +\n '`ai_assistant.conversations.manage` may list conversations across users in the same ' +\n 'tenant/organization. The ' +\n '`agent` and `status` filters are optional; `cursor` is the ISO timestamp returned by a ' +\n 'previous response.',\n responses: [\n {\n status: 200,\n description: 'Caller-owned conversation summaries.',\n mediaType: 'application/json',\n },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters.' },\n { status: 401, description: 'Unauthenticated caller.' },\n { status: 403, description: 'Caller lacks the `ai_assistant.view` feature.' },\n ],\n },\n POST: {\n operationId: 'aiAssistantCreateConversation',\n summary: 'Idempotently create a new AI chat conversation.',\n description:\n 'If a non-deleted conversation already exists with the supplied `conversationId` for the ' +\n 'authenticated caller in this tenant/org, returns the existing summary. Otherwise creates a ' +\n 'fresh row and writes the owner-participant row in the same transaction.',\n responses: [\n {\n status: 200,\n description: 'Existing conversation (idempotent path).',\n mediaType: 'application/json',\n },\n {\n status: 201,\n description: 'Newly created conversation.',\n mediaType: 'application/json',\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request body.' },\n { status: 401, description: 'Unauthenticated caller.' },\n { status: 403, description: 'Caller lacks the `ai_assistant.view` feature.' },\n ],\n },\n },\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: [REQUIRED_FEATURE] },\n POST: { requireAuth: true, requireFeatures: [REQUIRED_FEATURE] },\n}\n\nfunction jsonError(\n status: number,\n message: string,\n code: string,\n extra?: Record<string, unknown>,\n): NextResponse {\n return NextResponse.json({ error: message, code, ...(extra ?? {}) }, { status })\n}\n\nasync function loadCallerContext(req: NextRequest): Promise<\n | { kind: 'unauthorized' }\n | { kind: 'forbidden' }\n | { kind: 'missing-tenant' }\n | {\n kind: 'ok'\n tenantId: string\n organizationId: string | null\n userId: string\n canManageConversations: boolean\n }\n> {\n const auth = await getAuthFromRequest(req)\n if (!auth) return { kind: 'unauthorized' }\n const container = await createRequestContainer()\n const rbacService = container.resolve<RbacService>('rbacService')\n const acl = await rbacService.loadAcl(auth.sub, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!hasRequiredFeatures([REQUIRED_FEATURE], acl.features, acl.isSuperAdmin, rbacService)) {\n return { kind: 'forbidden' }\n }\n const canManageConversations = hasRequiredFeatures(\n [MANAGE_CONVERSATIONS_FEATURE],\n acl.features,\n acl.isSuperAdmin,\n rbacService,\n )\n if (!auth.tenantId) {\n return { kind: 'missing-tenant' }\n }\n return {\n kind: 'ok',\n tenantId: auth.tenantId,\n organizationId: auth.orgId ?? null,\n userId: auth.sub,\n canManageConversations,\n }\n}\n\nexport async function GET(req: NextRequest): Promise<Response> {\n const callerCtx = await loadCallerContext(req)\n if (callerCtx.kind === 'unauthorized') return jsonError(401, 'Unauthorized', 'unauthenticated')\n if (callerCtx.kind === 'forbidden') {\n return jsonError(403, `Caller lacks required feature \"${REQUIRED_FEATURE}\".`, 'forbidden')\n }\n if (callerCtx.kind === 'missing-tenant') {\n return NextResponse.json({ items: [], nextCursor: null })\n }\n\n const url = new URL(req.url)\n const parseResult = aiChatConversationListQuerySchema.safeParse({\n agent: url.searchParams.get('agent') ?? undefined,\n status: url.searchParams.get('status') ?? undefined,\n limit: url.searchParams.get('limit') ?? undefined,\n cursor: url.searchParams.get('cursor') ?? undefined,\n })\n if (!parseResult.success) {\n return jsonError(400, 'Invalid query parameters.', 'validation_error', {\n issues: parseResult.error.issues,\n })\n }\n\n try {\n const container = await createRequestContainer()\n const repo = createConversationStorage(container)\n const result = await repo.list(\n {\n tenantId: callerCtx.tenantId,\n organizationId: callerCtx.organizationId,\n userId: callerCtx.userId,\n canManageConversations: callerCtx.canManageConversations,\n },\n {\n agentId: parseResult.data.agent ?? null,\n status: parseResult.data.status ?? null,\n limit: parseResult.data.limit,\n cursor: parseResult.data.cursor ?? null,\n },\n )\n return NextResponse.json({\n items: result.items.map((row) => serializeAiChatConversation(row)),\n nextCursor: result.nextCursor,\n })\n } catch (error) {\n logger.error('AI Conversations GET \u2014 Failure', { err: error })\n return jsonError(\n 500,\n error instanceof Error ? error.message : 'Failed to list conversations.',\n 'internal_error',\n )\n }\n}\n\nexport async function POST(req: NextRequest): Promise<Response> {\n const callerCtx = await loadCallerContext(req)\n if (callerCtx.kind === 'unauthorized') return jsonError(401, 'Unauthorized', 'unauthenticated')\n if (callerCtx.kind === 'forbidden') {\n return jsonError(403, `Caller lacks required feature \"${REQUIRED_FEATURE}\".`, 'forbidden')\n }\n if (callerCtx.kind === 'missing-tenant') {\n return jsonError(400, 'Caller is not bound to a tenant.', 'tenant_required')\n }\n\n let rawBody: unknown\n try {\n rawBody = await req.json()\n } catch {\n return jsonError(400, 'Request body must be valid JSON.', 'validation_error')\n }\n\n const parseResult = aiChatConversationCreateSchema.safeParse(rawBody)\n if (!parseResult.success) {\n return jsonError(400, 'Invalid conversation payload.', 'validation_error', {\n issues: parseResult.error.issues,\n })\n }\n\n try {\n const container = await createRequestContainer()\n const repo = createConversationStorage(container)\n const ctx = {\n tenantId: callerCtx.tenantId,\n organizationId: callerCtx.organizationId,\n userId: callerCtx.userId,\n canManageConversations: false,\n }\n const beforeRow = parseResult.data.conversationId\n ? await repo.getById(parseResult.data.conversationId, ctx)\n : null\n const row = await repo.createOrGet(\n {\n conversationId: parseResult.data.conversationId,\n agentId: parseResult.data.agentId,\n title: parseResult.data.title ?? null,\n pageContext: parseResult.data.pageContext ?? null,\n },\n ctx,\n )\n const status = beforeRow ? 200 : 201\n return NextResponse.json(serializeAiChatConversation(row), { status })\n } catch (error) {\n if (error instanceof Error && error.name === 'AiChatConversationOrgNotFoundError') {\n return jsonError(400, error.message, 'organization_not_found')\n }\n if (error instanceof Error && error.name === 'AiChatConversationAccessError') {\n return jsonError(404, error.message, 'conversation_not_found')\n }\n logger.error('AI Conversations POST \u2014 Failure', { err: error })\n return jsonError(\n 500,\n error instanceof Error ? error.message : 'Failed to create conversation.',\n 'internal_error',\n )\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,oBAAsC;AAE/C,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,cAAc;AAE1C,MAAM,mBAAmB;AACzB,MAAM,+BAA+B;AAE9B,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aACE;AAAA,MAMF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B;AAAA,QACxD,EAAE,QAAQ,KAAK,aAAa,0BAA0B;AAAA,QACtD,EAAE,QAAQ,KAAK,aAAa,gDAAgD;AAAA,MAC9E;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aACE;AAAA,MAGF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MAC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AAS,YAAY,KAAK;AAAA,QAC1B,OAAO,YAAY,KAAK,SAAS;AAAA,QACjC,aAAa,YAAY,KAAK,eAAe;AAAA,MAC/C;AAAA,MACA;AAAA,IACF;AACA,UAAM,SAAS,YAAY,MAAM;AACjC,WAAO,aAAa,KAAK,4BAA4B,GAAG,GAAG,EAAE,OAAO,CAAC;AAAA,EACvE,SAAS,OAAO;AACd,QAAI,iBAAiB,SAAS,MAAM,SAAS,sCAAsC;AACjF,aAAO,UAAU,KAAK,MAAM,SAAS,wBAAwB;AAAA,IAC/D;AACA,QAAI,iBAAiB,SAAS,MAAM,SAAS,iCAAiC;AAC5E,aAAO,UAAU,KAAK,MAAM,SAAS,wBAAwB;AAAA,IAC/D;AACA,WAAO,MAAM,wCAAmC,EAAE,KAAK,MAAM,CAAC;AAC9D,WAAO;AAAA,MACL;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { NextResponse, type NextRequest } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n aiChatConversationCreateSchema,\n aiChatConversationListQuerySchema,\n} from '../../../data/validators'\nimport { hasRequiredFeatures } from '../../../lib/auth'\nimport {\n createConversationStorage,\n serializeAiChatConversation,\n} from '../../../lib/conversation-storage'\n\nconst logger = createLogger('ai_assistant')\n\nconst REQUIRED_FEATURE = 'ai_assistant.view'\nconst MANAGE_CONVERSATIONS_FEATURE = 'ai_assistant.conversations.manage'\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'AI Assistant',\n summary: 'Server-side AI chat conversations',\n methods: {\n GET: {\n operationId: 'aiAssistantListConversations',\n summary: 'List AI chat conversations visible to the caller.',\n description:\n 'Returns `{ items, nextCursor, nextPageToken }` for the authenticated caller, ordered by `lastMessageAt` ' +\n 'descending (conversations without messages first), then `createdAt` and `id`. View-only callers receive only their own conversations. Callers with ' +\n '`ai_assistant.conversations.manage` may list conversations across users in the same ' +\n 'tenant/organization. The ' +\n '`agent` and `status` filters are optional; `cursor` accepts the ISO timestamp `nextCursor` or ' +\n 'the opaque `nextPageToken` returned by a previous response. Follow `nextPageToken` to visit ' +\n 'every conversation exactly once; the timestamp `nextCursor` keeps its earlier behaviour and ' +\n 'can skip conversations without messages or sharing the boundary timestamp.',\n responses: [\n {\n status: 200,\n description: 'Caller-owned conversation summaries.',\n mediaType: 'application/json',\n },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters.' },\n { status: 401, description: 'Unauthenticated caller.' },\n { status: 403, description: 'Caller lacks the `ai_assistant.view` feature.' },\n ],\n },\n POST: {\n operationId: 'aiAssistantCreateConversation',\n summary: 'Idempotently create a new AI chat conversation.',\n description:\n 'If a non-deleted conversation already exists with the supplied `conversationId` for the ' +\n 'authenticated caller in this tenant/org, returns the existing summary. Otherwise creates a ' +\n 'fresh row and writes the owner-participant row in the same transaction.',\n responses: [\n {\n status: 200,\n description: 'Existing conversation (idempotent path).',\n mediaType: 'application/json',\n },\n {\n status: 201,\n description: 'Newly created conversation.',\n mediaType: 'application/json',\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request body.' },\n { status: 401, description: 'Unauthenticated caller.' },\n { status: 403, description: 'Caller lacks the `ai_assistant.view` feature.' },\n ],\n },\n },\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: [REQUIRED_FEATURE] },\n POST: { requireAuth: true, requireFeatures: [REQUIRED_FEATURE] },\n}\n\nfunction jsonError(\n status: number,\n message: string,\n code: string,\n extra?: Record<string, unknown>,\n): NextResponse {\n return NextResponse.json({ error: message, code, ...(extra ?? {}) }, { status })\n}\n\nasync function loadCallerContext(req: NextRequest): Promise<\n | { kind: 'unauthorized' }\n | { kind: 'forbidden' }\n | { kind: 'missing-tenant' }\n | {\n kind: 'ok'\n tenantId: string\n organizationId: string | null\n userId: string\n canManageConversations: boolean\n }\n> {\n const auth = await getAuthFromRequest(req)\n if (!auth) return { kind: 'unauthorized' }\n const container = await createRequestContainer()\n const rbacService = container.resolve<RbacService>('rbacService')\n const acl = await rbacService.loadAcl(auth.sub, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!hasRequiredFeatures([REQUIRED_FEATURE], acl.features, acl.isSuperAdmin, rbacService)) {\n return { kind: 'forbidden' }\n }\n const canManageConversations = hasRequiredFeatures(\n [MANAGE_CONVERSATIONS_FEATURE],\n acl.features,\n acl.isSuperAdmin,\n rbacService,\n )\n if (!auth.tenantId) {\n return { kind: 'missing-tenant' }\n }\n return {\n kind: 'ok',\n tenantId: auth.tenantId,\n organizationId: auth.orgId ?? null,\n userId: auth.sub,\n canManageConversations,\n }\n}\n\nexport async function GET(req: NextRequest): Promise<Response> {\n const callerCtx = await loadCallerContext(req)\n if (callerCtx.kind === 'unauthorized') return jsonError(401, 'Unauthorized', 'unauthenticated')\n if (callerCtx.kind === 'forbidden') {\n return jsonError(403, `Caller lacks required feature \"${REQUIRED_FEATURE}\".`, 'forbidden')\n }\n if (callerCtx.kind === 'missing-tenant') {\n return NextResponse.json({ items: [], nextCursor: null, nextPageToken: null })\n }\n\n const url = new URL(req.url)\n const parseResult = aiChatConversationListQuerySchema.safeParse({\n agent: url.searchParams.get('agent') ?? undefined,\n status: url.searchParams.get('status') ?? undefined,\n limit: url.searchParams.get('limit') ?? undefined,\n cursor: url.searchParams.get('cursor') ?? undefined,\n })\n if (!parseResult.success) {\n return jsonError(400, 'Invalid query parameters.', 'validation_error', {\n issues: parseResult.error.issues,\n })\n }\n\n try {\n const container = await createRequestContainer()\n const repo = createConversationStorage(container)\n const result = await repo.list(\n {\n tenantId: callerCtx.tenantId,\n organizationId: callerCtx.organizationId,\n userId: callerCtx.userId,\n canManageConversations: callerCtx.canManageConversations,\n },\n {\n agentId: parseResult.data.agent ?? null,\n status: parseResult.data.status ?? null,\n limit: parseResult.data.limit,\n cursor: parseResult.data.cursor ?? null,\n },\n )\n return NextResponse.json({\n items: result.items.map((row) => serializeAiChatConversation(row)),\n nextCursor: result.nextCursor,\n nextPageToken: result.nextPageToken,\n })\n } catch (error) {\n logger.error('AI Conversations GET \u2014 Failure', { err: error })\n return jsonError(\n 500,\n error instanceof Error ? error.message : 'Failed to list conversations.',\n 'internal_error',\n )\n }\n}\n\nexport async function POST(req: NextRequest): Promise<Response> {\n const callerCtx = await loadCallerContext(req)\n if (callerCtx.kind === 'unauthorized') return jsonError(401, 'Unauthorized', 'unauthenticated')\n if (callerCtx.kind === 'forbidden') {\n return jsonError(403, `Caller lacks required feature \"${REQUIRED_FEATURE}\".`, 'forbidden')\n }\n if (callerCtx.kind === 'missing-tenant') {\n return jsonError(400, 'Caller is not bound to a tenant.', 'tenant_required')\n }\n\n let rawBody: unknown\n try {\n rawBody = await req.json()\n } catch {\n return jsonError(400, 'Request body must be valid JSON.', 'validation_error')\n }\n\n const parseResult = aiChatConversationCreateSchema.safeParse(rawBody)\n if (!parseResult.success) {\n return jsonError(400, 'Invalid conversation payload.', 'validation_error', {\n issues: parseResult.error.issues,\n })\n }\n\n try {\n const container = await createRequestContainer()\n const repo = createConversationStorage(container)\n const ctx = {\n tenantId: callerCtx.tenantId,\n organizationId: callerCtx.organizationId,\n userId: callerCtx.userId,\n canManageConversations: false,\n }\n const beforeRow = parseResult.data.conversationId\n ? await repo.getById(parseResult.data.conversationId, ctx)\n : null\n const row = await repo.createOrGet(\n {\n conversationId: parseResult.data.conversationId,\n agentId: parseResult.data.agentId,\n title: parseResult.data.title ?? null,\n pageContext: parseResult.data.pageContext ?? null,\n },\n ctx,\n )\n const status = beforeRow ? 200 : 201\n return NextResponse.json(serializeAiChatConversation(row), { status })\n } catch (error) {\n if (error instanceof Error && error.name === 'AiChatConversationOrgNotFoundError') {\n return jsonError(400, error.message, 'organization_not_found')\n }\n if (error instanceof Error && error.name === 'AiChatConversationAccessError') {\n return jsonError(404, error.message, 'conversation_not_found')\n }\n logger.error('AI Conversations POST \u2014 Failure', { err: error })\n return jsonError(\n 500,\n error instanceof Error ? error.message : 'Failed to create conversation.',\n 'internal_error',\n )\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,oBAAsC;AAE/C,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,cAAc;AAE1C,MAAM,mBAAmB;AACzB,MAAM,+BAA+B;AAE9B,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aACE;AAAA,MAQF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B;AAAA,QACxD,EAAE,QAAQ,KAAK,aAAa,0BAA0B;AAAA,QACtD,EAAE,QAAQ,KAAK,aAAa,gDAAgD;AAAA,MAC9E;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aACE;AAAA,MAGF,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,QACA;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,WAAW;AAAA,QACb;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,wBAAwB;AAAA,QACpD,EAAE,QAAQ,KAAK,aAAa,0BA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,QACjC,aAAa,YAAY,KAAK,eAAe;AAAA,MAC/C;AAAA,MACA;AAAA,IACF;AACA,UAAM,SAAS,YAAY,MAAM;AACjC,WAAO,aAAa,KAAK,4BAA4B,GAAG,GAAG,EAAE,OAAO,CAAC;AAAA,EACvE,SAAS,OAAO;AACd,QAAI,iBAAiB,SAAS,MAAM,SAAS,sCAAsC;AACjF,aAAO,UAAU,KAAK,MAAM,SAAS,wBAAwB;AAAA,IAC/D;AACA,QAAI,iBAAiB,SAAS,MAAM,SAAS,iCAAiC;AAC5E,aAAO,UAAU,KAAK,MAAM,SAAS,wBAAwB;AAAA,IAC/D;AACA,WAAO,MAAM,wCAAmC,EAAE,KAAK,MAAM,CAAC;AAC9D,WAAO;AAAA,MACL;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU;AAAA,MACzC;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,4 @@
1
+ import { z } from "zod";
1
2
  import {
2
3
  findOneWithDecryption,
3
4
  findWithDecryption
@@ -148,17 +149,15 @@ class AiChatConversationRepository {
148
149
  if (options.agentId) where.agentId = options.agentId;
149
150
  if (options.status) where.status = options.status;
150
151
  if (options.cursor) {
151
- const cursorDate = parseIso(options.cursor);
152
- if (cursorDate) {
153
- where.lastMessageAt = { $lt: cursorDate };
154
- }
152
+ const cursorFilter = buildListCursorFilter(options.cursor);
153
+ if (cursorFilter) where.$and = [cursorFilter];
155
154
  }
156
155
  const rows = await findWithDecryption(
157
156
  this.em,
158
157
  AiChatConversation,
159
158
  where,
160
159
  {
161
- orderBy: [{ lastMessageAt: "desc" }, { createdAt: "desc" }],
160
+ orderBy: [{ lastMessageAt: "desc" }, { createdAt: "desc" }, { id: "desc" }],
162
161
  limit: limit + 1
163
162
  },
164
163
  {
@@ -167,12 +166,14 @@ class AiChatConversationRepository {
167
166
  }
168
167
  );
169
168
  let nextCursor = null;
169
+ let nextPageToken = null;
170
170
  if (rows.length > limit) {
171
171
  const lastIncluded = rows[limit - 1];
172
172
  const cursorValue = lastIncluded.lastMessageAt ?? lastIncluded.createdAt;
173
173
  nextCursor = cursorValue ? cursorValue.toISOString() : null;
174
+ nextPageToken = encodeListCursor(lastIncluded);
174
175
  }
175
- return { items: rows.slice(0, limit), nextCursor };
176
+ return { items: rows.slice(0, limit), nextCursor, nextPageToken };
176
177
  }
177
178
  /** Update within tenant/org. View-only callers can update only their own conversations. */
178
179
  async update(conversationId, patch, ctx) {
@@ -661,6 +662,45 @@ function parseIso(value) {
661
662
  const date = new Date(value);
662
663
  return Number.isNaN(date.getTime()) ? null : date;
663
664
  }
665
+ const listCursorSchema = z.object({
666
+ l: z.string().datetime().nullable(),
667
+ c: z.string().datetime(),
668
+ i: z.guid()
669
+ });
670
+ function encodeListCursor(row) {
671
+ const payload = {
672
+ l: row.lastMessageAt ? row.lastMessageAt.toISOString() : null,
673
+ c: row.createdAt.toISOString(),
674
+ i: row.id
675
+ };
676
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
677
+ }
678
+ function decodeListCursor(value) {
679
+ try {
680
+ const parsed = listCursorSchema.safeParse(
681
+ JSON.parse(Buffer.from(value, "base64url").toString("utf8"))
682
+ );
683
+ return parsed.success ? parsed.data : null;
684
+ } catch {
685
+ return null;
686
+ }
687
+ }
688
+ function buildListCursorFilter(value) {
689
+ const cursor = decodeListCursor(value);
690
+ if (!cursor) {
691
+ const legacyDate = parseIso(value);
692
+ return legacyDate ? { lastMessageAt: { $lt: legacyDate } } : null;
693
+ }
694
+ const lastMessageAt = cursor.l ? new Date(cursor.l) : null;
695
+ const createdAt = new Date(cursor.c);
696
+ return {
697
+ $or: [
698
+ lastMessageAt ? { lastMessageAt: { $lt: lastMessageAt } } : { lastMessageAt: { $ne: null } },
699
+ { lastMessageAt, createdAt: { $lt: createdAt } },
700
+ { lastMessageAt, createdAt, id: { $lt: cursor.i } }
701
+ ]
702
+ };
703
+ }
664
704
  function generateConversationId() {
665
705
  const cryptoMod = typeof globalThis === "object" ? globalThis.crypto : void 0;
666
706
  if (cryptoMod?.randomUUID) return cryptoMod.randomUUID();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/ai_assistant/data/repositories/AiChatConversationRepository.ts"],
4
- "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport {\n AiChatConversation,\n AiChatConversationParticipant,\n AiChatMessage,\n} from '../entities'\nimport type {\n AiChatMessageAppendInput,\n AiChatPageContextInput,\n} from '../validators'\n\n/**\n * Persistent store for AI chat conversations, participants, and messages.\n *\n * Owner-first MVP per spec\n * `2026-05-05-ai-chat-server-side-conversation-storage`. Every read/write\n * goes through `findOneWithDecryption` / `findWithDecryption` because the\n * conversation `title` and the message `content` / `ui_parts` /\n * `files_metadata` / `metadata` columns are declared in the module's\n * `encryption.ts` and are encrypted at rest when tenant data encryption is\n * enabled.\n *\n * Tenant + organization scope is required on every method. View-only callers\n * are owner-scoped. Callers with `ai_assistant.conversations.manage` may\n * list/read/update/delete any conversation in the same tenant/org, but never\n * outside that boundary. The participant row is written transactionally\n * alongside conversation create/import.\n *\n */\n\nexport interface AiChatConversationContext {\n tenantId: string\n organizationId?: string | null\n userId: string\n canManageConversations?: boolean\n}\n\nexport interface AiChatConversationCreateOrGetInput {\n conversationId?: string | null\n agentId: string\n title?: string | null\n pageContext?: AiChatPageContextInput | null\n /** Marks the conversation as imported from local storage (sets `importedFromLocalAt`). */\n importedFromLocal?: boolean\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiChatConversationListOptions {\n agentId?: string | null\n status?: 'open' | 'closed' | null\n limit?: number\n cursor?: string | null\n}\n\nexport interface AiChatConversationUpdateInput {\n title?: string | null\n status?: 'open' | 'closed'\n pageContext?: AiChatPageContextInput | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiChatTranscriptOptions {\n limit?: number\n /** ISO timestamp string; rows strictly older than this are returned. */\n before?: string | null\n}\n\nexport interface AiChatTranscriptResult {\n conversation: AiChatConversation\n messages: AiChatMessage[]\n nextCursor: string | null\n}\n\nexport interface AiChatMessageAppendOptions {\n /** Override the message timestamp (used to thread server-injected stream-completion turns). */\n createdAt?: Date\n /** Override `createdByUserId` (defaults to the calling context user). */\n createdByUserId?: string | null\n}\n\nexport interface AiChatConversationImportResult {\n conversation: AiChatConversation\n importedMessageCount: number\n skippedMessageCount: number\n}\n\nconst DEFAULT_LIST_LIMIT = 50\nconst MAX_LIST_LIMIT = 100\nconst DEFAULT_TRANSCRIPT_LIMIT = 100\nconst MAX_TRANSCRIPT_LIMIT = 200\n\nexport class AiChatConversationAccessError extends Error {\n override readonly name = 'AiChatConversationAccessError'\n constructor(message: string = 'Conversation is not accessible to the caller.') {\n super(message)\n }\n}\n\nexport class AiChatConversationDuplicateParticipantError extends Error {\n override readonly name = 'AiChatConversationDuplicateParticipantError'\n constructor(message: string = 'User is already an active participant in this conversation.') {\n super(message)\n }\n}\n\nexport class AiChatParticipantNotFoundError extends Error {\n override readonly name = 'AiChatParticipantNotFoundError'\n constructor(message: string = 'Participant not found or already revoked.') {\n super(message)\n }\n}\n\nexport class AiChatConversationOrgNotFoundError extends Error {\n override readonly name = 'AiChatConversationOrgNotFoundError'\n constructor(message: string = 'Organization does not exist or is inactive for this tenant.') {\n super(message)\n }\n}\n\nexport class AiChatConversationRepository {\n constructor(private readonly em: EntityManager) {}\n\n /**\n * Idempotent create. If a non-deleted conversation already exists for the\n * caller in this tenant/org with the same `conversationId`, returns the\n * existing row. The owner-participant row is created in the same\n * transaction; a partial failure leaves no orphan conversation.\n */\n async createOrGet(\n input: AiChatConversationCreateOrGetInput,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation> {\n assertContext(ctx, 'createOrGet')\n if (!input?.agentId) {\n throw new Error('AiChatConversationRepository.createOrGet requires agentId')\n }\n const now = input.now ?? new Date()\n const conversationId = (input.conversationId ?? '').trim() || generateConversationId()\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (existing) {\n if (existing.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError()\n }\n return existing\n }\n await assertOrganizationExists(tx as unknown as EntityManager, ctx)\n const conversation = tx.create(AiChatConversation, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n agentId: input.agentId,\n ownerUserId: ctx.userId,\n title: normalizeTitle(input.title),\n status: 'open',\n visibility: 'private',\n pageContext: input.pageContext ?? null,\n lastMessageAt: null,\n importedFromLocalAt: input.importedFromLocal ? now : null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n } as unknown as AiChatConversation)\n const participant = tx.create(AiChatConversationParticipant, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n userId: ctx.userId,\n role: 'owner',\n lastReadAt: null,\n createdAt: now,\n updatedAt: now,\n } as unknown as AiChatConversationParticipant)\n await tx.persist(conversation).persist(participant).flush()\n return conversation\n })\n }\n\n /** Fetch within tenant/org. View-only callers see only their own conversations. */\n async getById(\n conversationId: string,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation | null> {\n assertContext(ctx, 'getById')\n if (!conversationId) return null\n const row = await findOneAccessibleConversation(this.em, conversationId, ctx)\n if (!row) return null\n const isParticipant =\n !canManageConversations(ctx) && row.ownerUserId !== ctx.userId\n ? await this.loadParticipantFlag(\n this.em,\n ctx.tenantId!,\n ctx.organizationId,\n row.conversationId,\n ctx.userId!,\n )\n : false\n if (!canAccessConversation(row, ctx, isParticipant)) return null\n return row\n }\n\n /** Owner-scoped list unless the caller has tenant/org manage access. Participants also see shared conversations. */\n async list(\n ctx: AiChatConversationContext,\n options: AiChatConversationListOptions = {},\n ): Promise<{ items: AiChatConversation[]; nextCursor: string | null }> {\n assertContext(ctx, 'list')\n const limit = clampLimit(options.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT)\n const where: Record<string, unknown> = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n deletedAt: null,\n }\n if (!canManageConversations(ctx)) {\n const participantFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n userId: ctx.userId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const participantRows = await findWithDecryption<AiChatConversationParticipant>(\n this.em,\n AiChatConversationParticipant,\n participantFilter,\n { fields: ['conversationId'] as any },\n { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null },\n )\n const participantConvIds = participantRows.map((p) => p.conversationId)\n if (participantConvIds.length > 0) {\n where.$or = [\n { ownerUserId: ctx.userId },\n { conversationId: { $in: participantConvIds } },\n ]\n } else {\n where.ownerUserId = ctx.userId\n }\n }\n if (options.agentId) where.agentId = options.agentId\n if (options.status) where.status = options.status\n if (options.cursor) {\n const cursorDate = parseIso(options.cursor)\n if (cursorDate) {\n where.lastMessageAt = { $lt: cursorDate }\n }\n }\n const rows = await findWithDecryption<AiChatConversation>(\n this.em,\n AiChatConversation,\n where as any,\n {\n orderBy: [{ lastMessageAt: 'desc' }, { createdAt: 'desc' }] as any,\n limit: limit + 1,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n let nextCursor: string | null = null\n if (rows.length > limit) {\n const lastIncluded = rows[limit - 1]\n const cursorValue = lastIncluded.lastMessageAt ?? lastIncluded.createdAt\n nextCursor = cursorValue ? cursorValue.toISOString() : null\n }\n return { items: rows.slice(0, limit), nextCursor }\n }\n\n /** Update within tenant/org. View-only callers can update only their own conversations. */\n async update(\n conversationId: string,\n patch: AiChatConversationUpdateInput,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation> {\n assertContext(ctx, 'update')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.update requires conversationId')\n }\n return this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!existing) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (!canAccessConversation(existing, ctx)) {\n throw new AiChatConversationAccessError()\n }\n const now = patch.now ?? new Date()\n if (Object.prototype.hasOwnProperty.call(patch, 'title')) {\n existing.title = normalizeTitle(patch.title)\n }\n if (patch.status) existing.status = patch.status\n if (Object.prototype.hasOwnProperty.call(patch, 'pageContext')) {\n existing.pageContext = patch.pageContext ?? null\n }\n existing.updatedAt = now\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n /** Soft-delete the conversation and all its messages in one transaction. */\n async softDelete(\n conversationId: string,\n ctx: AiChatConversationContext,\n now: Date = new Date(),\n ): Promise<void> {\n assertContext(ctx, 'softDelete')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.softDelete requires conversationId')\n }\n await this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!existing) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (!canAccessConversation(existing, ctx)) {\n throw new AiChatConversationAccessError()\n }\n existing.deletedAt = now\n existing.status = 'closed'\n existing.updatedAt = now\n await tx.persist(existing).flush()\n\n const messages = await findWithDecryption<AiChatMessage>(\n tx as unknown as EntityManager,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n for (const msg of messages) {\n msg.deletedAt = now\n msg.updatedAt = now\n tx.persist(msg)\n }\n if (messages.length > 0) await tx.flush()\n })\n }\n\n /**\n * Owner-only transcript hydration. Internally fetched DESC so the `before`\n * cursor naturally advances toward older messages, then reversed so the\n * response contract (`messages` array ordered ascending by `createdAt`)\n * stays stable for callers. `nextCursor` points to the OLDEST message in\n * the returned page \u2014 the next call with `before=<cursor>` fetches the\n * next-older window.\n */\n async getTranscript(\n conversationId: string,\n ctx: AiChatConversationContext,\n options: AiChatTranscriptOptions = {},\n ): Promise<AiChatTranscriptResult | null> {\n assertContext(ctx, 'getTranscript')\n if (!conversationId) return null\n const conversation = await this.getById(conversationId, ctx)\n if (!conversation) return null\n const limit = clampLimit(options.limit, DEFAULT_TRANSCRIPT_LIMIT, MAX_TRANSCRIPT_LIMIT)\n const where: Record<string, unknown> = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n }\n if (options.before) {\n const beforeDate = parseIso(options.before)\n if (beforeDate) {\n where.createdAt = { $lt: beforeDate }\n }\n }\n const rows = await findWithDecryption<AiChatMessage>(\n this.em,\n AiChatMessage,\n where as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: limit + 1,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n let nextCursor: string | null = null\n let pageDesc: AiChatMessage[]\n if (rows.length > limit) {\n pageDesc = rows.slice(0, limit)\n const oldestIncluded = pageDesc[pageDesc.length - 1]\n nextCursor = oldestIncluded?.createdAt ? oldestIncluded.createdAt.toISOString() : null\n } else {\n pageDesc = rows\n }\n const messages = [...pageDesc].reverse()\n return { conversation, messages, nextCursor }\n }\n\n /**\n * Append a single message to an owner-accessible conversation. Honors\n * `clientMessageId` idempotency: if a non-deleted message with the same\n * client id already exists, returns it untouched.\n */\n async appendMessage(\n conversationId: string,\n input: AiChatMessageAppendInput,\n ctx: AiChatConversationContext,\n options: AiChatMessageAppendOptions = {},\n ): Promise<AiChatMessage> {\n assertContext(ctx, 'appendMessage')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.appendMessage requires conversationId')\n }\n return this.em.transactional(async (tx) => {\n const conversation = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conversation) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conversation.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError()\n }\n const now = options.createdAt ?? new Date()\n if (input.clientMessageId) {\n const existing = await findOneWithDecryption<AiChatMessage>(\n tx as unknown as EntityManager,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n clientMessageId: input.clientMessageId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing) return existing\n }\n const message = tx.create(AiChatMessage, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n clientMessageId: input.clientMessageId ?? null,\n role: input.role,\n content: input.content,\n uiParts: normalizeArray(input.uiParts),\n attachmentIds: normalizeArray(input.attachmentIds),\n filesMetadata: normalizeArray(input.files),\n model: input.model ?? null,\n metadata: input.metadata ?? null,\n createdByUserId:\n options.createdByUserId === undefined\n ? input.role === 'user'\n ? ctx.userId\n : null\n : options.createdByUserId,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n } as unknown as AiChatMessage)\n conversation.lastMessageAt = now\n conversation.updatedAt = now\n await tx.persist(message).persist(conversation).flush()\n return message\n })\n }\n\n /**\n * Lazy migration entrypoint: create-or-get the conversation and append the\n * provided messages with `clientMessageId` dedupe. Designed to be safe to\n * call repeatedly \u2014 repeated imports of the same payload return the same\n * counts of imported/skipped rows.\n */\n async importLocalConversation(\n input: {\n conversation: AiChatConversationCreateOrGetInput & {\n status?: 'open' | 'closed'\n }\n messages: AiChatMessageAppendInput[]\n },\n ctx: AiChatConversationContext,\n now: Date = new Date(),\n ): Promise<AiChatConversationImportResult> {\n assertContext(ctx, 'importLocalConversation')\n const conversation = await this.createOrGet(\n { ...input.conversation, importedFromLocal: true, now },\n ctx,\n )\n if (input.conversation.status && conversation.status !== input.conversation.status) {\n await this.update(\n conversation.conversationId,\n { status: input.conversation.status, now },\n ctx,\n )\n }\n let imported = 0\n let skipped = 0\n for (const message of input.messages) {\n if (!message.clientMessageId) {\n // Without an idempotency key the import has no safe way to dedupe.\n skipped += 1\n continue\n }\n const before = await findOneWithDecryption<AiChatMessage>(\n this.em,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId: conversation.conversationId,\n clientMessageId: message.clientMessageId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (before) {\n skipped += 1\n continue\n }\n await this.appendMessage(\n conversation.conversationId,\n message,\n ctx,\n { createdAt: now },\n )\n imported += 1\n }\n return {\n conversation,\n importedMessageCount: imported,\n skippedMessageCount: skipped,\n }\n }\n\n async listParticipants(\n conversationId: string,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversationParticipant[]> {\n assertContext(ctx, 'listParticipants')\n const conv = await findOneAccessibleConversation(this.em, conversationId, ctx)\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId && !canManageConversations(ctx)) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner or a manager can list participants.',\n )\n }\n const filter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n return findWithDecryption<AiChatConversationParticipant>(\n this.em,\n AiChatConversationParticipant,\n filter,\n { orderBy: { createdAt: 'asc' } as any },\n { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null },\n )\n }\n\n async addParticipant(\n conversationId: string,\n userId: string,\n role: 'viewer',\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversationParticipant> {\n assertContext(ctx, 'addParticipant')\n return this.em.transactional(async (tx) => {\n const conv = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner can add participants.',\n )\n }\n const existingFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n userId,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const existing = await findOneWithDecryption<AiChatConversationParticipant>(\n tx as unknown as EntityManager,\n AiChatConversationParticipant,\n existingFilter,\n )\n if (existing) {\n if (existing.deletedAt === null) {\n throw new AiChatConversationDuplicateParticipantError()\n }\n existing.deletedAt = null\n existing.role = role\n await tx.persist(existing).flush()\n if (conv.visibility === 'private') {\n conv.visibility = 'shared'\n await tx.persist(conv).flush()\n }\n return existing\n }\n const participant = tx.create(AiChatConversationParticipant, {\n tenantId: ctx.tenantId!,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n userId,\n role,\n } as unknown as AiChatConversationParticipant)\n if (conv.visibility === 'private') {\n conv.visibility = 'shared'\n }\n await tx.persist(participant).persist(conv).flush()\n return participant\n })\n }\n\n async revokeParticipant(\n conversationId: string,\n targetUserId: string,\n ctx: AiChatConversationContext,\n ): Promise<void> {\n assertContext(ctx, 'revokeParticipant')\n await this.em.transactional(async (tx) => {\n const conv = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner can revoke participants.',\n )\n }\n if (targetUserId === conv.ownerUserId) {\n throw new AiChatConversationAccessError('Cannot revoke the conversation owner.')\n }\n const participantFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n userId: targetUserId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const participant = await findOneWithDecryption<AiChatConversationParticipant>(\n tx as unknown as EntityManager,\n AiChatConversationParticipant,\n participantFilter,\n )\n if (!participant) throw new AiChatParticipantNotFoundError()\n participant.deletedAt = new Date()\n const remainingCount = await tx.count(AiChatConversationParticipant, {\n tenantId: ctx.tenantId,\n conversationId,\n deletedAt: null,\n role: { $ne: 'owner' },\n } as FilterQuery<AiChatConversationParticipant>)\n if (remainingCount <= 1) {\n conv.visibility = 'private'\n await tx.persist(conv)\n }\n await tx.persist(participant).flush()\n })\n }\n\n async getParticipantCount(\n tenantId: string,\n organizationId: string | null | undefined,\n conversationId: string,\n ): Promise<number> {\n return this.em.count(AiChatConversationParticipant, {\n tenantId,\n conversationId,\n deletedAt: null,\n role: { $ne: 'owner' },\n ...(organizationId ? { organizationId } : {}),\n } as FilterQuery<AiChatConversationParticipant>)\n }\n\n private async loadParticipantFlag(\n em: EntityManager,\n tenantId: string,\n organizationId: string | null | undefined,\n conversationId: string,\n userId: string,\n ): Promise<boolean> {\n const row = await findOneWithDecryption<AiChatConversationParticipant>(\n em,\n AiChatConversationParticipant,\n {\n tenantId,\n conversationId,\n userId,\n deletedAt: null,\n ...(organizationId ? { organizationId } : {}),\n } as FilterQuery<AiChatConversationParticipant>,\n )\n return row !== null\n }\n}\n\nfunction assertContext(ctx: AiChatConversationContext | undefined, method: string): void {\n if (!ctx?.tenantId) {\n throw new Error(`AiChatConversationRepository.${method} requires tenantId`)\n }\n if (!ctx?.userId) {\n throw new Error(`AiChatConversationRepository.${method} requires userId`)\n }\n}\n\nfunction canManageConversations(ctx: AiChatConversationContext): boolean {\n return ctx.canManageConversations === true\n}\n\nfunction canAccessConversation(\n row: AiChatConversation,\n ctx: AiChatConversationContext,\n isParticipant = false,\n): boolean {\n return canManageConversations(ctx) || row.ownerUserId === ctx.userId || isParticipant\n}\n\nasync function assertOrganizationExists(\n em: EntityManager,\n ctx: AiChatConversationContext,\n): Promise<void> {\n if (!ctx.organizationId) return\n const org = await findOneWithDecryption<Organization>(\n em,\n Organization,\n {\n id: ctx.organizationId,\n tenant: ctx.tenantId,\n deletedAt: null,\n isActive: true,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!org) {\n throw new AiChatConversationOrgNotFoundError(\n `Organization \"${ctx.organizationId}\" does not exist or is inactive in tenant \"${ctx.tenantId}\".`,\n )\n }\n}\n\nasync function findOneAccessibleConversation(\n em: EntityManager,\n conversationId: string,\n ctx: AiChatConversationContext,\n): Promise<AiChatConversation | null> {\n const row = await findOneWithDecryption<AiChatConversation>(\n em,\n AiChatConversation,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n}\n\nfunction normalizeTitle(title: string | null | undefined): string | null {\n if (title === undefined) return null\n if (title === null) return null\n const trimmed = title.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeArray<T>(value: T[] | null | undefined): T[] | null {\n if (!Array.isArray(value) || value.length === 0) return null\n return value\n}\n\nfunction clampLimit(value: number | undefined | null, fallback: number, max: number): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return fallback\n return Math.max(1, Math.min(Math.floor(value), max))\n}\n\nfunction parseIso(value: string): Date | null {\n if (!value) return null\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nfunction generateConversationId(): string {\n // Prefer the runtime crypto generator when present; fall back to a non-cryptographic\n // string for environments without `crypto.randomUUID()` (older Node / test mocks).\n const cryptoMod: { randomUUID?: () => string } | undefined =\n typeof globalThis === 'object' ? (globalThis as any).crypto : undefined\n if (cryptoMod?.randomUUID) return cryptoMod.randomUUID()\n return `chat_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\n}\n\nexport default AiChatConversationRepository\n"],
5
- "mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAmFP,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,uBAAuB;AAEtB,MAAM,sCAAsC,MAAM;AAAA,EAEvD,YAAY,UAAkB,iDAAiD;AAC7E,UAAM,OAAO;AAFf,SAAkB,OAAO;AAAA,EAGzB;AACF;AAEO,MAAM,oDAAoD,MAAM;AAAA,EAErE,YAAY,UAAkB,+DAA+D;AAC3F,UAAM,OAAO;AAFf,SAAkB,OAAO;AAAA,EAGzB;AACF;AAEO,MAAM,uCAAuC,MAAM;AAAA,EAExD,YAAY,UAAkB,6CAA6C;AACzE,UAAM,OAAO;AAFf,SAAkB,OAAO;AAAA,EAGzB;AACF;AAEO,MAAM,2CAA2C,MAAM;AAAA,EAE5D,YAAY,UAAkB,+DAA+D;AAC3F,UAAM,OAAO;AAFf,SAAkB,OAAO;AAAA,EAGzB;AACF;AAEO,MAAM,6BAA6B;AAAA,EACxC,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjD,MAAM,YACJ,OACA,KAC6B;AAC7B,kBAAc,KAAK,aAAa;AAChC,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,2DAA2D;AAAA,IAC7E;AACA,UAAM,MAAM,MAAM,OAAO,oBAAI,KAAK;AAClC,UAAM,kBAAkB,MAAM,kBAAkB,IAAI,KAAK,KAAK,uBAAuB;AAErF,WAAO,KAAK,GAAG,cAAc,OAAO,OAAO;AACzC,YAAM,WAAW,MAAM;AAAA,QACrB;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,UAAI,UAA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I,KAAK,MAAM,KAAK,GAAG,GAAG,CAAC;AACrD;AAEA,SAAS,SAAS,OAA4B;AAC5C,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,OAAO,IAAI,KAAK,KAAK;AAC3B,SAAO,OAAO,MAAM,KAAK,QAAQ,CAAC,IAAI,OAAO;AAC/C;AAEA,SAAS,yBAAiC;AAGxC,QAAM,YACJ,OAAO,eAAe,WAAY,WAAmB,SAAS;AAChE,MAAI,WAAW,WAAY,QAAO,UAAU,WAAW;AACvD,SAAO,QAAQ,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AACnF;AAEA,IAAO,uCAAQ;",
4
+ "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport {\n AiChatConversation,\n AiChatConversationParticipant,\n AiChatMessage,\n} from '../entities'\nimport type {\n AiChatMessageAppendInput,\n AiChatPageContextInput,\n} from '../validators'\n\n/**\n * Persistent store for AI chat conversations, participants, and messages.\n *\n * Owner-first MVP per spec\n * `2026-05-05-ai-chat-server-side-conversation-storage`. Every read/write\n * goes through `findOneWithDecryption` / `findWithDecryption` because the\n * conversation `title` and the message `content` / `ui_parts` /\n * `files_metadata` / `metadata` columns are declared in the module's\n * `encryption.ts` and are encrypted at rest when tenant data encryption is\n * enabled.\n *\n * Tenant + organization scope is required on every method. View-only callers\n * are owner-scoped. Callers with `ai_assistant.conversations.manage` may\n * list/read/update/delete any conversation in the same tenant/org, but never\n * outside that boundary. The participant row is written transactionally\n * alongside conversation create/import.\n *\n */\n\nexport interface AiChatConversationContext {\n tenantId: string\n organizationId?: string | null\n userId: string\n canManageConversations?: boolean\n}\n\nexport interface AiChatConversationCreateOrGetInput {\n conversationId?: string | null\n agentId: string\n title?: string | null\n pageContext?: AiChatPageContextInput | null\n /** Marks the conversation as imported from local storage (sets `importedFromLocalAt`). */\n importedFromLocal?: boolean\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiChatConversationListOptions {\n agentId?: string | null\n status?: 'open' | 'closed' | null\n limit?: number\n cursor?: string | null\n}\n\nexport interface AiChatConversationUpdateInput {\n title?: string | null\n status?: 'open' | 'closed'\n pageContext?: AiChatPageContextInput | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiChatTranscriptOptions {\n limit?: number\n /** ISO timestamp string; rows strictly older than this are returned. */\n before?: string | null\n}\n\nexport interface AiChatTranscriptResult {\n conversation: AiChatConversation\n messages: AiChatMessage[]\n nextCursor: string | null\n}\n\nexport interface AiChatMessageAppendOptions {\n /** Override the message timestamp (used to thread server-injected stream-completion turns). */\n createdAt?: Date\n /** Override `createdByUserId` (defaults to the calling context user). */\n createdByUserId?: string | null\n}\n\nexport interface AiChatConversationImportResult {\n conversation: AiChatConversation\n importedMessageCount: number\n skippedMessageCount: number\n}\n\nconst DEFAULT_LIST_LIMIT = 50\nconst MAX_LIST_LIMIT = 100\nconst DEFAULT_TRANSCRIPT_LIMIT = 100\nconst MAX_TRANSCRIPT_LIMIT = 200\n\nexport class AiChatConversationAccessError extends Error {\n override readonly name = 'AiChatConversationAccessError'\n constructor(message: string = 'Conversation is not accessible to the caller.') {\n super(message)\n }\n}\n\nexport class AiChatConversationDuplicateParticipantError extends Error {\n override readonly name = 'AiChatConversationDuplicateParticipantError'\n constructor(message: string = 'User is already an active participant in this conversation.') {\n super(message)\n }\n}\n\nexport class AiChatParticipantNotFoundError extends Error {\n override readonly name = 'AiChatParticipantNotFoundError'\n constructor(message: string = 'Participant not found or already revoked.') {\n super(message)\n }\n}\n\nexport class AiChatConversationOrgNotFoundError extends Error {\n override readonly name = 'AiChatConversationOrgNotFoundError'\n constructor(message: string = 'Organization does not exist or is inactive for this tenant.') {\n super(message)\n }\n}\n\nexport class AiChatConversationRepository {\n constructor(private readonly em: EntityManager) {}\n\n /**\n * Idempotent create. If a non-deleted conversation already exists for the\n * caller in this tenant/org with the same `conversationId`, returns the\n * existing row. The owner-participant row is created in the same\n * transaction; a partial failure leaves no orphan conversation.\n */\n async createOrGet(\n input: AiChatConversationCreateOrGetInput,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation> {\n assertContext(ctx, 'createOrGet')\n if (!input?.agentId) {\n throw new Error('AiChatConversationRepository.createOrGet requires agentId')\n }\n const now = input.now ?? new Date()\n const conversationId = (input.conversationId ?? '').trim() || generateConversationId()\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (existing) {\n if (existing.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError()\n }\n return existing\n }\n await assertOrganizationExists(tx as unknown as EntityManager, ctx)\n const conversation = tx.create(AiChatConversation, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n agentId: input.agentId,\n ownerUserId: ctx.userId,\n title: normalizeTitle(input.title),\n status: 'open',\n visibility: 'private',\n pageContext: input.pageContext ?? null,\n lastMessageAt: null,\n importedFromLocalAt: input.importedFromLocal ? now : null,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n } as unknown as AiChatConversation)\n const participant = tx.create(AiChatConversationParticipant, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n userId: ctx.userId,\n role: 'owner',\n lastReadAt: null,\n createdAt: now,\n updatedAt: now,\n } as unknown as AiChatConversationParticipant)\n await tx.persist(conversation).persist(participant).flush()\n return conversation\n })\n }\n\n /** Fetch within tenant/org. View-only callers see only their own conversations. */\n async getById(\n conversationId: string,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation | null> {\n assertContext(ctx, 'getById')\n if (!conversationId) return null\n const row = await findOneAccessibleConversation(this.em, conversationId, ctx)\n if (!row) return null\n const isParticipant =\n !canManageConversations(ctx) && row.ownerUserId !== ctx.userId\n ? await this.loadParticipantFlag(\n this.em,\n ctx.tenantId!,\n ctx.organizationId,\n row.conversationId,\n ctx.userId!,\n )\n : false\n if (!canAccessConversation(row, ctx, isParticipant)) return null\n return row\n }\n\n /** Owner-scoped list unless the caller has tenant/org manage access. Participants also see shared conversations. */\n async list(\n ctx: AiChatConversationContext,\n options: AiChatConversationListOptions = {},\n ): Promise<{ items: AiChatConversation[]; nextCursor: string | null; nextPageToken: string | null }> {\n assertContext(ctx, 'list')\n const limit = clampLimit(options.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT)\n const where: Record<string, unknown> = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n deletedAt: null,\n }\n if (!canManageConversations(ctx)) {\n const participantFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n userId: ctx.userId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const participantRows = await findWithDecryption<AiChatConversationParticipant>(\n this.em,\n AiChatConversationParticipant,\n participantFilter,\n { fields: ['conversationId'] as any },\n { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null },\n )\n const participantConvIds = participantRows.map((p) => p.conversationId)\n if (participantConvIds.length > 0) {\n where.$or = [\n { ownerUserId: ctx.userId },\n { conversationId: { $in: participantConvIds } },\n ]\n } else {\n where.ownerUserId = ctx.userId\n }\n }\n if (options.agentId) where.agentId = options.agentId\n if (options.status) where.status = options.status\n if (options.cursor) {\n const cursorFilter = buildListCursorFilter(options.cursor)\n if (cursorFilter) where.$and = [cursorFilter]\n }\n const rows = await findWithDecryption<AiChatConversation>(\n this.em,\n AiChatConversation,\n where as any,\n {\n orderBy: [{ lastMessageAt: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],\n limit: limit + 1,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n let nextCursor: string | null = null\n let nextPageToken: string | null = null\n if (rows.length > limit) {\n const lastIncluded = rows[limit - 1]\n const cursorValue = lastIncluded.lastMessageAt ?? lastIncluded.createdAt\n nextCursor = cursorValue ? cursorValue.toISOString() : null\n nextPageToken = encodeListCursor(lastIncluded)\n }\n return { items: rows.slice(0, limit), nextCursor, nextPageToken }\n }\n\n /** Update within tenant/org. View-only callers can update only their own conversations. */\n async update(\n conversationId: string,\n patch: AiChatConversationUpdateInput,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversation> {\n assertContext(ctx, 'update')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.update requires conversationId')\n }\n return this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!existing) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (!canAccessConversation(existing, ctx)) {\n throw new AiChatConversationAccessError()\n }\n const now = patch.now ?? new Date()\n if (Object.prototype.hasOwnProperty.call(patch, 'title')) {\n existing.title = normalizeTitle(patch.title)\n }\n if (patch.status) existing.status = patch.status\n if (Object.prototype.hasOwnProperty.call(patch, 'pageContext')) {\n existing.pageContext = patch.pageContext ?? null\n }\n existing.updatedAt = now\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n /** Soft-delete the conversation and all its messages in one transaction. */\n async softDelete(\n conversationId: string,\n ctx: AiChatConversationContext,\n now: Date = new Date(),\n ): Promise<void> {\n assertContext(ctx, 'softDelete')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.softDelete requires conversationId')\n }\n await this.em.transactional(async (tx) => {\n const existing = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!existing) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (!canAccessConversation(existing, ctx)) {\n throw new AiChatConversationAccessError()\n }\n existing.deletedAt = now\n existing.status = 'closed'\n existing.updatedAt = now\n await tx.persist(existing).flush()\n\n const messages = await findWithDecryption<AiChatMessage>(\n tx as unknown as EntityManager,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n for (const msg of messages) {\n msg.deletedAt = now\n msg.updatedAt = now\n tx.persist(msg)\n }\n if (messages.length > 0) await tx.flush()\n })\n }\n\n /**\n * Owner-only transcript hydration. Internally fetched DESC so the `before`\n * cursor naturally advances toward older messages, then reversed so the\n * response contract (`messages` array ordered ascending by `createdAt`)\n * stays stable for callers. `nextCursor` points to the OLDEST message in\n * the returned page \u2014 the next call with `before=<cursor>` fetches the\n * next-older window.\n */\n async getTranscript(\n conversationId: string,\n ctx: AiChatConversationContext,\n options: AiChatTranscriptOptions = {},\n ): Promise<AiChatTranscriptResult | null> {\n assertContext(ctx, 'getTranscript')\n if (!conversationId) return null\n const conversation = await this.getById(conversationId, ctx)\n if (!conversation) return null\n const limit = clampLimit(options.limit, DEFAULT_TRANSCRIPT_LIMIT, MAX_TRANSCRIPT_LIMIT)\n const where: Record<string, unknown> = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n }\n if (options.before) {\n const beforeDate = parseIso(options.before)\n if (beforeDate) {\n where.createdAt = { $lt: beforeDate }\n }\n }\n const rows = await findWithDecryption<AiChatMessage>(\n this.em,\n AiChatMessage,\n where as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: limit + 1,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n let nextCursor: string | null = null\n let pageDesc: AiChatMessage[]\n if (rows.length > limit) {\n pageDesc = rows.slice(0, limit)\n const oldestIncluded = pageDesc[pageDesc.length - 1]\n nextCursor = oldestIncluded?.createdAt ? oldestIncluded.createdAt.toISOString() : null\n } else {\n pageDesc = rows\n }\n const messages = [...pageDesc].reverse()\n return { conversation, messages, nextCursor }\n }\n\n /**\n * Append a single message to an owner-accessible conversation. Honors\n * `clientMessageId` idempotency: if a non-deleted message with the same\n * client id already exists, returns it untouched.\n */\n async appendMessage(\n conversationId: string,\n input: AiChatMessageAppendInput,\n ctx: AiChatConversationContext,\n options: AiChatMessageAppendOptions = {},\n ): Promise<AiChatMessage> {\n assertContext(ctx, 'appendMessage')\n if (!conversationId) {\n throw new Error('AiChatConversationRepository.appendMessage requires conversationId')\n }\n return this.em.transactional(async (tx) => {\n const conversation = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conversation) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conversation.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError()\n }\n const now = options.createdAt ?? new Date()\n if (input.clientMessageId) {\n const existing = await findOneWithDecryption<AiChatMessage>(\n tx as unknown as EntityManager,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n clientMessageId: input.clientMessageId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing) return existing\n }\n const message = tx.create(AiChatMessage, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n clientMessageId: input.clientMessageId ?? null,\n role: input.role,\n content: input.content,\n uiParts: normalizeArray(input.uiParts),\n attachmentIds: normalizeArray(input.attachmentIds),\n filesMetadata: normalizeArray(input.files),\n model: input.model ?? null,\n metadata: input.metadata ?? null,\n createdByUserId:\n options.createdByUserId === undefined\n ? input.role === 'user'\n ? ctx.userId\n : null\n : options.createdByUserId,\n createdAt: now,\n updatedAt: now,\n deletedAt: null,\n } as unknown as AiChatMessage)\n conversation.lastMessageAt = now\n conversation.updatedAt = now\n await tx.persist(message).persist(conversation).flush()\n return message\n })\n }\n\n /**\n * Lazy migration entrypoint: create-or-get the conversation and append the\n * provided messages with `clientMessageId` dedupe. Designed to be safe to\n * call repeatedly \u2014 repeated imports of the same payload return the same\n * counts of imported/skipped rows.\n */\n async importLocalConversation(\n input: {\n conversation: AiChatConversationCreateOrGetInput & {\n status?: 'open' | 'closed'\n }\n messages: AiChatMessageAppendInput[]\n },\n ctx: AiChatConversationContext,\n now: Date = new Date(),\n ): Promise<AiChatConversationImportResult> {\n assertContext(ctx, 'importLocalConversation')\n const conversation = await this.createOrGet(\n { ...input.conversation, importedFromLocal: true, now },\n ctx,\n )\n if (input.conversation.status && conversation.status !== input.conversation.status) {\n await this.update(\n conversation.conversationId,\n { status: input.conversation.status, now },\n ctx,\n )\n }\n let imported = 0\n let skipped = 0\n for (const message of input.messages) {\n if (!message.clientMessageId) {\n // Without an idempotency key the import has no safe way to dedupe.\n skipped += 1\n continue\n }\n const before = await findOneWithDecryption<AiChatMessage>(\n this.em,\n AiChatMessage,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId: conversation.conversationId,\n clientMessageId: message.clientMessageId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (before) {\n skipped += 1\n continue\n }\n await this.appendMessage(\n conversation.conversationId,\n message,\n ctx,\n { createdAt: now },\n )\n imported += 1\n }\n return {\n conversation,\n importedMessageCount: imported,\n skippedMessageCount: skipped,\n }\n }\n\n async listParticipants(\n conversationId: string,\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversationParticipant[]> {\n assertContext(ctx, 'listParticipants')\n const conv = await findOneAccessibleConversation(this.em, conversationId, ctx)\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId && !canManageConversations(ctx)) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner or a manager can list participants.',\n )\n }\n const filter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n return findWithDecryption<AiChatConversationParticipant>(\n this.em,\n AiChatConversationParticipant,\n filter,\n { orderBy: { createdAt: 'asc' } as any },\n { tenantId: ctx.tenantId ?? null, organizationId: ctx.organizationId ?? null },\n )\n }\n\n async addParticipant(\n conversationId: string,\n userId: string,\n role: 'viewer',\n ctx: AiChatConversationContext,\n ): Promise<AiChatConversationParticipant> {\n assertContext(ctx, 'addParticipant')\n return this.em.transactional(async (tx) => {\n const conv = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner can add participants.',\n )\n }\n const existingFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n userId,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const existing = await findOneWithDecryption<AiChatConversationParticipant>(\n tx as unknown as EntityManager,\n AiChatConversationParticipant,\n existingFilter,\n )\n if (existing) {\n if (existing.deletedAt === null) {\n throw new AiChatConversationDuplicateParticipantError()\n }\n existing.deletedAt = null\n existing.role = role\n await tx.persist(existing).flush()\n if (conv.visibility === 'private') {\n conv.visibility = 'shared'\n await tx.persist(conv).flush()\n }\n return existing\n }\n const participant = tx.create(AiChatConversationParticipant, {\n tenantId: ctx.tenantId!,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n userId,\n role,\n } as unknown as AiChatConversationParticipant)\n if (conv.visibility === 'private') {\n conv.visibility = 'shared'\n }\n await tx.persist(participant).persist(conv).flush()\n return participant\n })\n }\n\n async revokeParticipant(\n conversationId: string,\n targetUserId: string,\n ctx: AiChatConversationContext,\n ): Promise<void> {\n assertContext(ctx, 'revokeParticipant')\n await this.em.transactional(async (tx) => {\n const conv = await findOneAccessibleConversation(\n tx as unknown as EntityManager,\n conversationId,\n ctx,\n )\n if (!conv) {\n throw new AiChatConversationAccessError(\n `Conversation \"${conversationId}\" was not found for the caller.`,\n )\n }\n if (conv.ownerUserId !== ctx.userId) {\n throw new AiChatConversationAccessError(\n 'Only the conversation owner can revoke participants.',\n )\n }\n if (targetUserId === conv.ownerUserId) {\n throw new AiChatConversationAccessError('Cannot revoke the conversation owner.')\n }\n const participantFilter: FilterQuery<AiChatConversationParticipant> = {\n tenantId: ctx.tenantId,\n conversationId,\n userId: targetUserId,\n deletedAt: null,\n ...(ctx.organizationId ? { organizationId: ctx.organizationId } : {}),\n }\n const participant = await findOneWithDecryption<AiChatConversationParticipant>(\n tx as unknown as EntityManager,\n AiChatConversationParticipant,\n participantFilter,\n )\n if (!participant) throw new AiChatParticipantNotFoundError()\n participant.deletedAt = new Date()\n const remainingCount = await tx.count(AiChatConversationParticipant, {\n tenantId: ctx.tenantId,\n conversationId,\n deletedAt: null,\n role: { $ne: 'owner' },\n } as FilterQuery<AiChatConversationParticipant>)\n if (remainingCount <= 1) {\n conv.visibility = 'private'\n await tx.persist(conv)\n }\n await tx.persist(participant).flush()\n })\n }\n\n async getParticipantCount(\n tenantId: string,\n organizationId: string | null | undefined,\n conversationId: string,\n ): Promise<number> {\n return this.em.count(AiChatConversationParticipant, {\n tenantId,\n conversationId,\n deletedAt: null,\n role: { $ne: 'owner' },\n ...(organizationId ? { organizationId } : {}),\n } as FilterQuery<AiChatConversationParticipant>)\n }\n\n private async loadParticipantFlag(\n em: EntityManager,\n tenantId: string,\n organizationId: string | null | undefined,\n conversationId: string,\n userId: string,\n ): Promise<boolean> {\n const row = await findOneWithDecryption<AiChatConversationParticipant>(\n em,\n AiChatConversationParticipant,\n {\n tenantId,\n conversationId,\n userId,\n deletedAt: null,\n ...(organizationId ? { organizationId } : {}),\n } as FilterQuery<AiChatConversationParticipant>,\n )\n return row !== null\n }\n}\n\nfunction assertContext(ctx: AiChatConversationContext | undefined, method: string): void {\n if (!ctx?.tenantId) {\n throw new Error(`AiChatConversationRepository.${method} requires tenantId`)\n }\n if (!ctx?.userId) {\n throw new Error(`AiChatConversationRepository.${method} requires userId`)\n }\n}\n\nfunction canManageConversations(ctx: AiChatConversationContext): boolean {\n return ctx.canManageConversations === true\n}\n\nfunction canAccessConversation(\n row: AiChatConversation,\n ctx: AiChatConversationContext,\n isParticipant = false,\n): boolean {\n return canManageConversations(ctx) || row.ownerUserId === ctx.userId || isParticipant\n}\n\nasync function assertOrganizationExists(\n em: EntityManager,\n ctx: AiChatConversationContext,\n): Promise<void> {\n if (!ctx.organizationId) return\n const org = await findOneWithDecryption<Organization>(\n em,\n Organization,\n {\n id: ctx.organizationId,\n tenant: ctx.tenantId,\n deletedAt: null,\n isActive: true,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (!org) {\n throw new AiChatConversationOrgNotFoundError(\n `Organization \"${ctx.organizationId}\" does not exist or is inactive in tenant \"${ctx.tenantId}\".`,\n )\n }\n}\n\nasync function findOneAccessibleConversation(\n em: EntityManager,\n conversationId: string,\n ctx: AiChatConversationContext,\n): Promise<AiChatConversation | null> {\n const row = await findOneWithDecryption<AiChatConversation>(\n em,\n AiChatConversation,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n conversationId,\n deletedAt: null,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n}\n\nfunction normalizeTitle(title: string | null | undefined): string | null {\n if (title === undefined) return null\n if (title === null) return null\n const trimmed = title.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeArray<T>(value: T[] | null | undefined): T[] | null {\n if (!Array.isArray(value) || value.length === 0) return null\n return value\n}\n\nfunction clampLimit(value: number | undefined | null, fallback: number, max: number): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return fallback\n return Math.max(1, Math.min(Math.floor(value), max))\n}\n\nfunction parseIso(value: string): Date | null {\n if (!value) return null\n const date = new Date(value)\n return Number.isNaN(date.getTime()) ? null : date\n}\n\nconst listCursorSchema = z.object({\n l: z.string().datetime().nullable(),\n c: z.string().datetime(),\n i: z.guid(),\n})\n\nfunction encodeListCursor(row: AiChatConversation): string {\n const payload: z.infer<typeof listCursorSchema> = {\n l: row.lastMessageAt ? row.lastMessageAt.toISOString() : null,\n c: row.createdAt.toISOString(),\n i: row.id,\n }\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')\n}\n\nfunction decodeListCursor(value: string): z.infer<typeof listCursorSchema> | null {\n try {\n const parsed = listCursorSchema.safeParse(\n JSON.parse(Buffer.from(value, 'base64url').toString('utf8')),\n )\n return parsed.success ? parsed.data : null\n } catch {\n return null\n }\n}\n\nfunction buildListCursorFilter(value: string): Record<string, unknown> | null {\n const cursor = decodeListCursor(value)\n if (!cursor) {\n const legacyDate = parseIso(value)\n return legacyDate ? { lastMessageAt: { $lt: legacyDate } } : null\n }\n const lastMessageAt = cursor.l ? new Date(cursor.l) : null\n const createdAt = new Date(cursor.c)\n return {\n $or: [\n lastMessageAt ? { lastMessageAt: { $lt: lastMessageAt } } : { lastMessageAt: { $ne: null } },\n { lastMessageAt, createdAt: { $lt: createdAt } },\n { lastMessageAt, createdAt, id: { $lt: cursor.i } },\n ],\n }\n}\n\nfunction generateConversationId(): string {\n // Prefer the runtime crypto generator when present; fall back to a non-cryptographic\n // string for environments without `crypto.randomUUID()` (older Node / test mocks).\n const cryptoMod: { randomUUID?: () => string } | undefined =\n typeof globalThis === 'object' ? (globalThis as any).crypto : undefined\n if (cryptoMod?.randomUUID) return cryptoMod.randomUUID()\n return `chat_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 12)}`\n}\n\nexport default AiChatConversationRepository\n"],
5
+ "m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AAE,KAAK,KAAK,EAAE;AAAA,MAC3F,EAAE,eAAe,WAAW,EAAE,KAAK,UAAU,EAAE;AAAA,MAC/C,EAAE,eAAe,WAAW,IAAI,EAAE,KAAK,OAAO,EAAE,EAAE;AAAA,IACpD;AAAA,EACF;AACF;AAEA,SAAS,yBAAiC;AAGxC,QAAM,YACJ,OAAO,eAAe,WAAY,WAAmB,SAAS;AAChE,MAAI,WAAW,WAAY,QAAO,UAAU,WAAW;AACvD,SAAO,QAAQ,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AACnF;AAEA,IAAO,uCAAQ;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ai-assistant",
3
- "version": "0.10.1-develop.8182.1.0acd6a564c",
3
+ "version": "0.10.1-develop.8191.1.2563ac3bfc",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -103,16 +103,16 @@
103
103
  "zod-to-json-schema": "^3.25.2"
104
104
  },
105
105
  "peerDependencies": {
106
- "@open-mercato/shared": "0.10.1-develop.8182.1.0acd6a564c",
107
- "@open-mercato/ui": "0.10.1-develop.8182.1.0acd6a564c",
106
+ "@open-mercato/shared": "0.10.1-develop.8191.1.2563ac3bfc",
107
+ "@open-mercato/ui": "0.10.1-develop.8191.1.2563ac3bfc",
108
108
  "react": "^19.0.0",
109
109
  "react-dom": "^19.0.0",
110
110
  "zod": ">=3.23.0"
111
111
  },
112
112
  "devDependencies": {
113
- "@open-mercato/cli": "0.10.1-develop.8182.1.0acd6a564c",
114
- "@open-mercato/shared": "0.10.1-develop.8182.1.0acd6a564c",
115
- "@open-mercato/ui": "0.10.1-develop.8182.1.0acd6a564c",
113
+ "@open-mercato/cli": "0.10.1-develop.8191.1.2563ac3bfc",
114
+ "@open-mercato/shared": "0.10.1-develop.8191.1.2563ac3bfc",
115
+ "@open-mercato/ui": "0.10.1-develop.8191.1.2563ac3bfc",
116
116
  "@types/react": "^19.2.18",
117
117
  "@types/react-dom": "^19.2.5",
118
118
  "react": "19.2.8",
@@ -0,0 +1,80 @@
1
+ import { test, expect } from '@playwright/test';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api';
4
+ import { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures';
5
+ import { deleteConversationCascadeInDb } from './helpers/aiAssistantFixtures';
6
+
7
+ /**
8
+ * TC-AI-CONVERSATIONS-002 — Conversation list cursor pagination returns every row exactly once.
9
+ *
10
+ * Conversations without messages have a null `lastMessageAt` and sort first. Walking
11
+ * `nextPageToken` page by page must still reach every one of them, then the conversations
12
+ * that do have messages. `nextCursor` stays the ISO timestamp it was before.
13
+ */
14
+
15
+ const CONVERSATIONS = '/api/ai_assistant/ai/conversations';
16
+
17
+ interface ListResponse {
18
+ items: Array<{ conversationId: string }>;
19
+ nextCursor: string | null;
20
+ nextPageToken: string | null;
21
+ }
22
+
23
+ test.describe('TC-AI-CONVERSATIONS-002: conversation list cursor pagination', () => {
24
+ test('walking nextPageToken with limit=1 returns every conversation exactly once', async ({ request }) => {
25
+ test.slow();
26
+ const adminToken = await getAuthToken(request, 'admin');
27
+ const { tenantId } = getTokenScope(adminToken);
28
+ const agentId = `it_conv.cursor_${randomUUID().slice(0, 8)}`;
29
+ const created: string[] = [];
30
+
31
+ try {
32
+ const activeId = `it-conv-active-${randomUUID()}`;
33
+ created.push(activeId);
34
+ const importRes = await apiRequest(request, 'POST', `${CONVERSATIONS}/import`, {
35
+ token: adminToken,
36
+ data: {
37
+ conversation: { conversationId: activeId, agentId },
38
+ messages: [{ clientMessageId: `msg-${randomUUID()}`, role: 'user', content: 'hello' }],
39
+ },
40
+ });
41
+ expect(importRes.status(), 'import with a message succeeds').toBe(200);
42
+
43
+ const emptyIds: string[] = [];
44
+ for (let index = 0; index < 3; index += 1) {
45
+ const conversationId = `it-conv-empty-${index}-${randomUUID()}`;
46
+ created.push(conversationId);
47
+ const createRes = await apiRequest(request, 'POST', CONVERSATIONS, {
48
+ token: adminToken,
49
+ data: { agentId, conversationId },
50
+ });
51
+ expect(createRes.status(), 'create returns 201').toBe(201);
52
+ emptyIds.push(conversationId);
53
+ }
54
+
55
+ const seen: string[] = [];
56
+ let cursor: string | null = null;
57
+ for (let page = 0; page < 10; page += 1) {
58
+ const query = new URLSearchParams({ agent: agentId, limit: '1' });
59
+ if (cursor) query.set('cursor', cursor);
60
+ const listRes = await apiRequest(request, 'GET', `${CONVERSATIONS}?${query.toString()}`, {
61
+ token: adminToken,
62
+ });
63
+ expect(listRes.status()).toBe(200);
64
+ const body = await readJsonSafe<ListResponse>(listRes);
65
+ seen.push(...(body?.items ?? []).map((item) => item.conversationId));
66
+ if (body?.nextCursor) {
67
+ expect(new Date(body.nextCursor).toISOString(), 'nextCursor stays an ISO timestamp').toBe(body.nextCursor);
68
+ }
69
+ cursor = body?.nextPageToken ?? null;
70
+ if (!cursor) break;
71
+ }
72
+
73
+ expect(seen).toEqual([...emptyIds].reverse().concat(activeId));
74
+ } finally {
75
+ for (const conversationId of created) {
76
+ await deleteConversationCascadeInDb({ tenantId, conversationId }).catch(() => undefined);
77
+ }
78
+ }
79
+ });
80
+ });
@@ -27,12 +27,14 @@ export const openApi: OpenApiRouteDoc = {
27
27
  operationId: 'aiAssistantListConversations',
28
28
  summary: 'List AI chat conversations visible to the caller.',
29
29
  description:
30
- 'Returns `{ items, nextCursor }` for the authenticated caller, ordered by `lastMessageAt` ' +
31
- 'descending. View-only callers receive only their own conversations. Callers with ' +
30
+ 'Returns `{ items, nextCursor, nextPageToken }` for the authenticated caller, ordered by `lastMessageAt` ' +
31
+ 'descending (conversations without messages first), then `createdAt` and `id`. View-only callers receive only their own conversations. Callers with ' +
32
32
  '`ai_assistant.conversations.manage` may list conversations across users in the same ' +
33
33
  'tenant/organization. The ' +
34
- '`agent` and `status` filters are optional; `cursor` is the ISO timestamp returned by a ' +
35
- 'previous response.',
34
+ '`agent` and `status` filters are optional; `cursor` accepts the ISO timestamp `nextCursor` or ' +
35
+ 'the opaque `nextPageToken` returned by a previous response. Follow `nextPageToken` to visit ' +
36
+ 'every conversation exactly once; the timestamp `nextCursor` keeps its earlier behaviour and ' +
37
+ 'can skip conversations without messages or sharing the boundary timestamp.',
36
38
  responses: [
37
39
  {
38
40
  status: 200,
@@ -136,7 +138,7 @@ export async function GET(req: NextRequest): Promise<Response> {
136
138
  return jsonError(403, `Caller lacks required feature "${REQUIRED_FEATURE}".`, 'forbidden')
137
139
  }
138
140
  if (callerCtx.kind === 'missing-tenant') {
139
- return NextResponse.json({ items: [], nextCursor: null })
141
+ return NextResponse.json({ items: [], nextCursor: null, nextPageToken: null })
140
142
  }
141
143
 
142
144
  const url = new URL(req.url)
@@ -172,6 +174,7 @@ export async function GET(req: NextRequest): Promise<Response> {
172
174
  return NextResponse.json({
173
175
  items: result.items.map((row) => serializeAiChatConversation(row)),
174
176
  nextCursor: result.nextCursor,
177
+ nextPageToken: result.nextPageToken,
175
178
  })
176
179
  } catch (error) {
177
180
  logger.error('AI Conversations GET — Failure', { err: error })
@@ -1,4 +1,5 @@
1
1
  import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'
2
+ import { z } from 'zod'
2
3
  import {
3
4
  findOneWithDecryption,
4
5
  findWithDecryption,
@@ -215,7 +216,7 @@ export class AiChatConversationRepository {
215
216
  async list(
216
217
  ctx: AiChatConversationContext,
217
218
  options: AiChatConversationListOptions = {},
218
- ): Promise<{ items: AiChatConversation[]; nextCursor: string | null }> {
219
+ ): Promise<{ items: AiChatConversation[]; nextCursor: string | null; nextPageToken: string | null }> {
219
220
  assertContext(ctx, 'list')
220
221
  const limit = clampLimit(options.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT)
221
222
  const where: Record<string, unknown> = {
@@ -250,17 +251,15 @@ export class AiChatConversationRepository {
250
251
  if (options.agentId) where.agentId = options.agentId
251
252
  if (options.status) where.status = options.status
252
253
  if (options.cursor) {
253
- const cursorDate = parseIso(options.cursor)
254
- if (cursorDate) {
255
- where.lastMessageAt = { $lt: cursorDate }
256
- }
254
+ const cursorFilter = buildListCursorFilter(options.cursor)
255
+ if (cursorFilter) where.$and = [cursorFilter]
257
256
  }
258
257
  const rows = await findWithDecryption<AiChatConversation>(
259
258
  this.em,
260
259
  AiChatConversation,
261
260
  where as any,
262
261
  {
263
- orderBy: [{ lastMessageAt: 'desc' }, { createdAt: 'desc' }] as any,
262
+ orderBy: [{ lastMessageAt: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
264
263
  limit: limit + 1,
265
264
  },
266
265
  {
@@ -269,12 +268,14 @@ export class AiChatConversationRepository {
269
268
  },
270
269
  )
271
270
  let nextCursor: string | null = null
271
+ let nextPageToken: string | null = null
272
272
  if (rows.length > limit) {
273
273
  const lastIncluded = rows[limit - 1]
274
274
  const cursorValue = lastIncluded.lastMessageAt ?? lastIncluded.createdAt
275
275
  nextCursor = cursorValue ? cursorValue.toISOString() : null
276
+ nextPageToken = encodeListCursor(lastIncluded)
276
277
  }
277
- return { items: rows.slice(0, limit), nextCursor }
278
+ return { items: rows.slice(0, limit), nextCursor, nextPageToken }
278
279
  }
279
280
 
280
281
  /** Update within tenant/org. View-only callers can update only their own conversations. */
@@ -849,6 +850,49 @@ function parseIso(value: string): Date | null {
849
850
  return Number.isNaN(date.getTime()) ? null : date
850
851
  }
851
852
 
853
+ const listCursorSchema = z.object({
854
+ l: z.string().datetime().nullable(),
855
+ c: z.string().datetime(),
856
+ i: z.guid(),
857
+ })
858
+
859
+ function encodeListCursor(row: AiChatConversation): string {
860
+ const payload: z.infer<typeof listCursorSchema> = {
861
+ l: row.lastMessageAt ? row.lastMessageAt.toISOString() : null,
862
+ c: row.createdAt.toISOString(),
863
+ i: row.id,
864
+ }
865
+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url')
866
+ }
867
+
868
+ function decodeListCursor(value: string): z.infer<typeof listCursorSchema> | null {
869
+ try {
870
+ const parsed = listCursorSchema.safeParse(
871
+ JSON.parse(Buffer.from(value, 'base64url').toString('utf8')),
872
+ )
873
+ return parsed.success ? parsed.data : null
874
+ } catch {
875
+ return null
876
+ }
877
+ }
878
+
879
+ function buildListCursorFilter(value: string): Record<string, unknown> | null {
880
+ const cursor = decodeListCursor(value)
881
+ if (!cursor) {
882
+ const legacyDate = parseIso(value)
883
+ return legacyDate ? { lastMessageAt: { $lt: legacyDate } } : null
884
+ }
885
+ const lastMessageAt = cursor.l ? new Date(cursor.l) : null
886
+ const createdAt = new Date(cursor.c)
887
+ return {
888
+ $or: [
889
+ lastMessageAt ? { lastMessageAt: { $lt: lastMessageAt } } : { lastMessageAt: { $ne: null } },
890
+ { lastMessageAt, createdAt: { $lt: createdAt } },
891
+ { lastMessageAt, createdAt, id: { $lt: cursor.i } },
892
+ ],
893
+ }
894
+ }
895
+
852
896
  function generateConversationId(): string {
853
897
  // Prefer the runtime crypto generator when present; fall back to a non-cryptographic
854
898
  // string for environments without `crypto.randomUUID()` (older Node / test mocks).
@@ -72,11 +72,24 @@ function matchesWhere(row: Record<string, any>, where: any): boolean {
72
72
  if (!conditions.some((cond) => matchesWhere(row, cond))) return false
73
73
  continue
74
74
  }
75
+ if (key === '$and') {
76
+ const conditions = where[key] as unknown[]
77
+ if (!conditions.every((cond) => matchesWhere(row, cond))) return false
78
+ continue
79
+ }
75
80
  const expected = where[key]
76
81
  const actual = row[key] ?? null
77
82
  if (expected && typeof expected === 'object' && '$lt' in expected) {
78
- const lt = expected.$lt as Date
79
- if (!(actual instanceof Date) || !(actual.getTime() < lt.getTime())) return false
83
+ const lt = expected.$lt
84
+ if (typeof lt === 'string') {
85
+ if (typeof actual !== 'string' || !(actual < lt)) return false
86
+ continue
87
+ }
88
+ if (!(actual instanceof Date) || !(actual.getTime() < (lt as Date).getTime())) return false
89
+ continue
90
+ }
91
+ if (expected instanceof Date) {
92
+ if (!(actual instanceof Date) || actual.getTime() !== expected.getTime()) return false
80
93
  continue
81
94
  }
82
95
  if (expected && typeof expected === 'object' && '$in' in expected) {
@@ -108,8 +121,8 @@ function applyOrder<T extends Record<string, any>>(rows: T[], orderBy: any): T[]
108
121
  const aTime = av instanceof Date ? av.getTime() : av ?? null
109
122
  const bTime = bv instanceof Date ? bv.getTime() : bv ?? null
110
123
  if (aTime === bTime) continue
111
- if (aTime === null) return direction === 'asc' ? -1 : 1
112
- if (bTime === null) return direction === 'asc' ? 1 : -1
124
+ if (aTime === null) return direction === 'asc' ? 1 : -1
125
+ if (bTime === null) return direction === 'asc' ? -1 : 1
113
126
  if (aTime < bTime) return direction === 'asc' ? -1 : 1
114
127
  return direction === 'asc' ? 1 : -1
115
128
  }
@@ -450,6 +463,134 @@ describe('AiChatConversationRepository', () => {
450
463
  expect(result.items[0].agentId).toBe('agent-b')
451
464
  })
452
465
 
466
+ describe('list cursor pagination', () => {
467
+ const ctx = { tenantId: tenantAlpha, organizationId: null, userId: 'u-1' }
468
+
469
+ async function seed(
470
+ repo: AiChatConversationRepository,
471
+ em: ReturnType<typeof mockEm>,
472
+ rows: Array<{ conversationId: string; createdAt: string; lastMessageAt: string | null }>,
473
+ ) {
474
+ for (const [index, row] of rows.entries()) {
475
+ await repo.createOrGet(
476
+ { conversationId: row.conversationId, agentId: 'x', now: new Date(row.createdAt) },
477
+ ctx,
478
+ )
479
+ const stored = em.__stores.conv.find(
480
+ (candidate: ConvRow) => candidate.conversationId === row.conversationId,
481
+ )
482
+ stored.id = `00000000-0000-4000-8000-${String(index + 1).padStart(12, '0')}`
483
+ stored.lastMessageAt = row.lastMessageAt ? new Date(row.lastMessageAt) : null
484
+ }
485
+ }
486
+
487
+ async function walk(repo: AiChatConversationRepository, limit: number): Promise<string[]> {
488
+ const seen: string[] = []
489
+ let cursor: string | null = null
490
+ for (let page = 0; page < 20; page += 1) {
491
+ const result = await repo.list(ctx, { limit, cursor })
492
+ seen.push(...result.items.map((row) => row.conversationId))
493
+ if (!result.nextPageToken) return seen
494
+ cursor = result.nextPageToken
495
+ }
496
+ throw new Error('[internal] pagination did not terminate')
497
+ }
498
+
499
+ it('returns conversations that share the page-boundary lastMessageAt on a later page', async () => {
500
+ const em = mockEm()
501
+ const repo = new AiChatConversationRepository(em)
502
+ const tie = '2026-05-01T10:00:00.000Z'
503
+ await seed(repo, em, [
504
+ { conversationId: 'latest', createdAt: '2026-04-01T00:00:00.000Z', lastMessageAt: '2026-05-02T00:00:00.000Z' },
505
+ { conversationId: 'tie-newest', createdAt: '2026-04-05T00:00:00.000Z', lastMessageAt: tie },
506
+ { conversationId: 'tie-middle', createdAt: '2026-04-04T00:00:00.000Z', lastMessageAt: tie },
507
+ { conversationId: 'tie-older', createdAt: '2026-04-03T00:00:00.000Z', lastMessageAt: tie },
508
+ { conversationId: 'tie-oldest', createdAt: '2026-04-02T00:00:00.000Z', lastMessageAt: tie },
509
+ { conversationId: 'stale', createdAt: '2026-03-01T00:00:00.000Z', lastMessageAt: '2026-04-30T00:00:00.000Z' },
510
+ ])
511
+
512
+ expect(await walk(repo, 2)).toEqual([
513
+ 'latest',
514
+ 'tie-newest',
515
+ 'tie-middle',
516
+ 'tie-older',
517
+ 'tie-oldest',
518
+ 'stale',
519
+ ])
520
+ })
521
+
522
+ it('breaks a full lastMessageAt and createdAt tie by id without skipping rows', async () => {
523
+ const em = mockEm()
524
+ const repo = new AiChatConversationRepository(em)
525
+ const at = '2026-05-01T10:00:00.000Z'
526
+ await seed(repo, em, [
527
+ { conversationId: 'a', createdAt: at, lastMessageAt: at },
528
+ { conversationId: 'b', createdAt: at, lastMessageAt: at },
529
+ { conversationId: 'c', createdAt: at, lastMessageAt: at },
530
+ ])
531
+
532
+ expect(await walk(repo, 1)).toEqual(['c', 'b', 'a'])
533
+ })
534
+
535
+ it('pages through conversations without messages before the ones with messages', async () => {
536
+ const em = mockEm()
537
+ const repo = new AiChatConversationRepository(em)
538
+ await seed(repo, em, [
539
+ { conversationId: 'empty-new', createdAt: '2026-05-03T00:00:00.000Z', lastMessageAt: null },
540
+ { conversationId: 'empty-mid', createdAt: '2026-05-02T00:00:00.000Z', lastMessageAt: null },
541
+ { conversationId: 'empty-old', createdAt: '2026-04-01T00:00:00.000Z', lastMessageAt: null },
542
+ { conversationId: 'active-recent', createdAt: '2026-01-01T00:00:00.000Z', lastMessageAt: '2026-05-10T00:00:00.000Z' },
543
+ { conversationId: 'active-old', createdAt: '2026-01-02T00:00:00.000Z', lastMessageAt: '2026-02-01T00:00:00.000Z' },
544
+ ])
545
+
546
+ expect(await walk(repo, 2)).toEqual([
547
+ 'empty-new',
548
+ 'empty-mid',
549
+ 'empty-old',
550
+ 'active-recent',
551
+ 'active-old',
552
+ ])
553
+ })
554
+
555
+ it('keeps nextCursor as the ISO timestamp of the last row and adds nextPageToken', async () => {
556
+ const em = mockEm()
557
+ const repo = new AiChatConversationRepository(em)
558
+ await seed(repo, em, [
559
+ { conversationId: 'empty', createdAt: '2026-05-03T00:00:00.000Z', lastMessageAt: null },
560
+ { conversationId: 'active', createdAt: '2026-01-01T00:00:00.000Z', lastMessageAt: '2026-05-10T00:00:00.000Z' },
561
+ { conversationId: 'older', createdAt: '2026-01-01T00:00:00.000Z', lastMessageAt: '2026-04-10T00:00:00.000Z' },
562
+ ])
563
+
564
+ const first = await repo.list(ctx, { limit: 1 })
565
+ expect(first.items.map((row) => row.conversationId)).toEqual(['empty'])
566
+ expect(first.nextCursor).toBe('2026-05-03T00:00:00.000Z')
567
+ expect(first.nextPageToken).toEqual(expect.any(String))
568
+ expect(first.nextPageToken).not.toBe(first.nextCursor)
569
+
570
+ const second = await repo.list(ctx, { limit: 1, cursor: first.nextPageToken })
571
+ expect(second.items.map((row) => row.conversationId)).toEqual(['active'])
572
+ expect(second.nextCursor).toBe('2026-05-10T00:00:00.000Z')
573
+
574
+ const last = await repo.list(ctx, { limit: 1, cursor: second.nextPageToken })
575
+ expect(last.items.map((row) => row.conversationId)).toEqual(['older'])
576
+ expect(last.nextCursor).toBeNull()
577
+ expect(last.nextPageToken).toBeNull()
578
+ })
579
+
580
+ it('still accepts a plain ISO timestamp cursor issued before the compound cursor', async () => {
581
+ const em = mockEm()
582
+ const repo = new AiChatConversationRepository(em)
583
+ await seed(repo, em, [
584
+ { conversationId: 'newer', createdAt: '2026-04-01T00:00:00.000Z', lastMessageAt: '2026-05-02T00:00:00.000Z' },
585
+ { conversationId: 'older', createdAt: '2026-04-01T00:00:00.000Z', lastMessageAt: '2026-04-20T00:00:00.000Z' },
586
+ ])
587
+
588
+ const result = await repo.list(ctx, { limit: 5, cursor: '2026-05-01T00:00:00.000Z' })
589
+ expect(result.items.map((row) => row.conversationId)).toEqual(['older'])
590
+ expect(result.nextCursor).toBeNull()
591
+ })
592
+ })
593
+
453
594
  it('importLocalConversation imports unique messages and skips duplicates idempotently', async () => {
454
595
  const em = mockEm()
455
596
  const repo = new AiChatConversationRepository(em)