bailinghub 0.6.1 → 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 +9 -5
- package/README.md +8 -5
- 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 +14 -1
- package/docs/CHANGELOG.md +14 -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 +6 -0
- package/docs/README.md +6 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -0
- package/docs/RELEASE_NOTES_NEXT.md +3 -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 +1 -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 +1 -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 +1 -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
|
@@ -0,0 +1,120 @@
|
|
|
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', sequence: 1, client_turn_id: 'turn-1', kind: 'turn_start' },
|
|
9
|
+
{ event_id: 'user', sequence: 2, client_turn_id: 'turn-1', kind: 'user_message', content: 'Compare the CRM and ERP accounts. Only update the CRM account.' },
|
|
10
|
+
{ event_id: 'crm', sequence: 3, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_A, member_session_id: AUDIT_SESSION_A },
|
|
11
|
+
{ event_id: 'erp', sequence: 4, client_turn_id: 'turn-1', kind: 'run_link', run_id: AUDIT_RUN_B, member_session_id: AUDIT_SESSION_B },
|
|
12
|
+
{ event_id: 'reply', sequence: 5, client_turn_id: 'turn-1', kind: 'assistant_message', content: 'The visible reply spans two systems; their execution records remain separate.' },
|
|
13
|
+
{ event_id: 'end', sequence: 6, client_turn_id: 'turn-1', kind: 'turn_end', status: 'completed' },
|
|
14
|
+
] });
|
|
15
|
+
|
|
16
|
+
test('cross-app and cross-route members require their own bearer, preserve original runs and deduplicate ACK retries', async () => {
|
|
17
|
+
const fx = conversationAuditFixture({ crossBinding: true });
|
|
18
|
+
const input = fx.crossInput();
|
|
19
|
+
const head = await fx.repo.createCrossBinding(fx.auth(), input);
|
|
20
|
+
assert.equal(head.client_app_id, 'example-business', 'head identifies the writer, never the whole group');
|
|
21
|
+
assert.equal(head.route_key, 'orders');
|
|
22
|
+
assert.equal(head.state, 'enrolling');
|
|
23
|
+
assert.equal(head.confirmed_count, 1);
|
|
24
|
+
await assert.rejects(fx.repo.append(fx.auth(), head.conversation_id, events()), errorCode('conversation_audit_not_ready'));
|
|
25
|
+
await assert.rejects(fx.repo.confirm(fx.auth(AUDIT_SESSION_C), head.conversation_id), errorCode('conversation_audit_not_found'));
|
|
26
|
+
const spoofed = fx.auth(AUDIT_SESSION_A);
|
|
27
|
+
spoofed.session.session_id = AUDIT_SESSION_B;
|
|
28
|
+
await assert.rejects(fx.repo.confirm(spoofed, head.conversation_id), errorCode('conversation_audit_not_found'));
|
|
29
|
+
assert.equal((await fx.repo.confirm(fx.auth(AUDIT_SESSION_B), head.conversation_id)).state, 'ready');
|
|
30
|
+
await assert.rejects(fx.repo.append(fx.auth(AUDIT_SESSION_B), head.conversation_id, events()), errorCode('conversation_audit_not_found'));
|
|
31
|
+
await fx.repo.append(fx.auth(), head.conversation_id, events());
|
|
32
|
+
assert.equal((await fx.repo.append(fx.auth(), head.conversation_id, events())).last_sequence, 6);
|
|
33
|
+
assert.equal(fx.events.size, 6);
|
|
34
|
+
const detail = (await fx.repo.detailForAdmin(head.conversation_id))!;
|
|
35
|
+
assert.deepEqual(detail.members.map((member: any) => [member.session_id, member.client_app_id, member.client_name, member.route_key]), [
|
|
36
|
+
[AUDIT_SESSION_A, 'example-business', 'Example', 'orders'], [AUDIT_SESSION_B, 'example-erp', 'Example ERP', 'inventory'],
|
|
37
|
+
]);
|
|
38
|
+
assert.deepEqual(detail.events.filter((event: any) => event.kind === 'run_link').map((event: any) => [event.run_id, event.member_session_id, event.thread_id]), [
|
|
39
|
+
[AUDIT_RUN_A, AUDIT_SESSION_A, 101], [AUDIT_RUN_B, AUDIT_SESSION_B, 102],
|
|
40
|
+
]);
|
|
41
|
+
assert.equal(detail.events[4].content, events()[4]!.content);
|
|
42
|
+
assert.deepEqual(await fx.repo.findRunLinkForAdmin(AUDIT_RUN_B), { conversation_audit_id: head.conversation_id, client_turn_id: 'turn-1' });
|
|
43
|
+
assert.doesNotMatch(JSON.stringify(detail), /identity_hash|access_token|refresh_token|enrollment_hash/);
|
|
44
|
+
assert.equal(fx.queries.some(({ sql }) => /INSERT INTO bz_messages|UPDATE bz_threads|UPDATE bz_agent_client_runs|bz_agent_tool_invocations/.test(sql)), false);
|
|
45
|
+
const firstWrite = fx.queries.findIndex(({ sql }) => sql.startsWith('INSERT INTO bz_agent_conversation_events'));
|
|
46
|
+
const beforeWrite = fx.queries.slice(0, firstWrite);
|
|
47
|
+
for (const id of ['example-business', 'example-erp']) assert.ok(beforeWrite.some(({ sql, params, transactional }) => sql.includes('FROM bz_clients') && params[0] === id && transactional));
|
|
48
|
+
for (const route of ['orders', 'inventory']) assert.ok(beforeWrite.some(({ sql, params, transactional }) => sql.includes('FROM bz_routes') && params[0] === route && transactional));
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('v2 retry freezes every member binding and cannot replace a v1 archive', async () => {
|
|
52
|
+
const fx = conversationAuditFixture({ crossBinding: true });
|
|
53
|
+
const original = await fx.repo.createCrossBinding(fx.auth(), fx.crossInput());
|
|
54
|
+
assert.equal((await fx.repo.createCrossBinding(fx.auth(), fx.crossInput({ members: [...fx.crossInput().members].reverse() }))).conversation_id, original.conversation_id);
|
|
55
|
+
for (const patch of [
|
|
56
|
+
{ client_conversation_id: 'another-conversation' },
|
|
57
|
+
{ members: fx.crossInput().members.map((member) => member.session_id === AUDIT_SESSION_B ? { ...member, route: 'orders' } : member) },
|
|
58
|
+
{ members: fx.crossInput().members.map((member) => member.session_id === AUDIT_SESSION_B ? { ...member, label: 'renamed' } : member) },
|
|
59
|
+
]) await assert.rejects(fx.repo.createCrossBinding(fx.auth(), fx.crossInput(patch)), errorCode('conversation_audit_conflict'));
|
|
60
|
+
const legacy = conversationAuditFixture();
|
|
61
|
+
await legacy.ready();
|
|
62
|
+
await assert.rejects(legacy.repo.createCrossBinding(legacy.auth(), legacy.crossInput()), errorCode('conversation_audit_conflict'));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
for (const field of ['client_app_id', 'route_key', 'session_id', 'client_conversation_id', 'client_turn_id']) {
|
|
66
|
+
test(`cross-binding run links reject forged ${field} and roll back the entire batch`, async () => {
|
|
67
|
+
const fx = conversationAuditFixture({ crossBinding: true });
|
|
68
|
+
const head = await fx.readyCross();
|
|
69
|
+
fx.runs.get(AUDIT_RUN_B)![field] = field === 'session_id' ? AUDIT_SESSION_A : 'wrong-binding';
|
|
70
|
+
await assert.rejects(fx.repo.append(fx.auth(), head.conversation_id, events()), errorCode('conversation_audit_conflict'));
|
|
71
|
+
assert.equal(fx.events.size, 0);
|
|
72
|
+
assert.equal(fx.archives.get(head.conversation_id)!.last_sequence, 0);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
for (const mutation of ['revoked', 'expired', 'identity', 'subject', 'session-route', 'client-route', 'client-disabled', 'route-disabled', 'audience']) {
|
|
77
|
+
test(`cross-binding ${mutation} pauses the whole group, including create retries and ACK retries`, async () => {
|
|
78
|
+
const fx = conversationAuditFixture({ crossBinding: true });
|
|
79
|
+
const head = await fx.readyCross();
|
|
80
|
+
await fx.repo.append(fx.auth(), head.conversation_id, events());
|
|
81
|
+
const member = fx.sessions.get(AUDIT_SESSION_B)!;
|
|
82
|
+
if (mutation === 'revoked') member.revoked_at = '2026-01-01T00:00:00Z';
|
|
83
|
+
if (mutation === 'expired') member.refresh_expires_at = '2000-01-01T00:00:00Z';
|
|
84
|
+
if (mutation === 'identity') member.principal_json.tenant = 'changed-tenant';
|
|
85
|
+
if (mutation === 'subject') member.on_behalf_of = 'changed-subject';
|
|
86
|
+
if (mutation === 'session-route') member.allowed_routes = ['orders'];
|
|
87
|
+
if (mutation === 'client-route') fx.clients.get('example-erp')!.allowed_routes = [];
|
|
88
|
+
if (mutation === 'client-disabled') fx.clients.get('example-erp')!.enabled = false;
|
|
89
|
+
if (mutation === 'route-disabled') fx.routes.get('inventory')!.enabled = false;
|
|
90
|
+
if (mutation === 'audience') fx.routes.get('inventory')!.audience = { enabled: true, tenants: ['store-a'] };
|
|
91
|
+
await assert.rejects(fx.repo.createCrossBinding(fx.auth(), fx.crossInput()), errorCode('conversation_audit_authorization_invalid'));
|
|
92
|
+
await assert.rejects(fx.repo.confirm(fx.auth(), head.conversation_id), errorCode('conversation_audit_authorization_invalid'));
|
|
93
|
+
await assert.rejects(fx.repo.append(fx.auth(), head.conversation_id, events()), errorCode('conversation_audit_authorization_invalid'));
|
|
94
|
+
assert.equal(fx.events.size, 6);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
test('foreign-Hub or forged member bindings never establish an audit group', async () => {
|
|
99
|
+
for (const patch of [{ session_id: '123e4567-e89b-42d3-a456-426614174099' }, { client_app_id: 'example-business' }, { route: 'orders' }]) {
|
|
100
|
+
const fx = conversationAuditFixture({ crossBinding: true });
|
|
101
|
+
const input = fx.crossInput({ members: fx.crossInput().members.map((member) => member.session_id === AUDIT_SESSION_B ? { ...member, ...patch } : member) });
|
|
102
|
+
await assert.rejects(fx.repo.createCrossBinding(fx.auth(), input), errorCode('conversation_audit_authorization_invalid'));
|
|
103
|
+
assert.equal(fx.archives.size, 0);
|
|
104
|
+
assert.equal(fx.members.size, 0);
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('058 capability probe fails closed for missing/partial schema while 057 v1 remains usable', async () => {
|
|
109
|
+
const fx = conversationAuditFixture({ schemaReady: false });
|
|
110
|
+
assert.equal(await fx.repo.supportsCrossBindingMembers(), false);
|
|
111
|
+
await assert.rejects(fx.repo.createCrossBinding(fx.auth(), fx.crossInput()), errorCode('conversation_audit_cross_binding_unavailable'));
|
|
112
|
+
assert.equal(fx.archives.size, 0);
|
|
113
|
+
const legacy = await fx.ready();
|
|
114
|
+
await fx.repo.append(fx.auth(), legacy.conversation_id, events());
|
|
115
|
+
assert.equal(fx.events.size, 6);
|
|
116
|
+
const detail = (await fx.repo.detailForAdmin(legacy.conversation_id))!;
|
|
117
|
+
assert.equal(Object.hasOwn(detail.members[0], 'client_app_id'), false, 'legacy records are not relabelled as proven v2 bindings');
|
|
118
|
+
fx.migrationColumns.add('bz_agent_conversation_audits.membership_version');
|
|
119
|
+
assert.equal(await fx.repo.supportsCrossBindingMembers(), false);
|
|
120
|
+
});
|
|
@@ -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;
|