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.
Files changed (131) hide show
  1. package/README.en.md +146 -185
  2. package/README.md +135 -206
  3. package/THIRD_PARTY_NOTICES.md +6 -7
  4. package/assets/readme-demo-evidence.en-dark.svg +82 -0
  5. package/assets/readme-demo-evidence.en.svg +82 -0
  6. package/assets/readme-demo-evidence.zh-CN-dark.svg +82 -0
  7. package/assets/readme-demo-evidence.zh-CN.svg +82 -0
  8. package/assets/readme-entry-points.en-dark.svg +71 -0
  9. package/assets/readme-entry-points.en.svg +71 -0
  10. package/assets/readme-entry-points.zh-CN-dark.svg +71 -0
  11. package/assets/readme-entry-points.zh-CN.svg +71 -0
  12. package/assets/readme-product-overview.en-dark.svg +87 -0
  13. package/assets/readme-product-overview.en.svg +87 -0
  14. package/assets/readme-product-overview.zh-CN-dark.svg +87 -0
  15. package/assets/readme-product-overview.zh-CN.svg +87 -0
  16. package/docker-compose.images.yml +2 -2
  17. package/docs/AGENT_AUTH_API.en.md +25 -9
  18. package/docs/AGENT_AUTH_API.md +17 -5
  19. package/docs/AGENT_CLIENT_QUICKSTART.en.md +90 -18
  20. package/docs/AGENT_CLIENT_QUICKSTART.md +74 -16
  21. package/docs/AGENT_CONVERSATION_AUDIT.en.md +194 -0
  22. package/docs/AGENT_CONVERSATION_AUDIT.md +111 -0
  23. package/docs/CHANGELOG.en.md +23 -0
  24. package/docs/CHANGELOG.md +23 -0
  25. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  26. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  27. package/docs/README.en.md +7 -0
  28. package/docs/README.md +7 -0
  29. package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
  30. package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
  31. package/docs/RELEASE_NOTES_v0.6.0.en.md +51 -0
  32. package/docs/RELEASE_NOTES_v0.6.0.md +51 -0
  33. package/docs/user-guide/README.en.md +1 -0
  34. package/docs/user-guide/README.md +1 -0
  35. package/docs/user-guide/console-map.en.md +2 -0
  36. package/docs/user-guide/console-map.md +2 -1
  37. package/docs/user-guide/conversations.en.md +40 -0
  38. package/docs/user-guide/conversations.md +40 -0
  39. package/package.json +1 -1
  40. package/scripts/check-doc-links.mjs +3 -0
  41. package/scripts/check-image-tags.sh +1 -1
  42. package/scripts/check-release-consistency.test.mjs +5 -5
  43. package/scripts/e2e-console.mjs +89 -0
  44. package/scripts/generate-readme-assets.mjs +488 -7
  45. package/scripts/install.sh +1 -1
  46. package/scripts/publish-images.sh +1 -1
  47. package/scripts/release-audit.mjs +2 -0
  48. package/scripts/verify-github-repo.mjs +2 -0
  49. package/sql/057_agent_conversation_audit.sql +55 -0
  50. package/src/app/agent-conversation-audit.ts +30 -0
  51. package/src/app/oss-edition.ts +1 -0
  52. package/src/core/config/agent-direct-console-selection.test.ts +22 -0
  53. package/src/core/runtime/agent-conversation-audit.test.ts +38 -0
  54. package/src/core/runtime/agent-conversation-audit.ts +159 -0
  55. package/src/infrastructure/config/config-agent-auth-repository.test.ts +36 -0
  56. package/src/infrastructure/config/config-agent-auth-repository.ts +97 -0
  57. package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
  58. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +54 -0
  59. package/src/infrastructure/config/config-agent-conversation-audit-repository.test.ts +146 -0
  60. package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +262 -0
  61. package/src/infrastructure/config/configstore.ts +5 -0
  62. package/src/routes/admin-agent-clients.test.ts +120 -0
  63. package/src/routes/admin-agent-clients.ts +161 -0
  64. package/src/routes/admin-conversation-audit.ts +46 -0
  65. package/src/routes/admin-runtime.test.ts +38 -0
  66. package/src/routes/admin-runtime.ts +14 -3
  67. package/src/routes/admin.ts +6 -0
  68. package/src/routes/agent-api.ts +2 -0
  69. package/src/routes/agent-conversation-audit.test.ts +131 -0
  70. package/src/routes/agent-conversation-audit.ts +33 -0
  71. package/src/test-support/agent-conversation-audit-fixture.ts +123 -0
  72. package/web/console/assets/{Accounts-D4RRm5D1.js → Accounts-Ca_VnSu9.js} +1 -1
  73. package/web/console/assets/AgentClients-BPIvlLYY.js +1 -0
  74. package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
  75. package/web/console/assets/{Approvals-CsTTKb8o.js → Approvals-CMvPWacY.js} +1 -1
  76. package/web/console/assets/{Audit-BzvZ7JZw.js → Audit-CIRqOCnL.js} +1 -1
  77. package/web/console/assets/{BrandLockup-CYcA93wh.js → BrandLockup-BrytmTTH.js} +1 -1
  78. package/web/console/assets/{Channels-DRQZggqM.js → Channels-CApxH2TB.js} +1 -1
  79. package/web/console/assets/{ChatEntries-BUB7BWKU.js → ChatEntries-CJon3bWJ.js} +1 -1
  80. package/web/console/assets/Clients-BSA1rlTB.js +3 -0
  81. package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
  82. package/web/console/assets/{Cost-BZgFf1yM.js → Cost-BbhlQFP8.js} +1 -1
  83. package/web/console/assets/{Credentials-BTe2Q07j.js → Credentials-kqr1W0K7.js} +1 -1
  84. package/web/console/assets/{Diagnostics-WL-buYli.js → Diagnostics-Kljt9XTH.js} +1 -1
  85. package/web/console/assets/{Executors-CGZ-7Xmp.js → Executors-DnsB-Xz4.js} +1 -1
  86. package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
  87. package/web/console/assets/{Kb-VVw8oGsT.js → Kb-DLZSAFWP.js} +2 -2
  88. package/web/console/assets/{Login-rwvmBBPl.js → Login-DiTjPWmN.js} +1 -1
  89. package/web/console/assets/{Projects-CexaCEY1.js → Projects-CXcVCgCD.js} +1 -1
  90. package/web/console/assets/Routes-CXGl9SMM.css +1 -0
  91. package/web/console/assets/Routes-DN9_d9Po.js +124 -0
  92. package/web/console/assets/Runs-Cwbe6thL.js +3 -0
  93. package/web/console/assets/Runs-D8UmjP5G.css +1 -0
  94. package/web/console/assets/{Setup-Djh5yadQ.js → Setup-FqoCKmfZ.js} +1 -1
  95. package/web/console/assets/Shell-BEqpONiy.js +1 -0
  96. package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
  97. package/web/console/assets/{StorageBuckets-CQBR41W1.js → StorageBuckets-CkORbYXY.js} +1 -1
  98. package/web/console/assets/{SystemSettings-DgnopekD.js → SystemSettings-gTQAazu7.js} +1 -1
  99. package/web/console/assets/{SystemStatus-Bj8-kPt2.js → SystemStatus-DAmUUNqO.js} +1 -1
  100. package/web/console/assets/{Targets-BAfCt_nH.js → Targets-CZmDcjsE.js} +1 -1
  101. package/web/console/assets/{Tools-xjd0NZdE.js → Tools-CIHInlHL.js} +1 -1
  102. package/web/console/assets/index-BkLbd7Cc.js +2 -0
  103. package/web/console/assets/{index-DZEQL_yy.js → index-QnmD7N7F.js} +1 -1
  104. package/web/console/assets/{request-DkNPOweH.js → request-r7GHVJzw.js} +1 -1
  105. package/web/console/assets/{schema-CgPWAu1_.js → schema-BVn_hB7M.js} +1 -1
  106. package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
  107. package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
  108. package/web/console/assets/vendor-mammoth-BUEEDX6A.js +231 -0
  109. package/web/console/index.html +2 -2
  110. package/web-admin/package-lock.json +3 -3
  111. package/web-admin/src/agent-direct-selection.ts +21 -0
  112. package/web-admin/src/components/ClientConversations.vue +244 -0
  113. package/web-admin/src/components/conversation-audit.ts +121 -0
  114. package/web-admin/src/layout/Shell.vue +1 -1
  115. package/web-admin/src/pages/AgentClients.vue +254 -0
  116. package/web-admin/src/pages/Clients.vue +4 -2
  117. package/web-admin/src/pages/Routes.vue +54 -5
  118. package/web-admin/src/pages/Runs.vue +73 -17
  119. package/web-admin/src/router.ts +2 -0
  120. package/web-admin/tests/conversation-audit.fixture.mjs +182 -0
  121. package/web-admin/tests/conversation-audit.test.mjs +93 -0
  122. package/web/console/assets/Clients-CQ_MonGL.css +0 -1
  123. package/web/console/assets/Clients-HhCyrxfz.js +0 -3
  124. package/web/console/assets/Routes-B9ZHbQAp.js +0 -124
  125. package/web/console/assets/Routes-BbkFpi6Y.css +0 -1
  126. package/web/console/assets/Runs-4zDD9VOC.css +0 -1
  127. package/web/console/assets/Runs-BzFNPTwD.js +0 -3
  128. package/web/console/assets/Shell-BVIjmoY8.css +0 -1
  129. package/web/console/assets/Shell-kn763smL.js +0 -1
  130. package/web/console/assets/index-DfJA7iJS.js +0 -2
  131. package/web/console/assets/vendor-mammoth-DvgsHdlx.js +0 -231
