bailinghub 0.6.1 → 0.8.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 +8 -7
- package/README.md +7 -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.en.md +46 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +38 -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/AGENT_TASK_CONTROL.en.md +25 -0
- package/docs/AGENT_TASK_CONTROL.md +94 -0
- package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +134 -0
- package/docs/CHANGELOG.en.md +24 -1
- package/docs/CHANGELOG.md +24 -1
- package/docs/COMPATIBILITY.en.md +2 -0
- package/docs/CONTRACT.en.md +2 -0
- package/docs/CONTRACT.md +2 -0
- package/docs/GENERATED_ARTIFACTS.en.md +46 -0
- package/docs/GENERATED_ARTIFACTS.md +108 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/INVOCATION_RECEIPTS.md +111 -0
- package/docs/LOCAL_AGENT_SETUP.en.md +116 -0
- package/docs/LOCAL_AGENT_SETUP.md +116 -0
- package/docs/README.en.md +9 -0
- package/docs/README.md +9 -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/RELEASE_NOTES_v0.8.0.en.md +40 -0
- package/docs/RELEASE_NOTES_v0.8.0.md +62 -0
- package/docs/SDK.en.md +31 -0
- package/docs/TOOL_RATE_LIMITS.md +50 -0
- package/docs/UPGRADE_v0.8.0.en.md +71 -0
- package/docs/UPGRADE_v0.8.0.md +73 -0
- package/docs/user-guide/conversations.en.md +4 -2
- package/docs/user-guide/conversations.md +4 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +2 -0
- package/package.json +1 -1
- package/schemas/config/route.schema.json +16 -2
- package/schemas/config/tool-provider.schema.json +2 -1
- package/scripts/check-doc-links.mjs +2 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/e2e-console.mjs +32 -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/060_agent_artifacts.sql +11 -0
- package/sql/061_tool_rate_limit_policies.sql +3 -0
- package/sql/062_agent_task_control.sql +92 -0
- package/sql/README.en.md +15 -0
- package/sql/README.md +25 -0
- package/src/adapters/storage/object-storage.ts +15 -3
- package/src/adapters/storage/oss-signature.test.ts +40 -0
- package/src/adapters/storage/oss-signature.ts +21 -0
- package/src/app/agent-artifacts.test.ts +165 -0
- package/src/app/agent-artifacts.ts +85 -0
- package/src/app/agent-client-runtime.test.ts +76 -1
- package/src/app/agent-client-runtime.ts +13 -0
- package/src/app/agent-conversation-audit.ts +20 -0
- package/src/app/agent-invocation-snapshot.ts +35 -0
- package/src/app/agent-system-info.ts +41 -0
- package/src/app/agent-task-control.ts +187 -0
- package/src/app/agent-task-runtime.ts +68 -0
- package/src/app/agent-tool-invocations.test.ts +329 -1
- package/src/app/agent-tool-invocations.ts +239 -14
- package/src/app/agent-tool-job.test.ts +11 -1
- package/src/app/agent-tool-job.ts +8 -1
- package/src/app/builtin-tools.ts +4 -0
- package/src/app/oss-edition.ts +1 -0
- package/src/app/tool-approvals.ts +4 -0
- package/src/app/tool-assembly.ts +5 -0
- package/src/core/config/agent-setup.ts +37 -0
- package/src/core/config/artifact-config.ts +15 -0
- package/src/core/config/client-agent-setup.ts +25 -0
- package/src/core/config/config-codec.ts +3 -1
- package/src/core/config/config-models.ts +11 -1
- 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 +44 -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/tool-rate-limits.test.ts +59 -0
- package/src/core/contracts/tool-rate-limits.ts +48 -0
- package/src/core/contracts/tools.ts +122 -43
- package/src/core/contracts/types.ts +18 -1
- package/src/core/runtime/agent-conversation-audit.test.ts +19 -1
- package/src/core/runtime/agent-conversation-audit.ts +39 -0
- package/src/core/runtime/agent-task-control.test.ts +114 -0
- package/src/core/runtime/agent-task-control.ts +227 -0
- package/src/infrastructure/config/config-agent-artifact-repository.ts +32 -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-client-runtime-repository.ts +7 -1
- 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-agent-task-control-journal-mysql.test.ts +315 -0
- package/src/infrastructure/config/config-agent-task-control-mysql.test.ts +331 -0
- package/src/infrastructure/config/config-agent-task-control-repository.ts +640 -0
- package/src/infrastructure/config/config-client-repository.ts +21 -0
- package/src/infrastructure/config/config-rate-limit-ledger.integration.test.ts +52 -0
- package/src/infrastructure/config/config-rate-limit-ledger.ts +48 -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/config-storage-bucket-repository.ts +2 -2
- package/src/infrastructure/config/config-tool-provider-repository.ts +4 -4
- package/src/infrastructure/config/configstore.ts +16 -4
- 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-agent-tasks.ts +32 -0
- package/src/routes/admin-client-agent-setup.test.ts +93 -0
- package/src/routes/admin-dispatch-config.ts +2 -0
- package/src/routes/admin-tool-providers.test.ts +22 -0
- package/src/routes/admin-tool-providers.ts +9 -1
- package/src/routes/admin.ts +3 -0
- package/src/routes/agent-api.test.ts +76 -0
- package/src/routes/agent-api.ts +49 -1
- package/src/routes/agent-artifacts.ts +29 -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/routes/agent-task-control-http-mysql.test.ts +246 -0
- package/src/routes/private.ts +1 -0
- package/src/routes/run.ts +2 -1
- 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/src/test-support/agent-task-control-mysql-fixture.ts +75 -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-BRCR3O0P.js} +1 -1
- package/web/console/assets/AgentClients-Bf7sUUs_.js +1 -0
- package/web/console/assets/AgentClients-i52AI6YV.css +1 -0
- package/web/console/assets/AgentTasks--bqL_QKg.js +2 -0
- package/web/console/assets/AgentTasks-C8ox3TyS.css +1 -0
- package/web/console/assets/{Approvals-CMvPWacY.js → Approvals-BIbZvInm.js} +1 -1
- package/web/console/assets/{Audit-CIRqOCnL.js → Audit-KyPSmBdZ.js} +1 -1
- package/web/console/assets/{BrandLockup-BrytmTTH.js → BrandLockup-Sv5DU2G6.js} +1 -1
- package/web/console/assets/{Channels-CApxH2TB.js → Channels-B9n4fbxg.js} +1 -1
- package/web/console/assets/{ChatEntries-CJon3bWJ.js → ChatEntries-xsOCUXi_.js} +1 -1
- package/web/console/assets/Clients-CI3DBDHf.js +3 -0
- package/web/console/assets/Clients-CSHIsaWU.css +1 -0
- package/web/console/assets/{Cost-BbhlQFP8.js → Cost-JgNXQPlN.js} +1 -1
- package/web/console/assets/{Credentials-kqr1W0K7.js → Credentials-B5UUUdt0.js} +1 -1
- package/web/console/assets/{Diagnostics-Kljt9XTH.js → Diagnostics-BMGciWQb.js} +1 -1
- package/web/console/assets/{Executors-DnsB-Xz4.js → Executors-CRbboOCZ.js} +1 -1
- package/web/console/assets/{Kb-DLZSAFWP.js → Kb-CgLNGjRp.js} +1 -1
- package/web/console/assets/{Login-DiTjPWmN.js → Login-C52JmXzx.js} +1 -1
- package/web/console/assets/{Projects-CXcVCgCD.js → Projects-CDOvHPVS.js} +1 -1
- package/web/console/assets/Routes-DkMIjMQA.css +1 -0
- package/web/console/assets/Routes-X9vHLpKW.js +124 -0
- package/web/console/assets/Runs-CvGTV8I-.css +1 -0
- package/web/console/assets/Runs-DYNDXsqk.js +3 -0
- package/web/console/assets/{Setup-FqoCKmfZ.js → Setup-B91P6i1x.js} +1 -1
- package/web/console/assets/Shell-Bj6C8Hgo.css +1 -0
- package/web/console/assets/Shell-BsRa7bQQ.js +1 -0
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +1 -0
- package/web/console/assets/StorageBuckets-DkuDM0oX.js +1 -0
- package/web/console/assets/{SystemSettings-gTQAazu7.js → SystemSettings-B7Mqj3k1.js} +1 -1
- package/web/console/assets/{SystemStatus-DAmUUNqO.js → SystemStatus-Db93b6dc.js} +1 -1
- package/web/console/assets/{Targets-CZmDcjsE.js → Targets-CuuIYeZO.js} +1 -1
- package/web/console/assets/Tools-CHiqz9XZ.js +2 -0
- package/web/console/assets/Tools-DU8ei6sd.css +1 -0
- package/web/console/assets/index-UGvfF3Xr.js +2 -0
- package/web/console/assets/{request-r7GHVJzw.js → request-DeGya810.js} +1 -1
- package/web/console/assets/{schema-BVn_hB7M.js → schema-BqlqLw1R.js} +1 -1
- package/web/console/index.html +1 -1
- package/web-admin/scripts/agent-task-control-smoke.mjs +120 -0
- package/web-admin/scripts/subject-display-ui.mjs +78 -0
- package/web-admin/src/components/AgentSetupPanel.vue +275 -0
- package/web-admin/src/components/ClientConversations.vue +21 -4
- package/web-admin/src/components/ToolRateLimitEditor.vue +28 -0
- package/web-admin/src/components/conversation-audit.ts +20 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +99 -23
- package/web-admin/src/pages/AgentTasks.vue +281 -0
- package/web-admin/src/pages/Clients.vue +4 -1
- package/web-admin/src/pages/Routes.vue +10 -1
- package/web-admin/src/pages/StorageBuckets.vue +6 -6
- package/web-admin/src/pages/Tools.vue +53 -4
- package/web-admin/src/router.ts +2 -0
- 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
- package/web/console/assets/Shell-BEqpONiy.js +0 -1
- package/web/console/assets/Shell-D9Uw-fsa.css +0 -1
- package/web/console/assets/StorageBuckets-CkORbYXY.js +0 -1
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +0 -1
- package/web/console/assets/Tools-A20oaMaQ.css +0 -1
- package/web/console/assets/Tools-CIHInlHL.js +0 -2
- package/web/console/assets/index-BkLbd7Cc.js +0 -2
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { Pool, PoolConnection, ResultSetHeader } from 'mysql2/promise';
|
|
2
2
|
import { dt, dtIso } from '../../core/config/config-codec';
|
|
3
|
-
import type { AgentBusinessPrincipal, AgentSession } from '../../core/contracts/types';
|
|
3
|
+
import type { AgentBusinessPrincipal, AgentSession, AgentSubjectDisplay } from '../../core/contracts/types';
|
|
4
|
+
import { agentSubjectDisplayView, readAgentSubjectDisplay, validateAgentSubjectDisplay } from '../../core/contracts/agent-subject-display';
|
|
4
5
|
|
|
5
|
-
export type AgentAuthorizationStatus = 'pending' | 'approved' | 'consumed' | 'denied' | 'expired';
|
|
6
|
+
export type AgentAuthorizationStatus = 'pending' | 'approved' | 'consumed' | 'denied' | 'expired' | 'revoked';
|
|
6
7
|
|
|
7
8
|
export interface AgentAuthorization {
|
|
8
9
|
authorization_id: string;
|
|
@@ -11,6 +12,7 @@ export interface AgentAuthorization {
|
|
|
11
12
|
state: string;
|
|
12
13
|
requested_routes: string[];
|
|
13
14
|
device_label: string;
|
|
15
|
+
subject_display?: AgentSubjectDisplay | null;
|
|
14
16
|
code_challenge: string;
|
|
15
17
|
status: AgentAuthorizationStatus;
|
|
16
18
|
principal?: AgentBusinessPrincipal;
|
|
@@ -19,6 +21,7 @@ export interface AgentAuthorization {
|
|
|
19
21
|
created_at: string;
|
|
20
22
|
expires_at: string;
|
|
21
23
|
code_expires_at?: string;
|
|
24
|
+
session_id?: string;
|
|
22
25
|
}
|
|
23
26
|
|
|
24
27
|
export type AuthorizationMutationResult =
|
|
@@ -29,10 +32,18 @@ export type AuthorizationExchangeResult =
|
|
|
29
32
|
| { ok: true; session: AgentSession }
|
|
30
33
|
| { ok: false; reason: 'invalid_grant' };
|
|
31
34
|
|
|
35
|
+
export type AuthorizationRevocationResult =
|
|
36
|
+
| { ok: true; authorization: AgentAuthorization; sessionId?: string }
|
|
37
|
+
| { ok: false; reason: 'not_found' | 'wrong_client' };
|
|
38
|
+
|
|
32
39
|
export type RefreshRotationResult =
|
|
33
40
|
| { ok: true; session: AgentSession }
|
|
34
41
|
| { ok: false; reason: 'invalid_grant' | 'replayed' };
|
|
35
42
|
|
|
43
|
+
export type SubjectDisplayUpdateResult =
|
|
44
|
+
| { ok: true; session: AgentBusinessSessionRecord }
|
|
45
|
+
| { ok: false; reason: 'not_found' | 'inactive' };
|
|
46
|
+
|
|
36
47
|
export type AgentSessionAdminState = 'active' | 'expired' | 'revoked';
|
|
37
48
|
|
|
38
49
|
export interface AgentSessionAdminRecord extends AgentSession {
|
|
@@ -45,6 +56,32 @@ export interface AgentSessionAdminList {
|
|
|
45
56
|
total: number;
|
|
46
57
|
}
|
|
47
58
|
|
|
59
|
+
export interface AgentBusinessSessionRecord extends AgentSessionAdminRecord {
|
|
60
|
+
authorization_id?: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface AgentBusinessSessionCursor {
|
|
64
|
+
createdAt: string;
|
|
65
|
+
sessionId: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface AgentBusinessSessionListInput {
|
|
69
|
+
clientAppId: string;
|
|
70
|
+
authorizationId?: string;
|
|
71
|
+
onBehalfOf?: string;
|
|
72
|
+
principalId?: string;
|
|
73
|
+
/** Undefined leaves tenant unfiltered; an empty string selects no tenant. */
|
|
74
|
+
tenant?: string;
|
|
75
|
+
state?: AgentSessionAdminState | 'all';
|
|
76
|
+
limit: number;
|
|
77
|
+
cursor?: AgentBusinessSessionCursor;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface AgentBusinessSessionList {
|
|
81
|
+
list: AgentBusinessSessionRecord[];
|
|
82
|
+
nextCursor?: AgentBusinessSessionCursor;
|
|
83
|
+
}
|
|
84
|
+
|
|
48
85
|
export interface AgentSessionAdminSummary {
|
|
49
86
|
total: number;
|
|
50
87
|
active: number;
|
|
@@ -81,6 +118,7 @@ function authorizationRow(row: any): AgentAuthorization {
|
|
|
81
118
|
state: String(row.state_value),
|
|
82
119
|
requested_routes: stringArray(row.requested_routes),
|
|
83
120
|
device_label: String(row.device_label),
|
|
121
|
+
subject_display: readAgentSubjectDisplay(row.subject_display),
|
|
84
122
|
code_challenge: String(row.code_challenge),
|
|
85
123
|
status: String(row.status) as AgentAuthorizationStatus,
|
|
86
124
|
...(row.principal_json ? { principal: jsonObject<AgentBusinessPrincipal>(row.principal_json) } : {}),
|
|
@@ -89,6 +127,7 @@ function authorizationRow(row: any): AgentAuthorization {
|
|
|
89
127
|
created_at: iso(row.created_at),
|
|
90
128
|
expires_at: iso(row.expires_at),
|
|
91
129
|
...(row.code_expires_at ? { code_expires_at: iso(row.code_expires_at) } : {}),
|
|
130
|
+
...(row.session_id ? { session_id: String(row.session_id) } : {}),
|
|
92
131
|
};
|
|
93
132
|
}
|
|
94
133
|
|
|
@@ -97,6 +136,7 @@ function sessionRow(row: any): AgentSession {
|
|
|
97
136
|
session_id: String(row.session_id),
|
|
98
137
|
client_app_id: String(row.client_app_id),
|
|
99
138
|
device_label: String(row.device_label),
|
|
139
|
+
subject_display: readAgentSubjectDisplay(row.subject_display),
|
|
100
140
|
principal: jsonObject<AgentBusinessPrincipal>(row.principal_json),
|
|
101
141
|
on_behalf_of: String(row.on_behalf_of),
|
|
102
142
|
allowed_routes: stringArray(row.allowed_routes),
|
|
@@ -115,11 +155,36 @@ function sessionAdminState(row: any, now: Date): AgentSessionAdminState {
|
|
|
115
155
|
function sessionAdminRow(row: any, now: Date): AgentSessionAdminRecord {
|
|
116
156
|
return {
|
|
117
157
|
...sessionRow(row),
|
|
158
|
+
...agentSubjectDisplayView(row.subject_display),
|
|
118
159
|
...(row.last_seen_at ? { last_seen_at: iso(row.last_seen_at) } : {}),
|
|
119
160
|
state: sessionAdminState(row, now),
|
|
120
161
|
};
|
|
121
162
|
}
|
|
122
163
|
|
|
164
|
+
function businessSessionRow(row: any, now: Date): AgentBusinessSessionRecord {
|
|
165
|
+
const principal = jsonObject<Record<string, unknown>>(row.principal_json);
|
|
166
|
+
if (typeof principal.id !== 'string' || !Array.isArray(principal.roles) ||
|
|
167
|
+
!principal.roles.every((role) => typeof role === 'string')) throw new Error('Business Session principal is invalid.');
|
|
168
|
+
return {
|
|
169
|
+
...sessionAdminRow(row, now),
|
|
170
|
+
principal: {
|
|
171
|
+
id: principal.id, roles: [...principal.roles] as string[],
|
|
172
|
+
...(typeof principal.tenant === 'string' ? { tenant: principal.tenant } : {}),
|
|
173
|
+
...(typeof principal.audience === 'string' ? { audience: principal.audience } : {}),
|
|
174
|
+
...(typeof principal.channel === 'string' ? { channel: principal.channel } : {}),
|
|
175
|
+
},
|
|
176
|
+
...(row.authorization_id ? { authorization_id: String(row.authorization_id) } : {}),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Correlated aggregation preserves one row per Session, even if old/corrupt
|
|
181
|
+
// authorization data contains duplicate links. Ambiguous links are not guessed.
|
|
182
|
+
const BUSINESS_SESSION_COLUMNS = 's.session_id,s.client_app_id,s.device_label,s.subject_display,s.principal_json,s.on_behalf_of,s.allowed_routes,' +
|
|
183
|
+
's.access_expires_at,s.refresh_expires_at,s.created_at,s.updated_at,s.last_seen_at,s.revoked_at,' +
|
|
184
|
+
"DATE_FORMAT(s.created_at,'%Y-%m-%dT%H:%i:%s.000Z') AS cursor_created_at," +
|
|
185
|
+
'(SELECT CASE WHEN COUNT(*)=1 THEN MIN(a.authorization_id) ELSE NULL END FROM bz_agent_authorizations a ' +
|
|
186
|
+
"WHERE a.session_id=s.session_id AND a.client_app_id=s.client_app_id AND a.status='consumed') AS authorization_id";
|
|
187
|
+
|
|
123
188
|
async function rollback(connection: PoolConnection): Promise<void> {
|
|
124
189
|
await connection.rollback().catch(() => undefined);
|
|
125
190
|
}
|
|
@@ -156,11 +221,14 @@ export class AgentAuthRepository {
|
|
|
156
221
|
authorizationId: string;
|
|
157
222
|
clientAppId: string;
|
|
158
223
|
principal: AgentBusinessPrincipal;
|
|
224
|
+
subjectDisplay?: AgentSubjectDisplay | null;
|
|
159
225
|
onBehalfOf: string;
|
|
160
226
|
allowedRoutes: string[];
|
|
161
227
|
codeHash: string;
|
|
162
228
|
codeExpiresAt: string;
|
|
163
229
|
}): Promise<AuthorizationMutationResult> {
|
|
230
|
+
const display = validateAgentSubjectDisplay(input.subjectDisplay);
|
|
231
|
+
if (!display.ok) throw new Error('Invalid authorization subject display.');
|
|
164
232
|
const connection = await this.pool.getConnection();
|
|
165
233
|
try {
|
|
166
234
|
await connection.beginTransaction();
|
|
@@ -175,8 +243,9 @@ export class AgentAuthRepository {
|
|
|
175
243
|
}
|
|
176
244
|
if (String(row.status) !== 'pending') { await rollback(connection); return { ok: false, reason: 'invalid_state' }; }
|
|
177
245
|
const [result] = await connection.query<ResultSetHeader>(
|
|
178
|
-
'UPDATE bz_agent_authorizations SET status=\'approved\',principal_json=?,on_behalf_of=?,allowed_routes=?,code_hash=?,code_expires_at=?,approved_at=? WHERE authorization_id=? AND status=\'pending\'',
|
|
179
|
-
[JSON.stringify(input.principal), input.onBehalfOf, JSON.stringify(input.allowedRoutes), input.codeHash, dtIso(input.codeExpiresAt), dt(),
|
|
246
|
+
'UPDATE bz_agent_authorizations SET status=\'approved\',principal_json=?,on_behalf_of=?,allowed_routes=?,code_hash=?,code_expires_at=?,approved_at=?,subject_display=? WHERE authorization_id=? AND status=\'pending\'',
|
|
247
|
+
[JSON.stringify(input.principal), input.onBehalfOf, JSON.stringify(input.allowedRoutes), input.codeHash, dtIso(input.codeExpiresAt), dt(),
|
|
248
|
+
display.value ? JSON.stringify(display.value) : null, input.authorizationId],
|
|
180
249
|
);
|
|
181
250
|
if (result.affectedRows !== 1) { await rollback(connection); return { ok: false, reason: 'invalid_state' }; }
|
|
182
251
|
const [updated] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? LIMIT 1', [input.authorizationId]);
|
|
@@ -216,6 +285,43 @@ export class AgentAuthRepository {
|
|
|
216
285
|
}
|
|
217
286
|
}
|
|
218
287
|
|
|
288
|
+
/** Competes with code exchange on the same authorization row, before any Session mutation. */
|
|
289
|
+
async revokeAuthorization(input: { authorizationId: string; clientAppId: string }): Promise<AuthorizationRevocationResult> {
|
|
290
|
+
const connection = await this.pool.getConnection();
|
|
291
|
+
try {
|
|
292
|
+
await connection.beginTransaction();
|
|
293
|
+
const [rows] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? FOR UPDATE', [input.authorizationId]);
|
|
294
|
+
const row = (rows as any[])[0];
|
|
295
|
+
if (!row) { await rollback(connection); return { ok: false, reason: 'not_found' }; }
|
|
296
|
+
if (String(row.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'wrong_client' }; }
|
|
297
|
+
let sessionId: string | undefined;
|
|
298
|
+
if (row.status === 'consumed') {
|
|
299
|
+
if (!row.session_id) { await rollback(connection); return { ok: false, reason: 'not_found' }; }
|
|
300
|
+
const [sessions] = await connection.query('SELECT session_id,client_app_id FROM bz_agent_sessions WHERE session_id=? LIMIT 1 FOR UPDATE', [row.session_id]);
|
|
301
|
+
const session = (sessions as any[])[0];
|
|
302
|
+
if (!session) { await rollback(connection); return { ok: false, reason: 'not_found' }; }
|
|
303
|
+
if (String(session.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'wrong_client' }; }
|
|
304
|
+
sessionId = String(session.session_id);
|
|
305
|
+
const stamp = dt();
|
|
306
|
+
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, sessionId]);
|
|
307
|
+
await connection.query('UPDATE bz_agent_refresh_tokens SET status=\'revoked\',used_at=COALESCE(used_at,?) WHERE session_id=? AND status=\'active\'', [stamp, sessionId]);
|
|
308
|
+
} else if (row.status === 'pending' || row.status === 'approved') {
|
|
309
|
+
await connection.query("UPDATE bz_agent_authorizations SET status='revoked',code_hash=NULL,code_expires_at=NULL WHERE authorization_id=?", [input.authorizationId]);
|
|
310
|
+
} else if (!['revoked', 'denied', 'expired'].includes(String(row.status))) {
|
|
311
|
+
throw new Error('Agent authorization lifecycle state is invalid.');
|
|
312
|
+
}
|
|
313
|
+
const [updated] = await connection.query('SELECT * FROM bz_agent_authorizations WHERE authorization_id=? LIMIT 1', [input.authorizationId]);
|
|
314
|
+
const authorization = authorizationRow((updated as any[])[0]);
|
|
315
|
+
await connection.commit();
|
|
316
|
+
return { ok: true, authorization, ...(sessionId ? { sessionId } : {}) };
|
|
317
|
+
} catch (error) {
|
|
318
|
+
await rollback(connection);
|
|
319
|
+
throw error;
|
|
320
|
+
} finally {
|
|
321
|
+
connection.release();
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
219
325
|
async exchangeAuthorizationCode(input: {
|
|
220
326
|
codeHash: string;
|
|
221
327
|
clientAppId: string;
|
|
@@ -240,10 +346,11 @@ export class AgentAuthRepository {
|
|
|
240
346
|
}
|
|
241
347
|
const createdAt = dt();
|
|
242
348
|
await connection.query(
|
|
243
|
-
'INSERT INTO bz_agent_sessions (session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_token_hash,access_expires_at,refresh_expires_at,created_at,updated_at) VALUES (
|
|
349
|
+
'INSERT INTO bz_agent_sessions (session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_token_hash,access_expires_at,refresh_expires_at,created_at,updated_at,subject_display) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)',
|
|
244
350
|
[input.sessionId, input.clientAppId, row.device_label, typeof row.principal_json === 'string' ? row.principal_json : JSON.stringify(row.principal_json),
|
|
245
351
|
row.on_behalf_of, typeof row.allowed_routes === 'string' ? row.allowed_routes : JSON.stringify(row.allowed_routes), input.accessTokenHash,
|
|
246
|
-
dtIso(input.accessExpiresAt), dtIso(input.refreshExpiresAt), createdAt, createdAt
|
|
352
|
+
dtIso(input.accessExpiresAt), dtIso(input.refreshExpiresAt), createdAt, createdAt,
|
|
353
|
+
readAgentSubjectDisplay(row.subject_display) ? JSON.stringify(readAgentSubjectDisplay(row.subject_display)) : null],
|
|
247
354
|
);
|
|
248
355
|
await connection.query(
|
|
249
356
|
'INSERT INTO bz_agent_refresh_tokens (token_hash,session_id,status,created_at,expires_at) VALUES (?,? ,\'active\',?,?)',
|
|
@@ -276,6 +383,80 @@ export class AgentAuthRepository {
|
|
|
276
383
|
return sessionRow(row);
|
|
277
384
|
}
|
|
278
385
|
|
|
386
|
+
/** Client Token callers supply their authenticated App, never a model-selected scope. */
|
|
387
|
+
async getBusinessSession(clientAppId: string, sessionId: string): Promise<AgentBusinessSessionRecord | null> {
|
|
388
|
+
if (!clientAppId) throw new Error('Business Session queries require an authenticated Client App.');
|
|
389
|
+
const [rows] = await this.pool.query(`SELECT ${BUSINESS_SESSION_COLUMNS} FROM bz_agent_sessions s WHERE s.client_app_id=? AND s.session_id=? LIMIT 1`, [clientAppId, sessionId]);
|
|
390
|
+
const row = (rows as any[])[0];
|
|
391
|
+
return row && row.client_app_id === clientAppId && row.session_id === sessionId ? businessSessionRow(row, new Date()) : null;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Update presentation under the same Session lock as refresh/revoke. No identity or audit writes. */
|
|
395
|
+
async updateSubjectDisplay(input: {
|
|
396
|
+
clientAppId: string; sessionId: string; subjectDisplay: AgentSubjectDisplay | null;
|
|
397
|
+
}): Promise<SubjectDisplayUpdateResult> {
|
|
398
|
+
const display = validateAgentSubjectDisplay(input.subjectDisplay);
|
|
399
|
+
if (!input.clientAppId || !input.sessionId || !display.ok) throw new Error('Invalid subject display update.');
|
|
400
|
+
const connection = await this.pool.getConnection();
|
|
401
|
+
try {
|
|
402
|
+
await connection.beginTransaction();
|
|
403
|
+
const [rows] = await connection.query('SELECT * FROM bz_agent_sessions WHERE session_id=? AND client_app_id=? LIMIT 1 FOR UPDATE',
|
|
404
|
+
[input.sessionId, input.clientAppId]);
|
|
405
|
+
const row = (rows as any[])[0];
|
|
406
|
+
if (!row || row.client_app_id !== input.clientAppId || row.session_id !== input.sessionId) {
|
|
407
|
+
await rollback(connection); return { ok: false, reason: 'not_found' };
|
|
408
|
+
}
|
|
409
|
+
if (sessionAdminState(row, new Date()) !== 'active') { await rollback(connection); return { ok: false, reason: 'inactive' }; }
|
|
410
|
+
await connection.query('UPDATE bz_agent_sessions SET subject_display=?,updated_at=? WHERE session_id=? AND client_app_id=?',
|
|
411
|
+
[display.value ? JSON.stringify(display.value) : null, dt(), input.sessionId, input.clientAppId]);
|
|
412
|
+
const [updated] = await connection.query(`SELECT ${BUSINESS_SESSION_COLUMNS} FROM bz_agent_sessions s WHERE s.client_app_id=? AND s.session_id=? LIMIT 1`,
|
|
413
|
+
[input.clientAppId, input.sessionId]);
|
|
414
|
+
const session = businessSessionRow((updated as any[])[0], new Date());
|
|
415
|
+
await connection.commit();
|
|
416
|
+
return { ok: true, session };
|
|
417
|
+
} catch (error) {
|
|
418
|
+
await rollback(connection);
|
|
419
|
+
throw error;
|
|
420
|
+
} finally { connection.release(); }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async listBusinessSessions(input: AgentBusinessSessionListInput): Promise<AgentBusinessSessionList> {
|
|
424
|
+
if (!input.clientAppId) throw new Error('Business Session queries require an authenticated Client App.');
|
|
425
|
+
const now = new Date();
|
|
426
|
+
const limit = Math.min(Math.max(Math.floor(Number(input.limit) || 50), 1), 100);
|
|
427
|
+
const where = ['s.client_app_id=?'];
|
|
428
|
+
const params: unknown[] = [input.clientAppId];
|
|
429
|
+
if (input.authorizationId !== undefined) {
|
|
430
|
+
where.push("EXISTS (SELECT 1 FROM bz_agent_authorizations matched WHERE matched.authorization_id=? AND matched.client_app_id=s.client_app_id AND matched.session_id=s.session_id AND matched.status='consumed')");
|
|
431
|
+
params.push(input.authorizationId);
|
|
432
|
+
}
|
|
433
|
+
if (input.onBehalfOf !== undefined) { where.push('BINARY s.on_behalf_of=BINARY ?'); params.push(input.onBehalfOf); }
|
|
434
|
+
if (input.principalId !== undefined) {
|
|
435
|
+
where.push("BINARY JSON_UNQUOTE(JSON_EXTRACT(s.principal_json,'$.id'))=BINARY ?"); params.push(input.principalId);
|
|
436
|
+
}
|
|
437
|
+
if (input.tenant !== undefined) {
|
|
438
|
+
where.push("BINARY (CASE WHEN JSON_EXTRACT(s.principal_json,'$.tenant') IS NULL OR JSON_TYPE(JSON_EXTRACT(s.principal_json,'$.tenant'))='NULL' THEN '' ELSE JSON_UNQUOTE(JSON_EXTRACT(s.principal_json,'$.tenant')) END)=BINARY ?");
|
|
439
|
+
params.push(input.tenant);
|
|
440
|
+
}
|
|
441
|
+
if (input.state === 'active') { where.push('s.revoked_at IS NULL AND s.refresh_expires_at>?'); params.push(dtIso(now.toISOString())); }
|
|
442
|
+
else if (input.state === 'expired') { where.push('s.revoked_at IS NULL AND s.refresh_expires_at<=?'); params.push(dtIso(now.toISOString())); }
|
|
443
|
+
else if (input.state === 'revoked') where.push('s.revoked_at IS NOT NULL');
|
|
444
|
+
if (input.cursor) {
|
|
445
|
+
where.push('(s.created_at<? OR (s.created_at=? AND s.session_id<?))');
|
|
446
|
+
params.push(dtIso(input.cursor.createdAt), dtIso(input.cursor.createdAt), input.cursor.sessionId);
|
|
447
|
+
}
|
|
448
|
+
const [rows] = await this.pool.query(`SELECT ${BUSINESS_SESSION_COLUMNS} FROM bz_agent_sessions s WHERE ${where.join(' AND ')} ORDER BY s.created_at DESC,s.session_id DESC LIMIT ?`, [...params, limit + 1]);
|
|
449
|
+
const records = rows as any[];
|
|
450
|
+
if (records.some((row) => row.client_app_id !== input.clientAppId)) throw new Error('Business Session ownership mismatch.');
|
|
451
|
+
const selected = records.slice(0, limit);
|
|
452
|
+
const last = selected.at(-1);
|
|
453
|
+
if (records.length > limit && last && typeof last.cursor_created_at !== 'string') throw new Error('Business Session cursor timestamp is invalid.');
|
|
454
|
+
// Use a DB-formatted UTC literal for the cursor rather than reparsing a
|
|
455
|
+
// driver's local-time Date; the cursor must round-trip the stored DATETIME.
|
|
456
|
+
return { list: selected.map((row) => businessSessionRow(row, now)),
|
|
457
|
+
...(records.length > limit && last ? { nextCursor: { createdAt: String(last.cursor_created_at), sessionId: String(last.session_id) } } : {}) };
|
|
458
|
+
}
|
|
459
|
+
|
|
279
460
|
/** Admin-only projection. Token hashes and refresh-token rows never leave the repository. */
|
|
280
461
|
async listSessionsForAdmin(input: {
|
|
281
462
|
clientAppId?: string;
|
|
@@ -305,7 +486,7 @@ export class AgentAuthRepository {
|
|
|
305
486
|
const predicate = where.length ? ` WHERE ${where.join(' AND ')}` : '';
|
|
306
487
|
const [countRows] = await this.pool.query(`SELECT COUNT(*) AS total FROM bz_agent_sessions${predicate}`, params);
|
|
307
488
|
const [rows] = await this.pool.query(
|
|
308
|
-
`SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions${predicate} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
|
|
489
|
+
`SELECT session_id,client_app_id,device_label,subject_display,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions${predicate} ORDER BY created_at DESC LIMIT ? OFFSET ?`,
|
|
309
490
|
[...params, limit, offset],
|
|
310
491
|
);
|
|
311
492
|
return {
|
|
@@ -316,7 +497,7 @@ export class AgentAuthRepository {
|
|
|
316
497
|
|
|
317
498
|
async getSessionForAdmin(sessionId: string, now = new Date()): Promise<AgentSessionAdminRecord | null> {
|
|
318
499
|
const [rows] = await this.pool.query(
|
|
319
|
-
'SELECT session_id,client_app_id,device_label,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions WHERE session_id=? LIMIT 1',
|
|
500
|
+
'SELECT session_id,client_app_id,device_label,subject_display,principal_json,on_behalf_of,allowed_routes,access_expires_at,refresh_expires_at,created_at,updated_at,last_seen_at,revoked_at FROM bz_agent_sessions WHERE session_id=? LIMIT 1',
|
|
320
501
|
[sessionId],
|
|
321
502
|
);
|
|
322
503
|
return (rows as any[])[0] ? sessionAdminRow((rows as any[])[0], now) : null;
|
|
@@ -351,12 +532,17 @@ export class AgentAuthRepository {
|
|
|
351
532
|
const connection = await this.pool.getConnection();
|
|
352
533
|
try {
|
|
353
534
|
await connection.beginTransaction();
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
const
|
|
535
|
+
// Locate without locking, then lock Session before refresh rows just like
|
|
536
|
+
// revocation. Revalidate the token's original owner after both locks.
|
|
537
|
+
const [located] = await connection.query('SELECT session_id FROM bz_agent_refresh_tokens WHERE token_hash=? LIMIT 1', [input.refreshTokenHash]);
|
|
538
|
+
const sessionId = (located as any[])[0]?.session_id;
|
|
539
|
+
if (!sessionId) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
540
|
+
const [sessionRows] = await connection.query('SELECT * FROM bz_agent_sessions WHERE session_id=? FOR UPDATE', [sessionId]);
|
|
358
541
|
const session = (sessionRows as any[])[0];
|
|
359
542
|
if (!session || String(session.client_app_id) !== input.clientAppId) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
543
|
+
const [tokenRows] = await connection.query('SELECT * FROM bz_agent_refresh_tokens WHERE token_hash=? FOR UPDATE', [input.refreshTokenHash]);
|
|
544
|
+
const tokenRow = (tokenRows as any[])[0];
|
|
545
|
+
if (!tokenRow || String(tokenRow.session_id) !== String(sessionId)) { await rollback(connection); return { ok: false, reason: 'invalid_grant' }; }
|
|
360
546
|
if (String(tokenRow.status) !== 'active') {
|
|
361
547
|
const stamp = dt();
|
|
362
548
|
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, session.session_id]);
|
|
@@ -408,12 +594,14 @@ export class AgentAuthRepository {
|
|
|
408
594
|
const connection = await this.pool.getConnection();
|
|
409
595
|
try {
|
|
410
596
|
await connection.beginTransaction();
|
|
411
|
-
const [
|
|
412
|
-
|
|
413
|
-
[refreshTokenHash, clientAppId],
|
|
414
|
-
);
|
|
415
|
-
const sessionId = (rows as any[])[0]?.session_id;
|
|
597
|
+
const [located] = await connection.query('SELECT session_id FROM bz_agent_refresh_tokens WHERE token_hash=? LIMIT 1', [refreshTokenHash]);
|
|
598
|
+
const sessionId = (located as any[])[0]?.session_id;
|
|
416
599
|
if (!sessionId) { await rollback(connection); return false; }
|
|
600
|
+
const [sessions] = await connection.query('SELECT session_id,client_app_id FROM bz_agent_sessions WHERE session_id=? LIMIT 1 FOR UPDATE', [sessionId]);
|
|
601
|
+
const session = (sessions as any[])[0];
|
|
602
|
+
if (!session || String(session.client_app_id) !== clientAppId) { await rollback(connection); return false; }
|
|
603
|
+
const [tokens] = await connection.query('SELECT * FROM bz_agent_refresh_tokens WHERE token_hash=? FOR UPDATE', [refreshTokenHash]);
|
|
604
|
+
if (!(tokens as any[])[0] || String((tokens as any[])[0].session_id) !== String(sessionId)) { await rollback(connection); return false; }
|
|
417
605
|
const stamp = dt();
|
|
418
606
|
await connection.query('UPDATE bz_agent_sessions SET revoked_at=COALESCE(revoked_at,?),updated_at=? WHERE session_id=?', [stamp, stamp, sessionId]);
|
|
419
607
|
await connection.query('UPDATE bz_agent_refresh_tokens SET status=\'revoked\',used_at=COALESCE(used_at,?) WHERE session_id=? AND status=\'active\'', [stamp, sessionId]);
|
|
@@ -450,4 +638,6 @@ export class AgentAuthRepository {
|
|
|
450
638
|
}
|
|
451
639
|
}
|
|
452
640
|
|
|
453
|
-
|
|
641
|
+
type AgentAuthLifecycleMethod = 'getBusinessSession' | 'listBusinessSessions' | 'revokeAuthorization' | 'updateSubjectDisplay';
|
|
642
|
+
export type AgentAuthRepositoryContract = Omit<Pick<AgentAuthRepository, keyof AgentAuthRepository>, AgentAuthLifecycleMethod> &
|
|
643
|
+
Partial<Pick<AgentAuthRepository, AgentAuthLifecycleMethod>>;
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { dt } from '../../core/config/config-codec';
|
|
3
3
|
|
|
4
|
+
/** Message channel is a bounded display label; the original Client is preserved by agent_run_id. */
|
|
5
|
+
function agentMessageChannel(clientAppId: string): string {
|
|
6
|
+
const label = `agent:${clientAppId}`;
|
|
7
|
+
return label.length <= 64 ? label : `agent:sha256:${createHash('sha256').update(clientAppId).digest('hex').slice(0, 48)}`;
|
|
8
|
+
}
|
|
9
|
+
|
|
4
10
|
export interface AgentClientRunRecord {
|
|
5
11
|
run_id: string;
|
|
6
12
|
session_id: string;
|
|
@@ -244,7 +250,7 @@ export class AgentClientRuntimeRepository {
|
|
|
244
250
|
const at = dt();
|
|
245
251
|
await conn.query(
|
|
246
252
|
'INSERT INTO bz_messages (thread_id,direction,channel,principal_id,job_id,agent_run_id,external_message_id,content,created_at) VALUES (?,\'in\',?,?,?,?,?,?,?)',
|
|
247
|
-
[Number(row.thread_id),
|
|
253
|
+
[Number(row.thread_id), agentMessageChannel(input.client_app_id), input.principal_id || null, null, input.run_id, String(row.user_message_id), String(row.user_input), at],
|
|
248
254
|
);
|
|
249
255
|
await conn.query('UPDATE bz_threads SET message_count=message_count+1,last_active_at=? WHERE thread_id=?', [at, Number(row.thread_id)]);
|
|
250
256
|
await conn.query(
|
|
@@ -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
|
+
});
|