bailinghub 0.5.1 → 0.6.1

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.
Files changed (101) hide show
  1. package/README.en.md +146 -185
  2. package/README.md +135 -207
  3. package/THIRD_PARTY_NOTICES.md +6 -7
  4. package/assets/readme-demo-evidence.en-dark.svg +82 -0
  5. package/assets/readme-demo-evidence.en.svg +82 -0
  6. package/assets/readme-demo-evidence.zh-CN-dark.svg +82 -0
  7. package/assets/readme-demo-evidence.zh-CN.svg +82 -0
  8. package/assets/readme-entry-points.en-dark.svg +71 -0
  9. package/assets/readme-entry-points.en.svg +71 -0
  10. package/assets/readme-entry-points.zh-CN-dark.svg +71 -0
  11. package/assets/readme-entry-points.zh-CN.svg +71 -0
  12. package/assets/readme-product-overview.en-dark.svg +87 -0
  13. package/assets/readme-product-overview.en.svg +87 -0
  14. package/assets/readme-product-overview.zh-CN-dark.svg +87 -0
  15. package/assets/readme-product-overview.zh-CN.svg +87 -0
  16. package/docker-compose.images.yml +2 -2
  17. package/docs/AGENT_CLIENT_QUICKSTART.en.md +29 -8
  18. package/docs/AGENT_CLIENT_QUICKSTART.md +25 -6
  19. package/docs/AGENT_CONVERSATION_AUDIT.en.md +194 -0
  20. package/docs/AGENT_CONVERSATION_AUDIT.md +111 -0
  21. package/docs/CHANGELOG.en.md +21 -0
  22. package/docs/CHANGELOG.md +21 -0
  23. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  24. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  25. package/docs/README.en.md +7 -0
  26. package/docs/README.md +7 -0
  27. package/docs/RELEASE_NOTES_v0.6.0.en.md +53 -0
  28. package/docs/RELEASE_NOTES_v0.6.0.md +53 -0
  29. package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
  30. package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
  31. package/docs/user-guide/README.en.md +1 -0
  32. package/docs/user-guide/README.md +1 -0
  33. package/docs/user-guide/console-map.en.md +2 -0
  34. package/docs/user-guide/console-map.md +2 -1
  35. package/docs/user-guide/conversations.en.md +40 -0
  36. package/docs/user-guide/conversations.md +40 -0
  37. package/package.json +1 -1
  38. package/scripts/check-doc-links.mjs +3 -0
  39. package/scripts/check-image-tags.sh +1 -1
  40. package/scripts/check-release-consistency.test.mjs +2 -2
  41. package/scripts/e2e-console.mjs +89 -0
  42. package/scripts/generate-readme-assets.mjs +488 -7
  43. package/scripts/install.sh +1 -1
  44. package/scripts/publish-images.sh +1 -1
  45. package/scripts/release-audit.mjs +2 -0
  46. package/scripts/verify-github-repo.mjs +2 -0
  47. package/sql/057_agent_conversation_audit.sql +55 -0
  48. package/src/app/agent-conversation-audit.ts +30 -0
  49. package/src/core/runtime/agent-conversation-audit.test.ts +38 -0
  50. package/src/core/runtime/agent-conversation-audit.ts +159 -0
  51. package/src/infrastructure/config/config-agent-conversation-audit-repository.test.ts +146 -0
  52. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +262 -0
  53. package/src/infrastructure/config/configstore.ts +5 -0
  54. package/src/routes/admin-conversation-audit.ts +46 -0
  55. package/src/routes/admin-runtime.test.ts +38 -0
  56. package/src/routes/admin-runtime.ts +14 -3
  57. package/src/routes/admin.ts +3 -0
  58. package/src/routes/agent-api.ts +2 -0
  59. package/src/routes/agent-conversation-audit.test.ts +131 -0
  60. package/src/routes/agent-conversation-audit.ts +33 -0
  61. package/src/test-support/agent-conversation-audit-fixture.ts +123 -0
  62. package/web/console/assets/{Accounts-r10QUjLQ.js → Accounts-Ca_VnSu9.js} +1 -1
  63. package/web/console/assets/{AgentClients-UTTqbkjy.js → AgentClients-BPIvlLYY.js} +1 -1
  64. package/web/console/assets/{Approvals-BGKkYIya.js → Approvals-CMvPWacY.js} +1 -1
  65. package/web/console/assets/{Audit-CQmjOAoO.js → Audit-CIRqOCnL.js} +1 -1
  66. package/web/console/assets/{BrandLockup-BF_0pCa3.js → BrandLockup-BrytmTTH.js} +1 -1
  67. package/web/console/assets/{Channels-C4yZE67F.js → Channels-CApxH2TB.js} +1 -1
  68. package/web/console/assets/{ChatEntries-OqsqLjU6.js → ChatEntries-CJon3bWJ.js} +1 -1
  69. package/web/console/assets/{Clients-Dv3sv51C.js → Clients-BSA1rlTB.js} +1 -1
  70. package/web/console/assets/{Cost-C_-kiH59.js → Cost-BbhlQFP8.js} +1 -1
  71. package/web/console/assets/{Credentials-CPTEAiV6.js → Credentials-kqr1W0K7.js} +1 -1
  72. package/web/console/assets/{Diagnostics-O-NKFOeI.js → Diagnostics-Kljt9XTH.js} +1 -1
  73. package/web/console/assets/{Executors-GVIAiNgv.js → Executors-DnsB-Xz4.js} +1 -1
  74. package/web/console/assets/{Kb-BsCWkJI1.js → Kb-DLZSAFWP.js} +2 -2
  75. package/web/console/assets/{Login-VFjkHNMr.js → Login-DiTjPWmN.js} +1 -1
  76. package/web/console/assets/{Projects-Ds-sJwfy.js → Projects-CXcVCgCD.js} +1 -1
  77. package/web/console/assets/{Routes-Wwurw2UU.js → Routes-DN9_d9Po.js} +1 -1
  78. package/web/console/assets/Runs-Cwbe6thL.js +3 -0
  79. package/web/console/assets/Runs-D8UmjP5G.css +1 -0
  80. package/web/console/assets/{Setup-BLelw0_V.js → Setup-FqoCKmfZ.js} +1 -1
  81. package/web/console/assets/{Shell-CvaeK4j_.js → Shell-BEqpONiy.js} +1 -1
  82. package/web/console/assets/{StorageBuckets-Dv6u47yO.js → StorageBuckets-CkORbYXY.js} +1 -1
  83. package/web/console/assets/{SystemSettings-B9K7zaDU.js → SystemSettings-gTQAazu7.js} +1 -1
  84. package/web/console/assets/{SystemStatus-H-oKDo-y.js → SystemStatus-DAmUUNqO.js} +1 -1
  85. package/web/console/assets/{Targets-CCFhjPKf.js → Targets-CZmDcjsE.js} +1 -1
  86. package/web/console/assets/{Tools-D0H9xpFH.js → Tools-CIHInlHL.js} +1 -1
  87. package/web/console/assets/{index-CuoTgf6q.js → index-BkLbd7Cc.js} +2 -2
  88. package/web/console/assets/{index-DyX9Bz3V.js → index-QnmD7N7F.js} +1 -1
  89. package/web/console/assets/{request-F5lXa7Ro.js → request-r7GHVJzw.js} +1 -1
  90. package/web/console/assets/{schema-DUWaWqPn.js → schema-BVn_hB7M.js} +1 -1
  91. package/web/console/assets/vendor-mammoth-BUEEDX6A.js +231 -0
  92. package/web/console/index.html +1 -1
  93. package/web-admin/package-lock.json +3 -3
  94. package/web-admin/src/components/ClientConversations.vue +244 -0
  95. package/web-admin/src/components/conversation-audit.ts +121 -0
  96. package/web-admin/src/pages/Runs.vue +73 -17
  97. package/web-admin/tests/conversation-audit.fixture.mjs +182 -0
  98. package/web-admin/tests/conversation-audit.test.mjs +93 -0
  99. package/web/console/assets/Runs-4zDD9VOC.css +0 -1
  100. package/web/console/assets/Runs-DLPzXmSy.js +0 -3
  101. package/web/console/assets/vendor-mammoth-nXG51Cg7.js +0 -231