@@ -0,0 +1,146 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import { ConversationAuditError, parseConversationAuditEvents } from '../../core/runtime/agent-conversation-audit';
4
+ import { conversationAuditFixture, AUDIT_SESSION_A, AUDIT_SESSION_B, AUDIT_SESSION_C, AUDIT_RUN_A, AUDIT_RUN_B } from '../../test-support/agent-conversation-audit-fixture';
5
+
6
+ const errorCode = (code: string) => (error: unknown) => error instanceof ConversationAuditError && error.code === code;
7
+ const events = () => parseConversationAuditEvents({ events: [
8
+ { event_id: 'start-1', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
9
+ { event_id: 'user-1', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'Compare Store A and Store B.\nKeep this full visible request.' },
10
+ { event_id: 'link-a', sequence: 3, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_A, member_session_id: AUDIT_SESSION_A },
11
+ { event_id: 'link-b', sequence: 4, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_B, member_session_id: AUDIT_SESSION_B },
12
+ { event_id: 'assistant-1', sequence: 5, client_turn_id: 'turn-1', kind: 'assistant_message', content: 'The complete visible answer combines both stores.' },
13
+ { event_id: 'end-1', sequence: 6, client_turn_id: 'turn-1', kind: 'turn_end', status: 'completed' },
14
+ ] });
15
+
16
+ test('a frozen group requires the own bearer of each member before accepting any body', async () => {
17
+ const fx = conversationAuditFixture();
18
+ const created = await fx.repo.create(fx.auth(), fx.input());
19
+ assert.equal(created.state, 'enrolling');
20
+ assert.equal(created.confirmed_count, 1);
21
+ assert.equal(fx.events.size, 0);
22
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_not_ready'));
23
+ await assert.rejects(fx.repo.confirm(fx.auth(AUDIT_SESSION_C), created.conversation_id), errorCode('conversation_audit_not_found'));
24
+ assert.equal(fx.members.get(`${created.conversation_id}:${AUDIT_SESSION_B}`)!.confirmed_at, null);
25
+ const confirmed = await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), created.conversation_id);
26
+ assert.equal(confirmed.state, 'ready');
27
+ assert.equal(confirmed.confirmed_count, 2);
28
+ assert.equal((await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), created.conversation_id)).confirmed_count, 2);
29
+ await assert.rejects(fx.repo.append(fx.auth(AUDIT_SESSION_B), created.conversation_id, events()), errorCode('conversation_audit_not_found'));
30
+ assert.equal(fx.events.size, 0);
31
+ });
32
+
33
+ test('archive creation is creator-scoped and frozen input is idempotent, never joined by bare conversation id', async () => {
34
+ const fx = conversationAuditFixture();
35
+ const created = await fx.repo.create(fx.auth(), fx.input());
36
+ assert.equal((await fx.repo.create(fx.auth(), fx.input())).conversation_id, created.conversation_id);
37
+ await assert.rejects(fx.repo.create(fx.auth(), fx.input({ client_conversation_id: 'another-conversation' })), errorCode('conversation_audit_conflict'));
38
+ await assert.rejects(fx.repo.create(fx.auth(), fx.input({ member_session_ids: [AUDIT_SESSION_A], member_labels: {} })), errorCode('conversation_audit_conflict'));
39
+ const anotherCreator = await fx.repo.create(fx.auth(AUDIT_SESSION_B), fx.input());
40
+ assert.notEqual(anotherCreator.conversation_id, created.conversation_id);
41
+ assert.equal(fx.archives.size, 2);
42
+ });
43
+
44
+ test('full visible events are stored once, paginated without truncation, and linked to the original authorization runs', async () => {
45
+ const fx = conversationAuditFixture();
46
+ const created = await fx.ready();
47
+ const sent = events();
48
+ assert.equal((await fx.repo.append(fx.auth(), created.conversation_id, sent)).last_sequence, 6);
49
+ assert.equal((await fx.repo.append(fx.auth(), created.conversation_id, sent)).last_sequence, 6);
50
+ assert.equal(fx.events.size, 6);
51
+ const first = (await fx.repo.detailForAdmin(created.conversation_id, 0, 2))!;
52
+ assert.equal(first.events[1].content, sent[1]!.content);
53
+ assert.equal(first.has_more, true);
54
+ assert.equal(first.next_after_sequence, 2);
55
+ assert.equal(first.conversation.message_count, 2);
56
+ assert.equal(first.conversation.turn_count, 1);
57
+ assert.equal(first.conversation.last_turn_status, 'completed');
58
+ const second = (await fx.repo.detailForAdmin(created.conversation_id, 2, 2))!;
59
+ assert.deepEqual(second.events.map((event: any) => [event.run_id, event.thread_id]), [[AUDIT_RUN_A, 101], [AUDIT_RUN_B, 102]]);
60
+ assert.deepEqual(await fx.repo.findRunLinkForAdmin(AUDIT_RUN_B), { conversation_audit_id: created.conversation_id, client_turn_id: 'turn-1' });
61
+ const final = (await fx.repo.detailForAdmin(created.conversation_id, 4, 2))!;
62
+ assert.equal(final.has_more, false);
63
+ assert.equal(final.next_after_sequence, 6);
64
+ assert.equal(first.members[0].display_label, 'Store A');
65
+ assert.doesNotMatch(JSON.stringify(first), /identity_hash|enrollment_hash|access_token|refresh_token|context_json/);
66
+ assert.equal(fx.queries.some(({ sql }) => /INSERT INTO bz_messages|UPDATE bz_threads/.test(sql)), false);
67
+ const writeIndex = fx.queries.findIndex(({ sql }) => sql.startsWith('INSERT INTO bz_agent_conversation_events'));
68
+ for (const id of [AUDIT_SESSION_A, AUDIT_SESSION_B]) assert.ok(fx.queries.slice(0, writeIndex).some(({ sql, params, transactional }) => sql.includes('FROM bz_agent_sessions') && sql.includes('FOR UPDATE') && params[0] === id && transactional));
69
+ });
70
+
71
+ test('changed retries, gaps and event-id reuse fail atomically', async () => {
72
+ const fx = conversationAuditFixture();
73
+ const created = await fx.ready();
74
+ const sent = events();
75
+ await fx.repo.append(fx.auth(), created.conversation_id, sent.slice(0, 2));
76
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[1]!, content: 'Changed original message' }]), errorCode('conversation_audit_conflict'));
77
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [sent[3]!]), errorCode('conversation_audit_conflict'));
78
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[2]!, event_id: sent[1]!.event_id }]), errorCode('conversation_audit_conflict'));
79
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [sent[2]!, { ...sent[3]!, member_session_id: AUDIT_SESSION_C }]), errorCode('conversation_audit_conflict'));
80
+ assert.equal(fx.events.size, 2, 'the valid first event in a failed batch must also roll back');
81
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 2);
82
+ });
83
+
84
+ for (const field of ['session_id', 'client_app_id', 'route_key', 'client_conversation_id', 'client_turn_id']) {
85
+ test(`run_link rejects a different ${field} instead of widening its frozen ownership`, async () => {
86
+ const fx = conversationAuditFixture();
87
+ const created = await fx.ready();
88
+ fx.runs.get(AUDIT_RUN_A)![field] = field === 'session_id' ? AUDIT_SESSION_C : 'other-binding';
89
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_conflict'));
90
+ assert.equal(fx.events.size, 0);
91
+ });
92
+ }
93
+
94
+ for (const mutation of ['revoked', 'expired', 'principal', 'subject', 'session-route', 'client-route', 'client-disabled', 'route-disabled', 'audience']) {
95
+ test(`a ${mutation} authorization change blocks all further conversation text`, async () => {
96
+ const fx = conversationAuditFixture();
97
+ const created = await fx.ready();
98
+ const member = fx.sessions.get(AUDIT_SESSION_B)!;
99
+ if (mutation === 'revoked') member.revoked_at = '2026-01-01T00:00:00Z';
100
+ if (mutation === 'expired') member.refresh_expires_at = '2000-01-01T00:00:00Z';
101
+ if (mutation === 'principal') member.principal_json.tenant = 'other-store';
102
+ if (mutation === 'subject') member.on_behalf_of = 'other-subject';
103
+ if (mutation === 'session-route') member.allowed_routes = [];
104
+ if (mutation === 'client-route') fx.client.allowed_routes = [];
105
+ if (mutation === 'client-disabled') fx.client.enabled = false;
106
+ if (mutation === 'route-disabled') fx.route.enabled = false;
107
+ if (mutation === 'audience') fx.route.audience = { enabled: true, tenants: ['store-a'] };
108
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_authorization_invalid'));
109
+ assert.equal(fx.events.size, 0);
110
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 0);
111
+ });
112
+ }
113
+
114
+ test('a single run cannot be attributed to two different complete conversation archives', async () => {
115
+ const fx = conversationAuditFixture();
116
+ const first = await fx.ready();
117
+ await fx.repo.append(fx.auth(), first.conversation_id, events());
118
+ const second = await fx.repo.create(fx.auth(), fx.input({ client_archive_id: '323e4567-e89b-42d3-a456-426614174009' }));
119
+ await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), second.conversation_id);
120
+ await assert.rejects(fx.repo.append(fx.auth(), second.conversation_id, events()), errorCode('conversation_audit_conflict'));
121
+ assert.equal(fx.archives.get(second.conversation_id)!.last_sequence, 0);
122
+ });
123
+
124
+ test('late original run evidence may follow turn_end without reopening it or altering a newer turn', async () => {
125
+ const fx = conversationAuditFixture();
126
+ const created = await fx.ready();
127
+ const sent = events();
128
+ await fx.repo.append(fx.auth(), created.conversation_id, [sent[0]!, sent[1]!, { ...sent[5]!, sequence: 3, status: 'cancelled' }]);
129
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[2]!, sequence: 4 }]);
130
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_status, 'cancelled');
131
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ event_id: 'start-2', sequence: 5, client_turn_id: 'turn-2', kind: 'turn_start' }]);
132
+ await fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[3]!, sequence: 6 }]);
133
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_id, 'turn-2');
134
+ assert.equal(fx.archives.get(created.conversation_id)!.last_turn_status, 'running');
135
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, [{ ...sent[4]!, sequence: 7 }]), errorCode('conversation_audit_conflict'));
136
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 6);
137
+ });
138
+
139
+ test('the archive total byte ceiling rejects the whole next batch instead of truncating content', async () => {
140
+ const fx = conversationAuditFixture();
141
+ const created = await fx.ready();
142
+ fx.archives.get(created.conversation_id)!.content_bytes = 16 * 1024 * 1024 - 1;
143
+ await assert.rejects(fx.repo.append(fx.auth(), created.conversation_id, events()), errorCode('conversation_audit_limit'));
144
+ assert.equal(fx.events.size, 0);
145
+ assert.equal(fx.archives.get(created.conversation_id)!.last_sequence, 0);
146
+ });
@@ -0,0 +1,262 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { dt, rowClient, rowRoute } from '../../core/config/config-codec';
3
+ import type { AgentSession, Client, Route } from '../../core/contracts/types';
4
+ import {
5
+ assertAuditMemberActive, auditError, auditHash, auditIdentityHash,
6
+ CONVERSATION_AUDIT_MAX_BYTES, CONVERSATION_AUDIT_MAX_EVENTS,
7
+ type CreateConversationAuditInput, type ConversationAuditEventInput,
8
+ } from '../../core/runtime/agent-conversation-audit';
9
+
10
+ type Auth = { session: AgentSession; client: Client };
11
+ type Row = Record<string, any>;
12
+ const SESSION_COLUMNS = 'session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,created_at,access_expires_at,refresh_expires_at,revoked_at';
13
+
14
+ function json(value: unknown): any {
15
+ return typeof value === 'string' ? JSON.parse(value) : value;
16
+ }
17
+
18
+ function iso(value: any): string {
19
+ return new Date(value).toISOString();
20
+ }
21
+
22
+ function sessionOf(row: Row): AgentSession {
23
+ return {
24
+ session_id: String(row.session_id), client_app_id: String(row.client_app_id), device_label: String(row.device_label),
25
+ principal: json(row.principal_json), on_behalf_of: String(row.on_behalf_of), allowed_routes: json(row.allowed_routes),
26
+ created_at: iso(row.created_at), access_expires_at: iso(row.access_expires_at), refresh_expires_at: iso(row.refresh_expires_at),
27
+ ...(row.revoked_at ? { revoked_at: iso(row.revoked_at) } : {}),
28
+ };
29
+ }
30
+
31
+ function head(row: Row): Row {
32
+ return {
33
+ conversation_id: row.conversation_id, client_archive_id: row.client_archive_id,
34
+ client_conversation_id: row.client_conversation_id, client_app_id: row.client_app_id, route_key: row.route_key,
35
+ state: row.state, member_count: Number(row.member_count), confirmed_count: Number(row.confirmed_count),
36
+ last_sequence: Number(row.last_sequence), message_count: Number(row.message_count), turn_count: Number(row.turn_count),
37
+ last_turn_status: row.last_turn_status ?? null, created_at: iso(row.created_at), updated_at: iso(row.updated_at),
38
+ };
39
+ }
40
+
41
+ function eventView(row: Row): Row {
42
+ return {
43
+ event_id: row.event_id, sequence: Number(row.sequence), client_turn_id: row.client_turn_id, kind: row.kind,
44
+ ...(row.content !== null && row.content !== undefined ? { content: row.content } : {}),
45
+ ...(row.run_id ? { run_id: row.run_id, member_session_id: row.member_session_id, thread_id: Number(row.thread_id) } : {}),
46
+ ...(row.status ? { status: row.status } : {}), created_at: iso(row.created_at),
47
+ };
48
+ }
49
+
50
+ /** Separate audit ledger: no conversation body is added to bz_messages or memory. */
51
+ export class AgentConversationAuditRepository {
52
+ constructor(private readonly poolOf: () => any) {}
53
+ private get pool(): any { return this.poolOf(); }
54
+
55
+ private async transaction<T>(work: (connection: any) => Promise<T>): Promise<T> {
56
+ const connection = await this.pool.getConnection();
57
+ try {
58
+ await connection.beginTransaction();
59
+ const result = await work(connection);
60
+ await connection.commit();
61
+ return result;
62
+ } catch (error) {
63
+ await connection.rollback().catch(() => undefined);
64
+ if ((error as { code?: string }).code === 'ER_DUP_ENTRY') auditError();
65
+ throw error;
66
+ } finally { connection.release(); }
67
+ }
68
+
69
+ /** Lock the authorization configuration until commit, including revoke/refresh rows. */
70
+ private async lockedBinding(connection: any, clientAppId: string, routeKey: string): Promise<{ client: Client; route: Route }> {
71
+ const [clients] = await connection.query(
72
+ 'SELECT app_id,name,agent_authorize_url,allowed_routes,allowed_channels,enabled FROM bz_clients WHERE app_id=? FOR UPDATE', [clientAppId],
73
+ );
74
+ const [routes] = await connection.query('SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE', [routeKey]);
75
+ if (!clients[0] || !routes[0]) auditError('conversation_audit_authorization_invalid', 403);
76
+ return { client: rowClient(clients[0]), route: rowRoute(routes[0]) };
77
+ }
78
+
79
+ private async lockedSession(connection: any, id: string, binding: { client: Client; route: Route }, expectedIdentity?: string): Promise<AgentSession> {
80
+ const [rows] = await connection.query(`SELECT ${SESSION_COLUMNS} FROM bz_agent_sessions WHERE session_id=? FOR UPDATE`, [id]);
81
+ if (!rows[0]) auditError('conversation_audit_authorization_invalid', 403);
82
+ const session = sessionOf(rows[0]);
83
+ assertAuditMemberActive(session, binding.client, binding.route, expectedIdentity);
84
+ return session;
85
+ }
86
+
87
+ private async lockedConversation(connection: any, id: string, auth: Auth, creatorOnly: boolean): Promise<{ row: Row; members: Row[] }> {
88
+ const [rows] = await connection.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=? FOR UPDATE', [id]);
89
+ const row = rows[0] as Row | undefined;
90
+ if (!row || row.client_app_id !== auth.client.app_id || (creatorOnly && row.creator_session_id !== auth.session.session_id)) {
91
+ auditError('conversation_audit_not_found', 404);
92
+ }
93
+ const [members] = await connection.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id FOR UPDATE', [id]);
94
+ if (!(members as Row[]).some((member) => member.session_id === auth.session.session_id)) auditError('conversation_audit_not_found', 404);
95
+ return { row, members };
96
+ }
97
+
98
+ async create(auth: Auth, input: CreateConversationAuditInput): Promise<Row> {
99
+ if (!input.member_session_ids.includes(auth.session.session_id)) auditError('conversation_audit_not_found', 404);
100
+ return this.transaction(async (connection) => {
101
+ const enrollmentHash = auditHash(input);
102
+ const at = dt();
103
+ const row = {
104
+ conversation_id: randomUUID(), creator_session_id: auth.session.session_id, client_app_id: auth.client.app_id,
105
+ route_key: input.route, client_archive_id: input.client_archive_id, client_conversation_id: input.client_conversation_id,
106
+ enrollment_hash: enrollmentHash, state: input.member_session_ids.length === 1 ? 'ready' : 'enrolling',
107
+ member_count: input.member_session_ids.length, confirmed_count: 1, last_sequence: 0, content_bytes: 0,
108
+ message_count: 0, turn_count: 0, last_turn_id: null, last_turn_status: null, created_at: at, updated_at: at,
109
+ };
110
+ // Acquire the group lock first for every mutation. The unique archive key
111
+ // also makes concurrent identical creation retryable without a second group.
112
+ await connection.query('INSERT INTO bz_agent_conversation_audits SET ? ON DUPLICATE KEY UPDATE conversation_id=conversation_id', [row]);
113
+ const [existing] = await connection.query(
114
+ 'SELECT * FROM bz_agent_conversation_audits WHERE creator_session_id=? AND route_key=? AND client_archive_id=? FOR UPDATE',
115
+ [auth.session.session_id, input.route, input.client_archive_id],
116
+ );
117
+ const stored = existing[0];
118
+ if (!stored || stored.client_app_id !== auth.client.app_id || stored.enrollment_hash !== enrollmentHash) auditError();
119
+ const binding = await this.lockedBinding(connection, auth.client.app_id, input.route);
120
+ const creator = await this.lockedSession(connection, auth.session.session_id, binding, auditIdentityHash(auth.session));
121
+ if (stored.conversation_id !== row.conversation_id) return head(stored);
122
+ for (const id of input.member_session_ids) {
123
+ const confirmed = id === creator.session_id;
124
+ await connection.query('INSERT INTO bz_agent_conversation_members SET ?', [{
125
+ conversation_id: row.conversation_id, session_id: id, display_label: input.member_labels[id] ?? id,
126
+ identity_hash: confirmed ? auditIdentityHash(creator) : null,
127
+ principal_json: confirmed ? JSON.stringify(creator.principal) : null,
128
+ on_behalf_of: confirmed ? creator.on_behalf_of : null, confirmed_at: confirmed ? at : null,
129
+ }]);
130
+ }
131
+ return head(row);
132
+ });
133
+ }
134
+
135
+ async confirm(auth: Auth, conversationId: string): Promise<Row> {
136
+ return this.transaction(async (connection) => {
137
+ const { row, members } = await this.lockedConversation(connection, conversationId, auth, false);
138
+ const binding = await this.lockedBinding(connection, row.client_app_id, row.route_key);
139
+ const member = members.find((candidate) => candidate.session_id === auth.session.session_id)!;
140
+ const session = await this.lockedSession(connection, member.session_id, binding, member.identity_hash ?? auditIdentityHash(auth.session));
141
+ if (auditIdentityHash(session) !== auditIdentityHash(auth.session)) auditError('conversation_audit_authorization_invalid', 403);
142
+ const at = dt();
143
+ if (!member.confirmed_at) {
144
+ await connection.query(
145
+ 'UPDATE bz_agent_conversation_members SET identity_hash=?,principal_json=?,on_behalf_of=?,confirmed_at=? WHERE conversation_id=? AND session_id=?',
146
+ [auditIdentityHash(session), JSON.stringify(session.principal), session.on_behalf_of, at, conversationId, session.session_id],
147
+ );
148
+ member.identity_hash = auditIdentityHash(session);
149
+ member.confirmed_at = at;
150
+ }
151
+ const confirmed = members.filter((candidate) => candidate.confirmed_at).length;
152
+ if (confirmed === members.length) {
153
+ for (const candidate of members) await this.lockedSession(connection, candidate.session_id, binding, candidate.identity_hash);
154
+ }
155
+ row.confirmed_count = confirmed;
156
+ row.state = confirmed === members.length ? 'ready' : 'enrolling';
157
+ row.updated_at = at;
158
+ await connection.query('UPDATE bz_agent_conversation_audits SET confirmed_count=?,state=?,updated_at=? WHERE conversation_id=?',
159
+ [confirmed, row.state, at, conversationId]);
160
+ return head(row);
161
+ });
162
+ }
163
+
164
+ async append(auth: Auth, conversationId: string, events: ConversationAuditEventInput[]): Promise<Row> {
165
+ return this.transaction(async (connection) => {
166
+ const { row, members } = await this.lockedConversation(connection, conversationId, auth, true);
167
+ if (row.state !== 'ready' || members.length !== Number(row.member_count) || members.some((member) => !member.confirmed_at)) {
168
+ auditError('conversation_audit_not_ready');
169
+ }
170
+ const binding = await this.lockedBinding(connection, row.client_app_id, row.route_key);
171
+ for (const member of members) {
172
+ const session = await this.lockedSession(connection, member.session_id, binding, member.identity_hash);
173
+ if (session.session_id === auth.session.session_id && auditIdentityHash(session) !== auditIdentityHash(auth.session)) {
174
+ auditError('conversation_audit_authorization_invalid', 403);
175
+ }
176
+ }
177
+ const at = dt();
178
+ for (const event of events) {
179
+ const eventHash = auditHash(event);
180
+ const [duplicates] = await connection.query(
181
+ 'SELECT sequence,event_id,event_hash FROM bz_agent_conversation_events WHERE conversation_id=? AND (sequence=? OR event_id=?)',
182
+ [conversationId, event.sequence, event.event_id],
183
+ );
184
+ if (duplicates.length) {
185
+ if (duplicates.length !== 1 || Number(duplicates[0].sequence) !== event.sequence || duplicates[0].event_id !== event.event_id || duplicates[0].event_hash !== eventHash) auditError();
186
+ continue;
187
+ }
188
+ if (event.sequence !== Number(row.last_sequence) + 1) auditError();
189
+ const contentBytes = Buffer.byteLength(event.content ?? '', 'utf8');
190
+ if (event.sequence > CONVERSATION_AUDIT_MAX_EVENTS || Number(row.content_bytes) + contentBytes > CONVERSATION_AUDIT_MAX_BYTES) auditError('conversation_audit_limit', 413);
191
+ if (event.kind === 'turn_start') {
192
+ const [started] = await connection.query("SELECT sequence FROM bz_agent_conversation_events WHERE conversation_id=? AND client_turn_id=? AND kind='turn_start' LIMIT 1", [conversationId, event.client_turn_id]);
193
+ if (row.last_turn_status === 'running' || started.length) auditError();
194
+ row.last_turn_id = event.client_turn_id;
195
+ row.last_turn_status = 'running';
196
+ row.turn_count = Number(row.turn_count) + 1;
197
+ } else if (event.kind === 'run_link') {
198
+ // A startTurn response may arrive after cancellation/end, or while the
199
+ // next turn is running. Late execution evidence belongs to its original
200
+ // started turn and must never reopen or change the current turn.
201
+ const [started] = await connection.query("SELECT sequence FROM bz_agent_conversation_events WHERE conversation_id=? AND client_turn_id=? AND kind='turn_start' LIMIT 1", [conversationId, event.client_turn_id]);
202
+ if (!started.length) auditError();
203
+ } else if (row.last_turn_status !== 'running' || row.last_turn_id !== event.client_turn_id) auditError();
204
+ let threadId: number | null = null;
205
+ if (event.kind === 'run_link') {
206
+ if (!members.some((member) => member.session_id === event.member_session_id)) auditError();
207
+ const [runs] = await connection.query(
208
+ 'SELECT run_id,session_id,client_app_id,route_key,thread_id,client_conversation_id,client_turn_id FROM bz_agent_client_runs WHERE run_id=? FOR UPDATE', [event.run_id],
209
+ );
210
+ const run = runs[0];
211
+ if (!run || run.session_id !== event.member_session_id || run.client_app_id !== row.client_app_id || run.route_key !== row.route_key ||
212
+ run.client_conversation_id !== row.client_conversation_id || run.client_turn_id !== event.client_turn_id || !Number(run.thread_id)) auditError();
213
+ threadId = Number(run.thread_id);
214
+ }
215
+ if (event.kind === 'turn_end') row.last_turn_status = event.status;
216
+ if (event.kind === 'user_message' || event.kind === 'assistant_message') row.message_count = Number(row.message_count) + 1;
217
+ await connection.query('INSERT INTO bz_agent_conversation_events SET ?', [{
218
+ conversation_id: conversationId, sequence: event.sequence, event_id: event.event_id, client_turn_id: event.client_turn_id,
219
+ kind: event.kind, content: event.content ?? null, run_id: event.run_id ?? null, member_session_id: event.member_session_id ?? null,
220
+ thread_id: threadId, status: event.status ?? null, event_hash: eventHash, created_at: at,
221
+ }]);
222
+ row.last_sequence = event.sequence;
223
+ row.content_bytes = Number(row.content_bytes) + contentBytes;
224
+ }
225
+ await connection.query(
226
+ 'UPDATE bz_agent_conversation_audits SET last_sequence=?,content_bytes=?,message_count=?,turn_count=?,last_turn_id=?,last_turn_status=?,updated_at=? WHERE conversation_id=?',
227
+ [row.last_sequence, row.content_bytes, row.message_count, row.turn_count, row.last_turn_id, row.last_turn_status, at, conversationId],
228
+ );
229
+ return { conversation_id: conversationId, last_sequence: Number(row.last_sequence) };
230
+ });
231
+ }
232
+
233
+ async listForAdmin(limit = 50, offset = 0): Promise<Row> {
234
+ const n = Math.min(Math.max(Math.floor(limit) || 50, 1), 100);
235
+ const off = Math.max(Math.floor(offset) || 0, 0);
236
+ const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits ORDER BY updated_at DESC,conversation_id DESC LIMIT ? OFFSET ?', [n + 1, off]);
237
+ const items = (rows as Row[]).slice(0, n).map(head);
238
+ return { items, has_more: rows.length > n, next_offset: rows.length > n ? off + n : null };
239
+ }
240
+
241
+ async detailForAdmin(conversationId: string, afterSequence = 0, limit = 100): Promise<Row | null> {
242
+ const [rows] = await this.pool.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=?', [conversationId]);
243
+ if (!rows[0]) return null;
244
+ const n = Math.min(Math.max(Math.floor(limit) || 100, 1), 200);
245
+ const after = Math.max(Math.floor(afterSequence) || 0, 0);
246
+ const [members] = await this.pool.query('SELECT session_id,display_label,principal_json,on_behalf_of,confirmed_at FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id', [conversationId]);
247
+ const [rowsOfEvents] = await this.pool.query('SELECT * FROM bz_agent_conversation_events WHERE conversation_id=? AND sequence>? ORDER BY sequence LIMIT ?', [conversationId, after, n + 1]);
248
+ const events = (rowsOfEvents as Row[]).slice(0, n).map(eventView);
249
+ return {
250
+ conversation: head(rows[0]), members: (members as Row[]).map((member) => ({
251
+ session_id: member.session_id, display_label: member.display_label, confirmed: Boolean(member.confirmed_at),
252
+ ...(member.confirmed_at ? { principal: json(member.principal_json), on_behalf_of: member.on_behalf_of } : {}),
253
+ })), events, has_more: rowsOfEvents.length > n,
254
+ next_after_sequence: events.length ? events.at(-1)!.sequence : after,
255
+ };
256
+ }
257
+
258
+ async findRunLinkForAdmin(runId: string): Promise<{ conversation_audit_id: string; client_turn_id: string } | null> {
259
+ const [rows] = await this.pool.query("SELECT conversation_id,client_turn_id FROM bz_agent_conversation_events WHERE run_id=? AND kind='run_link' LIMIT 1", [runId]);
260
+ return rows[0] ? { conversation_audit_id: String(rows[0].conversation_id), client_turn_id: String(rows[0].client_turn_id) } : null;
261
+ }
262
+ }
@@ -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,120 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
5
+ import type { RuntimeStateStore } from '../core/state/state-contracts';
6
+ import { handleAdminAgentClientsApiFor } from './admin-agent-clients';
7
+
8
+ class FakeResponse {
9
+ statusCode = 0;
10
+ body = Buffer.alloc(0);
11
+ headers: Record<string, string | number | string[]> = {};
12
+ setHeader(name: string, value: string | number | string[]): void { this.headers[name.toLowerCase()] = value; }
13
+ writeHead(code: number, headers?: Record<string, string | number | string[]>): void {
14
+ this.statusCode = code;
15
+ Object.assign(this.headers, headers ?? {});
16
+ }
17
+ end(value?: string | Buffer): void { this.body = value ? Buffer.from(value) : Buffer.alloc(0); }
18
+ json(): any { return JSON.parse(this.body.toString('utf8')); }
19
+ }
20
+
21
+ const SESSION_ID = '123e4567-e89b-42d3-a456-426614174000';
22
+
23
+ function fakeDeps() {
24
+ let revoked = false;
25
+ const audits: any[] = [];
26
+ const session = {
27
+ session_id: SESSION_ID,
28
+ client_app_id: 'example-business',
29
+ device_label: 'Development workstation',
30
+ principal: { id: 'user-7', tenant: 'tenant-2', roles: ['manager'] },
31
+ on_behalf_of: 'tenant-2:user-7',
32
+ allowed_routes: ['orders'],
33
+ created_at: '2026-08-27T00:00:00.000Z',
34
+ access_expires_at: '2026-08-27T01:00:00.000Z',
35
+ refresh_expires_at: '2026-09-27T00:00:00.000Z',
36
+ last_seen_at: '2026-08-27T00:10:00.000Z',
37
+ state: 'active' as const,
38
+ };
39
+ const configStore = {
40
+ clients: {
41
+ list: async () => [{
42
+ app_id: 'example-business', name: 'Example business', token: 'PRIVATE_CLIENT_TOKEN', enabled: true,
43
+ allowed_routes: ['orders'], allowed_channels: [], rate_limit_per_min: 60,
44
+ agent_authorize_url: 'https://business.example.com/agent-authorize',
45
+ }],
46
+ },
47
+ routes: {
48
+ list: async () => [
49
+ { route_key: 'orders', name: 'Order assistant', enabled: true, tools: {}, agent_client: { enabled: true } },
50
+ { route_key: 'legacy', name: 'Legacy route', enabled: true, tools: {} },
51
+ ],
52
+ },
53
+ agentAuth: {
54
+ sessionSummaryForAdmin: async () => ({ total: 1, active: 1, expired: 0, revoked: 0 }),
55
+ listSessionsForAdmin: async () => ({ list: [session], total: 1 }),
56
+ getSessionForAdmin: async (id: string) => id === SESSION_ID ? session : null,
57
+ revokeSessionForClient: async () => { revoked = true; return true; },
58
+ },
59
+ agentClientRuntime: {
60
+ statsForAdmin: async () => [{
61
+ client_app_id: 'example-business', runs: 3, conversations: 2, completed: 2, failed: 1,
62
+ tool_calls: 5, total_tokens: 1200, approvals: { approved: 1 },
63
+ }],
64
+ },
65
+ } as unknown as ConfigStoreContract;
66
+ const stateStore = {
67
+ appendAudit: async (entry: any) => { audits.push(entry); },
68
+ } as unknown as RuntimeStateStore;
69
+ return {
70
+ deps: { configStore, stateStore, now: () => '2026-08-27T00:30:00.000Z' },
71
+ audits,
72
+ wasRevoked: () => revoked,
73
+ };
74
+ }
75
+
76
+ test('智能体客户端 overview 聚合既有资源且不暴露接入方 token', async () => {
77
+ const fx = fakeDeps();
78
+ const res = new FakeResponse();
79
+ const req = { url: '/admin/api/agent-clients/overview?days=7' } as IncomingMessage;
80
+ const handled = await handleAdminAgentClientsApiFor(
81
+ fx.deps,
82
+ 'GET',
83
+ '/admin/api/agent-clients/overview',
84
+ req,
85
+ res as unknown as ServerResponse,
86
+ { kind: 'admin', via: 'session', username: 'admin', role: 'admin' },
87
+ );
88
+ assert.equal(handled, true);
89
+ assert.equal(res.statusCode, 200);
90
+ const payload = res.json();
91
+ assert.equal(payload.days, 7);
92
+ assert.equal(payload.applications[0].stats.runs, 3);
93
+ assert.deepEqual(payload.workspaces.map((item: any) => item.route), ['orders']);
94
+ assert.equal(payload.summary.sessions.active, 1);
95
+ assert.equal(payload.summary.failure_rate, 1 / 3);
96
+ assert.equal(JSON.stringify(payload).includes('PRIVATE_CLIENT_TOKEN'), false);
97
+ assert.equal(Object.hasOwn(payload.applications[0], 'token'), false);
98
+ });
99
+
100
+ test('管理员撤销 Agent Session 幂等调用受 Client 归属约束并写审计', async () => {
101
+ const fx = fakeDeps();
102
+ const res = new FakeResponse();
103
+ await handleAdminAgentClientsApiFor(
104
+ fx.deps,
105
+ 'POST',
106
+ `/admin/api/agent-clients/sessions/${SESSION_ID}/revoke`,
107
+ { url: `/admin/api/agent-clients/sessions/${SESSION_ID}/revoke` } as IncomingMessage,
108
+ res as unknown as ServerResponse,
109
+ { kind: 'admin', via: 'session', username: 'operator', role: 'admin' },
110
+ );
111
+ assert.equal(res.statusCode, 200);
112
+ assert.equal(fx.wasRevoked(), true);
113
+ assert.equal(fx.audits.length, 1);
114
+ assert.equal(fx.audits[0].event, 'agent_session_admin_revoked');
115
+ assert.deepEqual(fx.audits[0].detail, {
116
+ session_id: SESSION_ID,
117
+ client_app_id: 'example-business',
118
+ by: 'operator',
119
+ });
120
+ });