bailinghub 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +146 -185
- package/README.md +135 -206
- package/THIRD_PARTY_NOTICES.md +6 -7
- package/assets/readme-demo-evidence.en-dark.svg +82 -0
- package/assets/readme-demo-evidence.en.svg +82 -0
- package/assets/readme-demo-evidence.zh-CN-dark.svg +82 -0
- package/assets/readme-demo-evidence.zh-CN.svg +82 -0
- package/assets/readme-entry-points.en-dark.svg +71 -0
- package/assets/readme-entry-points.en.svg +71 -0
- package/assets/readme-entry-points.zh-CN-dark.svg +71 -0
- package/assets/readme-entry-points.zh-CN.svg +71 -0
- package/assets/readme-product-overview.en-dark.svg +87 -0
- package/assets/readme-product-overview.en.svg +87 -0
- package/assets/readme-product-overview.zh-CN-dark.svg +87 -0
- package/assets/readme-product-overview.zh-CN.svg +87 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +25 -9
- package/docs/AGENT_AUTH_API.md +17 -5
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +90 -18
- package/docs/AGENT_CLIENT_QUICKSTART.md +74 -16
- package/docs/AGENT_CONVERSATION_AUDIT.en.md +194 -0
- package/docs/AGENT_CONVERSATION_AUDIT.md +111 -0
- package/docs/CHANGELOG.en.md +23 -0
- package/docs/CHANGELOG.md +23 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
- package/docs/RELEASE_NOTES_v0.6.0.en.md +51 -0
- package/docs/RELEASE_NOTES_v0.6.0.md +51 -0
- package/docs/user-guide/README.en.md +1 -0
- package/docs/user-guide/README.md +1 -0
- package/docs/user-guide/console-map.en.md +2 -0
- package/docs/user-guide/console-map.md +2 -1
- package/docs/user-guide/conversations.en.md +40 -0
- package/docs/user-guide/conversations.md +40 -0
- package/package.json +1 -1
- package/scripts/check-doc-links.mjs +3 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +5 -5
- package/scripts/e2e-console.mjs +89 -0
- package/scripts/generate-readme-assets.mjs +488 -7
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/verify-github-repo.mjs +2 -0
- package/sql/057_agent_conversation_audit.sql +55 -0
- package/src/app/agent-conversation-audit.ts +30 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/core/config/agent-direct-console-selection.test.ts +22 -0
- package/src/core/runtime/agent-conversation-audit.test.ts +38 -0
- package/src/core/runtime/agent-conversation-audit.ts +159 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +36 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +97 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +54 -0
- package/src/infrastructure/config/config-agent-conversation-audit-repository.test.ts +146 -0
- package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +262 -0
- package/src/infrastructure/config/configstore.ts +5 -0
- package/src/routes/admin-agent-clients.test.ts +120 -0
- package/src/routes/admin-agent-clients.ts +161 -0
- package/src/routes/admin-conversation-audit.ts +46 -0
- package/src/routes/admin-runtime.test.ts +38 -0
- package/src/routes/admin-runtime.ts +14 -3
- package/src/routes/admin.ts +6 -0
- package/src/routes/agent-api.ts +2 -0
- package/src/routes/agent-conversation-audit.test.ts +131 -0
- package/src/routes/agent-conversation-audit.ts +33 -0
- package/src/test-support/agent-conversation-audit-fixture.ts +123 -0
- package/web/console/assets/{Accounts-D4RRm5D1.js → Accounts-Ca_VnSu9.js} +1 -1
- package/web/console/assets/AgentClients-BPIvlLYY.js +1 -0
- package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
- package/web/console/assets/{Approvals-CsTTKb8o.js → Approvals-CMvPWacY.js} +1 -1
- package/web/console/assets/{Audit-BzvZ7JZw.js → Audit-CIRqOCnL.js} +1 -1
- package/web/console/assets/{BrandLockup-CYcA93wh.js → BrandLockup-BrytmTTH.js} +1 -1
- package/web/console/assets/{Channels-DRQZggqM.js → Channels-CApxH2TB.js} +1 -1
- package/web/console/assets/{ChatEntries-BUB7BWKU.js → ChatEntries-CJon3bWJ.js} +1 -1
- package/web/console/assets/Clients-BSA1rlTB.js +3 -0
- package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
- package/web/console/assets/{Cost-BZgFf1yM.js → Cost-BbhlQFP8.js} +1 -1
- package/web/console/assets/{Credentials-BTe2Q07j.js → Credentials-kqr1W0K7.js} +1 -1
- package/web/console/assets/{Diagnostics-WL-buYli.js → Diagnostics-Kljt9XTH.js} +1 -1
- package/web/console/assets/{Executors-CGZ-7Xmp.js → Executors-DnsB-Xz4.js} +1 -1
- package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
- package/web/console/assets/{Kb-VVw8oGsT.js → Kb-DLZSAFWP.js} +2 -2
- package/web/console/assets/{Login-rwvmBBPl.js → Login-DiTjPWmN.js} +1 -1
- package/web/console/assets/{Projects-CexaCEY1.js → Projects-CXcVCgCD.js} +1 -1
- package/web/console/assets/Routes-CXGl9SMM.css +1 -0
- package/web/console/assets/Routes-DN9_d9Po.js +124 -0
- package/web/console/assets/Runs-Cwbe6thL.js +3 -0
- package/web/console/assets/Runs-D8UmjP5G.css +1 -0
- package/web/console/assets/{Setup-Djh5yadQ.js → Setup-FqoCKmfZ.js} +1 -1
- package/web/console/assets/Shell-BEqpONiy.js +1 -0
- package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
- package/web/console/assets/{StorageBuckets-CQBR41W1.js → StorageBuckets-CkORbYXY.js} +1 -1
- package/web/console/assets/{SystemSettings-DgnopekD.js → SystemSettings-gTQAazu7.js} +1 -1
- package/web/console/assets/{SystemStatus-Bj8-kPt2.js → SystemStatus-DAmUUNqO.js} +1 -1
- package/web/console/assets/{Targets-BAfCt_nH.js → Targets-CZmDcjsE.js} +1 -1
- package/web/console/assets/{Tools-xjd0NZdE.js → Tools-CIHInlHL.js} +1 -1
- package/web/console/assets/index-BkLbd7Cc.js +2 -0
- package/web/console/assets/{index-DZEQL_yy.js → index-QnmD7N7F.js} +1 -1
- package/web/console/assets/{request-DkNPOweH.js → request-r7GHVJzw.js} +1 -1
- package/web/console/assets/{schema-CgPWAu1_.js → schema-BVn_hB7M.js} +1 -1
- package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
- package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
- package/web/console/assets/vendor-mammoth-BUEEDX6A.js +231 -0
- package/web/console/index.html +2 -2
- package/web-admin/package-lock.json +3 -3
- package/web-admin/src/agent-direct-selection.ts +21 -0
- package/web-admin/src/components/ClientConversations.vue +244 -0
- package/web-admin/src/components/conversation-audit.ts +121 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +254 -0
- package/web-admin/src/pages/Clients.vue +4 -2
- package/web-admin/src/pages/Routes.vue +54 -5
- package/web-admin/src/pages/Runs.vue +73 -17
- package/web-admin/src/router.ts +2 -0
- package/web-admin/tests/conversation-audit.fixture.mjs +182 -0
- package/web-admin/tests/conversation-audit.test.mjs +93 -0
- package/web/console/assets/Clients-CQ_MonGL.css +0 -1
- package/web/console/assets/Clients-HhCyrxfz.js +0 -3
- package/web/console/assets/Routes-B9ZHbQAp.js +0 -124
- package/web/console/assets/Routes-BbkFpi6Y.css +0 -1
- package/web/console/assets/Runs-4zDD9VOC.css +0 -1
- package/web/console/assets/Runs-BzFNPTwD.js +0 -3
- package/web/console/assets/Shell-BVIjmoY8.css +0 -1
- package/web/console/assets/Shell-kn763smL.js +0 -1
- package/web/console/assets/index-DfJA7iJS.js +0 -2
- package/web/console/assets/vendor-mammoth-DvgsHdlx.js +0 -231
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// 智能体客户端管理中心:聚合既有接入方、Agent Session 与 Agent Run。
|
|
2
|
+
// 不创建第二套 Client 资源,也不复用“执行器”概念;所有投影都排除 token、prompt、工具参数和业务结果。
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import type { Principal } from '../app/auth';
|
|
5
|
+
import { send } from '../app/http';
|
|
6
|
+
import { routeAgentClientConfig } from '../core/config/route-config';
|
|
7
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
8
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
9
|
+
import type { AgentClientAdminStats } from '../infrastructure/config/config-agent-client-runtime-repository';
|
|
10
|
+
import type { AgentSessionAdminState } from '../infrastructure/config/config-agent-auth-repository';
|
|
11
|
+
|
|
12
|
+
export interface AdminAgentClientsApiDeps {
|
|
13
|
+
configStore: ConfigStoreContract;
|
|
14
|
+
stateStore: RuntimeStateStore;
|
|
15
|
+
now: () => string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
19
|
+
const APP_ID_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/i;
|
|
20
|
+
|
|
21
|
+
function windowDays(value: string | null): number {
|
|
22
|
+
const n = Math.round(Number(value) || 30);
|
|
23
|
+
return Math.min(Math.max(n, 1), 90);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function sinceFor(nowValue: string, days: number): string {
|
|
27
|
+
const now = new Date(nowValue);
|
|
28
|
+
const base = Number.isFinite(now.getTime()) ? now.getTime() : Date.now();
|
|
29
|
+
return new Date(base - days * 86_400_000).toISOString().slice(0, 19).replace('T', ' ');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function emptyStats(clientAppId: string): AgentClientAdminStats {
|
|
33
|
+
return {
|
|
34
|
+
client_app_id: clientAppId,
|
|
35
|
+
runs: 0,
|
|
36
|
+
conversations: 0,
|
|
37
|
+
completed: 0,
|
|
38
|
+
failed: 0,
|
|
39
|
+
tool_calls: 0,
|
|
40
|
+
total_tokens: 0,
|
|
41
|
+
approvals: {},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function addApprovals(target: Record<string, number>, source: Record<string, number>): void {
|
|
46
|
+
for (const [status, value] of Object.entries(source)) target[status] = (target[status] ?? 0) + value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function actorOf(principal: Principal): string {
|
|
50
|
+
return principal.kind === 'admin' ? principal.username ?? 'admin-token' : 'unknown';
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function handleAdminAgentClientsApiFor(
|
|
54
|
+
deps: AdminAgentClientsApiDeps,
|
|
55
|
+
method: string,
|
|
56
|
+
path: string,
|
|
57
|
+
req: IncomingMessage,
|
|
58
|
+
res: ServerResponse,
|
|
59
|
+
principal: Principal,
|
|
60
|
+
): Promise<boolean> {
|
|
61
|
+
if (!path.startsWith('/admin/api/agent-clients')) return false;
|
|
62
|
+
const agentAuth = deps.configStore.agentAuth;
|
|
63
|
+
const runtime = deps.configStore.agentClientRuntime;
|
|
64
|
+
if (!agentAuth || !runtime) {
|
|
65
|
+
send(res, 503, { error: '智能体客户端管理中心需要 MySQL Agent Auth 与 Runtime 账本' });
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (path === '/admin/api/agent-clients/overview' && method === 'GET') {
|
|
70
|
+
const q = new URL(req.url ?? path, 'http://bailing.local').searchParams;
|
|
71
|
+
const days = windowDays(q.get('days'));
|
|
72
|
+
const now = new Date(deps.now());
|
|
73
|
+
const [clients, routes, stats, sessions] = await Promise.all([
|
|
74
|
+
deps.configStore.clients.list(),
|
|
75
|
+
deps.configStore.routes.list(),
|
|
76
|
+
runtime.statsForAdmin({ since: sinceFor(deps.now(), days) }),
|
|
77
|
+
agentAuth.sessionSummaryForAdmin(now),
|
|
78
|
+
]);
|
|
79
|
+
const byClient = new Map(stats.map((item) => [item.client_app_id, item]));
|
|
80
|
+
const applications = clients.map((client) => {
|
|
81
|
+
const clientStats = byClient.get(client.app_id) ?? emptyStats(client.app_id);
|
|
82
|
+
return {
|
|
83
|
+
app_id: client.app_id,
|
|
84
|
+
name: client.name,
|
|
85
|
+
enabled: client.enabled,
|
|
86
|
+
agent_auth_enabled: Boolean(client.agent_authorize_url),
|
|
87
|
+
agent_authorize_url: client.agent_authorize_url ?? null,
|
|
88
|
+
allowed_routes: client.allowed_routes,
|
|
89
|
+
last_used_at: client.last_used_at ?? null,
|
|
90
|
+
stats: clientStats,
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
const totals = stats.reduce((sum, item) => {
|
|
94
|
+
sum.runs += item.runs;
|
|
95
|
+
sum.conversations += item.conversations;
|
|
96
|
+
sum.completed += item.completed;
|
|
97
|
+
sum.failed += item.failed;
|
|
98
|
+
sum.tool_calls += item.tool_calls;
|
|
99
|
+
sum.total_tokens += item.total_tokens;
|
|
100
|
+
addApprovals(sum.approvals, item.approvals);
|
|
101
|
+
return sum;
|
|
102
|
+
}, { runs: 0, conversations: 0, completed: 0, failed: 0, tool_calls: 0, total_tokens: 0, approvals: {} as Record<string, number> });
|
|
103
|
+
send(res, 200, {
|
|
104
|
+
days,
|
|
105
|
+
applications,
|
|
106
|
+
workspaces: routes.filter((route) => Boolean(routeAgentClientConfig(route))).map((route) => ({
|
|
107
|
+
route: route.route_key,
|
|
108
|
+
name: route.name,
|
|
109
|
+
description: route.description ?? '',
|
|
110
|
+
})),
|
|
111
|
+
summary: {
|
|
112
|
+
applications: applications.length,
|
|
113
|
+
agent_auth_enabled: applications.filter((item) => item.agent_auth_enabled).length,
|
|
114
|
+
sessions,
|
|
115
|
+
...totals,
|
|
116
|
+
failure_rate: totals.runs ? totals.failed / totals.runs : 0,
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (path === '/admin/api/agent-clients/sessions' && method === 'GET') {
|
|
123
|
+
const q = new URL(req.url ?? path, 'http://bailing.local').searchParams;
|
|
124
|
+
const clientAppId = String(q.get('client_app_id') ?? '').trim();
|
|
125
|
+
if (clientAppId && !APP_ID_RE.test(clientAppId)) { send(res, 400, { error: 'client_app_id 无效' }); return true; }
|
|
126
|
+
const rawState = String(q.get('state') ?? 'all');
|
|
127
|
+
const state: AgentSessionAdminState | 'all' = ['active', 'expired', 'revoked'].includes(rawState)
|
|
128
|
+
? rawState as AgentSessionAdminState
|
|
129
|
+
: 'all';
|
|
130
|
+
send(res, 200, await agentAuth.listSessionsForAdmin({
|
|
131
|
+
...(clientAppId ? { clientAppId } : {}),
|
|
132
|
+
state,
|
|
133
|
+
limit: Number(q.get('limit')) || 50,
|
|
134
|
+
offset: Number(q.get('offset')) || 0,
|
|
135
|
+
now: new Date(deps.now()),
|
|
136
|
+
}));
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const revokeMatch = path.match(/^\/admin\/api\/agent-clients\/sessions\/([0-9a-f-]{36})\/revoke$/i);
|
|
141
|
+
if (revokeMatch && method === 'POST') {
|
|
142
|
+
const sessionId = revokeMatch[1]!;
|
|
143
|
+
if (!UUID_RE.test(sessionId)) { send(res, 404, { error: 'Agent Session 不存在' }); return true; }
|
|
144
|
+
const session = await agentAuth.getSessionForAdmin(sessionId, new Date(deps.now()));
|
|
145
|
+
if (!session) { send(res, 404, { error: 'Agent Session 不存在' }); return true; }
|
|
146
|
+
if (session.state === 'revoked') {
|
|
147
|
+
send(res, 200, { ok: true, session_id: sessionId, already_revoked: true });
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
const revoked = await agentAuth.revokeSessionForClient(session.client_app_id, sessionId);
|
|
151
|
+
if (!revoked) { send(res, 409, { error: 'Agent Session 状态已变化,请刷新后重试' }); return true; }
|
|
152
|
+
await deps.stateStore.appendAudit({
|
|
153
|
+
ts: deps.now(), job_id: '-', request_id: 'agent-client-admin', event: 'agent_session_admin_revoked',
|
|
154
|
+
detail: { session_id: sessionId, client_app_id: session.client_app_id, by: actorOf(principal) },
|
|
155
|
+
}).catch(() => undefined);
|
|
156
|
+
send(res, 200, { ok: true, session_id: sessionId, revoked: true });
|
|
157
|
+
return true;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { send } from '../app/http';
|
|
3
|
+
import { can, type Principal } from '../app/auth';
|
|
4
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
+
import { auditUuid, ConversationAuditError } from '../core/runtime/agent-conversation-audit';
|
|
6
|
+
|
|
7
|
+
export async function handleAdminConversationAuditFor(
|
|
8
|
+
store: ConfigStoreContract | null, method: string, path: string,
|
|
9
|
+
req: IncomingMessage, res: ServerResponse, principal: Principal,
|
|
10
|
+
): Promise<boolean> {
|
|
11
|
+
const base = '/admin/api/conversation-audits';
|
|
12
|
+
if (path !== base && !path.startsWith(`${base}/`)) return false;
|
|
13
|
+
if (principal.kind !== 'admin' || !can(principal, 'runs:read')) {
|
|
14
|
+
send(res, 403, { error: 'forbidden' });
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
res.setHeader('cache-control', 'no-store');
|
|
18
|
+
const detail = path.match(/^\/admin\/api\/conversation-audits\/([0-9a-f-]{36})$/i);
|
|
19
|
+
if (method !== 'GET' || (path !== base && !detail)) {
|
|
20
|
+
send(res, 404, { error: 'not_found' });
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
if (!store?.agentConversationAudit) {
|
|
24
|
+
send(res, 503, { error: 'conversation_audit_unavailable' });
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
29
|
+
const number = (key: string, fallback: number): number => {
|
|
30
|
+
const value = query.get(key);
|
|
31
|
+
if (value === null) return fallback;
|
|
32
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(Number(value))) throw new ConversationAuditError(400, 'invalid_request', 'Pagination requires non-negative safe integers.');
|
|
33
|
+
return Number(value);
|
|
34
|
+
};
|
|
35
|
+
if (path === base) {
|
|
36
|
+
send(res, 200, { schema: 'bailing.agent-conversation-audit-list.v1', ...await store.agentConversationAudit.listForAdmin(number('limit', 50), number('offset', 0)) });
|
|
37
|
+
} else {
|
|
38
|
+
const result = await store.agentConversationAudit.detailForAdmin(auditUuid(detail![1]), number('after_sequence', 0), number('limit', 100));
|
|
39
|
+
send(res, result ? 200 : 404, result ? { schema: 'bailing.agent-conversation-audit-detail.v1', ...result } : { error: 'conversation_audit_not_found' });
|
|
40
|
+
}
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error instanceof ConversationAuditError) send(res, error.statusCode, { error: error.code, message: error.message });
|
|
43
|
+
else send(res, 500, { error: 'conversation_audit_internal_error' });
|
|
44
|
+
}
|
|
45
|
+
return true;
|
|
46
|
+
}
|
|
@@ -212,3 +212,41 @@ test('Agent Run trace 对旧扩展仓储回退到单 job 审计与审批读取',
|
|
|
212
212
|
assert.equal(res.statusCode, 200);
|
|
213
213
|
assert.equal(res.json().invocations.length, 1);
|
|
214
214
|
});
|
|
215
|
+
|
|
216
|
+
test('Agent Run trace includes only the verified conversation backlink without copying its transcript', async () => {
|
|
217
|
+
const deps = depsFor();
|
|
218
|
+
const link = { conversation_audit_id: '723e4567-e89b-42d3-a456-426614174000', client_turn_id: 'turn-1' };
|
|
219
|
+
const lookups: string[] = [];
|
|
220
|
+
(deps.configStore as any).agentConversationAudit = {
|
|
221
|
+
findRunLinkForAdmin: async (id: string) => { lookups.push(id); return id === RUN_ID ? link : null; },
|
|
222
|
+
};
|
|
223
|
+
const res = new FakeResponse();
|
|
224
|
+
await handleAdminRuntimeApiFor(deps, 'GET', `/admin/api/threads/42/agent-runs/${RUN_ID}/trace`,
|
|
225
|
+
{} as IncomingMessage, res as unknown as ServerResponse,
|
|
226
|
+
{ kind: 'admin', via: 'session', role: 'viewer' });
|
|
227
|
+
assert.equal(res.statusCode, 200);
|
|
228
|
+
assert.equal(res.json().run.conversation_audit_id, link.conversation_audit_id);
|
|
229
|
+
assert.equal(res.json().run.client_turn_id, link.client_turn_id);
|
|
230
|
+
assert.deepEqual(lookups, [RUN_ID]);
|
|
231
|
+
assert.doesNotMatch(JSON.stringify(res.json()), /PRIVATE_FINAL_CONTENT|PRIVATE_USER_INPUT/);
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
test('a tool job receives the conversation backlink only after the original run ownership is verified', async () => {
|
|
235
|
+
const deps = depsFor();
|
|
236
|
+
const link = { conversation_audit_id: '723e4567-e89b-42d3-a456-426614174000', client_turn_id: 'turn-1' };
|
|
237
|
+
const lookups: string[] = [];
|
|
238
|
+
Object.assign(deps.configStore, {
|
|
239
|
+
agentConversationAudit: { findRunLinkForAdmin: async (id: string) => { lookups.push(id); return link; } },
|
|
240
|
+
conversations: { rawInputForJob: async () => null, messagesForJob: async () => [] },
|
|
241
|
+
deliveryDlq: { listByParentJob: async () => [] }, routes: { get: async () => null },
|
|
242
|
+
});
|
|
243
|
+
for (const id of [VALID_JOB_ID, FORGED_JOB_ID, OTHER_RUN_JOB_ID]) {
|
|
244
|
+
const res = new FakeResponse();
|
|
245
|
+
await handleAdminRuntimeApiFor(deps, 'GET', `/admin/api/runs/${id}/trace`,
|
|
246
|
+
{} as IncomingMessage, res as unknown as ServerResponse,
|
|
247
|
+
{ kind: 'admin', via: 'session', role: 'viewer' });
|
|
248
|
+
assert.equal(res.statusCode, 200);
|
|
249
|
+
assert.equal(res.json().job.conversation_audit_id, id === VALID_JOB_ID ? link.conversation_audit_id : undefined);
|
|
250
|
+
}
|
|
251
|
+
assert.deepEqual(lookups, [RUN_ID]);
|
|
252
|
+
});
|
|
@@ -167,6 +167,15 @@ export async function handleAdminRuntimeApiFor(
|
|
|
167
167
|
const configStore = deps.configStore;
|
|
168
168
|
const stateStore = deps.stateStore;
|
|
169
169
|
|
|
170
|
+
async function conversationLinkForJob(job: any): Promise<Record<string, string>> {
|
|
171
|
+
if (!configStore.agentConversationAudit || !configStore.agentClientRuntime || !isAgentToolInvocationJob(job)) return {};
|
|
172
|
+
const runId = job.metadata?.agent_run_id;
|
|
173
|
+
if (typeof runId !== 'string') return {};
|
|
174
|
+
const run = await configStore.agentClientRuntime.findRunForInvocation(runId);
|
|
175
|
+
if (!run || !isToolJobForAgentRun(job, run)) return {};
|
|
176
|
+
return await configStore.agentConversationAudit.findRunLinkForAdmin(runId) ?? {};
|
|
177
|
+
}
|
|
178
|
+
|
|
170
179
|
async function tracePayload(jobId: string): Promise<Record<string, unknown> | null> {
|
|
171
180
|
const job = await stateStore.getJob(jobId);
|
|
172
181
|
if (!job) return null;
|
|
@@ -179,7 +188,7 @@ export async function handleAdminRuntimeApiFor(
|
|
|
179
188
|
configStore.deliveryDlq.listByParentJob(jobId, true, 100).catch(() => []),
|
|
180
189
|
routeKey ? configStore.routes.get(routeKey).catch(() => null) : Promise.resolve(null),
|
|
181
190
|
]);
|
|
182
|
-
const jobWithRaw = { ...job, raw_input: rawInput };
|
|
191
|
+
const jobWithRaw = { ...job, raw_input: rawInput, ...await conversationLinkForJob(job) };
|
|
183
192
|
const trace = buildJobTrace({ job, audit, approvals, messages });
|
|
184
193
|
const dispatchSnapshot = {
|
|
185
194
|
status: job.status,
|
|
@@ -395,7 +404,7 @@ export async function handleAdminRuntimeApiFor(
|
|
|
395
404
|
audit: auditByJob[job.job_id] ?? [],
|
|
396
405
|
approvals: approvalsByJob[job.job_id] ?? [],
|
|
397
406
|
}));
|
|
398
|
-
|
|
407
|
+
const payload = buildAgentClientTrace({
|
|
399
408
|
run: {
|
|
400
409
|
run_id: run.run_id,
|
|
401
410
|
thread_id: run.thread_id,
|
|
@@ -412,7 +421,9 @@ export async function handleAdminRuntimeApiFor(
|
|
|
412
421
|
runAudit,
|
|
413
422
|
tools,
|
|
414
423
|
candidatesTruncated: candidates.truncated,
|
|
415
|
-
})
|
|
424
|
+
});
|
|
425
|
+
const conversationLink = await configStore.agentConversationAudit?.findRunLinkForAdmin(runId);
|
|
426
|
+
send(res, 200, { ...payload, run: { ...(payload.run as Record<string, unknown>), ...(conversationLink ?? {}) } });
|
|
416
427
|
return true;
|
|
417
428
|
}
|
|
418
429
|
|
package/src/routes/admin.ts
CHANGED
|
@@ -17,8 +17,10 @@ import { handleAdminDispatchConfigApiFor } from './admin-dispatch-config';
|
|
|
17
17
|
import { handleAdminInfraApiFor } from './admin-infra';
|
|
18
18
|
import { handleAdminKbApiFor } from './admin-kb';
|
|
19
19
|
import { handleAdminRuntimeApiFor } from './admin-runtime';
|
|
20
|
+
import { handleAdminConversationAuditFor } from './admin-conversation-audit';
|
|
20
21
|
import { handleAdminToolProviderApiFor } from './admin-tool-providers';
|
|
21
22
|
import { handleAdminBrandingApiFor } from './admin-branding';
|
|
23
|
+
import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
|
|
22
24
|
import { handleAdminDemoDatasetApiFor, type DemoDatasetServiceContract } from './admin-demo-dataset';
|
|
23
25
|
import { refreshTargets, type TargetRegistry } from '../core/targets/registry';
|
|
24
26
|
import type { AppConfig } from '../core/config/config';
|
|
@@ -101,10 +103,12 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
101
103
|
[/^\/admin\/api\/routes/, 'routes:read', 'routes:write'],
|
|
102
104
|
[/^\/admin\/api\/runs/, 'runs:read', 'runs:write'], // 重跑是写操作:viewer 只能看不能跑
|
|
103
105
|
[/^\/admin\/api\/threads/, 'runs:read', 'runs:read'], // 会话视图=运行面只读
|
|
106
|
+
[/^\/admin\/api\/conversation-audits/, 'runs:read', 'runs:read'],
|
|
104
107
|
[/^\/admin\/api\/status/, 'runs:read', 'runs:read'],
|
|
105
108
|
[/^\/admin\/api\/dispatch-status/, 'runs:read', 'runs:read'],
|
|
106
109
|
[/^\/admin\/api\/config-schemas/, 'audit:read', 'audit:read'],
|
|
107
110
|
[/^\/admin\/api\/cost/, 'runs:read', 'runs:read'], // 成本可观测=运行面只读
|
|
111
|
+
[/^\/admin\/api\/agent-clients/, 'clients:read', 'clients:write'],
|
|
108
112
|
[/^\/admin\/api\/clients/, 'clients:read', 'clients:write'],
|
|
109
113
|
[/^\/admin\/api\/credentials/, 'credentials:read', 'credentials:write'],
|
|
110
114
|
[/^\/admin\/api\/storage-buckets/, 'storage:read', 'storage:write'], // 含桶凭证,默认仅 admin(*)可管
|
|
@@ -183,6 +187,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
183
187
|
return true;
|
|
184
188
|
}
|
|
185
189
|
|
|
190
|
+
if (await handleAdminConversationAuditFor(configStore, method, path, req, res, principal)) return true;
|
|
186
191
|
if (await handleAdminRuntimeApiFor({
|
|
187
192
|
configStore,
|
|
188
193
|
stateStore: deps.stateStore,
|
|
@@ -192,6 +197,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
192
197
|
channelSend: deps.channelSend,
|
|
193
198
|
engineRuntime: deps.engineRuntime,
|
|
194
199
|
}, method, path, req, res, principal)) return true;
|
|
200
|
+
if (await handleAdminAgentClientsApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
195
201
|
if (await handleAdminBrandingApiFor({ brandingProvider: deps.brandingProvider }, method, path, req, res)) return true;
|
|
196
202
|
if (await handleAdminAccessApiFor({ configStore, stateStore: deps.stateStore, now: deps.now }, method, path, req, res, principal)) return true;
|
|
197
203
|
if (await handleAdminToolProviderApiFor({ cfg: deps.cfg, configStore, stateStore: deps.stateStore, toolIndex: deps.toolIndex, now: deps.now, sleep: deps.sleep }, method, path, req, res, principal)) return true;
|
package/src/routes/agent-api.ts
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
14
14
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
15
15
|
import { authenticateAgentAccess } from './agent-auth';
|
|
16
|
+
import { handleAgentConversationAuditFor } from './agent-conversation-audit';
|
|
16
17
|
import type { KbService } from '../services/kb';
|
|
17
18
|
import {
|
|
18
19
|
completeAgentRunFor,
|
|
@@ -91,6 +92,7 @@ export async function handleAgentApiHttpFor(deps: AgentApiHttpDeps, req: Incomin
|
|
|
91
92
|
if (!auth) { send(res, 401, { error: 'unauthorized' }); return true; }
|
|
92
93
|
const principal: Principal = { kind: 'agent', session: auth.session, client: auth.client };
|
|
93
94
|
const method = req.method ?? 'GET';
|
|
95
|
+
if (await handleAgentConversationAuditFor(deps.configStore, auth, req, res, path)) return true;
|
|
94
96
|
const runtimeDeps = (): AgentClientRuntimeDeps | null => deps.toolProxyDeps
|
|
95
97
|
? { toolProxyDeps: deps.toolProxyDeps, kbService: deps.kbService ?? null, stateStore: deps.stateStore }
|
|
96
98
|
: null;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { Readable } from 'node:stream';
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
7
|
+
import type { Principal } from '../app/auth';
|
|
8
|
+
import { handleAgentApiHttpFor } from './agent-api';
|
|
9
|
+
import { tokenHash } from './agent-auth';
|
|
10
|
+
import { handleAdminConversationAuditFor } from './admin-conversation-audit';
|
|
11
|
+
import { conversationAuditFixture, AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C } from '../test-support/agent-conversation-audit-fixture';
|
|
12
|
+
|
|
13
|
+
class Response {
|
|
14
|
+
statusCode = 0;
|
|
15
|
+
headers: Record<string, unknown> = {};
|
|
16
|
+
body = '';
|
|
17
|
+
setHeader(name: string, value: unknown) { this.headers[name.toLowerCase()] = value; }
|
|
18
|
+
writeHead(code: number, headers: Record<string, unknown> = {}) { this.statusCode = code; Object.assign(this.headers, headers); }
|
|
19
|
+
end(body?: string | Buffer) { this.body = String(body ?? ''); }
|
|
20
|
+
json(): any { return JSON.parse(this.body); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function request(method: string, path: string, body?: unknown, token?: string): IncomingMessage {
|
|
24
|
+
const req = Readable.from(body === undefined ? [] : [Buffer.from(JSON.stringify(body))]) as unknown as IncomingMessage;
|
|
25
|
+
req.method = method;
|
|
26
|
+
req.url = path;
|
|
27
|
+
req.headers = token ? { authorization: `Bearer ${token}` } : {};
|
|
28
|
+
return req;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const BASE = '/agent-api/v1/conversation-audits';
|
|
32
|
+
function fixture() {
|
|
33
|
+
const fx = conversationAuditFixture();
|
|
34
|
+
const tokens = new Map([AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C].map((id, index) => [id, `bha_${String(index).repeat(43)}`]));
|
|
35
|
+
const store = {
|
|
36
|
+
...fx.store,
|
|
37
|
+
clients: { get: async (id: string) => id === fx.client.app_id ? fx.client : null },
|
|
38
|
+
agentAuth: { getSessionByAccessHash: async (hash: string) => {
|
|
39
|
+
const pair = [...tokens].find(([, token]) => tokenHash(token) === hash);
|
|
40
|
+
if (!pair) return null;
|
|
41
|
+
const session = fx.auth(pair[0]).session;
|
|
42
|
+
return session.revoked_at ? null : session;
|
|
43
|
+
} },
|
|
44
|
+
} as unknown as ConfigStoreContract;
|
|
45
|
+
const deps = { configStore: store, stateStore: {} as RuntimeStateStore, isPaused: () => false, handleRun: async () => { throw new Error('No business dispatch is allowed'); } };
|
|
46
|
+
return Object.assign(fx, { store, deps, async api(method: string, path: string, body?: unknown, sessionId: string | null = AUDIT_SESSION_A) {
|
|
47
|
+
const res = new Response();
|
|
48
|
+
await handleAgentApiHttpFor(deps, request(method, path, body, sessionId ? tokens.get(sessionId) : undefined), res as unknown as ServerResponse, new URL(path, 'https://hub.example.com'));
|
|
49
|
+
return res;
|
|
50
|
+
} });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
test('the real Agent HTTP surface authenticates every confirmation and never exposes transcript reads', async () => {
|
|
54
|
+
const fx = fixture();
|
|
55
|
+
const input = fx.input();
|
|
56
|
+
assert.equal((await fx.api('POST', BASE, input, null)).statusCode, 401);
|
|
57
|
+
const created = await fx.api('POST', BASE, input);
|
|
58
|
+
assert.equal(created.statusCode, 200);
|
|
59
|
+
assert.equal(created.json().schema, 'bailing.agent-conversation-audit.v1');
|
|
60
|
+
assert.equal(created.headers['cache-control'], 'no-store');
|
|
61
|
+
const id = created.json().conversation_id;
|
|
62
|
+
const firstEvents = { events: [
|
|
63
|
+
{ event_id: 'start', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
|
|
64
|
+
{ event_id: 'user', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'COMPLETE_VISIBLE_USER_MESSAGE' },
|
|
65
|
+
] };
|
|
66
|
+
assert.equal((await fx.api('POST', `${BASE}/${id}/events`, firstEvents)).json().error, 'conversation_audit_not_ready');
|
|
67
|
+
assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, { session_id: AUDIT_SESSION_B })).statusCode, 400);
|
|
68
|
+
assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, {}, AUDIT_SESSION_C)).statusCode, 404);
|
|
69
|
+
assert.equal((await fx.api('POST', `${BASE}/${id}/confirm`, {}, AUDIT_SESSION_B)).json().state, 'ready');
|
|
70
|
+
const written = await fx.api('POST', `${BASE}/${id}/events`, firstEvents);
|
|
71
|
+
assert.deepEqual(written.json(), { schema: 'bailing.agent-conversation-audit-ack.v1', conversation_id: id, last_sequence: 2 });
|
|
72
|
+
for (const path of [BASE, `${BASE}/${id}`, `${BASE}/${id}/events`]) {
|
|
73
|
+
const read = await fx.api('GET', path);
|
|
74
|
+
assert.equal(read.statusCode, 404);
|
|
75
|
+
assert.doesNotMatch(read.body, /COMPLETE_VISIBLE_USER_MESSAGE/);
|
|
76
|
+
}
|
|
77
|
+
assert.equal(fx.events.size, 2);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('only an administrator with runs:read can read complete conversation pages', async () => {
|
|
81
|
+
const fx = fixture();
|
|
82
|
+
const created = await fx.api('POST', BASE, fx.input());
|
|
83
|
+
const id = created.json().conversation_id;
|
|
84
|
+
await fx.api('POST', `${BASE}/${id}/confirm`, {}, AUDIT_SESSION_B);
|
|
85
|
+
await fx.api('POST', `${BASE}/${id}/events`, { events: [
|
|
86
|
+
{ event_id: 'start', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
|
|
87
|
+
{ event_id: 'user', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'ADMIN_ONLY_VISIBLE_TEXT' },
|
|
88
|
+
{ event_id: 'end', sequence: 3, client_turn_id: 'turn-1', kind: 'turn_end', status: 'cancelled' },
|
|
89
|
+
] });
|
|
90
|
+
const admin = async (path: string, principal: Principal) => {
|
|
91
|
+
const res = new Response();
|
|
92
|
+
await handleAdminConversationAuditFor(fx.store, 'GET', path.split('?')[0]!, request('GET', path), res as unknown as ServerResponse, principal);
|
|
93
|
+
return res;
|
|
94
|
+
};
|
|
95
|
+
const path = `/admin/api/conversation-audits/${id}`;
|
|
96
|
+
for (const principal of [
|
|
97
|
+
{ kind: 'agent', ...fx.auth() },
|
|
98
|
+
{ kind: 'admin', via: 'session', role: 'kb_editor' },
|
|
99
|
+
{ kind: 'admin', via: 'session', role: 'admin', permissions: [] },
|
|
100
|
+
] as Principal[]) {
|
|
101
|
+
const denied = await admin(path, principal);
|
|
102
|
+
assert.equal(denied.statusCode, 403);
|
|
103
|
+
assert.doesNotMatch(denied.body, /ADMIN_ONLY_VISIBLE_TEXT/);
|
|
104
|
+
}
|
|
105
|
+
const viewer: Principal = { kind: 'admin', via: 'session', role: 'viewer' };
|
|
106
|
+
const first = await admin(`${path}?limit=1`, viewer);
|
|
107
|
+
assert.equal(first.statusCode, 200);
|
|
108
|
+
assert.equal(first.json().schema, 'bailing.agent-conversation-audit-detail.v1');
|
|
109
|
+
assert.equal(first.json().has_more, true);
|
|
110
|
+
assert.equal(first.json().next_after_sequence, 1);
|
|
111
|
+
const second = await admin(`${path}?limit=1&after_sequence=1`, viewer);
|
|
112
|
+
assert.equal(second.json().events[0].content, 'ADMIN_ONLY_VISIBLE_TEXT');
|
|
113
|
+
assert.equal(second.headers['cache-control'], 'no-store');
|
|
114
|
+
assert.equal((await admin(`${path}?after_sequence=-1`, viewer)).statusCode, 400);
|
|
115
|
+
const listed = await admin('/admin/api/conversation-audits?limit=1', viewer);
|
|
116
|
+
assert.equal(listed.json().items[0].message_count, 1);
|
|
117
|
+
assert.equal(listed.json().items[0].turn_count, 1);
|
|
118
|
+
assert.equal(listed.json().items[0].last_turn_status, 'cancelled');
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('missing storage is explicit and unexpected internal errors never expose raw database detail', async () => {
|
|
122
|
+
const fx = fixture();
|
|
123
|
+
const store = fx.deps.configStore!;
|
|
124
|
+
(store as any).agentConversationAudit = undefined;
|
|
125
|
+
assert.equal((await fx.api('POST', BASE, fx.input())).json().error, 'conversation_audit_unavailable');
|
|
126
|
+
(store as any).agentConversationAudit = { create: async () => { throw new Error('PASSWORD_AND_DATABASE_DETAIL_MUST_NOT_LEAK'); } };
|
|
127
|
+
const failure = await fx.api('POST', BASE, fx.input());
|
|
128
|
+
assert.equal(failure.statusCode, 500);
|
|
129
|
+
assert.equal(failure.json().error, 'conversation_audit_internal_error');
|
|
130
|
+
assert.doesNotMatch(failure.body, /PASSWORD|DATABASE_DETAIL/);
|
|
131
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { PayloadTooLargeError, readBody, send } from '../app/http';
|
|
3
|
+
import type { AgentToolAuthContext } from '../app/agent-tool-invocations';
|
|
4
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
5
|
+
import { createConversationAuditFor, confirmConversationAuditFor, appendConversationAuditFor } from '../app/agent-conversation-audit';
|
|
6
|
+
import { ConversationAuditError } from '../core/runtime/agent-conversation-audit';
|
|
7
|
+
|
|
8
|
+
/** Agent write-only surface. No GET or transcript body is exposed to a bearer. */
|
|
9
|
+
export async function handleAgentConversationAuditFor(
|
|
10
|
+
store: ConfigStoreContract | null, auth: AgentToolAuthContext,
|
|
11
|
+
req: IncomingMessage, res: ServerResponse, path: string,
|
|
12
|
+
): Promise<boolean> {
|
|
13
|
+
const base = '/agent-api/v1/conversation-audits';
|
|
14
|
+
if (path !== base && !path.startsWith(`${base}/`)) return false;
|
|
15
|
+
const member = path.match(/^\/agent-api\/v1\/conversation-audits\/([0-9a-f-]{36})\/(confirm|events)$/i);
|
|
16
|
+
if (req.method !== 'POST' || (path !== base && !member)) {
|
|
17
|
+
send(res, 404, { error: 'not_found' });
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
const body = await readBody(req, 2 * 1024 * 1024);
|
|
22
|
+
const result = path === base ? await createConversationAuditFor(store, auth, body)
|
|
23
|
+
: member![2] === 'confirm' ? await confirmConversationAuditFor(store, auth, member![1]!, body)
|
|
24
|
+
: await appendConversationAuditFor(store, auth, member![1]!, body);
|
|
25
|
+
send(res, 200, result);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (error instanceof ConversationAuditError) send(res, error.statusCode, { error: error.code, message: error.message });
|
|
28
|
+
else if (error instanceof PayloadTooLargeError) send(res, 413, { error: 'conversation_audit_limit' });
|
|
29
|
+
else if (error instanceof SyntaxError) send(res, 400, { error: 'invalid_request' });
|
|
30
|
+
else send(res, 500, { error: 'conversation_audit_internal_error', message: 'The conversation audit operation failed.' });
|
|
31
|
+
}
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import type { AgentSession, Client } from '../core/contracts/types';
|
|
3
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
4
|
+
import { AgentConversationAuditRepository } from '../infrastructure/config/config-agent-conversation-audit-repository';
|
|
5
|
+
import { parseCreateConversationAudit } from '../core/runtime/agent-conversation-audit';
|
|
6
|
+
|
|
7
|
+
type Row = Record<string, any>;
|
|
8
|
+
export const AUDIT_SESSION_A = '123e4567-e89b-42d3-a456-426614174001';
|
|
9
|
+
export const AUDIT_SESSION_B = '123e4567-e89b-42d3-a456-426614174002';
|
|
10
|
+
export const AUDIT_SESSION_C = '123e4567-e89b-42d3-a456-426614174003';
|
|
11
|
+
export const AUDIT_RUN_A = '223e4567-e89b-42d3-a456-426614174001';
|
|
12
|
+
export const AUDIT_RUN_B = '223e4567-e89b-42d3-a456-426614174002';
|
|
13
|
+
export const AUDIT_ARCHIVE = '323e4567-e89b-42d3-a456-426614174001';
|
|
14
|
+
|
|
15
|
+
function duplicate(): never { throw Object.assign(new Error('duplicate fixture key'), { code: 'ER_DUP_ENTRY' }); }
|
|
16
|
+
|
|
17
|
+
/** Synthetic SQL model for transactional repository tests; no socket, user DB or credentials. */
|
|
18
|
+
export function conversationAuditFixture() {
|
|
19
|
+
const client: Client = {
|
|
20
|
+
app_id: 'example-business', name: 'Example', token: '', agent_authorize_url: 'https://business.example.com/authorize',
|
|
21
|
+
allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 0, enabled: true,
|
|
22
|
+
};
|
|
23
|
+
const route: Row = { route_key: 'orders', name: 'Orders', enabled: true, profile: 'general',
|
|
24
|
+
agent_client: { enabled: true }, tools: { agent_direct: { enabled: true } } };
|
|
25
|
+
const sessions = new Map<string, Row>();
|
|
26
|
+
for (const [id, tenant] of [[AUDIT_SESSION_A, 'store-a'], [AUDIT_SESSION_B, 'store-b'], [AUDIT_SESSION_C, 'store-c']]) {
|
|
27
|
+
sessions.set(id!, {
|
|
28
|
+
session_id: id, client_app_id: client.app_id, device_label: tenant,
|
|
29
|
+
principal_json: { id: 'operator-7', tenant, roles: ['manager'] }, on_behalf_of: `${tenant}:operator-7`, allowed_routes: ['orders'],
|
|
30
|
+
created_at: '2026-01-01T00:00:00Z', access_expires_at: '2099-01-01T00:00:00Z', refresh_expires_at: '2099-02-01T00:00:00Z', revoked_at: null,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
let archives = new Map<string, Row>();
|
|
34
|
+
let members = new Map<string, Row>();
|
|
35
|
+
let events = new Map<string, Row>();
|
|
36
|
+
const runs = new Map<string, Row>([
|
|
37
|
+
[AUDIT_RUN_A, { run_id: AUDIT_RUN_A, session_id: AUDIT_SESSION_A, client_app_id: client.app_id, route_key: 'orders', thread_id: 101, client_conversation_id: 'client-conversation', client_turn_id: 'turn-1' }],
|
|
38
|
+
[AUDIT_RUN_B, { run_id: AUDIT_RUN_B, session_id: AUDIT_SESSION_B, client_app_id: client.app_id, route_key: 'orders', thread_id: 102, client_conversation_id: 'client-conversation', client_turn_id: 'turn-1' }],
|
|
39
|
+
]);
|
|
40
|
+
const queries: Array<{ sql: string; params: any[]; transactional: boolean }> = [];
|
|
41
|
+
let transaction = false;
|
|
42
|
+
let snapshot: { archives: Map<string, Row>; members: Map<string, Row>; events: Map<string, Row> };
|
|
43
|
+
const query = async (sql: string, params: any[] = []): Promise<[any, any]> => {
|
|
44
|
+
queries.push({ sql, params: structuredClone(params), transactional: transaction });
|
|
45
|
+
if (sql.includes('FOR UPDATE')) assert.equal(transaction, true, 'locking reads must be inside the mutation transaction');
|
|
46
|
+
let result: any;
|
|
47
|
+
if (sql.startsWith('SELECT') && sql.includes('FROM bz_clients')) result = params[0] === client.app_id ? [client] : [];
|
|
48
|
+
else if (sql.startsWith('SELECT') && sql.includes('FROM bz_routes')) result = params[0] === route.route_key ? [route] : [];
|
|
49
|
+
else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_sessions')) result = sessions.has(params[0]) ? [sessions.get(params[0])] : [];
|
|
50
|
+
else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_client_runs')) result = runs.has(params[0]) ? [runs.get(params[0])] : [];
|
|
51
|
+
else if (sql.startsWith('INSERT INTO bz_agent_conversation_audits')) {
|
|
52
|
+
const row = structuredClone(params[0]);
|
|
53
|
+
const existing = [...archives.values()].find((item) => item.creator_session_id === row.creator_session_id && item.route_key === row.route_key && item.client_archive_id === row.client_archive_id);
|
|
54
|
+
if (existing && !sql.includes('ON DUPLICATE')) duplicate();
|
|
55
|
+
if (!existing) archives.set(row.conversation_id, row);
|
|
56
|
+
result = { affectedRows: existing ? 0 : 1 };
|
|
57
|
+
} else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_conversation_audits')) {
|
|
58
|
+
if (sql.includes('WHERE creator_session_id')) result = [...archives.values()].filter((row) => row.creator_session_id === params[0] && row.route_key === params[1] && row.client_archive_id === params[2]);
|
|
59
|
+
else if (sql.includes('WHERE conversation_id')) result = archives.has(params[0]) ? [archives.get(params[0])] : [];
|
|
60
|
+
else result = [...archives.values()].sort((a, b) => b.updated_at.localeCompare(a.updated_at) || b.conversation_id.localeCompare(a.conversation_id)).slice(params[1], params[1] + params[0]);
|
|
61
|
+
} else if (sql.startsWith('INSERT INTO bz_agent_conversation_members')) {
|
|
62
|
+
const row = structuredClone(params[0]);
|
|
63
|
+
const key = `${row.conversation_id}:${row.session_id}`;
|
|
64
|
+
if (members.has(key)) duplicate();
|
|
65
|
+
members.set(key, row);
|
|
66
|
+
result = { affectedRows: 1 };
|
|
67
|
+
} else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_conversation_members')) {
|
|
68
|
+
result = [...members.values()].filter((member) => member.conversation_id === params[0]).sort((a, b) => a.session_id.localeCompare(b.session_id));
|
|
69
|
+
} else if (sql.startsWith('UPDATE bz_agent_conversation_members')) {
|
|
70
|
+
Object.assign(members.get(`${params[4]}:${params[5]}`)!, { identity_hash: params[0], principal_json: params[1], on_behalf_of: params[2], confirmed_at: params[3] });
|
|
71
|
+
result = { affectedRows: 1 };
|
|
72
|
+
} else if (sql.startsWith('UPDATE bz_agent_conversation_audits SET confirmed_count')) {
|
|
73
|
+
Object.assign(archives.get(params[3])!, { confirmed_count: params[0], state: params[1], updated_at: params[2] });
|
|
74
|
+
result = { affectedRows: 1 };
|
|
75
|
+
} else if (sql.startsWith('UPDATE bz_agent_conversation_audits SET last_sequence')) {
|
|
76
|
+
Object.assign(archives.get(params[7])!, {
|
|
77
|
+
last_sequence: params[0], content_bytes: params[1], message_count: params[2], turn_count: params[3],
|
|
78
|
+
last_turn_id: params[4], last_turn_status: params[5], updated_at: params[6],
|
|
79
|
+
});
|
|
80
|
+
result = { affectedRows: 1 };
|
|
81
|
+
} else if (sql.startsWith('INSERT INTO bz_agent_conversation_events')) {
|
|
82
|
+
const row = structuredClone(params[0]);
|
|
83
|
+
const key = `${row.conversation_id}:${row.sequence}`;
|
|
84
|
+
if (events.has(key) || [...events.values()].some((event) => (event.conversation_id === row.conversation_id && event.event_id === row.event_id) || (row.run_id && event.run_id === row.run_id))) duplicate();
|
|
85
|
+
events.set(key, row);
|
|
86
|
+
result = { affectedRows: 1 };
|
|
87
|
+
} else if (sql.startsWith('SELECT') && sql.includes('FROM bz_agent_conversation_events')) {
|
|
88
|
+
if (sql.includes('WHERE run_id')) result = [...events.values()].filter((event) => event.run_id === params[0] && event.kind === 'run_link');
|
|
89
|
+
else {
|
|
90
|
+
result = [...events.values()].filter((event) => event.conversation_id === params[0]);
|
|
91
|
+
if (sql.includes('(sequence=? OR event_id=?)')) result = result.filter((event: Row) => event.sequence === params[1] || event.event_id === params[2]);
|
|
92
|
+
else if (sql.includes("kind='turn_start'")) result = result.filter((event: Row) => event.client_turn_id === params[1] && event.kind === 'turn_start');
|
|
93
|
+
else if (sql.includes('sequence>?')) result = result.filter((event: Row) => event.sequence > params[1]).sort((a: Row, b: Row) => a.sequence - b.sequence).slice(0, params[2]);
|
|
94
|
+
}
|
|
95
|
+
} else throw new Error(`Unexpected synthetic query: ${sql}`);
|
|
96
|
+
return [structuredClone(result), []];
|
|
97
|
+
};
|
|
98
|
+
const connection = {
|
|
99
|
+
query,
|
|
100
|
+
async beginTransaction() { assert.equal(transaction, false); transaction = true; snapshot = structuredClone({ archives, members, events }); },
|
|
101
|
+
async commit() { transaction = false; },
|
|
102
|
+
async rollback() { ({ archives, members, events } = snapshot); transaction = false; },
|
|
103
|
+
release() {},
|
|
104
|
+
};
|
|
105
|
+
const repo = new AgentConversationAuditRepository(() => ({ query, getConnection: async () => connection }));
|
|
106
|
+
const auth = (id = AUDIT_SESSION_A) => {
|
|
107
|
+
const row = sessions.get(id)!;
|
|
108
|
+
return { client: structuredClone(client), session: {
|
|
109
|
+
...structuredClone(row), principal: structuredClone(row.principal_json),
|
|
110
|
+
} as AgentSession };
|
|
111
|
+
};
|
|
112
|
+
const input = (overrides: Row = {}) => parseCreateConversationAudit({
|
|
113
|
+
client_archive_id: AUDIT_ARCHIVE, client_conversation_id: 'client-conversation', route: 'orders',
|
|
114
|
+
member_session_ids: [AUDIT_SESSION_A, AUDIT_SESSION_B],
|
|
115
|
+
member_labels: { [AUDIT_SESSION_A]: 'Store A', [AUDIT_SESSION_B]: 'Store B' }, ...overrides,
|
|
116
|
+
});
|
|
117
|
+
const store = { agentConversationAudit: repo } as unknown as ConfigStoreContract;
|
|
118
|
+
return {
|
|
119
|
+
repo, store, auth, input, client, route, sessions, runs, queries,
|
|
120
|
+
get archives() { return archives; }, get members() { return members; }, get events() { return events; },
|
|
121
|
+
async ready() { const result = await repo.create(auth(), input()); return repo.confirm(auth(AUDIT_SESSION_B), String(result.conversation_id)); },
|
|
122
|
+
};
|
|
123
|
+
}
|