@@ -0,0 +1,30 @@
1
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
2
+ import type { AgentToolAuthContext } from './agent-tool-invocations';
3
+ import {
4
+ auditUuid, parseCreateConversationAudit, parseConversationAuditEvents, ConversationAuditError,
5
+ CONVERSATION_AUDIT_SCHEMA, CONVERSATION_AUDIT_ACK_SCHEMA,
6
+ } from '../core/runtime/agent-conversation-audit';
7
+
8
+ function repository(configStore: ConfigStoreContract | null) {
9
+ if (!configStore?.agentConversationAudit) {
10
+ throw new ConversationAuditError(503, 'conversation_audit_unavailable', 'Conversation audit storage is unavailable.');
11
+ }
12
+ return configStore.agentConversationAudit;
13
+ }
14
+
15
+ export async function createConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, body: unknown) {
16
+ const input = parseCreateConversationAudit(body);
17
+ return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repository(store).create(auth, input) };
18
+ }
19
+
20
+ export async function confirmConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, id: string, body: unknown) {
21
+ if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length) {
22
+ throw new ConversationAuditError(400, 'invalid_request', 'Member confirmation requires an empty object; identity comes from the bearer.');
23
+ }
24
+ return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repository(store).confirm(auth, auditUuid(id)) };
25
+ }
26
+
27
+ export async function appendConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, id: string, body: unknown) {
28
+ const events = parseConversationAuditEvents(body);
29
+ return { schema: CONVERSATION_AUDIT_ACK_SCHEMA, ...await repository(store).append(auth, auditUuid(id), events) };
30
+ }
@@ -0,0 +1,38 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { ConversationAuditError, parseCreateConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
4
+ import { conversationAuditFixture, AUDIT_SESSION_A } from '../../test-support/agent-conversation-audit-fixture';
5
+
6
+ test('visible text preserves original characters and refuses undeclared reasoning or identity fields', () => {
7
+ const event = { event_id: 'visible-1', sequence: 1, client_turn_id: 'turn-1', kind: 'user_message', content: ' 原始文本\n<tool>quoted</tool> ' };
8
+ assert.equal(parseConversationAuditEvents({ events: [event] })[0]!.content, event.content);
9
+ for (const invalid of [
10
+ { ...event, reasoning: 'not visible' }, { ...event, token: 'not allowed' },
11
+ { ...event, member_session_id: AUDIT_SESSION_A }, { ...event, content: '\u0000' },
12
+ { ...event, content: ' ' }, { ...event, content: 'a'.repeat(64_001) },
13
+ { ...event, kind: 'tool_result' }, { ...event, sequence: 0 },
14
+ ]) assert.throws(() => parseConversationAuditEvents({ events: [invalid] }), (error: unknown) => error instanceof ConversationAuditError && error.statusCode === 400);
15
+ });
16
+
17
+ test('membership accepts all 64 host scope slots and rejects duplicate or unbound display labels', () => {
18
+ const fx = conversationAuditFixture();
19
+ const ids = Array.from({ length: 64 }, (_, index) => `123e4567-e89b-42d3-a456-${String(index).padStart(12, '0')}`);
20
+ assert.equal(parseCreateConversationAudit({ ...fx.input(), member_session_ids: ids, member_labels: {} }).member_session_ids.length, 64);
21
+ for (const patch of [
22
+ { member_session_ids: [AUDIT_SESSION_A, AUDIT_SESSION_A] },
23
+ { member_labels: { '123e4567-e89b-42d3-a456-426614174099': 'An unselected member' } },
24
+ { member_labels: { [AUDIT_SESSION_A]: 'x'.repeat(129) } },
25
+ { tenant: 'client-supplied-audit-scope' },
26
+ ]) assert.throws(() => parseCreateConversationAudit({ ...fx.input(), ...patch }));
27
+ });
28
+
29
+ test('event batches enforce continuity, unique ids and explicit byte or total-event limits', () => {
30
+ const event = { event_id: 'visible', sequence: 1, client_turn_id: 'turn-1', kind: 'assistant_message', content: 'a' };
31
+ assert.throws(() => parseConversationAuditEvents({ events: [event, { ...event, event_id: 'next', sequence: 3 }] }));
32
+ assert.throws(() => parseConversationAuditEvents({ events: [event, { ...event, sequence: 2 }] }));
33
+ assert.throws(() => parseConversationAuditEvents({ events: Array.from({ length: 51 }, (_, index) => ({ ...event, event_id: `event-${index}`, sequence: index + 1 })) }));
34
+ for (const batch of [
35
+ [{ ...event, sequence: 20_001 }],
36
+ Array.from({ length: 5 }, (_, index) => ({ ...event, event_id: `large-${index}`, sequence: index + 1, content: 'a'.repeat(64_000) })),
37
+ ]) assert.throws(() => parseConversationAuditEvents({ events: batch }), (error: unknown) => error instanceof ConversationAuditError && error.code === 'conversation_audit_limit' && error.statusCode === 413);
38
+ });
@@ -0,0 +1,159 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { AgentSession, Client, Route } from '../contracts/types';
3
+ import { routeAgentClientConfig } from '../config/route-config';
4
+ import { agentDirectToolsConfig } from '../config/tools-config';
5
+ import { audienceAllows } from './identity-runtime';
6
+
7
+ export const CONVERSATION_AUDIT_SCHEMA = 'bailing.agent-conversation-audit.v1';
8
+ export const CONVERSATION_AUDIT_ACK_SCHEMA = 'bailing.agent-conversation-audit-ack.v1';
9
+ export const CONVERSATION_AUDIT_MAX_EVENTS = 20_000;
10
+ export const CONVERSATION_AUDIT_MAX_BYTES = 16 * 1024 * 1024;
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
12
+ const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
13
+ const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
14
+
15
+ export class ConversationAuditError extends Error {
16
+ constructor(readonly statusCode: number, readonly code: string, message: string) {
17
+ super(message);
18
+ this.name = 'ConversationAuditError';
19
+ }
20
+ }
21
+
22
+ export function auditError(code = 'conversation_audit_conflict', status = 409): never {
23
+ throw new ConversationAuditError(status, code, status === 404
24
+ ? 'The conversation audit is unavailable for this identity.'
25
+ : status === 403 ? 'The frozen conversation authorization is no longer valid.'
26
+ : status === 413 ? 'The conversation audit limit was exceeded; no events were truncated or saved.'
27
+ : 'The conversation audit request conflicts with its frozen membership or event history.');
28
+ }
29
+
30
+ function invalid(): never {
31
+ throw new ConversationAuditError(400, 'invalid_request', 'The conversation audit request contains invalid or undeclared fields.');
32
+ }
33
+
34
+ function record(value: unknown): value is Record<string, unknown> {
35
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
36
+ }
37
+
38
+ function fields(value: unknown, required: string[], optional: string[] = []): asserts value is Record<string, unknown> {
39
+ if (!record(value) || required.some((key) => !Object.hasOwn(value, key)) ||
40
+ Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) invalid();
41
+ }
42
+
43
+ export function auditUuid(value: unknown): string {
44
+ if (typeof value !== 'string' || !UUID.test(value)) invalid();
45
+ return value.toLowerCase();
46
+ }
47
+
48
+ function identifier(value: unknown): string {
49
+ if (typeof value !== 'string' || !ID.test(value)) invalid();
50
+ return value;
51
+ }
52
+
53
+ function text(value: unknown, maximum: number): string {
54
+ if (typeof value !== 'string' || !value.trim() || value.length > maximum || CONTROL.test(value)) invalid();
55
+ return value;
56
+ }
57
+
58
+ export interface CreateConversationAuditInput {
59
+ client_archive_id: string;
60
+ client_conversation_id: string;
61
+ route: string;
62
+ member_session_ids: string[];
63
+ member_labels: Record<string, string>;
64
+ }
65
+
66
+ export function parseCreateConversationAudit(value: unknown): CreateConversationAuditInput {
67
+ fields(value, ['client_archive_id', 'client_conversation_id', 'route', 'member_session_ids'], ['member_labels']);
68
+ if (typeof value.route !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(value.route) || value.route === 'auto' ||
69
+ !Array.isArray(value.member_session_ids) || value.member_session_ids.length < 1 || value.member_session_ids.length > 64) invalid();
70
+ const members = value.member_session_ids.map(auditUuid).sort();
71
+ if (new Set(members).size !== members.length) invalid();
72
+ const labels: Record<string, string> = {};
73
+ if (value.member_labels !== undefined) {
74
+ if (!record(value.member_labels)) invalid();
75
+ for (const [key, label] of Object.entries(value.member_labels)) {
76
+ const id = auditUuid(key);
77
+ if (!members.includes(id) || Object.hasOwn(labels, id)) invalid();
78
+ labels[id] = text(label, 128);
79
+ }
80
+ }
81
+ return {
82
+ client_archive_id: auditUuid(value.client_archive_id),
83
+ client_conversation_id: identifier(value.client_conversation_id),
84
+ route: value.route, member_session_ids: members, member_labels: labels,
85
+ };
86
+ }
87
+
88
+ export type ConversationAuditEventKind = 'turn_start' | 'user_message' | 'assistant_message' | 'run_link' | 'turn_end';
89
+ export type ConversationAuditTurnStatus = 'running' | 'completed' | 'failed' | 'cancelled';
90
+ export interface ConversationAuditEventInput {
91
+ event_id: string;
92
+ sequence: number;
93
+ client_turn_id: string;
94
+ kind: ConversationAuditEventKind;
95
+ content?: string;
96
+ run_id?: string;
97
+ member_session_id?: string;
98
+ status?: Exclude<ConversationAuditTurnStatus, 'running'>;
99
+ }
100
+
101
+ export function parseConversationAuditEvents(value: unknown): ConversationAuditEventInput[] {
102
+ fields(value, ['events']);
103
+ if (!Array.isArray(value.events) || value.events.length < 1 || value.events.length > 50) invalid();
104
+ const events = value.events.map((raw): ConversationAuditEventInput => {
105
+ const common = ['event_id', 'sequence', 'client_turn_id', 'kind'];
106
+ if (!record(raw)) invalid();
107
+ if (raw.kind === 'user_message' || raw.kind === 'assistant_message') fields(raw, [...common, 'content']);
108
+ else if (raw.kind === 'run_link') fields(raw, [...common, 'run_id', 'member_session_id']);
109
+ else if (raw.kind === 'turn_end') fields(raw, [...common, 'status']);
110
+ else if (raw.kind === 'turn_start') fields(raw, common);
111
+ else invalid();
112
+ if (!Number.isSafeInteger(raw.sequence) || Number(raw.sequence) < 1) invalid();
113
+ if (Number(raw.sequence) > CONVERSATION_AUDIT_MAX_EVENTS) auditError('conversation_audit_limit', 413);
114
+ const event: ConversationAuditEventInput = {
115
+ event_id: identifier(raw.event_id), sequence: Number(raw.sequence), client_turn_id: identifier(raw.client_turn_id),
116
+ kind: raw.kind as ConversationAuditEventKind,
117
+ };
118
+ if (raw.kind === 'user_message' || raw.kind === 'assistant_message') event.content = text(raw.content, 64_000);
119
+ if (raw.kind === 'run_link') {
120
+ event.run_id = auditUuid(raw.run_id);
121
+ event.member_session_id = auditUuid(raw.member_session_id);
122
+ }
123
+ if (raw.kind === 'turn_end') {
124
+ if (!['completed', 'failed', 'cancelled'].includes(String(raw.status))) invalid();
125
+ event.status = raw.status as ConversationAuditEventInput['status'];
126
+ }
127
+ return event;
128
+ });
129
+ if (new Set(events.map((event) => event.event_id)).size !== events.length ||
130
+ events.some((event, index) => index > 0 && event.sequence !== events[index - 1]!.sequence + 1)) invalid();
131
+ if (events.reduce((sum, event) => sum + Buffer.byteLength(event.content ?? '', 'utf8'), 0) > 256 * 1024) auditError('conversation_audit_limit', 413);
132
+ return events;
133
+ }
134
+
135
+ function stable(value: unknown): string {
136
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
137
+ if (record(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
138
+ return JSON.stringify(value) ?? 'null';
139
+ }
140
+
141
+ export function auditHash(value: unknown): string {
142
+ return createHash('sha256').update(stable(value), 'utf8').digest('hex');
143
+ }
144
+
145
+ export function auditIdentityHash(session: AgentSession): string {
146
+ return auditHash({ session_id: session.session_id, client_app_id: session.client_app_id, principal: session.principal, on_behalf_of: session.on_behalf_of });
147
+ }
148
+
149
+ /** The same route restrictions as Agent Runtime; group membership never expands them. */
150
+ export function assertAuditMemberActive(session: AgentSession, client: Client, route: Route, expectedIdentity?: string): void {
151
+ const allowed = (routes: string[]) => Array.isArray(routes) && (routes.includes('*') || routes.includes(route.route_key));
152
+ if (session.revoked_at || !Number.isFinite(Date.parse(session.refresh_expires_at)) || Date.parse(session.refresh_expires_at) <= Date.now() ||
153
+ session.client_app_id !== client.app_id || !client.enabled || !client.agent_authorize_url || !route.enabled ||
154
+ !allowed(client.allowed_routes) || !allowed(session.allowed_routes) || !routeAgentClientConfig(route) || !agentDirectToolsConfig(route.tools) ||
155
+ (expectedIdentity !== undefined && auditIdentityHash(session) !== expectedIdentity) ||
156
+ !audienceAllows(route.audience, { ...session.principal, client_app_id: client.app_id, channel: session.principal.channel ?? `agent:${client.app_id}` }).ok) {
157
+ auditError('conversation_audit_authorization_invalid', 403);
158
+ }
159
+ }
@@ -0,0 +1,146 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { ConversationAuditError, parseConversationAuditEvents } from '../../core/runtime/agent-conversation-audit';
4
+ import { conversationAuditFixture, AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C, AUDIT_RUN_A, AUDIT_RUN_B } from '../../test-support/agent-conversation-audit-fixture';
5
+
6
+ const errorCode = (code: string) => (error: unknown) => error instanceof ConversationAuditError && error.code === code;
7
+ const events = () => parseConversationAuditEvents({ events: [
8
+ { event_id: 'start-1', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
9
+ { event_id: 'user-1', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'Compare Store A and Store B.\nKeep this full visible request.' },
10
+ { event_id: 'link-a', sequence: 3, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_A, member_session_id: AUDIT_SESSION_A },
11
+ { event_id: 'link-b', sequence: 4, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_B, member_session_id: AUDIT_SESSION_B },
12
+ { event_id: 'assistant-1', sequence: 5, client_turn_id: 'turn-1', kind: 'assistant_message', content: 'The complete visible answer combines both stores.' },
13
+ { event_id: 'end-1', sequence: 6, client_turn_id: 'turn-1', kind: 'turn_end', status: 'completed' },
14
+ ] });
15
+
16
+ test('a frozen group requires the own bearer of each member before accepting any body', async () => {
17
+ const fx = conversationAuditFixture();
18
+ const created = await fx.repo.create(fx.auth(), fx.input());
19
+ assert.equal(created.state, 'enrolling');
20
+ assert.equal(created.confirmed_count, 1);
21
+ assert.equal(fx.events.size, 0);
22
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_not_ready'));
23
+ await assert.rejects(fx.repo.confirm(fx.auth(AUDIT_SESSION_C), created.conversation_id), errorCode('conversation_audit_not_found'));
24
+ assert.equal(fx.members.get(`${created.conversation_id}:${AUDIT_SESSION_B}`)!.confirmed_at, null);
25
+ const confirmed = await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), created.conversation_id);
26
+ assert.equal(confirmed.state, 'ready');
27
+ assert.equal(confirmed.confirmed_count, 2);
28
+ assert.equal((await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), created.conversation_id)).confirmed_count, 2);
29
+ await assert.rejects(fx.repo.append(fx.auth(AUDIT_SESSION_B), created.conversation_id, events()), errorCode('conversation_audit_not_found'));
30
+ assert.equal(fx.events.size, 0);
31
+ });
32
+
33
+ test('archive creation is creator-scoped and frozen input is idempotent, never joined by bare conversation id', async () => {
34
+ const fx = conversationAuditFixture();
35
+ const created = await fx.repo.create(fx.auth(), fx.input());
36
+ assert.equal((await fx.repo.create(fx.auth(), fx.input())).conversation_id, created.conversation_id);
37
+ await assert.rejects(fx.repo.create(fx.auth(), fx.input({ client_conversation_id: 'another-conversation' })), errorCode('conversation_audit_conflict'));
38
+ await assert.rejects(fx.repo.create(fx.auth(), fx.input({ member_session_ids: [AUDIT_SESSION_A], member_labels: {} })), errorCode('conversation_audit_conflict'));
39
+ const anotherCreator = await fx.repo.create(fx.auth(AUDIT_SESSION_B), fx.input());
40
+ assert.notEqual(anotherCreator.conversation_id, created.conversation_id);
41
+ assert.equal(fx.archives.size, 2);
42
+ });
43
+
44
+ test('full visible events are stored once, paginated without truncation, and linked to the original authorization runs', async () => {
45
+ const fx = conversationAuditFixture();
46
+ const created = await fx.ready();
47
+ const sent = events();
48
+ assert.equal((await fx.repo.append(fx.auth(), created.conversation_id, sent)).last_sequence, 6);
49
+ assert.equal((await fx.repo.append(fx.auth(), created.conversation_id, sent)).last_sequence, 6);
50
+ assert.equal(fx.events.size, 6);
51
+ const first = (await fx.repo.detailForAdmin(created.conversation_id, 0, 2))!;
52
+ assert.equal(first.events[1].content, sent[1]!.content);
53
+ assert.equal(first.has_more, true);
54
+ assert.equal(first.next_after_sequence, 2);
55
+ assert.equal(first.conversation.message_count, 2);
56
+ assert.equal(first.conversation.turn_count, 1);
57
+ assert.equal(first.conversation.last_turn_status, 'completed');
58
+ const second = (await fx.repo.detailForAdmin(created.conversation_id, 2, 2))!;
59
+ assert.deepEqual(second.events.map((event: any) => [event.run_id, event.thread_id]), [[AUDIT_RUN_A, 101], [AUDIT_RUN_B, 102]]);
60
+ assert.deepEqual(await fx.repo.findRunLinkForAdmin(AUDIT_RUN_B), { conversation_audit_id: created.conversation_id, client_turn_id: 'turn-1' });
61
+ const final = (await fx.repo.detailForAdmin(created.conversation_id, 4, 2))!;
62
+ assert.equal(final.has_more, false);
63
+ assert.equal(final.next_after_sequence, 6);
64
+ assert.equal(first.members[0].display_label, 'Store A');
65
+ assert.doesNotMatch(JSON.stringify(first), /identity_hash|enrollment_hash|access_token|refresh_token|context_json/);
66
+ assert.equal(fx.queries.some(({ sql }) => /INSERT INTO bz_messages|UPDATE bz_threads/.test(sql)), false);
67
+ const writeIndex = fx.queries.findIndex(({ sql }) => sql.startsWith('INSERT INTO bz_agent_conversation_events'));
68
+ for (const id of [AUDIT_SESSION_A, AUDIT_SESSION_B]) assert.ok(fx.queries.slice(0, writeIndex).some(({ sql, params, transactional }) => sql.includes('FROM bz_agent_sessions') && sql.includes('FOR UPDATE') && params[0] === id && transactional));
69
+ });
70
+
71
+ test('changed retries, gaps and event-id reuse fail atomically', async () => {
72
+ const fx = conversationAuditFixture();
73
+ const created = await fx.ready();
74
+ const sent = events();
75
+ await fx.repo.append(fx.auth(), created.conversation_id, sent.slice(0, 2));
76
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[1]!, content: 'Changed original message' }]), errorCode('conversation_audit_conflict'));
77
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [sent[3]!]), errorCode('conversation_audit_conflict'));
78
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[2]!, event_id: sent[1]!.event_id }]), errorCode('conversation_audit_conflict'));
79
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [sent[2]!, { ...sent[3]!, member_session_id: AUDIT_SESSION_C }]), errorCode('conversation_audit_conflict'));
80
+ assert.equal(fx.events.size, 2, 'the valid first event in a failed batch must also roll back');
81
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 2);
82
+ });
83
+
84
+ for (const field of ['session_id', 'client_app_id', 'route_key', 'client_conversation_id', 'client_turn_id']) {
85
+ test(`run_link rejects a different ${field} instead of widening its frozen ownership`, async () => {
86
+ const fx = conversationAuditFixture();
87
+ const created = await fx.ready();
88
+ fx.runs.get(AUDIT_RUN_A)![field] = field === 'session_id' ? AUDIT_SESSION_C : 'other-binding';
89
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_conflict'));
90
+ assert.equal(fx.events.size, 0);
91
+ });
92
+ }
93
+
94
+ for (const mutation of ['revoked', 'expired', 'principal', 'subject', 'session-route', 'client-route', 'client-disabled', 'route-disabled', 'audience']) {
95
+ test(`a ${mutation} authorization change blocks all further conversation text`, async () => {
96
+ const fx = conversationAuditFixture();
97
+ const created = await fx.ready();
98
+ const member = fx.sessions.get(AUDIT_SESSION_B)!;
99
+ if (mutation === 'revoked') member.revoked_at = '2026-01-01T00:00:00Z';
100
+ if (mutation === 'expired') member.refresh_expires_at = '2000-01-01T00:00:00Z';
101
+ if (mutation === 'principal') member.principal_json.tenant = 'other-store';
102
+ if (mutation === 'subject') member.on_behalf_of = 'other-subject';
103
+ if (mutation === 'session-route') member.allowed_routes = [];
104
+ if (mutation === 'client-route') fx.client.allowed_routes = [];
105
+ if (mutation === 'client-disabled') fx.client.enabled = false;
106
+ if (mutation === 'route-disabled') fx.route.enabled = false;
107
+ if (mutation === 'audience') fx.route.audience = { enabled: true, tenants: ['store-a'] };
108
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_authorization_invalid'));
109
+ assert.equal(fx.events.size, 0);
110
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 0);
111
+ });
112
+ }
113
+
114
+ test('a single run cannot be attributed to two different complete conversation archives', async () => {
115
+ const fx = conversationAuditFixture();
116
+ const first = await fx.ready();
117
+ await fx.repo.append(fx.auth(), first.conversation_id, events());
118
+ const second = await fx.repo.create(fx.auth(), fx.input({ client_archive_id: '323e4567-e89b-42d3-a456-426614174009' }));
119
+ await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), second.conversation_id);
120
+ await assert.rejects(fx.repo.append(fx.auth(), second.conversation_id, events()), errorCode('conversation_audit_conflict'));
121
+ assert.equal(fx.archives.get(second.conversation_id)!.last_sequence, 0);
122
+ });
123
+
124
+ test('late original run evidence may follow turn_end without reopening it or altering a newer turn', async () => {
125
+ const fx = conversationAuditFixture();
126
+ const created = await fx.ready();
127
+ const sent = events();
128
+ await fx.repo.append(fx.auth(), created.conversation_id, [sent[0]!, sent[1]!, { ...sent[5]!, sequence: 3, status: 'cancelled' }]);
129
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[2]!, sequence: 4 }]);
130
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_status, 'cancelled');
131
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ event_id: 'start-2', sequence: 5, client_turn_id: 'turn-2', kind: 'turn_start' }]);
132
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[3]!, sequence: 6 }]);
133
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_id, 'turn-2');
134
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_status, 'running');
135
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[4]!, sequence: 7 }]), errorCode('conversation_audit_conflict'));
136
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 6);
137
+ });
138
+
139
+ test('the archive total byte ceiling rejects the whole next batch instead of truncating content', async () => {
140
+ const fx = conversationAuditFixture();
141
+ const created = await fx.ready();
142
+ fx.archives.get(created.conversation_id)!.content_bytes = 16 * 1024 * 1024 - 1;
143
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_limit'));
144
+ assert.equal(fx.events.size, 0);
145
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 0);
146
+ });
@@ -0,0 +1,262 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { dt, rowClient, rowRoute } from '../../core/config/config-codec';
3
+ import type { AgentSession, Client, Route } from '../../core/contracts/types';
4
+ import {
5
+ assertAuditMemberActive, auditError, auditHash, auditIdentityHash,
6
+ CONVERSATION_AUDIT_MAX_BYTES, CONVERSATION_AUDIT_MAX_EVENTS,
7
+ type CreateConversationAuditInput, type ConversationAuditEventInput,
8
+ } from '../../core/runtime/agent-conversation-audit';
9
+
10
+ type Auth = { session: AgentSession; client: Client };
11
+ type Row = Record<string, any>;
12
+ const SESSION_COLUMNS = 'session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,created_at,access_expires_at,refresh_expires_at,revoked_at';
13
+
14
+ function json(value: unknown): any {
15
+ return typeof value === 'string' ? JSON.parse(value) : value;
16
+ }
17
+
18
+ function iso(value: any): string {
19
+ return new Date(value).toISOString();
20
+ }
21
+
22
+ function sessionOf(row: Row): AgentSession {
23
+ return {
24
+ session_id: String(row.session_id), client_app_id: String(row.client_app_id), device_label: String(row.device_label),
25
+ principal: json(row.principal_json), on_behalf_of: String(row.on_behalf_of), allowed_routes: json(row.allowed_routes),
26
+ created_at: iso(row.created_at), access_expires_at: iso(row.access_expires_at), refresh_expires_at: iso(row.refresh_expires_at),
27
+ ...(row.revoked_at ? { revoked_at: iso(row.revoked_at) } : {}),
28
+ };
29
+ }
30
+
31
+ function head(row: Row): Row {
32
+ return {
33
+ conversation_id: row.conversation_id, client_archive_id: row.client_archive_id,
34
+ client_conversation_id: row.client_conversation_id, client_app_id: row.client_app_id, route_key: row.route_key,
35
+ state: row.state, member_count: Number(row.member_count), confirmed_count: Number(row.confirmed_count),
36
+ last_sequence: Number(row.last_sequence), message_count: Number(row.message_count), turn_count: Number(row.turn_count),
37
+ last_turn_status: row.last_turn_status ?? null, created_at: iso(row.created_at), updated_at: iso(row.updated_at),
38
+ };
39
+ }
40
+
41
+ function eventView(row: Row): Row {
42
+ return {
43
+ event_id: row.event_id, sequence: Number(row.sequence), client_turn_id: row.client_turn_id, kind: row.kind,
44
+ ...(row.content !== null && row.content !== undefined ? { content: row.content } : {}),
45
+ ...(row.run_id ? { run_id: row.run_id, member_session_id: row.member_session_id, thread_id: Number(row.thread_id) } : {}),
46
+ ...(row.status ? { status: row.status } : {}), created_at: iso(row.created_at),
47
+ };
48
+ }
49
+
50
+ /** Separate audit ledger: no conversation body is added to bz_messages or memory. */
51
+ export class AgentConversationAuditRepository {
52
+ constructor(private readonly poolOf: () => any) {}
53
+ private get pool(): any { return this.poolOf(); }
54
+
55
+ private async transaction<T>(work: (connection: any) => Promise<T>): Promise<T> {
56
+ const connection = await this.pool.getConnection();
57
+ try {
58
+ await connection.beginTransaction();
59
+ const result = await work(connection);
60
+ await connection.commit();
61
+ return result;
62
+ } catch (error) {
63
+ await connection.rollback().catch(() => undefined);
64
+ if ((error as { code?: string }).code === 'ER_DUP_ENTRY') auditError();
65
+ throw error;
66
+ } finally { connection.release(); }
67
+ }
68
+
69
+ /** Lock the authorization configuration until commit, including revoke/refresh rows. */
70
+ private async lockedBinding(connection: any, clientAppId: string, routeKey: string): Promise<{ client: Client; route: Route }> {
71
+ const [clients] = await connection.query(
72
+ 'SELECT app_id,name,agent_authorize_url,allowed_routes,allowed_channels,enabled FROM bz_clients WHERE app_id=? FOR UPDATE', [clientAppId],
73
+ );
74
+ const [routes] = await connection.query('SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE', [routeKey]);
75
+ if (!clients[0] || !routes[0]) auditError('conversation_audit_authorization_invalid', 403);
76
+ return { client: rowClient(clients[0]), route: rowRoute(routes[0]) };
77
+ }
78
+
79
+ private async lockedSession(connection: any, id: string, binding: { client: Client; route: Route }, expectedIdentity?: string): Promise<AgentSession> {
80
+ const [rows] = await connection.query(`SELECT ${SESSION_COLUMNS} FROM bz_agent_sessions WHERE session_id=? FOR UPDATE`, [id]);
81
+ if (!rows[0]) auditError('conversation_audit_authorization_invalid', 403);
82
+ const session = sessionOf(rows[0]);
83
+ assertAuditMemberActive(session, binding.client, binding.route, expectedIdentity);
84
+ return session;
85
+ }
86
+
87
+ private async lockedConversation(connection: any, id: string, auth: Auth, creatorOnly: boolean): Promise<{ row: Row; members: Row[] }> {
88
+ const [rows] = await connection.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=? FOR UPDATE', [id]);
89
+ const row = rows[0] as Row | undefined;
90
+ if (!row || row.client_app_id !== auth.client.app_id || (creatorOnly && row.creator_session_id !== auth.session.session_id)) {
91
+ auditError('conversation_audit_not_found', 404);
92
+ }
93
+ const [members] = await connection.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id FOR UPDATE', [id]);
94
+ if (!(members as Row[]).some((member) => member.session_id === auth.session.session_id)) auditError('conversation_audit_not_found', 404);
95
+ return { row, members };
96
+ }
97
+
98
+ async create(auth: Auth, input: CreateConversationAuditInput): Promise<Row> {
99
+ if (!input.member_session_ids.includes(auth.session.session_id)) auditError('conversation_audit_not_found', 404);
100
+ return this.transaction(async (connection) => {
101
+ const enrollmentHash = auditHash(input);
102
+ const at = dt();
103
+ const row = {
104
+ conversation_id: randomUUID(), creator_session_id: auth.session.session_id, client_app_id: auth.client.app_id,
105
+ route_key: input.route, client_archive_id: input.client_archive_id, client_conversation_id: input.client_conversation_id,
106
+ enrollment_hash: enrollmentHash, state: input.member_session_ids.length === 1 ? 'ready' : 'enrolling',
107
+ member_count: input.member_session_ids.length, confirmed_count: 1, last_sequence: 0, content_bytes: 0,
108
+ message_count: 0, turn_count: 0, last_turn_id: null, last_turn_status: null, created_at: at, updated_at: at,
109
+ };
110
+ // Acquire the group lock first for every mutation. The unique archive key
111
+ // also makes concurrent identical creation retryable without a second group.
112
+ await connection.query('INSERT INTO bz_agent_conversation_audits SET ? ON DUPLICATE KEY UPDATE conversation_id=conversation_id', [row]);
113
+ const [existing] = await connection.query(
114
+ 'SELECT * FROM bz_agent_conversation_audits WHERE creator_session_id=? AND route_key=? AND client_archive_id=? FOR UPDATE',
115
+ [auth.session.session_id, input.route, input.client_archive_id],
116
+ );
117
+ const stored = existing[0];
118
+ if (!stored || stored.client_app_id !== auth.client.app_id || stored.enrollment_hash !== enrollmentHash) auditError();
119
+ const binding = await this.lockedBinding(connection, auth.client.app_id, input.route);
120
+ const creator = await this.lockedSession(connection, auth.session.session_id, binding, auditIdentityHash(auth.session));
121
+ if (stored.conversation_id !== row.conversation_id) return head(stored);
122
+ for (const id of input.member_session_ids) {
123
+ const confirmed = id === creator.session_id;
124
+ await connection.query('INSERT INTO bz_agent_conversation_members SET ?', [{
125
+ conversation_id: row.conversation_id, session_id: id, display_label: input.member_labels[id] ?? id,
126
+ identity_hash: confirmed ? auditIdentityHash(creator) : null,
127
+ principal_json: confirmed ? JSON.stringify(creator.principal) : null,
128
+ on_behalf_of: confirmed ? creator.on_behalf_of : null, confirmed_at: confirmed ? at : null,
129
+ }]);
130
+ }
131
+ return head(row);
132
+ });
133
+ }
134
+
135
+ async confirm(auth: Auth, conversationId: string): Promise<Row> {
136
+ return this.transaction(async (connection) => {
137
+ const { row, members } = await this.lockedConversation(connection, conversationId, auth, false);
138
+ const binding = await this.lockedBinding(connection, row.client_app_id, row.route_key);
139
+ const member = members.find((candidate) => candidate.session_id === auth.session.session_id)!;
140
+ const session = await this.lockedSession(connection, member.session_id, binding, member.identity_hash ?? auditIdentityHash(auth.session));
141
+ if (auditIdentityHash(session) !== auditIdentityHash(auth.session)) auditError('conversation_audit_authorization_invalid', 403);
142
+ const at = dt();
143
+ if (!member.confirmed_at) {
144
+ await connection.query(
145
+ 'UPDATE bz_agent_conversation_members SET identity_hash=?,principal_json=?,on_behalf_of=?,confirmed_at=? WHERE conversation_id=? AND session_id=?',
146
+ [auditIdentityHash(session), JSON.stringify(session.principal), session.on_behalf_of, at, conversationId, session.session_id],
147
+ );
148
+ member.identity_hash = auditIdentityHash(session);
149
+ member.confirmed_at = at;
150
+ }
151
+ const confirmed = members.filter((candidate) => candidate.confirmed_at).length;
152
+ if (confirmed === members.length) {
153
+ for (const candidate of members) await this.lockedSession(connection, candidate.session_id, binding, candidate.identity_hash);
154
+ }
155
+ row.confirmed_count = confirmed;
156
+ row.state = confirmed === members.length ? 'ready' : 'enrolling';
157
+ row.updated_at = at;
158
+ await connection.query('UPDATE bz_agent_conversation_audits SET confirmed_count=?,state=?,updated_at=? WHERE conversation_id=?',
159
+ [confirmed, row.state, at, conversationId]);
160
+ return head(row);
161
+ });
162
+ }
163
+
164
+ async append(auth: Auth, conversationId: string, events: ConversationAuditEventInput[]): Promise<Row> {
165
+ return this.transaction(async (connection) => {
166
+ const { row, members } = await this.lockedConversation(connection, conversationId, auth, true);
167
+ if (row.state !== 'ready' || members.length !== Number(row.member_count) || members.some((member) => !member.confirmed_at)) {
168
+ auditError('conversation_audit_not_ready');
169
+ }
170
+ const binding = await this.lockedBinding(connection, row.client_app_id, row.route_key);
171
+ for (const member of members) {
172
+ const session = await this.lockedSession(connection, member.session_id, binding, member.identity_hash);
173
+ if (session.session_id === auth.session.session_id && auditIdentityHash(session) !== auditIdentityHash(auth.session)) {
174
+ auditError('conversation_audit_authorization_invalid', 403);
175
+ }
176
+ }
177
+ const at = dt();
178
+ for (const event of events) {
179
+ const eventHash = auditHash(event);
180
+ const [duplicates] = await connection.query(
181
+ 'SELECT sequence,event_id,event_hash FROM bz_agent_conversation_events WHERE conversation_id=? AND (sequence=? OR event_id=?)',
182
+ [conversationId, event.sequence, event.event_id],
183
+ );
184
+ if (duplicates.length) {
185
+ if (duplicates.length !== 1 || Number(duplicates[0].sequence) !== event.sequence || duplicates[0].event_id !== event.event_id || duplicates[0].event_hash !== eventHash) auditError();
186
+ continue;
187
+ }
188
+ if (event.sequence !== Number(row.last_sequence) + 1) auditError();
189
+ const contentBytes = Buffer.byteLength(event.content ?? '', 'utf8');
190
+ if (event.sequence > CONVERSATION_AUDIT_MAX_EVENTS || Number(row.content_bytes) + contentBytes > CONVERSATION_AUDIT_MAX_BYTES) auditError('conversation_audit_limit', 413);
191
+ if (event.kind === 'turn_start') {
192
+ const [started] = await connection.query("SELECT sequence FROM bz_agent_conversation_events WHERE conversation_id=? AND client_turn_id=? AND kind='turn_start' LIMIT 1", [conversationId, event.client_turn_id]);
193
+ if (row.last_turn_status === 'running' || started.length) auditError();
194
+ row.last_turn_id = event.client_turn_id;
195
+ row.last_turn_status = 'running';
196
+ row.turn_count = Number(row.turn_count) + 1;
197
+ } else if (event.kind === 'run_link') {
198
+ // A startTurn response may arrive after cancellation/end, or while the
199
+ // next turn is running. Late execution evidence belongs to its original
200
+ // started turn and must never reopen or change the current turn.
201
+ const [started] = await connection.query("SELECT sequence FROM bz_agent_conversation_events WHERE conversation_id=? AND client_turn_id=? AND kind='turn_start' LIMIT 1", [conversationId, event.client_turn_id]);
202
+ if (!started.length) auditError();
203
+ } else if (row.last_turn_status !== 'running' || row.last_turn_id !== event.client_turn_id) auditError();
204
+ let threadId: number | null = null;
205
+ if (event.kind === 'run_link') {
206
+ if (!members.some((member) => member.session_id === event.member_session_id)) auditError();
207
+ const [runs] = await connection.query(
208
+ 'SELECT run_id,session_id,client_app_id,route_key,thread_id,client_conversation_id,client_turn_id FROM bz_agent_client_runs WHERE run_id=? FOR UPDATE', [event.run_id],
209
+ );
210
+ const run = runs[0];
211
+ if (!run || run.session_id !== event.member_session_id || run.client_app_id !== row.client_app_id || run.route_key !== row.route_key ||
212
+ run.client_conversation_id !== row.client_conversation_id || run.client_turn_id !== event.client_turn_id || !Number(run.thread_id)) auditError();
213
+ threadId = Number(run.thread_id);
214
+ }
215
+ if (event.kind === 'turn_end') row.last_turn_status = event.status;
216
+ if (event.kind === 'user_message' || event.kind === 'assistant_message') row.message_count = Number(row.message_count) + 1;
217
+ await connection.query('INSERT INTO bz_agent_conversation_events SET ?', [{
218
+ conversation_id: conversationId, sequence: event.sequence, event_id: event.event_id, client_turn_id: event.client_turn_id,
219
+ kind: event.kind, content: event.content ?? null, run_id: event.run_id ?? null, member_session_id: event.member_session_id ?? null,
220
+ thread_id: threadId, status: event.status ?? null, event_hash: eventHash, created_at: at,
221
+ }]);
222
+ row.last_sequence = event.sequence;
223
+ row.content_bytes = Number(row.content_bytes) + contentBytes;
224
+ }
225
+ await connection.query(
226
+ 'UPDATE bz_agent_conversation_audits SET last_sequence=?,content_bytes=?,message_count=?,turn_count=?,last_turn_id=?,last_turn_status=?,updated_at=? WHERE conversation_id=?',
227
+ [row.last_sequence, row.content_bytes, row.message_count, row.turn_count, row.last_turn_id, row.last_turn_status, at, conversationId],
228
+ );
229
+ return { conversation_id: conversationId, last_sequence: Number(row.last_sequence) };
230
+ });
231
+ }
232
+
233
+ async listForAdmin(limit = 50, offset = 0): Promise<Row> {
234
+ const n = Math.min(Math.max(Math.floor(limit) || 50, 1), 100);
235
+ const off = Math.max(Math.floor(offset) || 0, 0);
236
+ const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits ORDER BY updated_at DESC,conversation_id DESC LIMIT ? OFFSET ?', [n + 1, off]);
237
+ const items = (rows as Row[]).slice(0, n).map(head);
238
+ return { items, has_more: rows.length > n, next_offset: rows.length > n ? off + n : null };
239
+ }
240
+
241
+ async detailForAdmin(conversationId: string, afterSequence = 0, limit = 100): Promise<Row | null> {
242
+ const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=?', [conversationId]);
243
+ if (!rows[0]) return null;
244
+ const n = Math.min(Math.max(Math.floor(limit) || 100, 1), 200);
245
+ const after = Math.max(Math.floor(afterSequence) || 0, 0);
246
+ const [members] = await this.pool.query('SELECT session_id,display_label,principal_json,on_behalf_of,confirmed_at FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id', [conversationId]);
247
+ const [rowsOfEvents] = await this.pool.query('SELECT * FROM bz_agent_conversation_events WHERE conversation_id=? AND sequence>? ORDER BY sequence LIMIT ?', [conversationId, after, n + 1]);
248
+ const events = (rowsOfEvents as Row[]).slice(0, n).map(eventView);
249
+ return {
250
+ conversation: head(rows[0]), members: (members as Row[]).map((member) => ({
251
+ session_id: member.session_id, display_label: member.display_label, confirmed: Boolean(member.confirmed_at),
252
+ ...(member.confirmed_at ? { principal: json(member.principal_json), on_behalf_of: member.on_behalf_of } : {}),
253
+ })), events, has_more: rowsOfEvents.length > n,
254
+ next_after_sequence: events.length ? events.at(-1)!.sequence : after,
255
+ };
256
+ }
257
+
258
+ async findRunLinkForAdmin(runId: string): Promise<{ conversation_audit_id: string; client_turn_id: string } | null> {
259
+ const [rows] = await this.pool.query("SELECT conversation_id,client_turn_id FROM bz_agent_conversation_events WHERE run_id=? AND kind='run_link' LIMIT 1", [runId]);
260
+ return rows[0] ? { conversation_audit_id: String(rows[0].conversation_id), client_turn_id: String(rows[0].client_turn_id) } : null;
261
+ }
262
+ }