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,30 @@
|
|
|
1
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
2
|
+
import type { AgentToolAuthContext } from './agent-tool-invocations';
|
|
3
|
+
import {
|
|
4
|
+
auditUuid, parseCreateConversationAudit, parseConversationAuditEvents, ConversationAuditError,
|
|
5
|
+
CONVERSATION_AUDIT_SCHEMA, CONVERSATION_AUDIT_ACK_SCHEMA,
|
|
6
|
+
} from '../core/runtime/agent-conversation-audit';
|
|
7
|
+
|
|
8
|
+
function repository(configStore: ConfigStoreContract | null) {
|
|
9
|
+
if (!configStore?.agentConversationAudit) {
|
|
10
|
+
throw new ConversationAuditError(503, 'conversation_audit_unavailable', 'Conversation audit storage is unavailable.');
|
|
11
|
+
}
|
|
12
|
+
return configStore.agentConversationAudit;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function createConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, body: unknown) {
|
|
16
|
+
const input = parseCreateConversationAudit(body);
|
|
17
|
+
return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repository(store).create(auth, input) };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function confirmConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, id: string, body: unknown) {
|
|
21
|
+
if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length) {
|
|
22
|
+
throw new ConversationAuditError(400, 'invalid_request', 'Member confirmation requires an empty object; identity comes from the bearer.');
|
|
23
|
+
}
|
|
24
|
+
return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repository(store).confirm(auth, auditUuid(id)) };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function appendConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, id: string, body: unknown) {
|
|
28
|
+
const events = parseConversationAuditEvents(body);
|
|
29
|
+
return { schema: CONVERSATION_AUDIT_ACK_SCHEMA, ...await repository(store).append(auth, auditUuid(id), events) };
|
|
30
|
+
}
|
package/src/app/oss-edition.ts
CHANGED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import {
|
|
4
|
+
includesAllCurrentOperationIds,
|
|
5
|
+
mergeExactOperationIds,
|
|
6
|
+
} from '../../../web-admin/src/agent-direct-selection';
|
|
7
|
+
|
|
8
|
+
test('本地 Agent 全选当前写操作会保留手填项,并写入精确 operationId 快照', () => {
|
|
9
|
+
assert.deepEqual(
|
|
10
|
+
mergeExactOperationIds(
|
|
11
|
+
['manual_write', 'staff_edit'],
|
|
12
|
+
['staff_edit', 'item_add', '*', 'bad-operation'],
|
|
13
|
+
),
|
|
14
|
+
['manual_write', 'staff_edit', 'item_add'],
|
|
15
|
+
);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('本地 Agent 全选状态只比较当前工具目录,不把未来能力视为已授权', () => {
|
|
19
|
+
assert.equal(includesAllCurrentOperationIds(['staff_edit', 'item_add'], ['staff_edit', 'item_add']), true);
|
|
20
|
+
assert.equal(includesAllCurrentOperationIds(['staff_edit'], ['staff_edit', 'item_add']), false);
|
|
21
|
+
assert.equal(includesAllCurrentOperationIds([], []), false);
|
|
22
|
+
});
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { ConversationAuditError, parseCreateConversationAudit, parseConversationAuditEvents } from './agent-conversation-audit';
|
|
4
|
+
import { conversationAuditFixture, AUDIT_SESSION_A } from '../../test-support/agent-conversation-audit-fixture';
|
|
5
|
+
|
|
6
|
+
test('visible text preserves original characters and refuses undeclared reasoning or identity fields', () => {
|
|
7
|
+
const event = { event_id: 'visible-1', sequence: 1, client_turn_id: 'turn-1', kind: 'user_message', content: ' 原始文本\n<tool>quoted</tool> ' };
|
|
8
|
+
assert.equal(parseConversationAuditEvents({ events: [event] })[0]!.content, event.content);
|
|
9
|
+
for (const invalid of [
|
|
10
|
+
{ ...event, reasoning: 'not visible' }, { ...event, token: 'not allowed' },
|
|
11
|
+
{ ...event, member_session_id: AUDIT_SESSION_A }, { ...event, content: '\u0000' },
|
|
12
|
+
{ ...event, content: ' ' }, { ...event, content: 'a'.repeat(64_001) },
|
|
13
|
+
{ ...event, kind: 'tool_result' }, { ...event, sequence: 0 },
|
|
14
|
+
]) assert.throws(() => parseConversationAuditEvents({ events: [invalid] }), (error: unknown) => error instanceof ConversationAuditError && error.statusCode === 400);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('membership accepts all 64 host scope slots and rejects duplicate or unbound display labels', () => {
|
|
18
|
+
const fx = conversationAuditFixture();
|
|
19
|
+
const ids = Array.from({ length: 64 }, (_, index) => `123e4567-e89b-42d3-a456-${String(index).padStart(12, '0')}`);
|
|
20
|
+
assert.equal(parseCreateConversationAudit({ ...fx.input(), member_session_ids: ids, member_labels: {} }).member_session_ids.length, 64);
|
|
21
|
+
for (const patch of [
|
|
22
|
+
{ member_session_ids: [AUDIT_SESSION_A, AUDIT_SESSION_A] },
|
|
23
|
+
{ member_labels: { '123e4567-e89b-42d3-a456-426614174099': 'An unselected member' } },
|
|
24
|
+
{ member_labels: { [AUDIT_SESSION_A]: 'x'.repeat(129) } },
|
|
25
|
+
{ tenant: 'client-supplied-audit-scope' },
|
|
26
|
+
]) assert.throws(() => parseCreateConversationAudit({ ...fx.input(), ...patch }));
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('event batches enforce continuity, unique ids and explicit byte or total-event limits', () => {
|
|
30
|
+
const event = { event_id: 'visible', sequence: 1, client_turn_id: 'turn-1', kind: 'assistant_message', content: 'a' };
|
|
31
|
+
assert.throws(() => parseConversationAuditEvents({ events: [event, { ...event, event_id: 'next', sequence: 3 }] }));
|
|
32
|
+
assert.throws(() => parseConversationAuditEvents({ events: [event, { ...event, sequence: 2 }] }));
|
|
33
|
+
assert.throws(() => parseConversationAuditEvents({ events: Array.from({ length: 51 }, (_, index) => ({ ...event, event_id: `event-${index}`, sequence: index + 1 })) }));
|
|
34
|
+
for (const batch of [
|
|
35
|
+
[{ ...event, sequence: 20_001 }],
|
|
36
|
+
Array.from({ length: 5 }, (_, index) => ({ ...event, event_id: `large-${index}`, sequence: index + 1, content: 'a'.repeat(64_000) })),
|
|
37
|
+
]) assert.throws(() => parseConversationAuditEvents({ events: batch }), (error: unknown) => error instanceof ConversationAuditError && error.code === 'conversation_audit_limit' && error.statusCode === 413);
|
|
38
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { AgentSession, Client, Route } from '../contracts/types';
|
|
3
|
+
import { routeAgentClientConfig } from '../config/route-config';
|
|
4
|
+
import { agentDirectToolsConfig } from '../config/tools-config';
|
|
5
|
+
import { audienceAllows } from './identity-runtime';
|
|
6
|
+
|
|
7
|
+
export const CONVERSATION_AUDIT_SCHEMA = 'bailing.agent-conversation-audit.v1';
|
|
8
|
+
export const CONVERSATION_AUDIT_ACK_SCHEMA = 'bailing.agent-conversation-audit-ack.v1';
|
|
9
|
+
export const CONVERSATION_AUDIT_MAX_EVENTS = 20_000;
|
|
10
|
+
export const CONVERSATION_AUDIT_MAX_BYTES = 16 * 1024 * 1024;
|
|
11
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
12
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
13
|
+
const CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
|
14
|
+
|
|
15
|
+
export class ConversationAuditError extends Error {
|
|
16
|
+
constructor(readonly statusCode: number, readonly code: string, message: string) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'ConversationAuditError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function auditError(code = 'conversation_audit_conflict', status = 409): never {
|
|
23
|
+
throw new ConversationAuditError(status, code, status === 404
|
|
24
|
+
? 'The conversation audit is unavailable for this identity.'
|
|
25
|
+
: status === 403 ? 'The frozen conversation authorization is no longer valid.'
|
|
26
|
+
: status === 413 ? 'The conversation audit limit was exceeded; no events were truncated or saved.'
|
|
27
|
+
: 'The conversation audit request conflicts with its frozen membership or event history.');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function invalid(): never {
|
|
31
|
+
throw new ConversationAuditError(400, 'invalid_request', 'The conversation audit request contains invalid or undeclared fields.');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function record(value: unknown): value is Record<string, unknown> {
|
|
35
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function fields(value: unknown, required: string[], optional: string[] = []): asserts value is Record<string, unknown> {
|
|
39
|
+
if (!record(value) || required.some((key) => !Object.hasOwn(value, key)) ||
|
|
40
|
+
Object.keys(value).some((key) => !required.includes(key) && !optional.includes(key))) invalid();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function auditUuid(value: unknown): string {
|
|
44
|
+
if (typeof value !== 'string' || !UUID.test(value)) invalid();
|
|
45
|
+
return value.toLowerCase();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function identifier(value: unknown): string {
|
|
49
|
+
if (typeof value !== 'string' || !ID.test(value)) invalid();
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function text(value: unknown, maximum: number): string {
|
|
54
|
+
if (typeof value !== 'string' || !value.trim() || value.length > maximum || CONTROL.test(value)) invalid();
|
|
55
|
+
return value;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface CreateConversationAuditInput {
|
|
59
|
+
client_archive_id: string;
|
|
60
|
+
client_conversation_id: string;
|
|
61
|
+
route: string;
|
|
62
|
+
member_session_ids: string[];
|
|
63
|
+
member_labels: Record<string, string>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function parseCreateConversationAudit(value: unknown): CreateConversationAuditInput {
|
|
67
|
+
fields(value, ['client_archive_id', 'client_conversation_id', 'route', 'member_session_ids'], ['member_labels']);
|
|
68
|
+
if (typeof value.route !== 'string' || !/^[a-z0-9][a-z0-9_-]{1,63}$/.test(value.route) || value.route === 'auto' ||
|
|
69
|
+
!Array.isArray(value.member_session_ids) || value.member_session_ids.length < 1 || value.member_session_ids.length > 64) invalid();
|
|
70
|
+
const members = value.member_session_ids.map(auditUuid).sort();
|
|
71
|
+
if (new Set(members).size !== members.length) invalid();
|
|
72
|
+
const labels: Record<string, string> = {};
|
|
73
|
+
if (value.member_labels !== undefined) {
|
|
74
|
+
if (!record(value.member_labels)) invalid();
|
|
75
|
+
for (const [key, label] of Object.entries(value.member_labels)) {
|
|
76
|
+
const id = auditUuid(key);
|
|
77
|
+
if (!members.includes(id) || Object.hasOwn(labels, id)) invalid();
|
|
78
|
+
labels[id] = text(label, 128);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
client_archive_id: auditUuid(value.client_archive_id),
|
|
83
|
+
client_conversation_id: identifier(value.client_conversation_id),
|
|
84
|
+
route: value.route, member_session_ids: members, member_labels: labels,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type ConversationAuditEventKind = 'turn_start' | 'user_message' | 'assistant_message' | 'run_link' | 'turn_end';
|
|
89
|
+
export type ConversationAuditTurnStatus = 'running' | 'completed' | 'failed' | 'cancelled';
|
|
90
|
+
export interface ConversationAuditEventInput {
|
|
91
|
+
event_id: string;
|
|
92
|
+
sequence: number;
|
|
93
|
+
client_turn_id: string;
|
|
94
|
+
kind: ConversationAuditEventKind;
|
|
95
|
+
content?: string;
|
|
96
|
+
run_id?: string;
|
|
97
|
+
member_session_id?: string;
|
|
98
|
+
status?: Exclude<ConversationAuditTurnStatus, 'running'>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function parseConversationAuditEvents(value: unknown): ConversationAuditEventInput[] {
|
|
102
|
+
fields(value, ['events']);
|
|
103
|
+
if (!Array.isArray(value.events) || value.events.length < 1 || value.events.length > 50) invalid();
|
|
104
|
+
const events = value.events.map((raw): ConversationAuditEventInput => {
|
|
105
|
+
const common = ['event_id', 'sequence', 'client_turn_id', 'kind'];
|
|
106
|
+
if (!record(raw)) invalid();
|
|
107
|
+
if (raw.kind === 'user_message' || raw.kind === 'assistant_message') fields(raw, [...common, 'content']);
|
|
108
|
+
else if (raw.kind === 'run_link') fields(raw, [...common, 'run_id', 'member_session_id']);
|
|
109
|
+
else if (raw.kind === 'turn_end') fields(raw, [...common, 'status']);
|
|
110
|
+
else if (raw.kind === 'turn_start') fields(raw, common);
|
|
111
|
+
else invalid();
|
|
112
|
+
if (!Number.isSafeInteger(raw.sequence) || Number(raw.sequence) < 1) invalid();
|
|
113
|
+
if (Number(raw.sequence) > CONVERSATION_AUDIT_MAX_EVENTS) auditError('conversation_audit_limit', 413);
|
|
114
|
+
const event: ConversationAuditEventInput = {
|
|
115
|
+
event_id: identifier(raw.event_id), sequence: Number(raw.sequence), client_turn_id: identifier(raw.client_turn_id),
|
|
116
|
+
kind: raw.kind as ConversationAuditEventKind,
|
|
117
|
+
};
|
|
118
|
+
if (raw.kind === 'user_message' || raw.kind === 'assistant_message') event.content = text(raw.content, 64_000);
|
|
119
|
+
if (raw.kind === 'run_link') {
|
|
120
|
+
event.run_id = auditUuid(raw.run_id);
|
|
121
|
+
event.member_session_id = auditUuid(raw.member_session_id);
|
|
122
|
+
}
|
|
123
|
+
if (raw.kind === 'turn_end') {
|
|
124
|
+
if (!['completed', 'failed', 'cancelled'].includes(String(raw.status))) invalid();
|
|
125
|
+
event.status = raw.status as ConversationAuditEventInput['status'];
|
|
126
|
+
}
|
|
127
|
+
return event;
|
|
128
|
+
});
|
|
129
|
+
if (new Set(events.map((event) => event.event_id)).size !== events.length ||
|
|
130
|
+
events.some((event, index) => index > 0 && event.sequence !== events[index - 1]!.sequence + 1)) invalid();
|
|
131
|
+
if (events.reduce((sum, event) => sum + Buffer.byteLength(event.content ?? '', 'utf8'), 0) > 256 * 1024) auditError('conversation_audit_limit', 413);
|
|
132
|
+
return events;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function stable(value: unknown): string {
|
|
136
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
|
|
137
|
+
if (record(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`;
|
|
138
|
+
return JSON.stringify(value) ?? 'null';
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function auditHash(value: unknown): string {
|
|
142
|
+
return createHash('sha256').update(stable(value), 'utf8').digest('hex');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function auditIdentityHash(session: AgentSession): string {
|
|
146
|
+
return auditHash({ session_id: session.session_id, client_app_id: session.client_app_id, principal: session.principal, on_behalf_of: session.on_behalf_of });
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The same route restrictions as Agent Runtime; group membership never expands them. */
|
|
150
|
+
export function assertAuditMemberActive(session: AgentSession, client: Client, route: Route, expectedIdentity?: string): void {
|
|
151
|
+
const allowed = (routes: string[]) => Array.isArray(routes) && (routes.includes('*') || routes.includes(route.route_key));
|
|
152
|
+
if (session.revoked_at || !Number.isFinite(Date.parse(session.refresh_expires_at)) || Date.parse(session.refresh_expires_at) <= Date.now() ||
|
|
153
|
+
session.client_app_id !== client.app_id || !client.enabled || !client.agent_authorize_url || !route.enabled ||
|
|
154
|
+
!allowed(client.allowed_routes) || !allowed(session.allowed_routes) || !routeAgentClientConfig(route) || !agentDirectToolsConfig(route.tools) ||
|
|
155
|
+
(expectedIdentity !== undefined && auditIdentityHash(session) !== expectedIdentity) ||
|
|
156
|
+
!audienceAllows(route.audience, { ...session.principal, client_app_id: client.app_id, channel: session.principal.channel ?? `agent:${client.app_id}` }).ok) {
|
|
157
|
+
auditError('conversation_audit_authorization_invalid', 403);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -145,3 +145,39 @@ test('AgentAuthRepository rejects an approved authorization after its short code
|
|
|
145
145
|
assert.deepEqual(result, { ok: false, reason: 'invalid_grant' });
|
|
146
146
|
assert.equal(insertedSession, false);
|
|
147
147
|
});
|
|
148
|
+
|
|
149
|
+
test('AgentAuthRepository admin session projection filters state and never returns token hashes', async () => {
|
|
150
|
+
const queries: Array<{ sql: string; params: unknown[] }> = [];
|
|
151
|
+
const row = sessionRow({
|
|
152
|
+
access_expires_at: '2026-08-27 01:00:00',
|
|
153
|
+
refresh_expires_at: '2026-09-27 00:00:00',
|
|
154
|
+
created_at: '2026-08-27 00:00:00',
|
|
155
|
+
updated_at: '2026-08-27 00:10:00',
|
|
156
|
+
last_seen_at: '2026-08-27 00:10:00',
|
|
157
|
+
});
|
|
158
|
+
const pool = {
|
|
159
|
+
async query(sql: string, params: unknown[] = []) {
|
|
160
|
+
queries.push({ sql, params });
|
|
161
|
+
if (sql.startsWith('SELECT COUNT(*) AS total,')) {
|
|
162
|
+
return [[{ total: 3, active: 1, expired: 1, revoked: 1 }], []];
|
|
163
|
+
}
|
|
164
|
+
if (sql.startsWith('SELECT COUNT(*) AS total')) return [[{ total: 1 }], []];
|
|
165
|
+
if (sql.startsWith('SELECT session_id,client_app_id')) return [[row], []];
|
|
166
|
+
throw new Error(`unexpected query: ${sql}`);
|
|
167
|
+
},
|
|
168
|
+
} as unknown as Pool;
|
|
169
|
+
const repo = new AgentAuthRepository(() => pool);
|
|
170
|
+
const now = new Date('2026-08-27T00:30:00.000Z');
|
|
171
|
+
const result = await repo.listSessionsForAdmin({
|
|
172
|
+
clientAppId: 'example-business', state: 'active', limit: 25, offset: 5, now,
|
|
173
|
+
});
|
|
174
|
+
assert.equal(result.total, 1);
|
|
175
|
+
assert.equal(result.list[0]?.state, 'active');
|
|
176
|
+
assert.equal(result.list[0]?.last_seen_at, new Date('2026-08-27 00:10:00').toISOString());
|
|
177
|
+
assert.equal(Object.hasOwn(result.list[0]!, 'access_token_hash'), false);
|
|
178
|
+
assert.match(queries[0]!.sql, /client_app_id=\? AND revoked_at IS NULL AND refresh_expires_at>\?/);
|
|
179
|
+
assert.deepEqual(queries[1]!.params.slice(-2), [25, 5]);
|
|
180
|
+
|
|
181
|
+
const summary = await repo.sessionSummaryForAdmin(now);
|
|
182
|
+
assert.deepEqual(summary, { total: 3, active: 1, expired: 1, revoked: 1 });
|
|
183
|
+
});
|
|
@@ -33,6 +33,25 @@ export type RefreshRotationResult =
|
|
|
33
33
|
| { ok: true; session: AgentSession }
|
|
34
34
|
| { ok: false; reason: 'invalid_grant' | 'replayed' };
|
|
35
35
|
|
|
36
|
+
export type AgentSessionAdminState = 'active' | 'expired' | 'revoked';
|
|
37
|
+
|
|
38
|
+
export interface AgentSessionAdminRecord extends AgentSession {
|
|
39
|
+
last_seen_at?: string;
|
|
40
|
+
state: AgentSessionAdminState;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface AgentSessionAdminList {
|
|
44
|
+
list: AgentSessionAdminRecord[];
|
|
45
|
+
total: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface AgentSessionAdminSummary {
|
|
49
|
+
total: number;
|
|
50
|
+
active: number;
|
|
51
|
+
expired: number;
|
|
52
|
+
revoked: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
36
55
|
function jsonObject<T extends object>(value: unknown): T {
|
|
37
56
|
if (value && typeof value === 'object' && !Array.isArray(value)) return value as T;
|
|
38
57
|
if (typeof value === 'string') {
|
|
@@ -88,6 +107,19 @@ function sessionRow(row: any): AgentSession {
|
|
|
88
107
|
};
|
|
89
108
|
}
|
|
90
109
|
|
|
110
|
+
function sessionAdminState(row: any, now: Date): AgentSessionAdminState {
|
|
111
|
+
if (row.revoked_at) return 'revoked';
|
|
112
|
+
return new Date(row.refresh_expires_at).getTime() <= now.getTime() ? 'expired' : 'active';
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function sessionAdminRow(row: any, now: Date): AgentSessionAdminRecord {
|
|
116
|
+
return {
|
|
117
|
+
...sessionRow(row),
|
|
118
|
+
...(row.last_seen_at ? { last_seen_at: iso(row.last_seen_at) } : {}),
|
|
119
|
+
state: sessionAdminState(row, now),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
91
123
|
async function rollback(connection: PoolConnection): Promise<void> {
|
|
92
124
|
await connection.rollback().catch(() => undefined);
|
|
93
125
|
}
|
|
@@ -244,6 +276,71 @@ export class AgentAuthRepository {
|
|
|
244
276
|
return sessionRow(row);
|
|
245
277
|
}
|
|
246
278
|
|
|
279
|
+
/** Admin-only projection. Token hashes and refresh-token rows never leave the repository. */
|
|
280
|
+
async listSessionsForAdmin(input: {
|
|
281
|
+
clientAppId?: string;
|
|
282
|
+
state?: AgentSessionAdminState | 'all';
|
|
283
|
+
limit?: number;
|
|
284
|
+
offset?: number;
|
|
285
|
+
now?: Date;
|
|
286
|
+
} = {}): Promise<AgentSessionAdminList> {
|
|
287
|
+
const now = input.now ?? new Date();
|
|
288
|
+
const limit = Math.min(Math.max(Math.round(Number(input.limit) || 50), 1), 200);
|
|
289
|
+
const offset = Math.max(Math.round(Number(input.offset) || 0), 0);
|
|
290
|
+
const where: string[] = [];
|
|
291
|
+
const params: unknown[] = [];
|
|
292
|
+
if (input.clientAppId) {
|
|
293
|
+
where.push('client_app_id=?');
|
|
294
|
+
params.push(input.clientAppId);
|
|
295
|
+
}
|
|
296
|
+
if (input.state === 'active') {
|
|
297
|
+
where.push('revoked_at IS NULL AND refresh_expires_at>?');
|
|
298
|
+
params.push(dtIso(now.toISOString()));
|
|
299
|
+
} else if (input.state === 'expired') {
|
|
300
|
+
where.push('revoked_at IS NULL AND refresh_expires_at<=?');
|
|
301
|
+
params.push(dtIso(now.toISOString()));
|
|
302
|
+
} else if (input.state === 'revoked') {
|
|
303
|
+
where.push('revoked_at IS NOT NULL');
|
|
304
|
+
}
|
|
305
|
+
const predicate = where.length ? ` WHERE ${where.join(' AND ')}` : '';
|
|
306
|
+
const [countRows] = await this.pool.query(`SELECT COUNT(*) AS total FROM bz_agent_sessions${predicate}`, params);
|
|
307
|
+
const [rows] = await this.pool.query(
|
|
308
|
+
`SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions${predicate} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
|
|
309
|
+
[...params, limit, offset],
|
|
310
|
+
);
|
|
311
|
+
return {
|
|
312
|
+
list: (rows as any[]).map((row) => sessionAdminRow(row, now)),
|
|
313
|
+
total: Number((countRows as any[])[0]?.total ?? 0),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async getSessionForAdmin(sessionId: string, now = new Date()): Promise<AgentSessionAdminRecord | null> {
|
|
318
|
+
const [rows] = await this.pool.query(
|
|
319
|
+
'SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions WHERE session_id=? LIMIT 1',
|
|
320
|
+
[sessionId],
|
|
321
|
+
);
|
|
322
|
+
return (rows as any[])[0] ? sessionAdminRow((rows as any[])[0], now) : null;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async sessionSummaryForAdmin(now = new Date()): Promise<AgentSessionAdminSummary> {
|
|
326
|
+
const stamp = dtIso(now.toISOString());
|
|
327
|
+
const [rows] = await this.pool.query(
|
|
328
|
+
'SELECT COUNT(*) AS total,' +
|
|
329
|
+
' SUM(CASE WHEN revoked_at IS NULL AND refresh_expires_at>? THEN 1 ELSE 0 END) AS active,' +
|
|
330
|
+
' SUM(CASE WHEN revoked_at IS NULL AND refresh_expires_at<=? THEN 1 ELSE 0 END) AS expired,' +
|
|
331
|
+
' SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked' +
|
|
332
|
+
' FROM bz_agent_sessions',
|
|
333
|
+
[stamp, stamp],
|
|
334
|
+
);
|
|
335
|
+
const row = (rows as any[])[0] ?? {};
|
|
336
|
+
return {
|
|
337
|
+
total: Number(row.total ?? 0),
|
|
338
|
+
active: Number(row.active ?? 0),
|
|
339
|
+
expired: Number(row.expired ?? 0),
|
|
340
|
+
revoked: Number(row.revoked ?? 0),
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
247
344
|
async rotateRefreshToken(input: {
|
|
248
345
|
refreshTokenHash: string;
|
|
249
346
|
clientAppId: string;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repository';
|
|
4
|
+
|
|
5
|
+
test('AgentClientRuntimeRepository admin stats return aggregates only and parameterize client scope', async () => {
|
|
6
|
+
const queries: Array<{ sql: string; params: unknown[] }> = [];
|
|
7
|
+
const pool = {
|
|
8
|
+
async query(sql: string, params: unknown[] = []) {
|
|
9
|
+
queries.push({ sql, params });
|
|
10
|
+
if (sql.includes('FROM bz_agent_client_runs')) {
|
|
11
|
+
return [[{
|
|
12
|
+
client_app_id: 'example-business', runs: 4, conversations: 2,
|
|
13
|
+
completed: 3, failed: 1, tool_calls: 7, total_tokens: 2400,
|
|
14
|
+
}], []];
|
|
15
|
+
}
|
|
16
|
+
if (sql.includes('FROM bz_tool_approvals')) {
|
|
17
|
+
return [[
|
|
18
|
+
{ client_app_id: 'example-business', status: 'approved', total: 2 },
|
|
19
|
+
{ client_app_id: 'example-business', status: 'denied', total: 1 },
|
|
20
|
+
], []];
|
|
21
|
+
}
|
|
22
|
+
throw new Error(`unexpected query: ${sql}`);
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
const repo = new AgentClientRuntimeRepository(() => pool);
|
|
26
|
+
const result = await repo.statsForAdmin({
|
|
27
|
+
since: '2026-08-20 00:00:00', clientAppId: 'example-business',
|
|
28
|
+
});
|
|
29
|
+
assert.deepEqual(result, [{
|
|
30
|
+
client_app_id: 'example-business', runs: 4, conversations: 2,
|
|
31
|
+
completed: 3, failed: 1, tool_calls: 7, total_tokens: 2400,
|
|
32
|
+
approvals: { approved: 2, denied: 1 },
|
|
33
|
+
}]);
|
|
34
|
+
assert.equal(queries.length, 2);
|
|
35
|
+
assert.deepEqual(queries[0]!.params, ['2026-08-20 00:00:00', 'example-business']);
|
|
36
|
+
assert.deepEqual(queries[1]!.params, ['2026-08-20 00:00:00', 'example-business']);
|
|
37
|
+
assert.doesNotMatch(queries[0]!.sql, /user_input|final_content|context_json/);
|
|
38
|
+
});
|
|
@@ -37,6 +37,17 @@ export interface ReserveAgentClientRunInput {
|
|
|
37
37
|
user_input: string;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
export interface AgentClientAdminStats {
|
|
41
|
+
client_app_id: string;
|
|
42
|
+
runs: number;
|
|
43
|
+
conversations: number;
|
|
44
|
+
completed: number;
|
|
45
|
+
failed: number;
|
|
46
|
+
tool_calls: number;
|
|
47
|
+
total_tokens: number;
|
|
48
|
+
approvals: Record<string, number>;
|
|
49
|
+
}
|
|
50
|
+
|
|
40
51
|
export class AgentClientRuntimeConflictError extends Error {
|
|
41
52
|
override readonly name = 'AgentClientRuntimeConflictError';
|
|
42
53
|
}
|
|
@@ -169,6 +180,49 @@ export class AgentClientRuntimeRepository {
|
|
|
169
180
|
return rows[0] ? runRow(rows[0]) : null;
|
|
170
181
|
}
|
|
171
182
|
|
|
183
|
+
/** Safe aggregate for the Agent Client admin center. No prompts, tool arguments, or results are returned. */
|
|
184
|
+
async statsForAdmin(input: { since: string; clientAppId?: string }): Promise<AgentClientAdminStats[]> {
|
|
185
|
+
const where = input.clientAppId ? 'created_at>=? AND client_app_id=?' : 'created_at>=?';
|
|
186
|
+
const params = input.clientAppId ? [input.since, input.clientAppId] : [input.since];
|
|
187
|
+
const [runRows] = await this.pool.query(
|
|
188
|
+
'SELECT client_app_id,COUNT(*) AS runs,' +
|
|
189
|
+
' COUNT(DISTINCT CONCAT_WS(\'|\',session_id,route_key,client_conversation_id)) AS conversations,' +
|
|
190
|
+
' SUM(CASE WHEN status=\'completed\' THEN 1 ELSE 0 END) AS completed,' +
|
|
191
|
+
' SUM(CASE WHEN status IN (\'failed\',\'cancelled\') THEN 1 ELSE 0 END) AS failed,' +
|
|
192
|
+
' SUM(COALESCE(CAST(JSON_UNQUOTE(JSON_EXTRACT(usage_json,\'$.tool_calls\')) AS UNSIGNED),0)) AS tool_calls,' +
|
|
193
|
+
' SUM(COALESCE(CAST(JSON_UNQUOTE(JSON_EXTRACT(usage_json,\'$.total_tokens\')) AS UNSIGNED),0)) AS total_tokens' +
|
|
194
|
+
` FROM bz_agent_client_runs WHERE ${where} GROUP BY client_app_id ORDER BY client_app_id`,
|
|
195
|
+
params,
|
|
196
|
+
);
|
|
197
|
+
const approvalWhere = input.clientAppId
|
|
198
|
+
? 'j.created_at>=? AND j.agent_session_id IS NOT NULL AND j.client_app_id=?'
|
|
199
|
+
: 'j.created_at>=? AND j.agent_session_id IS NOT NULL';
|
|
200
|
+
const [approvalRows] = await this.pool.query(
|
|
201
|
+
'SELECT j.client_app_id,a.status,COUNT(*) AS total FROM bz_tool_approvals a' +
|
|
202
|
+
` JOIN bz_jobs j ON j.job_id=a.job_id WHERE ${approvalWhere}` +
|
|
203
|
+
' GROUP BY j.client_app_id,a.status ORDER BY j.client_app_id,a.status',
|
|
204
|
+
params,
|
|
205
|
+
);
|
|
206
|
+
const approvals = new Map<string, Record<string, number>>();
|
|
207
|
+
for (const row of approvalRows as any[]) {
|
|
208
|
+
const clientAppId = String(row.client_app_id);
|
|
209
|
+
const status = String(row.status);
|
|
210
|
+
const current = approvals.get(clientAppId) ?? {};
|
|
211
|
+
current[status] = Number(row.total ?? 0);
|
|
212
|
+
approvals.set(clientAppId, current);
|
|
213
|
+
}
|
|
214
|
+
return (runRows as any[]).map((row) => ({
|
|
215
|
+
client_app_id: String(row.client_app_id),
|
|
216
|
+
runs: Number(row.runs ?? 0),
|
|
217
|
+
conversations: Number(row.conversations ?? 0),
|
|
218
|
+
completed: Number(row.completed ?? 0),
|
|
219
|
+
failed: Number(row.failed ?? 0),
|
|
220
|
+
tool_calls: Number(row.tool_calls ?? 0),
|
|
221
|
+
total_tokens: Number(row.total_tokens ?? 0),
|
|
222
|
+
approvals: approvals.get(String(row.client_app_id)) ?? {},
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
|
|
172
226
|
async finalizeTurn(input: {
|
|
173
227
|
run_id: string;
|
|
174
228
|
session_id: string;
|