bailinghub 0.6.0 → 0.7.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 +11 -7
- package/README.md +10 -7
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +112 -1
- package/docs/AGENT_AUTH_API.md +99 -1
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +32 -5
- package/docs/AGENT_CLIENT_QUICKSTART.md +27 -4
- package/docs/AGENT_CLIENT_RUNTIME_API.md +4 -1
- package/docs/AGENT_CONVERSATION_AUDIT.en.md +109 -4
- package/docs/AGENT_CONVERSATION_AUDIT.md +84 -3
- package/docs/AGENT_SUBJECT_DISPLAY.en.md +95 -0
- package/docs/AGENT_SUBJECT_DISPLAY.md +95 -0
- package/docs/AGENT_SYSTEM_INFO.en.md +99 -0
- package/docs/AGENT_SYSTEM_INFO.md +97 -0
- package/docs/CHANGELOG.en.md +25 -2
- package/docs/CHANGELOG.md +24 -1
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
- package/docs/LOCAL_AGENT_SETUP.md +116 -0
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.md +3 -0
- package/docs/RELEASE_NOTES_v0.6.0.en.md +4 -2
- package/docs/RELEASE_NOTES_v0.6.0.md +2 -0
- package/docs/RELEASE_NOTES_v0.6.1.en.md +53 -0
- package/docs/RELEASE_NOTES_v0.6.1.md +53 -0
- package/docs/RELEASE_NOTES_v0.7.0.en.md +116 -0
- package/docs/RELEASE_NOTES_v0.7.0.md +116 -0
- package/docs/SDK.en.md +31 -0
- package/docs/user-guide/conversations.en.md +4 -2
- package/docs/user-guide/conversations.md +4 -2
- package/package.json +1 -1
- package/schemas/config/route.schema.json +15 -2
- 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/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +2 -0
- package/scripts/sdk-agent-auth-lifecycle-check.mjs +178 -0
- package/scripts/sdk-runtime-test.mjs +5 -2
- package/scripts/verify-github-repo.mjs +2 -0
- package/sdk/php/README.md +29 -0
- package/sdk/php/src/AgentAuth.php +100 -4
- package/sdk/php/src/HubClient.php +2 -1
- package/sdk/php7/README.md +31 -0
- package/sdk/php7/src/AgentAuth.php +99 -4
- package/sdk/php7/src/HubClient.php +2 -1
- package/sql/058_agent_conversation_member_bindings.sql +9 -0
- package/sql/059_agent_subject_display.sql +5 -0
- package/sql/README.en.md +15 -0
- package/sql/README.md +25 -0
- package/src/app/agent-conversation-audit.ts +20 -0
- package/src/app/agent-system-info.ts +41 -0
- package/src/app/agent-tool-invocations.ts +16 -4
- package/src/core/config/agent-setup.ts +37 -0
- package/src/core/config/client-agent-setup.ts +25 -0
- package/src/core/config/config-schema.test.ts +11 -0
- package/src/core/config/route-config.test.ts +28 -0
- package/src/core/config/route-config.ts +43 -4
- package/src/core/contracts/agent-subject-display.test.ts +19 -0
- package/src/core/contracts/agent-subject-display.ts +36 -0
- package/src/core/contracts/types.ts +15 -0
- package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
- package/src/core/runtime/agent-conversation-audit.ts +39 -0
- package/src/infrastructure/config/config-agent-auth-business-sessions.test.ts +120 -0
- package/src/infrastructure/config/config-agent-auth-lifecycle-race.test.ts +152 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +208 -18
- package/src/infrastructure/config/config-agent-conversation-audit-cross-binding.test.ts +120 -0
- package/src/infrastructure/config/config-agent-conversation-audit-repository.ts +117 -23
- package/src/infrastructure/config/config-agent-subject-display.test.ts +103 -0
- package/src/infrastructure/config/config-client-repository.ts +21 -0
- package/src/infrastructure/config/config-route-agent-setup.test.ts +59 -0
- package/src/infrastructure/config/config-route-repository.ts +24 -0
- package/src/infrastructure/config/configstore.ts +7 -3
- package/src/infrastructure/schema/core-schema-migrator.test.ts +90 -0
- package/src/routes/admin-access.ts +37 -0
- package/src/routes/admin-agent-clients.ts +11 -0
- package/src/routes/admin-agent-setup.test.ts +130 -0
- package/src/routes/admin-agent-setup.ts +68 -0
- package/src/routes/admin-client-agent-setup.test.ts +93 -0
- package/src/routes/admin-dispatch-config.ts +2 -0
- package/src/routes/agent-api.ts +7 -0
- package/src/routes/agent-auth-lifecycle-http.test.ts +177 -0
- package/src/routes/agent-auth-lifecycle.test.ts +193 -0
- package/src/routes/agent-auth.test.ts +1 -1
- package/src/routes/agent-auth.ts +206 -16
- package/src/routes/agent-conversation-audit-cross-binding-http.test.ts +122 -0
- package/src/routes/agent-conversation-audit.ts +8 -2
- package/src/routes/agent-subject-display-http.test.ts +145 -0
- package/src/routes/agent-system-info.test.ts +132 -0
- package/src/test-support/agent-auth-business-query-fixture.ts +43 -0
- package/src/test-support/agent-auth-lifecycle-fixture.ts +288 -0
- package/src/test-support/agent-conversation-audit-fixture.ts +30 -6
- package/src/test-support/agent-conversation-audit-http-fixture.ts +84 -0
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-Ca_VnSu9.js → Accounts-ChL9k-XA.js} +1 -1
- package/web/console/assets/AgentClients-Bs7UgVDj.js +1 -0
- package/web/console/assets/AgentClients-DkgPTEbq.css +1 -0
- package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-Bs6FGbp2.js} +1 -1
- package/web/console/assets/{Audit-CIRqOCnL.js → Audit-4WWYhkFM.js} +1 -1
- package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-D2GhCipL.js} +1 -1
- package/web/console/assets/{Channels-CApxH2TB.js → Channels-CmoGpiCJ.js} +1 -1
- package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-BFRMtwta.js} +1 -1
- package/web/console/assets/Clients-CSHIsaWU.css +1 -0
- package/web/console/assets/Clients-DGkkSXyA.js +3 -0
- package/web/console/assets/{Cost-BbhlQFP8.js → Cost-BmGt0MfS.js} +1 -1
- package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-CR-sYINT.js} +1 -1
- package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-DAPbKSJp.js} +1 -1
- package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CgpiT3o8.js} +1 -1
- package/web/console/assets/{Kb-DLZSAFWP.js → Kb-Cm9dVSQw.js} +1 -1
- package/web/console/assets/{Login-DiTjPWmN.js → Login-CyUcsTZ_.js} +1 -1
- package/web/console/assets/{Projects-CXcVCgCD.js → Projects-DldFPgWg.js} +1 -1
- package/web/console/assets/Routes-DkMIjMQA.css +1 -0
- package/web/console/assets/Routes-DubfjlBD.js +124 -0
- package/web/console/assets/Runs-1hxgkuR4.js +3 -0
- package/web/console/assets/Runs-CvGTV8I-.css +1 -0
- package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-DBLOnI2_.js} +1 -1
- package/web/console/assets/{Shell-BEqpONiy.js → Shell-gJ5Vz_E7.js} +1 -1
- package/web/console/assets/{StorageBuckets-CkORbYXY.js → StorageBuckets-DkDW16tj.js} +1 -1
- package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-cDkudo2y.js} +1 -1
- package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-DZd6s8OX.js} +1 -1
- package/web/console/assets/{Targets-CZmDcjsE.js → Targets-DYNGq1NU.js} +1 -1
- package/web/console/assets/{Tools-CIHInlHL.js → Tools-DpWM59vV.js} +1 -1
- package/web/console/assets/{index-BkLbd7Cc.js → index-DGqs28gI.js} +2 -2
- package/web/console/assets/{request-r7GHVJzw.js → request-B7MLvOqo.js} +1 -1
- package/web/console/assets/{schema-BVn_hB7M.js → schema-CMuwjYdJ.js} +1 -1
- package/web/console/index.html +1 -1
- package/web-admin/scripts/subject-display-ui.mjs +78 -0
- package/web-admin/src/components/AgentSetupPanel.vue +262 -0
- package/web-admin/src/components/ClientConversations.vue +21 -4
- package/web-admin/src/components/conversation-audit.ts +20 -0
- package/web-admin/src/pages/AgentClients.vue +97 -23
- package/web-admin/src/pages/Clients.vue +4 -1
- package/web-admin/src/pages/Routes.vue +10 -1
- package/web-admin/tests/conversation-audit.fixture.mjs +13 -10
- package/web-admin/tests/conversation-audit.test.mjs +63 -1
- package/web/console/assets/AgentClients-BPIvlLYY.js +0 -1
- package/web/console/assets/AgentClients-DsWADpzr.css +0 -1
- package/web/console/assets/Clients-BSA1rlTB.js +0 -3
- package/web/console/assets/Clients-CNIVs7Qn.css +0 -1
- package/web/console/assets/Routes-CXGl9SMM.css +0 -1
- package/web/console/assets/Routes-DN9_d9Po.js +0 -124
- package/web/console/assets/Runs-Cwbe6thL.js +0 -3
- package/web/console/assets/Runs-D8UmjP5G.css +0 -1
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
assertAuditMemberActive, auditError, auditHash, auditIdentityHash,
|
|
6
6
|
CONVERSATION_AUDIT_MAX_BYTES, CONVERSATION_AUDIT_MAX_EVENTS,
|
|
7
7
|
type CreateConversationAuditInput, type ConversationAuditEventInput,
|
|
8
|
+
type CreateCrossBindingConversationAuditInput,
|
|
8
9
|
} from '../../core/runtime/agent-conversation-audit';
|
|
9
10
|
|
|
10
11
|
type Auth = { session: AgentSession; client: Client };
|
|
@@ -52,6 +53,17 @@ export class AgentConversationAuditRepository {
|
|
|
52
53
|
constructor(private readonly poolOf: () => any) {}
|
|
53
54
|
private get pool(): any { return this.poolOf(); }
|
|
54
55
|
|
|
56
|
+
/** Advertise support only after the separately applied additive migration. */
|
|
57
|
+
async supportsCrossBindingMembers(): Promise<boolean> {
|
|
58
|
+
const [rows] = await this.pool.query(`SELECT TABLE_NAME AS table_name,COLUMN_NAME AS column_name
|
|
59
|
+
FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND
|
|
60
|
+
((TABLE_NAME='bz_agent_conversation_audits' AND COLUMN_NAME='membership_version') OR
|
|
61
|
+
(TABLE_NAME='bz_agent_conversation_members' AND COLUMN_NAME IN ('client_app_id','route_key','client_name')))`);
|
|
62
|
+
const present = new Set((rows as Row[]).map((row) => `${row.table_name}.${row.column_name}`));
|
|
63
|
+
return ['bz_agent_conversation_audits.membership_version', 'bz_agent_conversation_members.client_app_id',
|
|
64
|
+
'bz_agent_conversation_members.route_key', 'bz_agent_conversation_members.client_name'].every((column) => present.has(column));
|
|
65
|
+
}
|
|
66
|
+
|
|
55
67
|
private async transaction<T>(work: (connection: any) => Promise<T>): Promise<T> {
|
|
56
68
|
const connection = await this.pool.getConnection();
|
|
57
69
|
try {
|
|
@@ -68,12 +80,49 @@ export class AgentConversationAuditRepository {
|
|
|
68
80
|
|
|
69
81
|
/** Lock the authorization configuration until commit, including revoke/refresh rows. */
|
|
70
82
|
private async lockedBinding(connection: any, clientAppId: string, routeKey: string): Promise<{ client: Client; route: Route }> {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
83
|
+
return (await this.lockedBindings(connection, [{ client_app_id: clientAppId, route_key: routeKey }])).get(`${clientAppId}\0${routeKey}`)!;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private async lockedBindings(connection: any, bindings: Array<{ client_app_id: string; route_key: string }>): Promise<Map<string, { client: Client; route: Route }>> {
|
|
87
|
+
const clients = new Map<string, Client>();
|
|
88
|
+
const routes = new Map<string, Route>();
|
|
89
|
+
// All clients, then all routes, then all sessions: one order across groups,
|
|
90
|
+
// including overlapping v1 groups, instead of a per-member lock inversion.
|
|
91
|
+
for (const id of [...new Set(bindings.map((binding) => binding.client_app_id))].sort()) {
|
|
92
|
+
const [rows] = await connection.query(
|
|
93
|
+
'SELECT app_id,name,agent_authorize_url,allowed_routes,allowed_channels,enabled FROM bz_clients WHERE app_id=? FOR UPDATE', [id]);
|
|
94
|
+
if (!rows[0] || rows[0].app_id !== id) auditError('conversation_audit_authorization_invalid', 403);
|
|
95
|
+
clients.set(id, rowClient(rows[0]));
|
|
96
|
+
}
|
|
97
|
+
for (const key of [...new Set(bindings.map((binding) => binding.route_key))].sort()) {
|
|
98
|
+
const [rows] = await connection.query('SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE', [key]);
|
|
99
|
+
if (!rows[0] || rows[0].route_key !== key) auditError('conversation_audit_authorization_invalid', 403);
|
|
100
|
+
routes.set(key, rowRoute(rows[0]));
|
|
101
|
+
}
|
|
102
|
+
return new Map(bindings.map((binding) => [`${binding.client_app_id}\0${binding.route_key}`,
|
|
103
|
+
{ client: clients.get(binding.client_app_id)!, route: routes.get(binding.route_key)! }]));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private memberBinding(row: Row, member: Row): { client_app_id: string; route_key: string } {
|
|
107
|
+
if (Number(row.membership_version ?? 1) === 1) return { client_app_id: row.client_app_id, route_key: row.route_key };
|
|
108
|
+
if (Number(row.membership_version) !== 2 || typeof member.client_app_id !== 'string' || !member.client_app_id ||
|
|
109
|
+
typeof member.route_key !== 'string' || !member.route_key) auditError('conversation_audit_authorization_invalid', 403);
|
|
110
|
+
return { client_app_id: member.client_app_id, route_key: member.route_key };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
private async lockedGroup(connection: any, row: Row, members: Row[]): Promise<Map<string, { session: AgentSession; client: Client; route: Route }>> {
|
|
114
|
+
if (!members.length || members.length !== Number(row.member_count) ||
|
|
115
|
+
new Set(members.map((member) => member.session_id)).size !== members.length) auditError('conversation_audit_authorization_invalid', 403);
|
|
116
|
+
const bindings = await this.lockedBindings(connection, members.map((member) => this.memberBinding(row, member)));
|
|
117
|
+
const result = new Map<string, { session: AgentSession; client: Client; route: Route }>();
|
|
118
|
+
for (const member of [...members].sort((a, b) => a.session_id.localeCompare(b.session_id))) {
|
|
119
|
+
const identity = this.memberBinding(row, member);
|
|
120
|
+
const binding = bindings.get(`${identity.client_app_id}\0${identity.route_key}`)!;
|
|
121
|
+
if (member.confirmed_at && !member.identity_hash) auditError('conversation_audit_authorization_invalid', 403);
|
|
122
|
+
const session = await this.lockedSession(connection, member.session_id, binding, member.identity_hash ?? undefined);
|
|
123
|
+
result.set(member.session_id, { ...binding, session });
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
77
126
|
}
|
|
78
127
|
|
|
79
128
|
private async lockedSession(connection: any, id: string, binding: { client: Client; route: Route }, expectedIdentity?: string): Promise<AgentSession> {
|
|
@@ -87,14 +136,62 @@ export class AgentConversationAuditRepository {
|
|
|
87
136
|
private async lockedConversation(connection: any, id: string, auth: Auth, creatorOnly: boolean): Promise<{ row: Row; members: Row[] }> {
|
|
88
137
|
const [rows] = await connection.query('SELECT * FROM bz_agent_conversation_audits WHERE conversation_id=? FOR UPDATE', [id]);
|
|
89
138
|
const row = rows[0] as Row | undefined;
|
|
90
|
-
if (!row ||
|
|
139
|
+
if (!row || (creatorOnly && row.creator_session_id !== auth.session.session_id)) {
|
|
91
140
|
auditError('conversation_audit_not_found', 404);
|
|
92
141
|
}
|
|
93
142
|
const [members] = await connection.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id FOR UPDATE', [id]);
|
|
94
|
-
|
|
143
|
+
const member = (members as Row[]).find((candidate) => candidate.session_id === auth.session.session_id);
|
|
144
|
+
if (!member || this.memberBinding(row, member).client_app_id !== auth.client.app_id || auth.session.client_app_id !== auth.client.app_id) {
|
|
145
|
+
auditError('conversation_audit_not_found', 404);
|
|
146
|
+
}
|
|
95
147
|
return { row, members };
|
|
96
148
|
}
|
|
97
149
|
|
|
150
|
+
async createCrossBinding(auth: Auth, input: CreateCrossBindingConversationAuditInput): Promise<Row> {
|
|
151
|
+
if (!await this.supportsCrossBindingMembers()) auditError('conversation_audit_cross_binding_unavailable', 503);
|
|
152
|
+
const creatorMember = input.members.find((member) => member.session_id === auth.session.session_id);
|
|
153
|
+
if (!creatorMember || creatorMember.client_app_id !== auth.client.app_id) auditError('conversation_audit_not_found', 404);
|
|
154
|
+
return this.transaction(async (connection) => {
|
|
155
|
+
const at = dt();
|
|
156
|
+
const enrollmentHash = auditHash(input);
|
|
157
|
+
const row: Row = {
|
|
158
|
+
conversation_id: randomUUID(), creator_session_id: auth.session.session_id, client_app_id: auth.client.app_id,
|
|
159
|
+
route_key: creatorMember.route, membership_version: 2,
|
|
160
|
+
client_archive_id: input.client_archive_id, client_conversation_id: input.client_conversation_id,
|
|
161
|
+
enrollment_hash: enrollmentHash, state: input.members.length === 1 ? 'ready' : 'enrolling',
|
|
162
|
+
member_count: input.members.length, confirmed_count: 1, last_sequence: 0, content_bytes: 0,
|
|
163
|
+
message_count: 0, turn_count: 0, last_turn_id: null, last_turn_status: null, created_at: at, updated_at: at,
|
|
164
|
+
};
|
|
165
|
+
await connection.query('INSERT INTO bz_agent_conversation_audits SET ? ON DUPLICATE KEY UPDATE conversation_id=conversation_id', [row]);
|
|
166
|
+
const [existing] = await connection.query(
|
|
167
|
+
'SELECT * FROM bz_agent_conversation_audits WHERE creator_session_id=? AND route_key=? AND client_archive_id=? FOR UPDATE',
|
|
168
|
+
[auth.session.session_id, creatorMember.route, input.client_archive_id]);
|
|
169
|
+
const stored = existing[0];
|
|
170
|
+
if (!stored || stored.client_app_id !== auth.client.app_id || stored.enrollment_hash !== enrollmentHash || Number(stored.membership_version) !== 2) auditError();
|
|
171
|
+
let members: Row[] = input.members.map((member) => ({
|
|
172
|
+
session_id: member.session_id, client_app_id: member.client_app_id, route_key: member.route,
|
|
173
|
+
display_label: member.label ?? member.session_id,
|
|
174
|
+
}));
|
|
175
|
+
if (stored.conversation_id !== row.conversation_id) {
|
|
176
|
+
[members] = await connection.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id FOR UPDATE', [stored.conversation_id]);
|
|
177
|
+
}
|
|
178
|
+
const group = await this.lockedGroup(connection, stored, members);
|
|
179
|
+
const creator = group.get(auth.session.session_id)!.session;
|
|
180
|
+
if (auditIdentityHash(creator) !== auditIdentityHash(auth.session)) auditError('conversation_audit_authorization_invalid', 403);
|
|
181
|
+
if (stored.conversation_id !== row.conversation_id) return head(stored);
|
|
182
|
+
for (const member of members) {
|
|
183
|
+
const confirmed = member.session_id === creator.session_id;
|
|
184
|
+
await connection.query('INSERT INTO bz_agent_conversation_members SET ?', [{
|
|
185
|
+
conversation_id: row.conversation_id, ...member, client_name: group.get(member.session_id)!.client.name,
|
|
186
|
+
identity_hash: confirmed ? auditIdentityHash(creator) : null,
|
|
187
|
+
principal_json: confirmed ? JSON.stringify(creator.principal) : null,
|
|
188
|
+
on_behalf_of: confirmed ? creator.on_behalf_of : null, confirmed_at: confirmed ? at : null,
|
|
189
|
+
}]);
|
|
190
|
+
}
|
|
191
|
+
return head(row);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
98
195
|
async create(auth: Auth, input: CreateConversationAuditInput): Promise<Row> {
|
|
99
196
|
if (!input.member_session_ids.includes(auth.session.session_id)) auditError('conversation_audit_not_found', 404);
|
|
100
197
|
return this.transaction(async (connection) => {
|
|
@@ -135,9 +232,9 @@ export class AgentConversationAuditRepository {
|
|
|
135
232
|
async confirm(auth: Auth, conversationId: string): Promise<Row> {
|
|
136
233
|
return this.transaction(async (connection) => {
|
|
137
234
|
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
235
|
const member = members.find((candidate) => candidate.session_id === auth.session.session_id)!;
|
|
140
|
-
const
|
|
236
|
+
const group = await this.lockedGroup(connection, row, members);
|
|
237
|
+
const session = group.get(member.session_id)!.session;
|
|
141
238
|
if (auditIdentityHash(session) !== auditIdentityHash(auth.session)) auditError('conversation_audit_authorization_invalid', 403);
|
|
142
239
|
const at = dt();
|
|
143
240
|
if (!member.confirmed_at) {
|
|
@@ -149,9 +246,6 @@ export class AgentConversationAuditRepository {
|
|
|
149
246
|
member.confirmed_at = at;
|
|
150
247
|
}
|
|
151
248
|
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
249
|
row.confirmed_count = confirmed;
|
|
156
250
|
row.state = confirmed === members.length ? 'ready' : 'enrolling';
|
|
157
251
|
row.updated_at = at;
|
|
@@ -167,13 +261,8 @@ export class AgentConversationAuditRepository {
|
|
|
167
261
|
if (row.state !== 'ready' || members.length !== Number(row.member_count) || members.some((member) => !member.confirmed_at)) {
|
|
168
262
|
auditError('conversation_audit_not_ready');
|
|
169
263
|
}
|
|
170
|
-
const
|
|
171
|
-
|
|
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
|
-
}
|
|
264
|
+
const group = await this.lockedGroup(connection, row, members);
|
|
265
|
+
if (auditIdentityHash(group.get(auth.session.session_id)!.session) !== auditIdentityHash(auth.session)) auditError('conversation_audit_authorization_invalid', 403);
|
|
177
266
|
const at = dt();
|
|
178
267
|
for (const event of events) {
|
|
179
268
|
const eventHash = auditHash(event);
|
|
@@ -203,12 +292,14 @@ export class AgentConversationAuditRepository {
|
|
|
203
292
|
} else if (row.last_turn_status !== 'running' || row.last_turn_id !== event.client_turn_id) auditError();
|
|
204
293
|
let threadId: number | null = null;
|
|
205
294
|
if (event.kind === 'run_link') {
|
|
206
|
-
|
|
295
|
+
const member = members.find((candidate) => candidate.session_id === event.member_session_id);
|
|
296
|
+
if (!member) auditError();
|
|
297
|
+
const binding = this.memberBinding(row, member);
|
|
207
298
|
const [runs] = await connection.query(
|
|
208
299
|
'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
300
|
);
|
|
210
301
|
const run = runs[0];
|
|
211
|
-
if (!run || run.session_id !== event.member_session_id || run.client_app_id !==
|
|
302
|
+
if (!run || run.session_id !== event.member_session_id || run.client_app_id !== binding.client_app_id || run.route_key !== binding.route_key ||
|
|
212
303
|
run.client_conversation_id !== row.client_conversation_id || run.client_turn_id !== event.client_turn_id || !Number(run.thread_id)) auditError();
|
|
213
304
|
threadId = Number(run.thread_id);
|
|
214
305
|
}
|
|
@@ -243,12 +334,15 @@ export class AgentConversationAuditRepository {
|
|
|
243
334
|
if (!rows[0]) return null;
|
|
244
335
|
const n = Math.min(Math.max(Math.floor(limit) || 100, 1), 200);
|
|
245
336
|
const after = Math.max(Math.floor(afterSequence) || 0, 0);
|
|
246
|
-
const [members] = await this.pool.query('SELECT
|
|
337
|
+
const [members] = await this.pool.query('SELECT * FROM bz_agent_conversation_members WHERE conversation_id=? ORDER BY session_id', [conversationId]);
|
|
247
338
|
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
339
|
const events = (rowsOfEvents as Row[]).slice(0, n).map(eventView);
|
|
249
340
|
return {
|
|
250
341
|
conversation: head(rows[0]), members: (members as Row[]).map((member) => ({
|
|
251
342
|
session_id: member.session_id, display_label: member.display_label, confirmed: Boolean(member.confirmed_at),
|
|
343
|
+
...(Number(rows[0].membership_version) === 2 ? {
|
|
344
|
+
client_app_id: member.client_app_id, client_name: member.client_name, route_key: member.route_key,
|
|
345
|
+
} : {}),
|
|
252
346
|
...(member.confirmed_at ? { principal: json(member.principal_json), on_behalf_of: member.on_behalf_of } : {}),
|
|
253
347
|
})), events, has_more: rowsOfEvents.length > n,
|
|
254
348
|
next_after_sequence: events.length ? events.at(-1)!.sequence : after,
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { APP, AUTH, SESSION, OTHER_SESSION, FUTURE, LedgerFixture } from '../../test-support/agent-auth-lifecycle-fixture';
|
|
4
|
+
|
|
5
|
+
function withoutDisplay(row: Record<string, unknown>) {
|
|
6
|
+
const copy = structuredClone(row); delete copy.subject_display; delete copy.updated_at; return copy;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
async function fixture() {
|
|
10
|
+
const f = new LedgerFixture();
|
|
11
|
+
const approved = await f.repository.approveAuthorization({ authorizationId: AUTH, clientAppId: APP,
|
|
12
|
+
principal: { id: 'operator-a', tenant: 'account-a', roles: ['manager'] }, onBehalfOf: 'account-a:operator-a',
|
|
13
|
+
allowedRoutes: ['shop'], codeHash: 'synthetic-code-hash', codeExpiresAt: FUTURE, subjectDisplay: { name: 'Account A' } });
|
|
14
|
+
assert.equal(approved.ok, true);
|
|
15
|
+
assert.equal((await f.exchange()).ok, true);
|
|
16
|
+
return f;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
test('subject name survives authorization, exchange, refresh, rename and clear without changing identity', async () => {
|
|
20
|
+
const f = await fixture();
|
|
21
|
+
assert.deepEqual((await f.repository.getAuthorization(AUTH))?.subject_display, { name: 'Account A' });
|
|
22
|
+
assert.deepEqual((await f.repository.getSessionByAccessHash('access-original'))?.subject_display, { name: 'Account A' });
|
|
23
|
+
const original = structuredClone(f.rows.session.get(SESSION)!);
|
|
24
|
+
const originalTokens = structuredClone([...f.rows.token.entries()]);
|
|
25
|
+
const renamed = await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Account North' } });
|
|
26
|
+
assert.equal(renamed.ok, true);
|
|
27
|
+
if (renamed.ok) {
|
|
28
|
+
assert.deepEqual(renamed.session.subject_display, { name: 'Account North' });
|
|
29
|
+
assert.equal(renamed.session.authorization_id, AUTH);
|
|
30
|
+
}
|
|
31
|
+
assert.deepEqual(withoutDisplay(f.rows.session.get(SESSION)!), withoutDisplay(original));
|
|
32
|
+
assert.deepEqual([...f.rows.token.entries()], originalTokens);
|
|
33
|
+
assert.deepEqual((await f.repository.getAuthorization(AUTH))?.subject_display, { name: 'Account A' }, 'approval-time metadata remains a snapshot');
|
|
34
|
+
const rotated = await f.rotate();
|
|
35
|
+
assert.equal(rotated.ok, true);
|
|
36
|
+
if (rotated.ok) assert.deepEqual(rotated.session.subject_display, { name: 'Account North' });
|
|
37
|
+
const clear = await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: null });
|
|
38
|
+
assert.equal(clear.ok, true);
|
|
39
|
+
if (clear.ok) assert.equal(clear.session.subject_display, null);
|
|
40
|
+
assert.equal(f.rows.session.size, 1);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('same display names stay separate and cross-client/inactive updates fail without mutations', async () => {
|
|
44
|
+
const f = await fixture();
|
|
45
|
+
const original = structuredClone(f.rows.session.get(SESSION)!);
|
|
46
|
+
f.rows.session.set(OTHER_SESSION, { ...original, session_id: OTHER_SESSION, on_behalf_of: 'account-b:operator-b' });
|
|
47
|
+
assert.equal((await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: OTHER_SESSION, subjectDisplay: { name: 'Account A' } })).ok, true);
|
|
48
|
+
assert.equal(f.rows.session.size, 2);
|
|
49
|
+
assert.equal(f.rows.session.get(SESSION)!.on_behalf_of, original.on_behalf_of);
|
|
50
|
+
assert.equal(f.rows.session.get(OTHER_SESSION)!.on_behalf_of, 'account-b:operator-b');
|
|
51
|
+
assert.deepEqual(await f.repository.updateSubjectDisplay({ clientAppId: 'other-client', sessionId: SESSION, subjectDisplay: { name: 'Wrong' } }), { ok: false, reason: 'not_found' });
|
|
52
|
+
for (const patch of [{ refresh_expires_at: '2000-01-01 00:00:00' }, { revoked_at: '2026-01-01 00:00:00' }]) {
|
|
53
|
+
f.rows.session.set(SESSION, { ...original, ...patch });
|
|
54
|
+
const before = structuredClone(f.rows.session.get(SESSION));
|
|
55
|
+
assert.deepEqual(await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Wrong' } }), { ok: false, reason: 'inactive' });
|
|
56
|
+
assert.deepEqual(f.rows.session.get(SESSION), before);
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('old unnamed Session can be backfilled without changing original credentials', async () => {
|
|
61
|
+
const f = new LedgerFixture(); await f.approve(); await f.exchange();
|
|
62
|
+
const original = structuredClone(f.rows.session.get(SESSION)!);
|
|
63
|
+
assert.equal((await f.repository.getSessionByAccessHash('access-original'))?.subject_display, null);
|
|
64
|
+
await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Workspace A' } });
|
|
65
|
+
assert.deepEqual(withoutDisplay(f.rows.session.get(SESSION)!), withoutDisplay(original));
|
|
66
|
+
assert.deepEqual((await f.repository.getSessionByAccessHash('access-original'))?.subject_display, { name: 'Workspace A' });
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('display write/commit failures roll back and a same-value retry does not rotate a Session', async () => {
|
|
70
|
+
const f = await fixture(); const original = structuredClone(f.rows.session.get(SESSION));
|
|
71
|
+
for (const failure of ['query', 'commit']) {
|
|
72
|
+
if (failure === 'query') f.failNext('SET subject_display='); else f.failNextCommit();
|
|
73
|
+
await assert.rejects(() => f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Updated' } }));
|
|
74
|
+
assert.deepEqual(f.rows.session.get(SESSION), original);
|
|
75
|
+
}
|
|
76
|
+
for (let i = 0; i < 2; i++) assert.equal((await f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Updated' } })).ok, true);
|
|
77
|
+
assert.equal(f.rows.session.size, 1); assert.equal(f.rows.token.size, 1);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('revocation wins over a waiting display update and cannot be undone by a name', async () => {
|
|
81
|
+
const f = await fixture();
|
|
82
|
+
const held = f.holdNextLock('session', SESSION);
|
|
83
|
+
const revoke = f.repository.revokeSessionForClient(APP, SESSION);
|
|
84
|
+
await held.arrived;
|
|
85
|
+
const blocked = f.waitForBlocked('session', SESSION);
|
|
86
|
+
const update = f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Updated' } });
|
|
87
|
+
await blocked; held.release();
|
|
88
|
+
assert.equal(await revoke, true);
|
|
89
|
+
assert.deepEqual(await update, { ok: false, reason: 'inactive' });
|
|
90
|
+
assert.deepEqual(JSON.parse(f.rows.session.get(SESSION)!.subject_display), { name: 'Account A' });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('concurrent refresh and display update preserve both independent changes', async () => {
|
|
94
|
+
const f = await fixture();
|
|
95
|
+
const held = f.holdNextLock('session', SESSION);
|
|
96
|
+
const refresh = f.rotate(); await held.arrived;
|
|
97
|
+
const blocked = f.waitForBlocked('session', SESSION);
|
|
98
|
+
const update = f.repository.updateSubjectDisplay({ clientAppId: APP, sessionId: SESSION, subjectDisplay: { name: 'Updated' } });
|
|
99
|
+
await blocked; held.release();
|
|
100
|
+
assert.equal((await refresh).ok, true); assert.equal((await update).ok, true);
|
|
101
|
+
const current = await f.repository.getSessionByAccessHash('access-next');
|
|
102
|
+
assert.equal(current?.session_id, SESSION); assert.deepEqual(current?.subject_display, { name: 'Updated' });
|
|
103
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
2
|
import { dt, rowClient } from '../../core/config/config-codec';
|
|
3
3
|
import type { Client } from '../../core/contracts/types';
|
|
4
|
+
import { clientAgentSetupRevision, type ClientAgentSetup } from '../../core/config/client-agent-setup';
|
|
4
5
|
|
|
5
6
|
export class ClientRepository {
|
|
6
7
|
constructor(private readonly poolOf: () => any) {}
|
|
@@ -23,6 +24,26 @@ export class ClientRepository {
|
|
|
23
24
|
return rows[0] ? rowClient(rows[0]) : null;
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
/** Narrow, optimistic update; unrelated settings and the current token are untouched. */
|
|
28
|
+
async updateAgentSetup(appId: string, expectedRevision: string, settings: ClientAgentSetup): Promise<'updated' | 'conflict' | 'not_found'> {
|
|
29
|
+
const connection = await this.pool.getConnection();
|
|
30
|
+
try {
|
|
31
|
+
await connection.beginTransaction();
|
|
32
|
+
const [rows] = await connection.query('SELECT * FROM bz_clients WHERE app_id=? LIMIT 1 FOR UPDATE', [appId]);
|
|
33
|
+
if (!rows[0]) { await connection.rollback(); return 'not_found'; }
|
|
34
|
+
if (clientAgentSetupRevision(rowClient(rows[0])) !== expectedRevision) { await connection.rollback(); return 'conflict'; }
|
|
35
|
+
await connection.query(
|
|
36
|
+
'UPDATE bz_clients SET enabled=?,agent_authorize_url=?,allowed_routes=?,updated_at=? WHERE app_id=?',
|
|
37
|
+
[settings.enabled ? 1 : 0, settings.agent_authorize_url || null, JSON.stringify(settings.allowed_routes), dt(), appId],
|
|
38
|
+
);
|
|
39
|
+
await connection.commit();
|
|
40
|
+
return 'updated';
|
|
41
|
+
} catch (error) {
|
|
42
|
+
await connection.rollback();
|
|
43
|
+
throw error;
|
|
44
|
+
} finally { connection.release(); }
|
|
45
|
+
}
|
|
46
|
+
|
|
26
47
|
async upsert(c: Omit<Client, 'token'>, rotateToken = false): Promise<string> {
|
|
27
48
|
const existing = await this.get(c.app_id);
|
|
28
49
|
const token = !existing || rotateToken ? randomBytes(16).toString('hex') : existing.token;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { RouteRepository } from './config-route-repository';
|
|
4
|
+
import { agentSetupRevision } from '../../core/config/agent-setup';
|
|
5
|
+
import { rowRoute } from '../../core/config/config-codec';
|
|
6
|
+
|
|
7
|
+
function fixture() {
|
|
8
|
+
let row: Record<string, unknown> | null = {
|
|
9
|
+
route_key: 'helpdesk', name: 'Helpdesk', enabled: 1, target: 'notify', target_config: JSON.stringify({ private_setting: 'keep' }),
|
|
10
|
+
profile: 'general', permission: 'readonly', session_policy: 'new', memory: JSON.stringify({ recent_messages: 10 }),
|
|
11
|
+
agent_client: JSON.stringify({ enabled: false }), tools: JSON.stringify({ max_calls: 3 }),
|
|
12
|
+
};
|
|
13
|
+
const events: string[] = [];
|
|
14
|
+
let failUpdate = false;
|
|
15
|
+
const connection = {
|
|
16
|
+
beginTransaction: async () => { events.push('begin'); },
|
|
17
|
+
query: async (sql: string, args: unknown[]) => {
|
|
18
|
+
events.push(sql);
|
|
19
|
+
if (sql === 'SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE') return [[row ? structuredClone(row) : undefined].filter(Boolean)];
|
|
20
|
+
assert.equal(sql, 'UPDATE bz_routes SET agent_client=?,tools=?,updated_at=? WHERE route_key=?');
|
|
21
|
+
if (failUpdate) throw new Error('synthetic storage error');
|
|
22
|
+
assert.equal(args[3], 'helpdesk');
|
|
23
|
+
row = { ...row, agent_client: args[0], tools: args[1], updated_at: args[2] };
|
|
24
|
+
return [{ affectedRows: 1 }];
|
|
25
|
+
},
|
|
26
|
+
commit: async () => { events.push('commit'); }, rollback: async () => { events.push('rollback'); }, release: () => { events.push('release'); },
|
|
27
|
+
};
|
|
28
|
+
return { repository: new RouteRepository(() => ({ getConnection: async () => connection })), events,
|
|
29
|
+
row: () => row, missing: () => { row = null; }, fail: () => { failUpdate = true; } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test('Agent setup repository compares under lock and updates only the intended columns', async () => {
|
|
33
|
+
const f = fixture();
|
|
34
|
+
const before = structuredClone(f.row()!);
|
|
35
|
+
const revision = agentSetupRevision(rowRoute(before));
|
|
36
|
+
const result = await f.repository.compareAndSetAgentSetup('helpdesk', revision, { agent_client: { enabled: true }, tools: { max_calls: 3, agent_direct: { enabled: true } } });
|
|
37
|
+
assert.equal(result.status, 'updated');
|
|
38
|
+
const { agent_client: _agent, tools: _tools, updated_at: _updated, ...rest } = f.row()!;
|
|
39
|
+
const { agent_client: _oldAgent, tools: _oldTools, ...oldRest } = before;
|
|
40
|
+
assert.deepEqual(rest, oldRest);
|
|
41
|
+
assert.equal(f.events[0], 'begin');
|
|
42
|
+
assert.equal(f.events[1], 'SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE');
|
|
43
|
+
assert.deepEqual(f.events.slice(-2), ['commit', 'release']);
|
|
44
|
+
const stale = await f.repository.compareAndSetAgentSetup('helpdesk', revision, { agent_client: {}, tools: {} });
|
|
45
|
+
assert.equal(stale.status, 'conflict');
|
|
46
|
+
assert.deepEqual(f.events.slice(-2), ['rollback', 'release']);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('Agent setup repository releases its lock on missing route and update failure', async () => {
|
|
50
|
+
for (const failure of ['missing', 'storage'] as const) {
|
|
51
|
+
const f = fixture();
|
|
52
|
+
const revision = agentSetupRevision(rowRoute(f.row()!));
|
|
53
|
+
if (failure === 'missing') f.missing(); else f.fail();
|
|
54
|
+
const promise = f.repository.compareAndSetAgentSetup('helpdesk', revision, { agent_client: undefined, tools: undefined });
|
|
55
|
+
if (failure === 'missing') assert.equal((await promise).status, 'not_found');
|
|
56
|
+
else await assert.rejects(promise, /synthetic storage error/);
|
|
57
|
+
assert.deepEqual(f.events.slice(-2), ['rollback', 'release']);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { dt, rowRoute } from '../../core/config/config-codec';
|
|
2
2
|
import type { Route } from '../../core/contracts/types';
|
|
3
|
+
import { agentSetupRevision, type AgentSetupUpdate, type AgentSetupUpdateResult } from '../../core/config/agent-setup';
|
|
3
4
|
|
|
4
5
|
export class RouteRepository {
|
|
5
6
|
constructor(private readonly poolOf: () => any) {}
|
|
@@ -20,6 +21,29 @@ export class RouteRepository {
|
|
|
20
21
|
await this.write(r, true);
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
/** Lock, compare and update only Agent setup; never overwrite unrelated route configuration. */
|
|
25
|
+
async compareAndSetAgentSetup(key: string, expectedRevision: string, update: AgentSetupUpdate): Promise<AgentSetupUpdateResult> {
|
|
26
|
+
const connection = await this.pool.getConnection();
|
|
27
|
+
try {
|
|
28
|
+
await connection.beginTransaction();
|
|
29
|
+
const [rows] = await connection.query('SELECT * FROM bz_routes WHERE route_key=? FOR UPDATE', [key]);
|
|
30
|
+
if (!rows[0]) { await connection.rollback(); return { status: 'not_found' }; }
|
|
31
|
+
const route = rowRoute(rows[0]);
|
|
32
|
+
if (agentSetupRevision(route) !== expectedRevision) { await connection.rollback(); return { status: 'conflict' }; }
|
|
33
|
+
const encode = (value: object | undefined) => value && Object.keys(value).length ? JSON.stringify(value) : null;
|
|
34
|
+
await connection.query('UPDATE bz_routes SET agent_client=?,tools=?,updated_at=? WHERE route_key=?', [
|
|
35
|
+
encode(update.agent_client), encode(update.tools), dt(), key,
|
|
36
|
+
]);
|
|
37
|
+
await connection.commit();
|
|
38
|
+
return { status: 'updated', route: { ...route, agent_client: update.agent_client, tools: update.tools } };
|
|
39
|
+
} catch (error) {
|
|
40
|
+
await connection.rollback();
|
|
41
|
+
throw error;
|
|
42
|
+
} finally {
|
|
43
|
+
connection.release();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
23
47
|
/** Insert-only variant for ownership-sensitive bootstrap flows. */
|
|
24
48
|
async create(r: Route): Promise<void> {
|
|
25
49
|
await this.write(r, false);
|
|
@@ -29,8 +29,10 @@ import { AgentClientRuntimeRepository } from './config-agent-client-runtime-repo
|
|
|
29
29
|
import { AgentConversationAuditRepository } from './config-agent-conversation-audit-repository';
|
|
30
30
|
import { MysqlPoolOwner, type MysqlPoolResource } from '../mysql/pool-owner';
|
|
31
31
|
|
|
32
|
-
export type RouteRepositoryContract = Pick<RouteRepository, keyof RouteRepository
|
|
33
|
-
|
|
32
|
+
export type RouteRepositoryContract = Omit<Pick<RouteRepository, keyof RouteRepository>, 'compareAndSetAgentSetup'>
|
|
33
|
+
& Partial<Pick<RouteRepository, 'compareAndSetAgentSetup'>>;
|
|
34
|
+
export type ClientRepositoryContract = Omit<Pick<ClientRepository, keyof ClientRepository>, 'updateAgentSetup'>
|
|
35
|
+
& Partial<Pick<ClientRepository, 'updateAgentSetup'>>;
|
|
34
36
|
export type CredentialRepositoryContract = Pick<CredentialRepository, keyof CredentialRepository>;
|
|
35
37
|
export type ChannelRepositoryContract = Pick<ChannelRepository, keyof ChannelRepository>;
|
|
36
38
|
/** 新增的探针窄更新对旧扩展仓储保持可选;运行时可回退到既有 upsert。 */
|
|
@@ -61,7 +63,9 @@ export type ObservabilityLedgerContract =
|
|
|
61
63
|
Omit<Pick<ObservabilityLedger, keyof ObservabilityLedger>, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>
|
|
62
64
|
& Partial<Pick<ObservabilityLedger, 'operationalMetricsSnapshot' | 'agentToolJobCandidatesForRun' | 'auditsForJobs'>>;
|
|
63
65
|
export type AgentClientRuntimeRepositoryContract = Pick<AgentClientRuntimeRepository, keyof AgentClientRuntimeRepository>;
|
|
64
|
-
|
|
66
|
+
// Existing private hosts may retain their v1 adapter without implementing v2.
|
|
67
|
+
export type AgentConversationAuditRepositoryContract = Omit<Pick<AgentConversationAuditRepository, keyof AgentConversationAuditRepository>, 'createCrossBinding' | 'supportsCrossBindingMembers'>
|
|
68
|
+
& Partial<Pick<AgentConversationAuditRepository, 'createCrossBinding' | 'supportsCrossBindingMembers'>>;
|
|
65
69
|
|
|
66
70
|
export interface ConfigStoreContract {
|
|
67
71
|
readonly routes: RouteRepositoryContract;
|
|
@@ -199,6 +199,96 @@ test('Core Schema Migrator: 同名列结构冲突时不容忍、不记账', asyn
|
|
|
199
199
|
assert.equal(connection.ledger.has('003_executor.sql'), false);
|
|
200
200
|
});
|
|
201
201
|
|
|
202
|
+
test('Core Schema Migrator: 058 upgrades a 057 ledger additively and is idempotent for private Hosts', async () => {
|
|
203
|
+
const connection = new FakeMigrationConnection();
|
|
204
|
+
seedLedgerWithCurrentChecksums(connection);
|
|
205
|
+
connection.ledger.delete('058_agent_conversation_member_bindings.sql');
|
|
206
|
+
const original057 = connection.ledger.get('057_agent_conversation_audit.sql');
|
|
207
|
+
const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
208
|
+
assert.deepEqual(result.appliedFiles, ['058_agent_conversation_member_bindings.sql']);
|
|
209
|
+
assert.equal(connection.migrationStatements.length, 4);
|
|
210
|
+
for (const sql of connection.migrationStatements) {
|
|
211
|
+
assert.match(sql, /^ALTER TABLE `bz_agent_conversation_(audits|members)` ADD COLUMN /);
|
|
212
|
+
assert.match(sql, / DEFAULT /);
|
|
213
|
+
assert.doesNotMatch(sql, /\b(?:UPDATE|DELETE|DROP|MODIFY|RENAME)\b/i);
|
|
214
|
+
}
|
|
215
|
+
assert.equal(connection.ledger.get('057_agent_conversation_audit.sql'), original057);
|
|
216
|
+
const rerun = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
217
|
+
assert.deepEqual(rerun.appliedFiles, []);
|
|
218
|
+
assert.equal(connection.migrationStatements.length, 4);
|
|
219
|
+
assert.equal(connection.ends, 0, 'the private Host retains ownership of its injected connection');
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('Core Schema Migrator: a partial 058 replay verifies actual column definitions before recording success', async () => {
|
|
223
|
+
const migration = '058_agent_conversation_member_bindings.sql';
|
|
224
|
+
for (const conflicting of [false, true]) {
|
|
225
|
+
const connection = new FakeMigrationConnection();
|
|
226
|
+
seedLedgerWithCurrentChecksums(connection);
|
|
227
|
+
connection.ledger.delete(migration);
|
|
228
|
+
connection.statementFaults = [
|
|
229
|
+
{ pattern: /ADD COLUMN `membership_version`/, errno: 1060 },
|
|
230
|
+
{ pattern: /ADD COLUMN `client_app_id`/, errno: 1060 },
|
|
231
|
+
];
|
|
232
|
+
connection.fullColumns.set('bz_agent_conversation_audits', [
|
|
233
|
+
{ Field: 'membership_version', Type: 'tinyint unsigned', Null: 'NO', Default: '1' },
|
|
234
|
+
]);
|
|
235
|
+
connection.fullColumns.set('bz_agent_conversation_members', [
|
|
236
|
+
{ Field: 'client_app_id', Type: conflicting ? 'varchar(32)' : 'varchar(64)', Null: 'YES', Default: null },
|
|
237
|
+
]);
|
|
238
|
+
if (conflicting) {
|
|
239
|
+
await assert.rejects(migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection }), /058_agent_conversation_member_bindings\.sql 执行失败/);
|
|
240
|
+
assert.equal(connection.ledger.has(migration), false);
|
|
241
|
+
} else {
|
|
242
|
+
const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
243
|
+
assert.deepEqual(result.appliedFiles, [migration]);
|
|
244
|
+
assert.equal(result.toleratedStatements, 2);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test('Core Schema Migrator: 059 adds only nullable display columns, preserves the ledger and skips replay', async () => {
|
|
250
|
+
const connection = new FakeMigrationConnection();
|
|
251
|
+
seedLedgerWithCurrentChecksums(connection);
|
|
252
|
+
const migration = '059_agent_subject_display.sql';
|
|
253
|
+
connection.ledger.delete(migration);
|
|
254
|
+
const prior = new Map(connection.ledger);
|
|
255
|
+
const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
256
|
+
assert.deepEqual(result.appliedFiles, [migration]);
|
|
257
|
+
assert.equal(connection.migrationStatements.length, 2);
|
|
258
|
+
for (const sql of connection.migrationStatements) {
|
|
259
|
+
assert.match(sql, /^ALTER TABLE `bz_agent_(authorizations|sessions)` ADD COLUMN `subject_display` JSON DEFAULT NULL/);
|
|
260
|
+
assert.doesNotMatch(sql, /\b(?:UPDATE|DELETE|DROP|MODIFY|RENAME)\b/i);
|
|
261
|
+
}
|
|
262
|
+
for (const [name, checksum] of prior) assert.equal(connection.ledger.get(name), checksum);
|
|
263
|
+
const rerun = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
264
|
+
assert.deepEqual(rerun.appliedFiles, []);
|
|
265
|
+
assert.equal(connection.migrationStatements.length, 2);
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
test('Core Schema Migrator: partial 059 replay verifies JSON type, nullability and default', async () => {
|
|
269
|
+
const migration = '059_agent_subject_display.sql';
|
|
270
|
+
for (const shape of [
|
|
271
|
+
{ Type: 'json', Null: 'YES', Default: null },
|
|
272
|
+
{ Type: 'text', Null: 'YES', Default: null },
|
|
273
|
+
{ Type: 'json', Null: 'NO', Default: null },
|
|
274
|
+
{ Type: 'json', Null: 'YES', Default: '{}' },
|
|
275
|
+
]) {
|
|
276
|
+
const connection = new FakeMigrationConnection();
|
|
277
|
+
seedLedgerWithCurrentChecksums(connection);
|
|
278
|
+
connection.ledger.delete(migration);
|
|
279
|
+
connection.statementFaults = [{ pattern: /ADD COLUMN `subject_display`/, errno: 1060 }];
|
|
280
|
+
connection.fullColumns.set('bz_agent_authorizations', [{ Field: 'subject_display', ...shape }]);
|
|
281
|
+
if (shape.Type === 'json' && shape.Null === 'YES' && shape.Default === null) {
|
|
282
|
+
const result = await migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection });
|
|
283
|
+
assert.deepEqual(result.appliedFiles, [migration]);
|
|
284
|
+
assert.equal(result.toleratedStatements, 1);
|
|
285
|
+
} else {
|
|
286
|
+
await assert.rejects(migrateBailingHubCoreSchema({ mysql: MYSQL_CONFIG, connection }), /059_agent_subject_display\.sql 执行失败/);
|
|
287
|
+
assert.equal(connection.ledger.has(migration), false);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
|
|
202
292
|
test('Core Schema Migrator: 兼容文件名旧账本,补录摘要但绝不重放已记账 SQL', async () => {
|
|
203
293
|
const connection = new FakeMigrationConnection();
|
|
204
294
|
const official = officialMigrations();
|
|
@@ -7,6 +7,7 @@ import type { Client, ExecutorToken } from '../core/contracts/types';
|
|
|
7
7
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
8
8
|
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
9
9
|
import { maskKey } from './admin-format';
|
|
10
|
+
import { clientAgentSetupView } from '../core/config/client-agent-setup';
|
|
10
11
|
|
|
11
12
|
export interface AdminAccessApiDeps {
|
|
12
13
|
configStore: ConfigStoreContract | null;
|
|
@@ -57,6 +58,42 @@ export async function handleAdminAccessApiFor(
|
|
|
57
58
|
return true;
|
|
58
59
|
}
|
|
59
60
|
|
|
61
|
+
const setupMatch = path.match(/^\/admin\/api\/clients\/([a-z0-9][a-z0-9_-]{1,63})\/agent-setup$/);
|
|
62
|
+
if (setupMatch && (method === 'GET' || method === 'PUT')) {
|
|
63
|
+
if (!can(principal, method === 'GET' ? 'clients:read' : 'clients:write')) {
|
|
64
|
+
send(res, 403, { error: 'forbidden' }); return true;
|
|
65
|
+
}
|
|
66
|
+
const current = await configStore.clients.get(setupMatch[1]!);
|
|
67
|
+
if (!current) { send(res, 404, { error: 'client_not_found' }); return true; }
|
|
68
|
+
if (method === 'GET') { send(res, 200, clientAgentSetupView(current)); return true; }
|
|
69
|
+
if (!configStore.clients.updateAgentSetup) { send(res, 503, { error: 'agent_setup_unsupported' }); return true; }
|
|
70
|
+
let raw: unknown;
|
|
71
|
+
try { raw = await readBody(req, 32 * 1024); }
|
|
72
|
+
catch { send(res, 400, { error: 'invalid_agent_setup' }); return true; }
|
|
73
|
+
const body = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : null;
|
|
74
|
+
if (!body || Object.keys(body).length !== 4 || Object.keys(body).some((key) => !['expected_revision', 'enabled', 'agent_authorize_url', 'allowed_routes'].includes(key))
|
|
75
|
+
|| typeof body['expected_revision'] !== 'string' || !/^[a-f0-9]{64}$/.test(body['expected_revision'])
|
|
76
|
+
|| typeof body['enabled'] !== 'boolean'
|
|
77
|
+
|| !(body['agent_authorize_url'] === null || typeof body['agent_authorize_url'] === 'string')
|
|
78
|
+
|| !Array.isArray(body['allowed_routes']) || body['allowed_routes'].length > 256
|
|
79
|
+
|| !body['allowed_routes'].every((value) => typeof value === 'string' && /^(?:\*|[a-z0-9][a-z0-9_-]{1,63})$/.test(value))) {
|
|
80
|
+
send(res, 400, { error: 'invalid_agent_setup' }); return true;
|
|
81
|
+
}
|
|
82
|
+
const prepared = prepareClientConfig({ ...current,
|
|
83
|
+
enabled: body['enabled'], agent_authorize_url: body['agent_authorize_url'] as string | undefined,
|
|
84
|
+
allowed_routes: body['allowed_routes'] as string[],
|
|
85
|
+
});
|
|
86
|
+
if (!prepared.ok) { send(res, 400, { error: prepared.error }); return true; }
|
|
87
|
+
const result = await configStore.clients.updateAgentSetup(current.app_id, body['expected_revision'], {
|
|
88
|
+
enabled: prepared.value.enabled, agent_authorize_url: prepared.value.agent_authorize_url || null,
|
|
89
|
+
allowed_routes: prepared.value.allowed_routes,
|
|
90
|
+
});
|
|
91
|
+
if (result !== 'updated') { send(res, result === 'conflict' ? 409 : 404, { error: result === 'conflict' ? 'agent_setup_conflict' : 'client_not_found' }); return true; }
|
|
92
|
+
const saved = await configStore.clients.get(current.app_id);
|
|
93
|
+
if (!saved) { send(res, 404, { error: 'client_not_found' }); return true; }
|
|
94
|
+
send(res, 200, clientAgentSetupView(saved)); return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
60
97
|
if (path === '/admin/api/clients') {
|
|
61
98
|
// token 即调用方凭证,与工具源 secret / 凭证 api_key 同等对待:列表只给掩码,完整值走显式 reveal(见下)
|
|
62
99
|
if (method === 'GET') {
|