bailinghub 0.5.1 → 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 -207
- 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_CLIENT_QUICKSTART.en.md +29 -8
- package/docs/AGENT_CLIENT_QUICKSTART.md +25 -6
- package/docs/AGENT_CONVERSATION_AUDIT.en.md +194 -0
- package/docs/AGENT_CONVERSATION_AUDIT.md +111 -0
- package/docs/CHANGELOG.en.md +11 -0
- package/docs/CHANGELOG.md +11 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/README.en.md +5 -0
- package/docs/README.md +5 -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 +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- 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 +1 -0
- package/scripts/verify-github-repo.mjs +1 -0
- package/sql/057_agent_conversation_audit.sql +55 -0
- package/src/app/agent-conversation-audit.ts +30 -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-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-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 +3 -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-r10QUjLQ.js → Accounts-Ca_VnSu9.js} +1 -1
- package/web/console/assets/{AgentClients-UTTqbkjy.js → AgentClients-BPIvlLYY.js} +1 -1
- package/web/console/assets/{Approvals-BGKkYIya.js → Approvals-CMvPWacY.js} +1 -1
- package/web/console/assets/{Audit-CQmjOAoO.js → Audit-CIRqOCnL.js} +1 -1
- package/web/console/assets/{BrandLockup-BF_0pCa3.js → BrandLockup-BrytmTTH.js} +1 -1
- package/web/console/assets/{Channels-C4yZE67F.js → Channels-CApxH2TB.js} +1 -1
- package/web/console/assets/{ChatEntries-OqsqLjU6.js → ChatEntries-CJon3bWJ.js} +1 -1
- package/web/console/assets/{Clients-Dv3sv51C.js → Clients-BSA1rlTB.js} +1 -1
- package/web/console/assets/{Cost-C_-kiH59.js → Cost-BbhlQFP8.js} +1 -1
- package/web/console/assets/{Credentials-CPTEAiV6.js → Credentials-kqr1W0K7.js} +1 -1
- package/web/console/assets/{Diagnostics-O-NKFOeI.js → Diagnostics-Kljt9XTH.js} +1 -1
- package/web/console/assets/{Executors-GVIAiNgv.js → Executors-DnsB-Xz4.js} +1 -1
- package/web/console/assets/{Kb-BsCWkJI1.js → Kb-DLZSAFWP.js} +2 -2
- package/web/console/assets/{Login-VFjkHNMr.js → Login-DiTjPWmN.js} +1 -1
- package/web/console/assets/{Projects-Ds-sJwfy.js → Projects-CXcVCgCD.js} +1 -1
- package/web/console/assets/{Routes-Wwurw2UU.js → Routes-DN9_d9Po.js} +1 -1
- package/web/console/assets/Runs-Cwbe6thL.js +3 -0
- package/web/console/assets/Runs-D8UmjP5G.css +1 -0
- package/web/console/assets/{Setup-BLelw0_V.js → Setup-FqoCKmfZ.js} +1 -1
- package/web/console/assets/{Shell-CvaeK4j_.js → Shell-BEqpONiy.js} +1 -1
- package/web/console/assets/{StorageBuckets-Dv6u47yO.js → StorageBuckets-CkORbYXY.js} +1 -1
- package/web/console/assets/{SystemSettings-B9K7zaDU.js → SystemSettings-gTQAazu7.js} +1 -1
- package/web/console/assets/{SystemStatus-H-oKDo-y.js → SystemStatus-DAmUUNqO.js} +1 -1
- package/web/console/assets/{Targets-CCFhjPKf.js → Targets-CZmDcjsE.js} +1 -1
- package/web/console/assets/{Tools-D0H9xpFH.js → Tools-CIHInlHL.js} +1 -1
- package/web/console/assets/{index-CuoTgf6q.js → index-BkLbd7Cc.js} +2 -2
- package/web/console/assets/{index-DyX9Bz3V.js → index-QnmD7N7F.js} +1 -1
- package/web/console/assets/{request-F5lXa7Ro.js → request-r7GHVJzw.js} +1 -1
- package/web/console/assets/{schema-DUWaWqPn.js → schema-BVn_hB7M.js} +1 -1
- package/web/console/assets/vendor-mammoth-BUEEDX6A.js +231 -0
- package/web/console/index.html +1 -1
- package/web-admin/package-lock.json +3 -3
- package/web-admin/src/components/ClientConversations.vue +244 -0
- package/web-admin/src/components/conversation-audit.ts +121 -0
- package/web-admin/src/pages/Runs.vue +73 -17
- package/web-admin/tests/conversation-audit.fixture.mjs +182 -0
- package/web-admin/tests/conversation-audit.test.mjs +93 -0
- package/web/console/assets/Runs-4zDD9VOC.css +0 -1
- package/web/console/assets/Runs-DLPzXmSy.js +0 -3
- package/web/console/assets/vendor-mammoth-nXG51Cg7.js +0 -231
|
@@ -26,6 +26,7 @@ import { InstanceBrandingRepository } from './config-instance-branding-repositor
|
|
|
26
26
|
import type { InstanceBrandingRepositoryContract } from './config-instance-branding-repository';
|
|
27
27
|
import { AgentAuthRepository, type AgentAuthRepositoryContract } from './config-agent-auth-repository';
|
|
28
28
|
import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
|
|
29
|
+
import { AgentConversationAuditRepository } from './config-agent-conversation-audit-repository';
|
|
29
30
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
30
31
|
|
|
31
32
|
export type RouteRepositoryContract = Pick<RouteRepository, keyof RouteRepository>;
|
|
@@ -60,6 +61,7 @@ export type ObservabilityLedgerContract =
|
|
|
60
61
|
Omit<Pick<ObservabilityLedger, keyof ObservabilityLedger>, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>
|
|
61
62
|
& Partial<Pick<ObservabilityLedger, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>>;
|
|
62
63
|
export type AgentClientRuntimeRepositoryContract = Pick<AgentClientRuntimeRepository, keyof AgentClientRuntimeRepository>;
|
|
64
|
+
export type AgentConversationAuditRepositoryContract = Pick<AgentConversationAuditRepository, keyof AgentConversationAuditRepository>;
|
|
63
65
|
|
|
64
66
|
export interface ConfigStoreContract {
|
|
65
67
|
readonly routes: RouteRepositoryContract;
|
|
@@ -89,6 +91,8 @@ export interface ConfigStoreContract {
|
|
|
89
91
|
readonly agentAuth?: AgentAuthRepositoryContract;
|
|
90
92
|
/** Agent Client Runtime v1 对旧宿主保持可选;缺失时新 API fail closed。 */
|
|
91
93
|
readonly agentClientRuntime?: AgentClientRuntimeRepositoryContract;
|
|
94
|
+
/** Optional, admin-only visible transcript ledger; never a source of Agent memory. */
|
|
95
|
+
readonly agentConversationAudit?: AgentConversationAuditRepositoryContract;
|
|
92
96
|
init(): Promise<void>;
|
|
93
97
|
close?(): Promise<void>;
|
|
94
98
|
readonly db: Pool;
|
|
@@ -123,6 +127,7 @@ export class ConfigStore implements ConfigStoreContract {
|
|
|
123
127
|
readonly observability = new ObservabilityLedger(() => this.pool);
|
|
124
128
|
readonly agentAuth = new AgentAuthRepository(() => this.pool);
|
|
125
129
|
readonly agentClientRuntime = new AgentClientRuntimeRepository(() => this.pool);
|
|
130
|
+
readonly agentConversationAudit = new AgentConversationAuditRepository(() => this.pool);
|
|
126
131
|
|
|
127
132
|
constructor(cfg: AppConfig['state']['mysql'], poolOwner?: MysqlPoolResource) {
|
|
128
133
|
this.poolOwner = poolOwner ?? new MysqlPoolOwner(cfg);
|
|
@@ -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,6 +17,7 @@ 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';
|
|
22
23
|
import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
|
|
@@ -102,6 +103,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
102
103
|
[/^\/admin\/api\/routes/, 'routes:read', 'routes:write'],
|
|
103
104
|
[/^\/admin\/api\/runs/, 'runs:read', 'runs:write'], // 重跑是写操作:viewer 只能看不能跑
|
|
104
105
|
[/^\/admin\/api\/threads/, 'runs:read', 'runs:read'], // 会话视图=运行面只读
|
|
106
|
+
[/^\/admin\/api\/conversation-audits/, 'runs:read', 'runs:read'],
|
|
105
107
|
[/^\/admin\/api\/status/, 'runs:read', 'runs:read'],
|
|
106
108
|
[/^\/admin\/api\/dispatch-status/, 'runs:read', 'runs:read'],
|
|
107
109
|
[/^\/admin\/api\/config-schemas/, 'audit:read', 'audit:read'],
|
|
@@ -185,6 +187,7 @@ export async function handleAdminApiFor(deps: AdminApiDeps, method: string, path
|
|
|
185
187
|
return true;
|
|
186
188
|
}
|
|
187
189
|
|
|
190
|
+
if (await handleAdminConversationAuditFor(configStore, method, path, req, res, principal)) return true;
|
|
188
191
|
if (await handleAdminRuntimeApiFor({
|
|
189
192
|
configStore,
|
|
190
193
|
stateStore: deps.stateStore,
|
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
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{aj as K,E as V}from"./vendor-element-CZoEjZr8.js";import{a as C}from"./request-
|
|
1
|
+
import{aj as K,E as V}from"./vendor-element-CZoEjZr8.js";import{a as C}from"./request-r7GHVJzw.js";import{f as W,c as X}from"./util-4bN2dv7B.js";import{u as Y}from"./index-BkLbd7Cc.js";import{H as c}from"./HelpTip-i-KJhf5s.js";import{d as Z,z as h,c as L,S as n,J as t,R as O,r as _,ai as i,o as b,e as o,Q as r,P as s,u as ee,I as E,O as $,a3 as le,q as te}from"./vendor-vue-B2uhHUfE.js";import{_ as ne}from"./_plugin-vue_export-helper-DlAUqK2U.js";const ae={class:"head"},oe={class:"account-main"},se={class:"account-stack"},de={class:"muted"},ie={class:"account-stack"},ue={class:"muted"},re=Z({__name:"Accounts",setup(me){const y={admin:"全能",kb_editor:"知识库维护",viewer:"只读任务"},N=Y(),x=_([]),T=_(["admin","kb_editor","viewer"]),u=_(!1),m=_(!1),w=_(!1),d=te({username:"",display_name:"",role:"kb_editor",password:"",enabled:!0});async function g(){var e;const a=await C("/admin/api/admins");x.value=a.list,(e=a.roles)!=null&&e.length&&(T.value=a.roles)}function S(a){return a==="admin"?"admin":a==="kb_editor"?"kb_editor":a==="viewer"?"viewer":a}function M(a){return a?`最近登录 ${W(a)}`:"从未登录"}function j(){m.value=!1,Object.assign(d,{username:"",display_name:"",role:"kb_editor",password:"",enabled:!0}),u.value=!0}function q(a){m.value=!0,Object.assign(d,{username:a.username,display_name:a.display_name||"",role:a.role,password:"",enabled:!!a.enabled}),u.value=!0}async function D(){w.value=!0;try{const a=await C("/admin/api/admins",{method:"POST",body:JSON.stringify(d)});u.value=!1,await g(),a.generated_password?(await K.alert(`账号 ${a.username} 的初始密码(只显示这一次,请立即发给使用人):
|
|
2
2
|
|
|
3
3
|
${a.generated_password}`,"账号已创建",{confirmButtonText:"复制密码"}).catch(()=>{}),await X(a.generated_password,"密码已复制")):V.success("已保存")}catch(a){V.error(a.message)}finally{w.value=!1}}async function I(a){try{await C("/admin/api/admins/"+encodeURIComponent(a),{method:"DELETE"}),await g()}catch(e){V.error(e.message)}}return h(g),(a,e)=>{const p=i("el-button"),v=i("el-table-column"),U=i("el-tag"),R=i("el-popconfirm"),z=i("el-table"),A=i("el-card"),k=i("el-input"),f=i("el-form-item"),H=i("el-option"),J=i("el-select"),P=i("el-switch"),F=i("el-form"),Q=i("el-drawer");return b(),L(O,null,[n(A,{shadow:"never"},{header:t(()=>[o("div",ae,[e[9]||(e[9]=o("b",null,"后台账号",-1)),e[10]||(e[10]=s()),n(c,{title:"后台账号 / 角色"},{default:t(()=>[...e[7]||(e[7]=[o("p",null,"后台账号只用于维护中枢控制台,不等同于业务系统用户,也不参与聊天/工具调用的业务身份。",-1),o("p",null,[s("角色决定可见板块与管理权限:"),o("code",null,"admin"),s(" 管全局配置,"),o("code",null,"kb_editor"),s(" 维护知识库,"),o("code",null,"viewer"),s(" 查看运行记录。")],-1)])]),_:1}),n(p,{type:"primary",style:{"margin-left":"auto"},onClick:j},{default:t(()=>[...e[8]||(e[8]=[s("新建账号",-1)])]),_:1})])]),default:t(()=>[n(z,{data:x.value},{default:t(()=>[n(v,{label:"账号","min-width":"240","show-overflow-tooltip":""},{default:t(({row:l})=>[o("div",oe,[o("b",null,r(l.display_name||l.username),1),o("code",null,r(l.username),1)])]),_:1}),n(v,{label:"角色权限","min-width":"220"},{default:t(({row:l})=>[o("div",se,[n(U,{type:l.role==="admin"?"warning":"info",effect:"plain"},{default:t(()=>[s(r(S(l.role)),1)]),_:2},1032,["type"]),o("span",de,r(y[l.role]||"自定义角色"),1)])]),_:1}),n(v,{label:"登录状态","min-width":"190"},{default:t(({row:l})=>[o("div",ie,[n(U,{type:l.enabled?"success":"info",effect:"plain"},{default:t(()=>[s(r(l.enabled?"启用":"停用"),1)]),_:2},1032,["type"]),o("span",ue,r(M(l.last_login_at)),1)])]),_:1}),n(v,{"min-width":"80",align:"right"},{default:t(({row:l})=>{var B;return[n(p,{link:"",type:"primary",onClick:G=>q(l)},{default:t(()=>[...e[11]||(e[11]=[s("编辑",-1)])]),_:1},8,["onClick"]),l.username!==((B=ee(N).me)==null?void 0:B.username)?(b(),E(R,{key:0,title:"删除该账号?其登录会话立即失效。",width:"240",onConfirm:G=>I(l.username)},{reference:t(()=>[n(p,{link:"",type:"danger"},{default:t(()=>[...e[12]||(e[12]=[s("删",-1)])]),_:1})]),_:1},8,["onConfirm"])):$("",!0)]}),_:1})]),_:1},8,["data"])]),_:1}),n(Q,{modelValue:u.value,"onUpdate:modelValue":e[6]||(e[6]=l=>u.value=l),title:m.value?"编辑账号":"新建账号",size:"420px"},{footer:t(()=>[n(p,{onClick:e[5]||(e[5]=l=>u.value=!1)},{default:t(()=>[...e[22]||(e[22]=[s("取消",-1)])]),_:1}),n(p,{type:"primary",loading:w.value,onClick:D},{default:t(()=>[...e[23]||(e[23]=[s("保存",-1)])]),_:1},8,["loading"])]),default:t(()=>[n(F,{"label-position":"top"},{default:t(()=>[n(f,null,{label:t(()=>[...e[13]||(e[13]=[s("用户名 ",-1),o("span",{class:"field-required"},"必填",-1)])]),default:t(()=>[n(k,{modelValue:d.username,"onUpdate:modelValue":e[0]||(e[0]=l=>d.username=l),disabled:m.value,placeholder:"如 ops-admin",class:"mono"},null,8,["modelValue","disabled"])]),_:1}),n(f,{label:"显示名(可选)"},{default:t(()=>[n(k,{modelValue:d.display_name,"onUpdate:modelValue":e[1]||(e[1]=l=>d.display_name=l)},null,8,["modelValue"])]),_:1}),n(f,null,{label:t(()=>[e[15]||(e[15]=s("角色 ",-1)),e[16]||(e[16]=o("span",{class:"field-required"},"必填",-1)),e[17]||(e[17]=s()),n(c,{title:"角色"},{default:t(()=>[...e[14]||(e[14]=[o("p",null,[o("b",null,"admin"),s(":管理全局配置与账号;"),o("b",null,"kb_editor"),s(":维护知识库;"),o("b",null,"viewer"),s(":只读查看运行记录。")],-1)])]),_:1})]),default:t(()=>[n(J,{modelValue:d.role,"onUpdate:modelValue":e[2]||(e[2]=l=>d.role=l),style:{width:"100%"}},{default:t(()=>[(b(!0),L(O,null,le(T.value,l=>(b(),E(H,{key:l,value:l,label:l+(y[l]?"("+y[l]+")":"")},null,8,["value","label"]))),128))]),_:1},8,["modelValue"])]),_:1}),n(f,null,{label:t(()=>[e[19]||(e[19]=s("密码 ",-1)),n(c,{title:"密码"},{default:t(()=>[...e[18]||(e[18]=[o("p",null,"新建时留空会自动生成,并只显示一次。编辑时留空表示不修改;填写后该账号其他登录会话会立即下线。",-1)])]),_:1})]),default:t(()=>[n(k,{modelValue:d.password,"onUpdate:modelValue":e[3]||(e[3]=l=>d.password=l),type:"password","show-password":"",autocomplete:"new-password",placeholder:"至少 8 位"},null,8,["modelValue"])]),_:1}),m.value?(b(),E(f,{key:0},{label:t(()=>[e[21]||(e[21]=s("启用 ",-1)),n(c,{title:"启用状态"},{default:t(()=>[...e[20]||(e[20]=[o("p",null,"停用账号会立即使其登录会话失效。",-1)])]),_:1})]),default:t(()=>[n(P,{modelValue:d.enabled,"onUpdate:modelValue":e[4]||(e[4]=l=>d.enabled=l)},null,8,["modelValue"])]),_:1})):$("",!0)]),_:1})]),_:1},8,["modelValue","title"])],64)}}}),we=ne(re,[["__scopeId","data-v-f7ba53c9"]]);export{we as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as be,z as ke,c as y,S as s,J as a,q as J,ai as r,o as u,K as ae,e as l,Q as o,L as ye,P as c,I as b,R as L,a3 as F,u as oe,O as we,aC as he,r as v,m as z,as as Ce}from"./vendor-vue-B2uhHUfE.js";import{E as w,aj as Ve}from"./vendor-element-CZoEjZr8.js";import{H as xe}from"./HelpTip-i-KJhf5s.js";import{k as W,b as Se}from"./index-CuoTgf6q.js";import{_ as $e}from"./_plugin-vue_export-helper-DlAUqK2U.js";const ze={class:"agent-clients-page"},Ne={class:"head"},Ae={class:"actions"},Te={class:"overview"},Ue={class:"metric primary"},Ee={class:"metric"},je={class:"metric"},Oe={class:"metric"},Re={class:"metric"},Pe={class:"section-head"},Be={class:"stack"},De={class:"stack"},Ie={class:"muted mono"},Je={class:"tags"},Le={class:"stack right"},Fe={class:"muted"},We={class:"section-head"},He={class:"actions"},Me={class:"stack"},qe={class:"stack"},Ke={class:"muted"},Qe={class:"stack"},Ze={class:"muted"},Ge={class:"stack"},Xe={class:"muted"},Ye={key:1,class:"muted"},el={key:2,class:"pagination"},ll={class:"form-grid"},tl={class:"code-block"},nl={class:"code-block"},N=50,sl=be({__name:"AgentClients",setup(al){const H=he(),A=v(30),h=v(!1),T=v(!1),U=v(""),C=v([]),M=v([]),E=v([]),j=v(0),V=v(1),p=J({applications:0,agent_auth_enabled:0,sessions:{},runs:0,conversations:0,failed:0,tool_calls:0,total_tokens:0,failure_rate:0,approvals:{}}),k=J({client_app_id:"",state:"all"}),i=J({open:!1,app_id:"",name:"",workspace:"",workspaces:[]}),O=z(()=>Se()),ie=z(()=>Object.values(p.approvals||{}).reduce((n,e)=>n+Number(e||0),0)),q=z(()=>JSON.stringify({hubUrl:O.value,clientAppId:i.app_id,workspace:i.workspace,connectionName:i.name.trim()||"default"},null,2)),K=z(()=>`/bailinghub connections add ${x(i.name.trim()||"default")} ${x(O.value)} ${x(i.app_id)} ${x(i.workspace)}`);function x(n){return JSON.stringify(n)}function _(n){return new Intl.NumberFormat("zh-CN").format(Number(n||0))}function de(n){return`${(Number(n||0)*100).toFixed(1)}%`}function Q(n){return n?`${n.slice(0,8)}…${n.slice(-4)}`:"—"}function Z(n){return n?new Date(n).toLocaleString("zh-CN",{hour12:!1}):"从未"}function ue(n){return n==="active"?"有效":n==="expired"?"已过期":"已撤销"}function re(n){return n==="active"?"success":n==="expired"?"warning":"info"}function ce(n){return n.includes("*")?["全部 Workspace"]:n.slice(0,4)}function G(n){return M.value.filter(e=>n.allowed_routes.includes("*")||n.allowed_routes.includes(e.route))}async function X(){h.value=!0;try{const n=await W(`/admin/api/agent-clients/overview?days=${A.value}`);if(!n.ok)throw new Error((await n.json().catch(()=>({}))).error||"加载失败");const e=await n.json();C.value=e.applications||[],M.value=e.workspaces||[],Object.assign(p,e.summary||{})}catch(n){w.error(n instanceof Error?n.message:"加载智能体客户端失败")}finally{h.value=!1}}async function R(){T.value=!0;try{const n=new URLSearchParams({state:k.state,limit:String(N),offset:String((V.value-1)*N)});k.client_app_id&&n.set("client_app_id",k.client_app_id);const e=await W(`/admin/api/agent-clients/sessions?${n}`);if(!e.ok)throw new Error((await e.json().catch(()=>({}))).error||"加载失败");const d=await e.json();E.value=d.list||[],j.value=Number(d.total||0)}catch(n){w.error(n instanceof Error?n.message:"加载授权设备失败")}finally{T.value=!1}}async function P(){await Promise.all([X(),R()])}async function Y(){V.value=1,await R()}function pe(n){var d;const e=G(n);i.app_id=n.app_id,i.name=n.app_id.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default",i.workspaces=e,i.workspace=((d=e[0])==null?void 0:d.route)||"",i.open=!0}async function ee(n){await navigator.clipboard.writeText(n),w.success("已复制")}async function _e(n){await Ve.confirm(`撤销设备“${n.device_label||Q(n.session_id)}”的 Agent Session?撤销后需要重新登录授权。`,"远程撤销",{type:"warning",confirmButtonText:"确认撤销"}),U.value=n.session_id;try{const e=await W(`/admin/api/agent-clients/sessions/${n.session_id}/revoke`,{method:"POST"});if(!e.ok)throw new Error((await e.json().catch(()=>({}))).error||"撤销失败");w.success("Agent Session 已撤销"),await P()}catch(e){w.error(e instanceof Error?e.message:"撤销失败")}finally{U.value=""}}return ke(P),(n,e)=>{const d=r("el-option"),S=r("el-select"),g=r("el-button"),B=r("el-card"),le=r("el-empty"),m=r("el-table-column"),D=r("el-tag"),te=r("el-table"),me=r("el-pagination"),fe=r("el-alert"),I=r("el-input"),$=r("el-form-item"),ve=r("el-form"),ge=r("el-dialog"),ne=Ce("loading");return u(),y("div",ze,[s(B,{shadow:"never"},{header:a(()=>[l("div",Ne,[l("div",null,[e[13]||(e[13]=l("b",null,"智能体客户端",-1)),s(xe,{title:"和执行器有什么区别"},{default:a(()=>[...e[12]||(e[12]=[l("p",null,[l("b",null,"智能体客户端"),c("在本地理解用户意图、选择能力并完成多步编排;中枢继续负责业务身份、授权、审批、执行与审计。")],-1),l("p",null,[l("b",null,"执行器"),c("是中枢下发 Job、由本地运行时执行本地任务后回报结果。两者是独立概念。")],-1),l("p",null,"本页聚合现有接入方、Agent Session 和 Agent Run,不创建第二套接入方配置。",-1),l("p",null,"每个接入方只配置一个不绑定账号、租户或门店的业务授权入口;账号切换与租户选择由业务授权页完成。",-1)])]),_:1})]),l("div",Ae,[s(S,{modelValue:A.value,"onUpdate:modelValue":e[0]||(e[0]=t=>A.value=t),size:"small",style:{width:"108px"},onChange:X},{default:a(()=>[s(d,{value:7,label:"近 7 天"}),s(d,{value:30,label:"近 30 天"}),s(d,{value:90,label:"近 90 天"})]),_:1},8,["modelValue"]),s(g,{size:"small",loading:h.value,onClick:P},{default:a(()=>[...e[14]||(e[14]=[c("刷新",-1)])]),_:1},8,["loading"])])])]),default:a(()=>{var t,f;return[ae((u(),y("div",Te,[l("div",Ue,[e[15]||(e[15]=l("span",null,"客户端应用",-1)),l("b",null,o(_(p.agent_auth_enabled)),1),l("em",null,"共 "+o(_(p.applications))+" 个接入方",1)]),l("div",Ee,[e[16]||(e[16]=l("span",null,"有效授权设备",-1)),l("b",null,o(_((t=p.sessions)==null?void 0:t.active)),1),l("em",null,"总会话 "+o(_((f=p.sessions)==null?void 0:f.total)),1)]),l("div",je,[e[17]||(e[17]=l("span",null,"Agent Run",-1)),l("b",null,o(_(p.runs)),1),l("em",null,o(_(p.conversations))+" 个本地会话",1)]),l("div",Oe,[e[18]||(e[18]=l("span",null,"工具调用",-1)),l("b",null,o(_(p.tool_calls)),1),l("em",null,"审批 "+o(_(ie.value))+" 次",1)]),l("div",Re,[e[19]||(e[19]=l("span",null,"累计 Token",-1)),l("b",null,o(_(p.total_tokens)),1),e[20]||(e[20]=l("em",null,"由客户端公开 usage 汇总",-1))]),l("div",{class:ye(["metric",{danger:Number(p.failure_rate||0)>.1}])},[e[21]||(e[21]=l("span",null,"失败率",-1)),l("b",null,o(de(p.failure_rate)),1),l("em",null,o(_(p.failed))+" 个失败或取消",1)],2)])),[[ne,h.value]])]}),_:1}),s(B,{shadow:"never"},{header:a(()=>[l("div",Pe,[e[23]||(e[23]=l("div",null,[l("b",null,"客户端应用"),l("span",null,"复用“接入方”配置;只有设置 Agent 授权页后才能发起浏览器登录。")],-1)),s(g,{size:"small",onClick:e[1]||(e[1]=t=>oe(H).push("/clients"))},{default:a(()=>[...e[22]||(e[22]=[c("管理接入方",-1)])]),_:1})])]),default:a(()=>[C.value.length?(u(),b(te,{key:1,data:C.value,size:"small"},{default:a(()=>[s(m,{label:"应用",width:180},{default:a(({row:t})=>[l("div",Be,[l("b",null,o(t.name||t.app_id),1),l("code",null,o(t.app_id),1)])]),_:1}),s(m,{label:"Agent 登录","min-width":240,"show-overflow-tooltip":""},{default:a(({row:t})=>[l("div",De,[l("div",null,[s(D,{size:"small",effect:"plain",type:t.enabled&&t.agent_auth_enabled?"success":"info"},{default:a(()=>[c(o(t.enabled&&t.agent_auth_enabled?"可授权":"未开放"),1)]),_:2},1032,["type"])]),l("span",Ie,o(t.agent_authorize_url||"未配置授权页"),1)])]),_:1}),s(m,{label:"允许 Workspace",width:180},{default:a(({row:t})=>[l("div",Je,[(u(!0),y(L,null,F(ce(t.allowed_routes),f=>(u(),b(D,{key:f,size:"small",effect:"plain",type:"info"},{default:a(()=>[c(o(f),1)]),_:2},1024))),128))])]),_:1}),s(m,{label:"近期开销",width:150,align:"right"},{default:a(({row:t})=>[l("div",Le,[l("span",null,o(_(t.stats.runs))+" Run / "+o(_(t.stats.tool_calls))+" 调用",1),l("span",Fe,o(_(t.stats.total_tokens))+" Token",1)])]),_:1}),s(m,{width:160,align:"right"},{default:a(({row:t})=>[s(g,{link:"",type:"primary",disabled:!t.agent_auth_enabled||!G(t).length,onClick:f=>pe(t)},{default:a(()=>[...e[24]||(e[24]=[c("生成连接配置",-1)])]),_:1},8,["disabled","onClick"]),s(g,{link:"",onClick:e[2]||(e[2]=f=>oe(H).push("/clients"))},{default:a(()=>[...e[25]||(e[25]=[c("编辑",-1)])]),_:1})]),_:1})]),_:1},8,["data"])):(u(),b(le,{key:0,description:"还没有接入方"}))]),_:1}),s(B,{shadow:"never"},{header:a(()=>[l("div",We,[e[26]||(e[26]=l("div",null,[l("b",null,"授权设备与 Agent Session"),l("span",null,"远程撤销后,后续 access/refresh token 都会失效;本地客户端需要重新登录。")],-1)),l("div",He,[s(S,{modelValue:k.client_app_id,"onUpdate:modelValue":e[3]||(e[3]=t=>k.client_app_id=t),clearable:"",filterable:"",size:"small",placeholder:"全部应用",style:{width:"190px"},onChange:Y},{default:a(()=>[(u(!0),y(L,null,F(C.value,t=>(u(),b(d,{key:t.app_id,label:t.name||t.app_id,value:t.app_id},null,8,["label","value"]))),128))]),_:1},8,["modelValue"]),s(S,{modelValue:k.state,"onUpdate:modelValue":e[4]||(e[4]=t=>k.state=t),size:"small",style:{width:"112px"},onChange:Y},{default:a(()=>[s(d,{value:"all",label:"全部状态"}),s(d,{value:"active",label:"有效"}),s(d,{value:"expired",label:"已过期"}),s(d,{value:"revoked",label:"已撤销"})]),_:1},8,["modelValue"])])])]),default:a(()=>[E.value.length?ae((u(),b(te,{key:1,data:E.value,size:"small"},{default:a(()=>[s(m,{label:"设备",width:170},{default:a(({row:t})=>[l("div",Me,[l("b",null,o(t.device_label||"未命名设备"),1),l("code",null,o(Q(t.session_id)),1)])]),_:1}),s(m,{label:"业务主体",width:150},{default:a(({row:t})=>{var f,se;return[l("div",qe,[l("span",null,o(((f=t.principal)==null?void 0:f.id)||t.on_behalf_of),1),l("span",Ke,o(((se=t.principal)==null?void 0:se.tenant)||"未声明租户"),1)])]}),_:1}),s(m,{label:"应用 / Workspace","min-width":190},{default:a(({row:t})=>[l("div",Qe,[l("code",null,o(t.client_app_id),1),l("span",Ze,o((t.allowed_routes||[]).join("、")||"无可用路由"),1)])]),_:1}),s(m,{label:"活跃与有效期",width:185},{default:a(({row:t})=>[l("div",Ge,[l("span",null,"活跃 "+o(Z(t.last_seen_at)),1),l("span",Xe,"到期 "+o(Z(t.refresh_expires_at)),1)])]),_:1}),s(m,{label:"状态",width:80},{default:a(({row:t})=>[s(D,{size:"small",effect:"plain",type:re(t.state)},{default:a(()=>[c(o(ue(t.state)),1)]),_:2},1032,["type"])]),_:1}),s(m,{width:90,align:"right"},{default:a(({row:t})=>[t.state!=="revoked"?(u(),b(g,{key:0,link:"",type:"danger",loading:U.value===t.session_id,onClick:f=>_e(t)},{default:a(()=>[...e[27]||(e[27]=[c("远程撤销",-1)])]),_:1},8,["loading","onClick"])):(u(),y("span",Ye,"已处理"))]),_:1})]),_:1},8,["data"])),[[ne,T.value]]):(u(),b(le,{key:0,description:"当前筛选下没有 Agent Session"})),j.value>N?(u(),y("div",el,[s(me,{"current-page":V.value,"onUpdate:currentPage":e[5]||(e[5]=t=>V.value=t),"page-size":N,total:j.value,layout:"prev, pager, next, total",onCurrentChange:R},null,8,["current-page","total"])])):we("",!0)]),_:1}),s(ge,{modelValue:i.open,"onUpdate:modelValue":e[11]||(e[11]=t=>i.open=t),title:"生成智能体客户端连接配置",width:"620px"},{footer:a(()=>[s(g,{onClick:e[8]||(e[8]=t=>i.open=!1)},{default:a(()=>[...e[28]||(e[28]=[c("关闭",-1)])]),_:1}),s(g,{onClick:e[9]||(e[9]=t=>ee(q.value))},{default:a(()=>[...e[29]||(e[29]=[c("复制 JSON",-1)])]),_:1}),s(g,{type:"primary",onClick:e[10]||(e[10]=t=>ee(K.value))},{default:a(()=>[...e[30]||(e[30]=[c("复制 DSH 命令",-1)])]),_:1})]),default:a(()=>[s(fe,{type:"info",closable:!1,"show-icon":"",title:"这里只生成公开连接元数据,不包含业务 URL、业务身份、Client Token、Agent Token 或模型密钥。"}),e[31]||(e[31]=l("p",{class:"connection-note"},[l("code",null,"connectionName"),c(" 只是本机连接选择器。登录时会统一打开接入方配置的业务授权页,由该页面确认当前账号与租户。")],-1)),s(ve,{"label-position":"top",class:"connection-form"},{default:a(()=>[s($,{label:"Hub 地址"},{default:a(()=>[s(I,{"model-value":O.value,readonly:"",class:"mono"},null,8,["model-value"])]),_:1}),l("div",ll,[s($,{label:"Client App ID"},{default:a(()=>[s(I,{"model-value":i.app_id,readonly:"",class:"mono"},null,8,["model-value"])]),_:1}),s($,{label:"Connection Name"},{default:a(()=>[s(I,{modelValue:i.name,"onUpdate:modelValue":e[6]||(e[6]=t=>i.name=t),maxlength:"128",class:"mono"},null,8,["modelValue"])]),_:1})]),s($,{label:"Workspace"},{default:a(()=>[s(S,{modelValue:i.workspace,"onUpdate:modelValue":e[7]||(e[7]=t=>i.workspace=t),style:{width:"100%"}},{default:a(()=>[(u(!0),y(L,null,F(i.workspaces,t=>(u(),b(d,{key:t.route,label:t.name+"("+t.route+")",value:t.route},null,8,["label","value"]))),128))]),_:1},8,["modelValue"])]),_:1})]),_:1}),l("div",tl,[l("pre",null,o(q.value),1)]),l("div",nl,[l("pre",null,o(K.value),1)])]),_:1},8,["modelValue"])])}}}),cl=$e(sl,[["__scopeId","data-v-3b41db19"]]);export{cl as default};
|
|
1
|
+
import{d as be,z as ke,c as y,S as s,J as a,q as J,ai as r,o as u,K as ae,e as l,Q as o,L as ye,P as c,I as b,R as L,a3 as F,u as oe,O as we,aC as he,r as v,m as z,as as Ce}from"./vendor-vue-B2uhHUfE.js";import{E as w,aj as Ve}from"./vendor-element-CZoEjZr8.js";import{H as xe}from"./HelpTip-i-KJhf5s.js";import{k as W,b as Se}from"./index-BkLbd7Cc.js";import{_ as $e}from"./_plugin-vue_export-helper-DlAUqK2U.js";const ze={class:"agent-clients-page"},Ne={class:"head"},Ae={class:"actions"},Te={class:"overview"},Ue={class:"metric primary"},Ee={class:"metric"},je={class:"metric"},Oe={class:"metric"},Re={class:"metric"},Pe={class:"section-head"},Be={class:"stack"},De={class:"stack"},Ie={class:"muted mono"},Je={class:"tags"},Le={class:"stack right"},Fe={class:"muted"},We={class:"section-head"},He={class:"actions"},Me={class:"stack"},qe={class:"stack"},Ke={class:"muted"},Qe={class:"stack"},Ze={class:"muted"},Ge={class:"stack"},Xe={class:"muted"},Ye={key:1,class:"muted"},el={key:2,class:"pagination"},ll={class:"form-grid"},tl={class:"code-block"},nl={class:"code-block"},N=50,sl=be({__name:"AgentClients",setup(al){const H=he(),A=v(30),h=v(!1),T=v(!1),U=v(""),C=v([]),M=v([]),E=v([]),j=v(0),V=v(1),p=J({applications:0,agent_auth_enabled:0,sessions:{},runs:0,conversations:0,failed:0,tool_calls:0,total_tokens:0,failure_rate:0,approvals:{}}),k=J({client_app_id:"",state:"all"}),i=J({open:!1,app_id:"",name:"",workspace:"",workspaces:[]}),O=z(()=>Se()),ie=z(()=>Object.values(p.approvals||{}).reduce((n,e)=>n+Number(e||0),0)),q=z(()=>JSON.stringify({hubUrl:O.value,clientAppId:i.app_id,workspace:i.workspace,connectionName:i.name.trim()||"default"},null,2)),K=z(()=>`/bailinghub connections add ${x(i.name.trim()||"default")} ${x(O.value)} ${x(i.app_id)} ${x(i.workspace)}`);function x(n){return JSON.stringify(n)}function _(n){return new Intl.NumberFormat("zh-CN").format(Number(n||0))}function de(n){return`${(Number(n||0)*100).toFixed(1)}%`}function Q(n){return n?`${n.slice(0,8)}…${n.slice(-4)}`:"—"}function Z(n){return n?new Date(n).toLocaleString("zh-CN",{hour12:!1}):"从未"}function ue(n){return n==="active"?"有效":n==="expired"?"已过期":"已撤销"}function re(n){return n==="active"?"success":n==="expired"?"warning":"info"}function ce(n){return n.includes("*")?["全部 Workspace"]:n.slice(0,4)}function G(n){return M.value.filter(e=>n.allowed_routes.includes("*")||n.allowed_routes.includes(e.route))}async function X(){h.value=!0;try{const n=await W(`/admin/api/agent-clients/overview?days=${A.value}`);if(!n.ok)throw new Error((await n.json().catch(()=>({}))).error||"加载失败");const e=await n.json();C.value=e.applications||[],M.value=e.workspaces||[],Object.assign(p,e.summary||{})}catch(n){w.error(n instanceof Error?n.message:"加载智能体客户端失败")}finally{h.value=!1}}async function R(){T.value=!0;try{const n=new URLSearchParams({state:k.state,limit:String(N),offset:String((V.value-1)*N)});k.client_app_id&&n.set("client_app_id",k.client_app_id);const e=await W(`/admin/api/agent-clients/sessions?${n}`);if(!e.ok)throw new Error((await e.json().catch(()=>({}))).error||"加载失败");const d=await e.json();E.value=d.list||[],j.value=Number(d.total||0)}catch(n){w.error(n instanceof Error?n.message:"加载授权设备失败")}finally{T.value=!1}}async function P(){await Promise.all([X(),R()])}async function Y(){V.value=1,await R()}function pe(n){var d;const e=G(n);i.app_id=n.app_id,i.name=n.app_id.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default",i.workspaces=e,i.workspace=((d=e[0])==null?void 0:d.route)||"",i.open=!0}async function ee(n){await navigator.clipboard.writeText(n),w.success("已复制")}async function _e(n){await Ve.confirm(`撤销设备“${n.device_label||Q(n.session_id)}”的 Agent Session?撤销后需要重新登录授权。`,"远程撤销",{type:"warning",confirmButtonText:"确认撤销"}),U.value=n.session_id;try{const e=await W(`/admin/api/agent-clients/sessions/${n.session_id}/revoke`,{method:"POST"});if(!e.ok)throw new Error((await e.json().catch(()=>({}))).error||"撤销失败");w.success("Agent Session 已撤销"),await P()}catch(e){w.error(e instanceof Error?e.message:"撤销失败")}finally{U.value=""}}return ke(P),(n,e)=>{const d=r("el-option"),S=r("el-select"),g=r("el-button"),B=r("el-card"),le=r("el-empty"),m=r("el-table-column"),D=r("el-tag"),te=r("el-table"),me=r("el-pagination"),fe=r("el-alert"),I=r("el-input"),$=r("el-form-item"),ve=r("el-form"),ge=r("el-dialog"),ne=Ce("loading");return u(),y("div",ze,[s(B,{shadow:"never"},{header:a(()=>[l("div",Ne,[l("div",null,[e[13]||(e[13]=l("b",null,"智能体客户端",-1)),s(xe,{title:"和执行器有什么区别"},{default:a(()=>[...e[12]||(e[12]=[l("p",null,[l("b",null,"智能体客户端"),c("在本地理解用户意图、选择能力并完成多步编排;中枢继续负责业务身份、授权、审批、执行与审计。")],-1),l("p",null,[l("b",null,"执行器"),c("是中枢下发 Job、由本地运行时执行本地任务后回报结果。两者是独立概念。")],-1),l("p",null,"本页聚合现有接入方、Agent Session 和 Agent Run,不创建第二套接入方配置。",-1),l("p",null,"每个接入方只配置一个不绑定账号、租户或门店的业务授权入口;账号切换与租户选择由业务授权页完成。",-1)])]),_:1})]),l("div",Ae,[s(S,{modelValue:A.value,"onUpdate:modelValue":e[0]||(e[0]=t=>A.value=t),size:"small",style:{width:"108px"},onChange:X},{default:a(()=>[s(d,{value:7,label:"近 7 天"}),s(d,{value:30,label:"近 30 天"}),s(d,{value:90,label:"近 90 天"})]),_:1},8,["modelValue"]),s(g,{size:"small",loading:h.value,onClick:P},{default:a(()=>[...e[14]||(e[14]=[c("刷新",-1)])]),_:1},8,["loading"])])])]),default:a(()=>{var t,f;return[ae((u(),y("div",Te,[l("div",Ue,[e[15]||(e[15]=l("span",null,"客户端应用",-1)),l("b",null,o(_(p.agent_auth_enabled)),1),l("em",null,"共 "+o(_(p.applications))+" 个接入方",1)]),l("div",Ee,[e[16]||(e[16]=l("span",null,"有效授权设备",-1)),l("b",null,o(_((t=p.sessions)==null?void 0:t.active)),1),l("em",null,"总会话 "+o(_((f=p.sessions)==null?void 0:f.total)),1)]),l("div",je,[e[17]||(e[17]=l("span",null,"Agent Run",-1)),l("b",null,o(_(p.runs)),1),l("em",null,o(_(p.conversations))+" 个本地会话",1)]),l("div",Oe,[e[18]||(e[18]=l("span",null,"工具调用",-1)),l("b",null,o(_(p.tool_calls)),1),l("em",null,"审批 "+o(_(ie.value))+" 次",1)]),l("div",Re,[e[19]||(e[19]=l("span",null,"累计 Token",-1)),l("b",null,o(_(p.total_tokens)),1),e[20]||(e[20]=l("em",null,"由客户端公开 usage 汇总",-1))]),l("div",{class:ye(["metric",{danger:Number(p.failure_rate||0)>.1}])},[e[21]||(e[21]=l("span",null,"失败率",-1)),l("b",null,o(de(p.failure_rate)),1),l("em",null,o(_(p.failed))+" 个失败或取消",1)],2)])),[[ne,h.value]])]}),_:1}),s(B,{shadow:"never"},{header:a(()=>[l("div",Pe,[e[23]||(e[23]=l("div",null,[l("b",null,"客户端应用"),l("span",null,"复用“接入方”配置;只有设置 Agent 授权页后才能发起浏览器登录。")],-1)),s(g,{size:"small",onClick:e[1]||(e[1]=t=>oe(H).push("/clients"))},{default:a(()=>[...e[22]||(e[22]=[c("管理接入方",-1)])]),_:1})])]),default:a(()=>[C.value.length?(u(),b(te,{key:1,data:C.value,size:"small"},{default:a(()=>[s(m,{label:"应用",width:180},{default:a(({row:t})=>[l("div",Be,[l("b",null,o(t.name||t.app_id),1),l("code",null,o(t.app_id),1)])]),_:1}),s(m,{label:"Agent 登录","min-width":240,"show-overflow-tooltip":""},{default:a(({row:t})=>[l("div",De,[l("div",null,[s(D,{size:"small",effect:"plain",type:t.enabled&&t.agent_auth_enabled?"success":"info"},{default:a(()=>[c(o(t.enabled&&t.agent_auth_enabled?"可授权":"未开放"),1)]),_:2},1032,["type"])]),l("span",Ie,o(t.agent_authorize_url||"未配置授权页"),1)])]),_:1}),s(m,{label:"允许 Workspace",width:180},{default:a(({row:t})=>[l("div",Je,[(u(!0),y(L,null,F(ce(t.allowed_routes),f=>(u(),b(D,{key:f,size:"small",effect:"plain",type:"info"},{default:a(()=>[c(o(f),1)]),_:2},1024))),128))])]),_:1}),s(m,{label:"近期开销",width:150,align:"right"},{default:a(({row:t})=>[l("div",Le,[l("span",null,o(_(t.stats.runs))+" Run / "+o(_(t.stats.tool_calls))+" 调用",1),l("span",Fe,o(_(t.stats.total_tokens))+" Token",1)])]),_:1}),s(m,{width:160,align:"right"},{default:a(({row:t})=>[s(g,{link:"",type:"primary",disabled:!t.agent_auth_enabled||!G(t).length,onClick:f=>pe(t)},{default:a(()=>[...e[24]||(e[24]=[c("生成连接配置",-1)])]),_:1},8,["disabled","onClick"]),s(g,{link:"",onClick:e[2]||(e[2]=f=>oe(H).push("/clients"))},{default:a(()=>[...e[25]||(e[25]=[c("编辑",-1)])]),_:1})]),_:1})]),_:1},8,["data"])):(u(),b(le,{key:0,description:"还没有接入方"}))]),_:1}),s(B,{shadow:"never"},{header:a(()=>[l("div",We,[e[26]||(e[26]=l("div",null,[l("b",null,"授权设备与 Agent Session"),l("span",null,"远程撤销后,后续 access/refresh token 都会失效;本地客户端需要重新登录。")],-1)),l("div",He,[s(S,{modelValue:k.client_app_id,"onUpdate:modelValue":e[3]||(e[3]=t=>k.client_app_id=t),clearable:"",filterable:"",size:"small",placeholder:"全部应用",style:{width:"190px"},onChange:Y},{default:a(()=>[(u(!0),y(L,null,F(C.value,t=>(u(),b(d,{key:t.app_id,label:t.name||t.app_id,value:t.app_id},null,8,["label","value"]))),128))]),_:1},8,["modelValue"]),s(S,{modelValue:k.state,"onUpdate:modelValue":e[4]||(e[4]=t=>k.state=t),size:"small",style:{width:"112px"},onChange:Y},{default:a(()=>[s(d,{value:"all",label:"全部状态"}),s(d,{value:"active",label:"有效"}),s(d,{value:"expired",label:"已过期"}),s(d,{value:"revoked",label:"已撤销"})]),_:1},8,["modelValue"])])])]),default:a(()=>[E.value.length?ae((u(),b(te,{key:1,data:E.value,size:"small"},{default:a(()=>[s(m,{label:"设备",width:170},{default:a(({row:t})=>[l("div",Me,[l("b",null,o(t.device_label||"未命名设备"),1),l("code",null,o(Q(t.session_id)),1)])]),_:1}),s(m,{label:"业务主体",width:150},{default:a(({row:t})=>{var f,se;return[l("div",qe,[l("span",null,o(((f=t.principal)==null?void 0:f.id)||t.on_behalf_of),1),l("span",Ke,o(((se=t.principal)==null?void 0:se.tenant)||"未声明租户"),1)])]}),_:1}),s(m,{label:"应用 / Workspace","min-width":190},{default:a(({row:t})=>[l("div",Qe,[l("code",null,o(t.client_app_id),1),l("span",Ze,o((t.allowed_routes||[]).join("、")||"无可用路由"),1)])]),_:1}),s(m,{label:"活跃与有效期",width:185},{default:a(({row:t})=>[l("div",Ge,[l("span",null,"活跃 "+o(Z(t.last_seen_at)),1),l("span",Xe,"到期 "+o(Z(t.refresh_expires_at)),1)])]),_:1}),s(m,{label:"状态",width:80},{default:a(({row:t})=>[s(D,{size:"small",effect:"plain",type:re(t.state)},{default:a(()=>[c(o(ue(t.state)),1)]),_:2},1032,["type"])]),_:1}),s(m,{width:90,align:"right"},{default:a(({row:t})=>[t.state!=="revoked"?(u(),b(g,{key:0,link:"",type:"danger",loading:U.value===t.session_id,onClick:f=>_e(t)},{default:a(()=>[...e[27]||(e[27]=[c("远程撤销",-1)])]),_:1},8,["loading","onClick"])):(u(),y("span",Ye,"已处理"))]),_:1})]),_:1},8,["data"])),[[ne,T.value]]):(u(),b(le,{key:0,description:"当前筛选下没有 Agent Session"})),j.value>N?(u(),y("div",el,[s(me,{"current-page":V.value,"onUpdate:currentPage":e[5]||(e[5]=t=>V.value=t),"page-size":N,total:j.value,layout:"prev, pager, next, total",onCurrentChange:R},null,8,["current-page","total"])])):we("",!0)]),_:1}),s(ge,{modelValue:i.open,"onUpdate:modelValue":e[11]||(e[11]=t=>i.open=t),title:"生成智能体客户端连接配置",width:"620px"},{footer:a(()=>[s(g,{onClick:e[8]||(e[8]=t=>i.open=!1)},{default:a(()=>[...e[28]||(e[28]=[c("关闭",-1)])]),_:1}),s(g,{onClick:e[9]||(e[9]=t=>ee(q.value))},{default:a(()=>[...e[29]||(e[29]=[c("复制 JSON",-1)])]),_:1}),s(g,{type:"primary",onClick:e[10]||(e[10]=t=>ee(K.value))},{default:a(()=>[...e[30]||(e[30]=[c("复制 DSH 命令",-1)])]),_:1})]),default:a(()=>[s(fe,{type:"info",closable:!1,"show-icon":"",title:"这里只生成公开连接元数据,不包含业务 URL、业务身份、Client Token、Agent Token 或模型密钥。"}),e[31]||(e[31]=l("p",{class:"connection-note"},[l("code",null,"connectionName"),c(" 只是本机连接选择器。登录时会统一打开接入方配置的业务授权页,由该页面确认当前账号与租户。")],-1)),s(ve,{"label-position":"top",class:"connection-form"},{default:a(()=>[s($,{label:"Hub 地址"},{default:a(()=>[s(I,{"model-value":O.value,readonly:"",class:"mono"},null,8,["model-value"])]),_:1}),l("div",ll,[s($,{label:"Client App ID"},{default:a(()=>[s(I,{"model-value":i.app_id,readonly:"",class:"mono"},null,8,["model-value"])]),_:1}),s($,{label:"Connection Name"},{default:a(()=>[s(I,{modelValue:i.name,"onUpdate:modelValue":e[6]||(e[6]=t=>i.name=t),maxlength:"128",class:"mono"},null,8,["modelValue"])]),_:1})]),s($,{label:"Workspace"},{default:a(()=>[s(S,{modelValue:i.workspace,"onUpdate:modelValue":e[7]||(e[7]=t=>i.workspace=t),style:{width:"100%"}},{default:a(()=>[(u(!0),y(L,null,F(i.workspaces,t=>(u(),b(d,{key:t.route,label:t.name+"("+t.route+")",value:t.route},null,8,["label","value"]))),128))]),_:1},8,["modelValue"])]),_:1})]),_:1}),l("div",tl,[l("pre",null,o(q.value),1)]),l("div",nl,[l("pre",null,o(K.value),1)])]),_:1},8,["modelValue"])])}}}),cl=$e(sl,[["__scopeId","data-v-3b41db19"]]);export{cl as default};
|