bailinghub 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.gitignore +5 -0
  2. package/README.en.md +5 -2
  3. package/README.md +6 -2
  4. package/SECURITY.md +11 -0
  5. package/docker-compose.images.yml +2 -2
  6. package/docs/AGENT_AUTH_API.en.md +191 -0
  7. package/docs/AGENT_AUTH_API.md +202 -0
  8. package/docs/AGENT_CLIENT_QUICKSTART.en.md +263 -0
  9. package/docs/AGENT_CLIENT_QUICKSTART.md +245 -0
  10. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
  11. package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
  12. package/docs/CHANGELOG.en.md +25 -0
  13. package/docs/CHANGELOG.md +25 -0
  14. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  15. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  16. package/docs/README.en.md +10 -2
  17. package/docs/README.md +10 -2
  18. package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
  19. package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
  20. package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
  21. package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
  22. package/package.json +3 -2
  23. package/schemas/config/client.schema.json +7 -0
  24. package/schemas/config/common.schema.json +30 -0
  25. package/schemas/config/route.schema.json +11 -0
  26. package/scripts/check-doc-links.mjs +2 -1
  27. package/scripts/check-image-tags.sh +1 -1
  28. package/scripts/check-release-consistency.test.mjs +5 -5
  29. package/scripts/e2e-console.mjs +144 -0
  30. package/scripts/export-oss.mjs +5 -12
  31. package/scripts/install.sh +1 -1
  32. package/scripts/public-content-denylist.mjs +82 -0
  33. package/scripts/public-content-denylist.test.mjs +53 -0
  34. package/scripts/publish-images.sh +1 -1
  35. package/scripts/release-audit.mjs +9 -13
  36. package/scripts/sdk-runtime-test.mjs +171 -7
  37. package/scripts/security-scan.mjs +8 -5
  38. package/scripts/validate-examples.mjs +3 -1
  39. package/scripts/verify-github-repo.mjs +8 -12
  40. package/scripts/verify-oss-export.mjs +6 -12
  41. package/sdk/php/README.md +27 -1
  42. package/sdk/php/src/AgentAuth.php +78 -0
  43. package/sdk/php/src/HubClient.php +3 -0
  44. package/sdk/php7/README.md +32 -2
  45. package/sdk/php7/src/AgentAuth.php +77 -0
  46. package/sdk/php7/src/HubClient.php +3 -0
  47. package/sql/055_agent_auth.sql +72 -0
  48. package/sql/056_agent_client_runtime.sql +60 -0
  49. package/src/adapters/channels/wecom-api.ts +1 -1
  50. package/src/app/agent-client-runtime.test.ts +221 -0
  51. package/src/app/agent-client-runtime.ts +408 -0
  52. package/src/app/agent-tool-invocations.test.ts +462 -0
  53. package/src/app/agent-tool-invocations.ts +795 -0
  54. package/src/app/agent-tool-job.test.ts +62 -0
  55. package/src/app/agent-tool-job.ts +41 -0
  56. package/src/app/auth.ts +2 -1
  57. package/src/app/kernel.ts +2 -0
  58. package/src/app/oss-edition.ts +1 -0
  59. package/src/app/runtime-context.ts +8 -0
  60. package/src/app/tool-approvals.ts +5 -1
  61. package/src/app/tool-assembly.ts +19 -1
  62. package/src/app/tool-context.ts +2 -1
  63. package/src/core/config/agent-direct-console-selection.test.ts +22 -0
  64. package/src/core/config/config-codec.ts +2 -1
  65. package/src/core/config/config-models.test.ts +10 -0
  66. package/src/core/config/config-models.ts +21 -0
  67. package/src/core/config/config-schema.test.ts +6 -0
  68. package/src/core/config/route-config.test.ts +15 -0
  69. package/src/core/config/route-config.ts +36 -0
  70. package/src/core/config/tools-config.test.ts +58 -1
  71. package/src/core/config/tools-config.ts +84 -0
  72. package/src/core/contracts/tools.ts +162 -29
  73. package/src/core/contracts/types.ts +36 -0
  74. package/src/core/runtime/agent-client-trace.test.ts +154 -0
  75. package/src/core/runtime/agent-client-trace.ts +288 -0
  76. package/src/core/runtime/launch-runtime.ts +13 -0
  77. package/src/core/runtime/trace-runtime.test.ts +18 -1
  78. package/src/core/runtime/trace-runtime.ts +28 -3
  79. package/src/core/state/state-codec.ts +2 -0
  80. package/src/infrastructure/config/config-agent-auth-repository.test.ts +183 -0
  81. package/src/infrastructure/config/config-agent-auth-repository.ts +453 -0
  82. package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
  83. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +307 -0
  84. package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
  85. package/src/infrastructure/config/config-approval-ledger.ts +16 -0
  86. package/src/infrastructure/config/config-client-repository.ts +3 -3
  87. package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
  88. package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
  89. package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
  90. package/src/infrastructure/config/config-observability-ledger.ts +65 -10
  91. package/src/infrastructure/config/config-route-repository.ts +4 -3
  92. package/src/infrastructure/config/configstore.ts +14 -3
  93. package/src/infrastructure/state/state-mysql.ts +2 -2
  94. package/src/kernel-api/v1/contracts.ts +8 -0
  95. package/src/routes/admin-agent-clients.test.ts +120 -0
  96. package/src/routes/admin-agent-clients.ts +161 -0
  97. package/src/routes/admin-runtime.test.ts +214 -0
  98. package/src/routes/admin-runtime.ts +82 -2
  99. package/src/routes/admin.ts +3 -0
  100. package/src/routes/agent-api.test.ts +379 -0
  101. package/src/routes/agent-api.ts +251 -0
  102. package/src/routes/agent-auth.test.ts +276 -0
  103. package/src/routes/agent-auth.ts +395 -0
  104. package/src/routes/approvals.ts +4 -1
  105. package/src/routes/critical-routes.test.ts +235 -1
  106. package/src/routes/private-default.ts +2 -1
  107. package/src/routes/private.ts +16 -1
  108. package/src/routes/run.ts +79 -13
  109. package/web/connect/bailing-connect-php.tgz +0 -0
  110. package/web/connect/bailing-connect-php7.tgz +0 -0
  111. package/web/console/assets/{Accounts-DuUY2UJU.js → Accounts-r10QUjLQ.js} +1 -1
  112. package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
  113. package/web/console/assets/AgentClients-UTTqbkjy.js +1 -0
  114. package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-BGKkYIya.js} +1 -1
  115. package/web/console/assets/{Audit-CQwJRIJT.js → Audit-CQmjOAoO.js} +1 -1
  116. package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-BF_0pCa3.js} +1 -1
  117. package/web/console/assets/{Channels-BIploUT-.js → Channels-C4yZE67F.js} +1 -1
  118. package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-OqsqLjU6.js} +1 -1
  119. package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
  120. package/web/console/assets/Clients-Dv3sv51C.js +3 -0
  121. package/web/console/assets/{Cost-BF52tfU2.js → Cost-C_-kiH59.js} +1 -1
  122. package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-CPTEAiV6.js} +1 -1
  123. package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-O-NKFOeI.js} +1 -1
  124. package/web/console/assets/{Executors-CzlZlznA.js → Executors-GVIAiNgv.js} +1 -1
  125. package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
  126. package/web/console/assets/{Kb-CVX22U4k.js → Kb-BsCWkJI1.js} +2 -2
  127. package/web/console/assets/{Login-PoUVsBI-.js → Login-VFjkHNMr.js} +1 -1
  128. package/web/console/assets/{Projects-DYlbjLQy.js → Projects-Ds-sJwfy.js} +1 -1
  129. package/web/console/assets/Routes-CXGl9SMM.css +1 -0
  130. package/web/console/assets/Routes-Wwurw2UU.js +124 -0
  131. package/web/console/assets/Runs-4zDD9VOC.css +1 -0
  132. package/web/console/assets/Runs-DLPzXmSy.js +3 -0
  133. package/web/console/assets/{Setup-xiPXit_b.js → Setup-BLelw0_V.js} +1 -1
  134. package/web/console/assets/Shell-CvaeK4j_.js +1 -0
  135. package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
  136. package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-Dv6u47yO.js} +1 -1
  137. package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-B9K7zaDU.js} +1 -1
  138. package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-H-oKDo-y.js} +1 -1
  139. package/web/console/assets/{Targets-y1KllVXT.js → Targets-CCFhjPKf.js} +1 -1
  140. package/web/console/assets/{Tools-DoEP_y9x.js → Tools-D0H9xpFH.js} +1 -1
  141. package/web/console/assets/index-CuoTgf6q.js +2 -0
  142. package/web/console/assets/{index-DZEQL_yy.js → index-DyX9Bz3V.js} +1 -1
  143. package/web/console/assets/{request-CBLNpLth.js → request-F5lXa7Ro.js} +1 -1
  144. package/web/console/assets/{schema-DzwLpuOy.js → schema-DUWaWqPn.js} +1 -1
  145. package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
  146. package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
  147. package/web/console/assets/{vendor-mammoth-DvgsHdlx.js → vendor-mammoth-nXG51Cg7.js} +1 -1
  148. package/web/console/index.html +2 -2
  149. package/web-admin/src/agent-direct-selection.ts +21 -0
  150. package/web-admin/src/layout/Shell.vue +1 -1
  151. package/web-admin/src/pages/AgentClients.vue +254 -0
  152. package/web-admin/src/pages/Clients.vue +13 -3
  153. package/web-admin/src/pages/Routes.vue +331 -16
  154. package/web-admin/src/pages/Runs.vue +159 -38
  155. package/web-admin/src/router.ts +2 -0
  156. package/web/console/assets/Clients--D7NQJKk.css +0 -1
  157. package/web/console/assets/Clients-DS29eUi2.js +0 -3
  158. package/web/console/assets/Routes-DSEvGujN.js +0 -124
  159. package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
  160. package/web/console/assets/Runs-B-TsYZEt.js +0 -3
  161. package/web/console/assets/Runs-CUtSsPW-.css +0 -1
  162. package/web/console/assets/Shell-BVIjmoY8.css +0 -1
  163. package/web/console/assets/Shell-DNiWZOYB.js +0 -1
  164. package/web/console/assets/index-CxPIS6G7.js +0 -2
@@ -0,0 +1,288 @@
1
+ import type { Job, ToolApproval, TraceSeverity, TraceStage } from '../contracts/types';
2
+ import { redactText } from './redaction-runtime';
3
+ import {
4
+ traceSeverityOf,
5
+ traceStageOf,
6
+ traceSummaryOf,
7
+ traceTitleOf,
8
+ type RawTraceAudit,
9
+ } from './trace-runtime';
10
+
11
+ export type AgentClientTraceSource = 'local_agent' | 'hub_governance';
12
+
13
+ export interface AgentClientTraceRun {
14
+ run_id: string;
15
+ thread_id: number;
16
+ client_app_id: string;
17
+ route_key: string;
18
+ status: string;
19
+ model: string | null;
20
+ runtime: string | null;
21
+ usage: Record<string, unknown> | null;
22
+ created_at: string;
23
+ updated_at: string;
24
+ completed_at: string | null;
25
+ }
26
+
27
+ export interface AgentClientTraceToolInput {
28
+ job: Job;
29
+ audit: RawTraceAudit[];
30
+ approvals: ToolApproval[];
31
+ }
32
+
33
+ export interface AgentClientTraceEvent {
34
+ ts: string;
35
+ event: string;
36
+ stage: TraceStage;
37
+ severity: TraceSeverity;
38
+ title: string;
39
+ summary: string;
40
+ detail: Record<string, unknown>;
41
+ source: AgentClientTraceSource;
42
+ tool_job_id?: string;
43
+ }
44
+
45
+ const SAFE_USAGE_KEYS = [
46
+ 'input_tokens',
47
+ 'cached_input_tokens',
48
+ 'output_tokens',
49
+ 'total_tokens',
50
+ 'tool_calls',
51
+ 'cost_usd',
52
+ ] as const;
53
+
54
+ const SAFE_AUDIT_KEYS = [
55
+ 'provider',
56
+ 'tool',
57
+ 'scope',
58
+ 'method',
59
+ 'path',
60
+ 'status',
61
+ 'ok',
62
+ 'duration_ms',
63
+ 'approval_id',
64
+ 'state',
65
+ 'business_status',
66
+ 'route',
67
+ 'invocation_id',
68
+ 'client_app_id',
69
+ 'agent_thread_id',
70
+ 'thread_id',
71
+ 'active_tools',
72
+ 'args_bytes',
73
+ 'args_truncated',
74
+ 'resp_bytes',
75
+ 'resp_truncated',
76
+ 'policy',
77
+ 'by',
78
+ 'used',
79
+ 'limit',
80
+ 'remaining',
81
+ 'attempt',
82
+ 'max',
83
+ 'via',
84
+ ] as const;
85
+
86
+ function objectValue(value: unknown): Record<string, unknown> {
87
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
88
+ }
89
+
90
+ function safeText(value: unknown, limit: number): string {
91
+ return redactText(String(value ?? '')).slice(0, limit);
92
+ }
93
+
94
+ function safeUsage(value: Record<string, unknown> | null): Record<string, number> | null {
95
+ if (!value) return null;
96
+ const out: Record<string, number> = {};
97
+ for (const key of SAFE_USAGE_KEYS) {
98
+ const n = Number(value[key]);
99
+ if (Number.isFinite(n) && n >= 0) out[key] = n;
100
+ }
101
+ return Object.keys(out).length ? out : null;
102
+ }
103
+
104
+ function safeScalar(value: unknown): unknown {
105
+ if (typeof value === 'string') return safeText(value, 512);
106
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;
107
+ if (typeof value === 'boolean' || value === null) return value;
108
+ return undefined;
109
+ }
110
+
111
+ function argumentKeys(value: unknown): string[] {
112
+ let parsed = value;
113
+ if (typeof value === 'string') {
114
+ try { parsed = JSON.parse(value) as unknown; }
115
+ catch { return []; }
116
+ }
117
+ const keys = Array.isArray(parsed)
118
+ ? parsed.filter((item): item is string => typeof item === 'string')
119
+ : parsed && typeof parsed === 'object'
120
+ ? Object.keys(parsed as Record<string, unknown>)
121
+ : [];
122
+ return [...new Set(keys.map((key) => safeText(key, 128)).filter(Boolean))].slice(0, 50);
123
+ }
124
+
125
+ /**
126
+ * 会话页是日常审计视图,不复用完整 Job Trace 的 raw detail。
127
+ * 即使 Tool Provider 开了 log_payload,这里也只显示键名、字节数和治理结果;完整载荷仍留在授权的单 Job 审计页。
128
+ */
129
+ export function safeAgentClientAuditDetail(event: string, value: unknown): Record<string, unknown> {
130
+ const detail = objectValue(value);
131
+ const out: Record<string, unknown> = {};
132
+ for (const key of SAFE_AUDIT_KEYS) {
133
+ const kept = safeScalar(detail[key]);
134
+ if (kept !== undefined) out[key] = kept;
135
+ }
136
+ if (event === 'tool_call') {
137
+ const keys = argumentKeys(detail['args']);
138
+ if (keys.length) out['argument_keys'] = keys;
139
+ }
140
+ return out;
141
+ }
142
+
143
+ function safeAuditEvent(
144
+ audit: RawTraceAudit,
145
+ source: AgentClientTraceSource,
146
+ toolJobId?: string,
147
+ ): AgentClientTraceEvent {
148
+ const event = String(audit.event || 'unknown');
149
+ const detail = safeAgentClientAuditDetail(event, audit.detail);
150
+ const rebuiltSummary = traceSummaryOf(event, detail);
151
+ // Agent Client 早期记录在新增专属 stage/title 前已可能落库,查询时只对这组已知事件补齐语义。
152
+ // 其他审计事件仍以写入时固化的 stage/title 为事实,避免查询层重新解释历史。
153
+ const remapAgentEvent = event.startsWith('agent_client_') || event.startsWith('agent_tool_');
154
+ return {
155
+ ts: new Date(audit.ts).toISOString(),
156
+ event,
157
+ stage: remapAgentEvent ? traceStageOf(event, detail) : audit.stage,
158
+ severity: remapAgentEvent ? traceSeverityOf(event, detail) : audit.severity,
159
+ // title 同样由事件名重建,不投影可由写入方自定义的文本。
160
+ title: safeText(traceTitleOf(event), 128),
161
+ // 不回落到 raw audit.summary:审批 confirmPrompt 等历史摘要可能已替换过真实参数值。
162
+ summary: safeText(rebuiltSummary, 512),
163
+ detail,
164
+ source,
165
+ ...(toolJobId ? { tool_job_id: toolJobId } : {}),
166
+ };
167
+ }
168
+
169
+ function elapsedMs(start: string, end: string | null): number | undefined {
170
+ if (!end) return undefined;
171
+ const a = new Date(start).getTime();
172
+ const b = new Date(end).getTime();
173
+ return Number.isFinite(a) && Number.isFinite(b) && b >= a ? b - a : undefined;
174
+ }
175
+
176
+ function latestApproval(approvals: ToolApproval[]): ToolApproval | undefined {
177
+ return approvals.length ? approvals[approvals.length - 1] : undefined;
178
+ }
179
+
180
+ export function buildAgentClientTrace(input: {
181
+ run: AgentClientTraceRun;
182
+ runAudit: RawTraceAudit[];
183
+ tools: AgentClientTraceToolInput[];
184
+ candidatesTruncated?: boolean;
185
+ }): Record<string, unknown> {
186
+ const runUsage = safeUsage(input.run.usage);
187
+ const approvalCount = input.tools.reduce((count, tool) => count + tool.approvals.length, 0);
188
+ const events: Array<AgentClientTraceEvent & { order: number }> = [];
189
+ let order = 0;
190
+ events.push({
191
+ ts: new Date(input.run.created_at).toISOString(),
192
+ event: 'agent_client_run_started',
193
+ stage: 'launch',
194
+ severity: 'info',
195
+ title: '本地智能体开始处理',
196
+ summary: '本轮由本地智能体负责理解、规划和工具选择',
197
+ detail: { planner: 'local_agent', hidden_reasoning_sync: false },
198
+ source: 'local_agent',
199
+ order: order++,
200
+ });
201
+
202
+ for (const audit of input.runAudit) {
203
+ if (audit.event === 'agent_client_run_completed') continue;
204
+ events.push({ ...safeAuditEvent(audit, 'hub_governance'), order: order++ });
205
+ }
206
+
207
+ const invocations = input.tools.map(({ job, audit, approvals }) => {
208
+ for (const entry of audit) {
209
+ events.push({ ...safeAuditEvent(entry, 'hub_governance', job.job_id), order: order++ });
210
+ }
211
+ const metadata = objectValue(job.metadata);
212
+ const result = objectValue(job.result);
213
+ const approval = latestApproval(approvals);
214
+ const duration = elapsedMs(job.created_at, job.updated_at);
215
+ return {
216
+ job_id: job.job_id,
217
+ invocation_id: safeText(metadata['agent_invocation_id'], 64),
218
+ tool: safeText(metadata['agent_tool'], 64),
219
+ status: job.status,
220
+ state: safeText(result['state'], 64) || null,
221
+ ok: typeof result['ok'] === 'boolean' ? result['ok'] : null,
222
+ business_status: safeScalar(result['business_status']) ?? null,
223
+ approval_status: approval?.status ?? null,
224
+ approval_id: approval?.id ?? null,
225
+ event_count: audit.length,
226
+ ...(duration !== undefined ? { duration_ms: duration } : {}),
227
+ created_at: new Date(job.created_at).toISOString(),
228
+ updated_at: new Date(job.updated_at).toISOString(),
229
+ };
230
+ });
231
+
232
+ if (input.run.completed_at) {
233
+ events.push({
234
+ ts: new Date(input.run.completed_at).toISOString(),
235
+ event: 'agent_client_run_completed',
236
+ stage: 'delivery',
237
+ severity: input.run.status === 'completed' ? 'info' : input.run.status === 'failed' ? 'error' : 'warning',
238
+ title: '本地智能体已提交最终回复',
239
+ summary: [input.run.status, input.run.model, input.run.runtime].filter(Boolean).map((v) => safeText(v, 191)).join(' · '),
240
+ detail: { status: input.run.status },
241
+ source: 'local_agent',
242
+ order: order++,
243
+ });
244
+ }
245
+
246
+ events.sort((a, b) => {
247
+ const byTime = new Date(a.ts).getTime() - new Date(b.ts).getTime();
248
+ return byTime || a.order - b.order;
249
+ });
250
+ const publicEvents = events.map(({ order: _order, ...event }) => event);
251
+ const duration = elapsedMs(input.run.created_at, input.run.completed_at ?? input.run.updated_at);
252
+
253
+ return {
254
+ kind: 'agent_client_run',
255
+ run: {
256
+ run_id: input.run.run_id,
257
+ thread_id: input.run.thread_id,
258
+ client_app_id: input.run.client_app_id,
259
+ route_key: input.run.route_key,
260
+ status: input.run.status,
261
+ model: input.run.model,
262
+ runtime: input.run.runtime,
263
+ usage: runUsage,
264
+ created_at: new Date(input.run.created_at).toISOString(),
265
+ updated_at: new Date(input.run.updated_at).toISOString(),
266
+ completed_at: input.run.completed_at ? new Date(input.run.completed_at).toISOString() : null,
267
+ governance: {
268
+ planner: 'local_agent',
269
+ execution: 'bailinghub_governed',
270
+ hidden_reasoning_sync: false,
271
+ tool_payloads: 'summary_only',
272
+ },
273
+ },
274
+ trace: {
275
+ summary: {
276
+ event_count: publicEvents.length,
277
+ tool_invocations: invocations.length,
278
+ approvals: approvalCount,
279
+ warning_count: publicEvents.filter((event) => event.severity === 'warning').length,
280
+ error_count: publicEvents.filter((event) => event.severity === 'error').length,
281
+ ...(duration !== undefined ? { duration_ms: duration } : {}),
282
+ partial: !!input.candidatesTruncated,
283
+ },
284
+ events: publicEvents,
285
+ },
286
+ invocations,
287
+ };
288
+ }
@@ -7,6 +7,15 @@ import { resolveMemoryConfig } from './memory';
7
7
  import { type MemoryStoreLike } from './memory-runtime';
8
8
  import type { AuditEntry, Job, Route, SessionTarget } from '../contracts/types';
9
9
 
10
+ /** 由受信 Agent API 构造的中性身份归属;不承载付费或权益语义。 */
11
+ export interface AgentAttribution {
12
+ agentSessionId: string;
13
+ clientAppId: string;
14
+ subjectId: string;
15
+ businessTenantRef?: string;
16
+ onBehalfOf: string;
17
+ }
18
+
10
19
  /** launchJob 的入参:触发面(/run、/chat)各自做完闸门与会话解析后交到这里。 */
11
20
  export interface LaunchSpec {
12
21
  requestId: string;
@@ -26,6 +35,8 @@ export interface LaunchSpec {
26
35
  threadScope: string; // ''=不记总账
27
36
  principalId: string | null;
28
37
  channel: string; // 总账入站消息的渠道标识(接入方 app_id / 'admin' / 'chat:<entry>')
38
+ /** 只有独立 Agent API 可填;普通 /run 永不从请求体构造。 */
39
+ agentAttribution?: AgentAttribution;
29
40
  }
30
41
 
31
42
  export interface LaunchStateStoreLike {
@@ -79,6 +90,7 @@ export async function rejectLaunchJob(
79
90
  job_id: randomUUID(), request_id: s.requestId, status: 'rejected',
80
91
  target: s.target, profile: s.profileName, project: s.project ?? '', source: s.source,
81
92
  client_app_id: s.clientAppId, thread_id: input.threadId, session_id: s.session.sessionId,
93
+ agent_session_id: s.agentAttribution?.agentSessionId, on_behalf_of: s.agentAttribution?.onBehalfOf,
82
94
  input_preview: s.fullInput.slice(0, 200), input: sanitizeUserInput(s.fullInput),
83
95
  dispatch: { target_config: s.route?.target_config ?? {}, is_continue: s.session.isContinue, route_key: s.routeKey ?? undefined, route_name: s.route?.name },
84
96
  error: input.error, metadata: s.metadata, callback_url: s.callbackUrl, created_at: deps.now(), updated_at: deps.now(),
@@ -150,6 +162,7 @@ export async function launchJobRecord(s: LaunchSpec, deps: LaunchRuntimeDeps): P
150
162
  job_id: randomUUID(), request_id: s.requestId, status: 'queued',
151
163
  target: s.target, profile: s.profileName, project: s.project ?? '', source: s.source,
152
164
  client_app_id: s.clientAppId, thread_id: threadId, session_id: s.session.sessionId,
165
+ agent_session_id: s.agentAttribution?.agentSessionId, on_behalf_of: s.agentAttribution?.onBehalfOf,
153
166
  input_preview: s.fullInput.slice(0, 200),
154
167
  input: initial ? initial.dispatchInput : safeUserInput,
155
168
  dispatch: baseDispatch as Job['dispatch'],
@@ -1,7 +1,7 @@
1
1
  // 覆盖:trace 解释层。audit 是事实账本,本模块负责把散装事件稳定映射为阶段、级别、摘要和统计。
2
2
  import { test } from 'node:test';
3
3
  import assert from 'node:assert/strict';
4
- import { buildJobTrace, completeTraceEntry, normalizeTraceEvent, traceSeverityOf, traceStageOf } from './trace-runtime';
4
+ import { buildJobTrace, completeTraceEntry, normalizeTraceEvent, traceSeverityOf, traceStageOf, traceSummaryOf } from './trace-runtime';
5
5
  import type { Job } from '../contracts/types';
6
6
 
7
7
  function job(extra: Partial<Job> = {}): Job {
@@ -135,6 +135,23 @@ test('traceSeverityOf: 错误、降级、跳过和正常事件分级', () => {
135
135
  assert.equal(traceSeverityOf('delivery_skipped'), 'warning');
136
136
  assert.equal(traceSeverityOf('retry_scheduled'), 'warning');
137
137
  assert.equal(traceSeverityOf('tool_result', { ok: true, status: 200 }), 'info');
138
+ assert.equal(traceSeverityOf('agent_tool_invocation_state', { state: 'in_progress', ok: false }), 'info');
139
+ assert.equal(traceSeverityOf('agent_tool_invocation_state', { state: 'awaiting_approval', ok: false }), 'warning');
140
+ assert.equal(traceSeverityOf('agent_tool_invocation_state', { state: 'reconciliation_required', ok: false }), 'error');
141
+ });
142
+
143
+ test('Agent Client 生命周期与直调工具事件使用明确的展示阶段和标题', () => {
144
+ assert.equal(traceStageOf('agent_client_run_started'), 'launch');
145
+ assert.equal(traceStageOf('agent_client_turn_context_ready'), 'context');
146
+ assert.equal(traceStageOf('agent_tool_invocation_created'), 'tool');
147
+ assert.equal(traceStageOf('agent_client_run_completed'), 'delivery');
148
+ assert.equal(completeTraceEntry({
149
+ ts: '2026-08-26T00:00:00.000Z', job_id: 'run', request_id: 'turn',
150
+ event: 'agent_client_turn_context_ready', detail: { route: 'tenant-agent', active_tools: 3 },
151
+ }).title, '运行上下文已就绪');
152
+ assert.equal(traceSummaryOf('agent_tool_invocation_state', {
153
+ tool: 'staff_edit', state: 'executed', business_status: 200,
154
+ }), 'staff_edit · executed · business=200');
138
155
  });
139
156
 
140
157
  test('completeTraceEntry + normalizeTraceEvent: 写入时固化结构化 trace 字段并保留对象 detail', () => {
@@ -93,17 +93,18 @@ export function completeTraceEntry(entry: AuditEntry): Required<AuditEntry> {
93
93
  }
94
94
 
95
95
  export function traceStageOf(event: string, detail: Record<string, unknown> = {}): TraceStage {
96
- if (event === 'received' || event === 'awaiting_executor' || event === 'rejected') return 'launch';
96
+ if (event === 'received' || event === 'awaiting_executor' || event === 'rejected' || event === 'agent_client_run_started') return 'launch';
97
97
  if (
98
98
  event === 'kb_injected' || event === 'kb_error' ||
99
+ event === 'agent_client_turn_context_ready' ||
99
100
  event === 'perception_degraded' || event === 'speech_degraded' || event === 'file_input' || event === 'file_input_degraded' ||
100
101
  event === 'tools_retrieval_degraded' || event === 'tools_retrieval_diagnostics'
101
102
  ) return 'context';
102
103
  if (event.startsWith('memory_summary') || event === 'memory_summarized') return 'summary';
103
104
  if (event === 'recovered' || event === 'rerun' || event === 'retry_scheduled') return 'recovery';
104
105
  if (event.includes('approval') || event === 'tool_approved' || event === 'tool_denied' || event === 'tool_args_drift') return 'approval';
105
- if (event.startsWith('tool_') || event === 'tools_retrieved' || event === 'tool_lookup' || event === 'builtin_send' || event.startsWith('builtin_send_')) return 'tool';
106
- if (event.startsWith('delivery') || event.startsWith('channel_delivery') || event.startsWith('dlq_')) return 'delivery';
106
+ if (event.startsWith('tool_') || event.startsWith('agent_tool_') || event === 'tools_retrieved' || event === 'tool_lookup' || event === 'builtin_send' || event.startsWith('builtin_send_')) return 'tool';
107
+ if (event === 'agent_client_run_completed' || event.startsWith('delivery') || event.startsWith('channel_delivery') || event.startsWith('dlq_')) return 'delivery';
107
108
  if (event.startsWith('channel_') || event.startsWith('wecom_') || event === 'chat_upload' || event === 'chat_upload_error' || event === 'chat_rated') return 'channel';
108
109
  if (
109
110
  event === 'started' || event === 'dispatched' || event === 'finished' ||
@@ -124,6 +125,13 @@ export function traceStageOf(event: string, detail: Record<string, unknown> = {}
124
125
 
125
126
  export function traceSeverityOf(event: string, detail: Record<string, unknown> = {}): TraceSeverity {
126
127
  const status = String(detail['status'] ?? '');
128
+ if (event === 'agent_tool_invocation_state') {
129
+ const state = String(detail['state'] ?? '');
130
+ if (state === 'in_progress') return 'info';
131
+ if (state === 'awaiting_approval' || state === 'denied' || state === 'business_rejected' || state === 'rejected_before_dispatch') return 'warning';
132
+ if (state === 'reconciliation_required') return 'error';
133
+ if (state === 'executed') return detail['ok'] === false ? 'error' : 'info';
134
+ }
127
135
  if (event === 'tools_retrieval_diagnostics' && status !== 'ok') return 'warning';
128
136
  if (event === 'finished' && (status === 'error' || status === 'rejected')) return 'error';
129
137
  if (event.includes('error') || event.includes('failed') || event.endsWith('_failure')) return 'error';
@@ -136,6 +144,11 @@ export function traceSeverityOf(event: string, detail: Record<string, unknown> =
136
144
  export function traceTitleOf(event: string): string {
137
145
  const titles: Record<string, string> = {
138
146
  received: '任务已接收',
147
+ agent_client_run_started: '本地智能体开始处理',
148
+ agent_client_turn_context_ready: '运行上下文已就绪',
149
+ agent_client_run_completed: '本地智能体已提交最终回复',
150
+ agent_tool_invocation_created: 'ACC 工具调用已建立',
151
+ agent_tool_invocation_state: 'ACC 工具调用状态更新',
139
152
  awaiting_executor: '等待执行器认领',
140
153
  rejected: '任务被拒绝',
141
154
  started: '本地执行开始',
@@ -196,6 +209,18 @@ export function traceTitleOf(event: string): string {
196
209
 
197
210
  export function traceSummaryOf(event: string, detail: Record<string, unknown> = {}): string {
198
211
  if (event === 'received') return compact([detail['target'], detail['profile'], detail['source']]);
212
+ if (event === 'agent_client_run_started') return '本地智能体规划;中枢保留治理与审计';
213
+ if (event === 'agent_client_turn_context_ready') return compact([
214
+ detail['route'],
215
+ detail['active_tools'] != null ? `${detail['active_tools']} active tools` : '',
216
+ ]);
217
+ if (event === 'agent_client_run_completed') return compact([detail['status']]);
218
+ if (event === 'agent_tool_invocation_created') return compact([detail['tool'], detail['route']]);
219
+ if (event === 'agent_tool_invocation_state') return compact([
220
+ detail['tool'],
221
+ detail['state'],
222
+ detail['business_status'] != null ? `business=${detail['business_status']}` : '',
223
+ ]);
199
224
  if (event === 'awaiting_executor') return compact([detail['target']]);
200
225
  if (event === 'rejected') return compact([detail['reason'], detail['quota'] != null ? `quota=${detail['quota']}` : '']);
201
226
  if (event === 'dispatched') return compact([detail['executor_id'], detail['target'], detail['tools'] != null ? `${detail['tools']} tools` : '']);
@@ -19,6 +19,8 @@ export function rowToJob(r: any): Job {
19
19
  project: r.project,
20
20
  source: r.source,
21
21
  client_app_id: r.client_app_id ?? undefined,
22
+ agent_session_id: r.agent_session_id ?? undefined,
23
+ on_behalf_of: r.on_behalf_of ?? undefined,
22
24
  thread_id: r.thread_id != null ? Number(r.thread_id) : undefined,
23
25
  session_id: r.session_id ?? undefined,
24
26
  input_preview: r.input_preview ?? '',
@@ -0,0 +1,183 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+ import type { Pool } from 'mysql2/promise';
4
+ import { AgentAuthRepository } from './config-agent-auth-repository';
5
+
6
+ function sessionRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
7
+ return {
8
+ session_id: '123e4567-e89b-42d3-a456-426614174000',
9
+ client_app_id: 'example-business',
10
+ device_label: 'Mac mini',
11
+ principal_json: JSON.stringify({ id: 'user-7', tenant: 'tenant-2', roles: ['manager'] }),
12
+ on_behalf_of: 'tenant-2:user-7',
13
+ allowed_routes: JSON.stringify(['orders']),
14
+ access_token_hash: 'a'.repeat(64),
15
+ access_expires_at: '2099-01-01 00:15:00',
16
+ refresh_expires_at: '2099-01-30 00:00:00',
17
+ created_at: '2099-01-01 00:00:00',
18
+ updated_at: '2099-01-01 00:00:00',
19
+ last_seen_at: null,
20
+ revoked_at: null,
21
+ ...overrides,
22
+ };
23
+ }
24
+
25
+ test('AgentAuthRepository refresh rotation keeps the original absolute refresh expiry', async () => {
26
+ const originalRefreshExpiry = '2099-01-30 00:00:00';
27
+ let insertedRefreshExpiry: unknown;
28
+ let updatedSessionParams: unknown[] = [];
29
+ const row = sessionRow({ refresh_expires_at: originalRefreshExpiry });
30
+ const connection = {
31
+ beginTransaction: async () => undefined,
32
+ commit: async () => undefined,
33
+ rollback: async () => undefined,
34
+ release: () => undefined,
35
+ async query(sql: string, params: unknown[] = []) {
36
+ if (sql.startsWith('SELECT * FROM bz_agent_refresh_tokens')) {
37
+ return [[{ token_hash: 'r'.repeat(64), session_id: row.session_id, status: 'active', expires_at: originalRefreshExpiry }], []];
38
+ }
39
+ if (sql.startsWith('SELECT * FROM bz_agent_sessions') && sql.includes('FOR UPDATE')) return [[row], []];
40
+ if (sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=\'used\'')) return [{ affectedRows: 1 }, []];
41
+ if (sql.startsWith('INSERT INTO bz_agent_refresh_tokens')) {
42
+ insertedRefreshExpiry = params[3];
43
+ return [{ affectedRows: 1 }, []];
44
+ }
45
+ if (sql.startsWith('UPDATE bz_agent_sessions SET access_token_hash=')) {
46
+ updatedSessionParams = params;
47
+ row.access_token_hash = params[0];
48
+ row.access_expires_at = params[1];
49
+ return [{ affectedRows: 1 }, []];
50
+ }
51
+ if (sql.startsWith('SELECT * FROM bz_agent_sessions')) return [[row], []];
52
+ throw new Error(`unexpected query: ${sql}`);
53
+ },
54
+ };
55
+ const pool = { getConnection: async () => connection } as unknown as Pool;
56
+ const repo = new AgentAuthRepository(() => pool);
57
+ const result = await repo.rotateRefreshToken({
58
+ refreshTokenHash: 'r'.repeat(64),
59
+ clientAppId: 'example-business',
60
+ accessTokenHash: 'b'.repeat(64),
61
+ nextRefreshTokenHash: 'n'.repeat(64),
62
+ accessExpiresAt: '2099-01-01T00:30:00.000Z',
63
+ });
64
+
65
+ assert.equal(result.ok, true);
66
+ assert.equal(insertedRefreshExpiry, originalRefreshExpiry);
67
+ assert.equal(updatedSessionParams.length, 4);
68
+ assert.equal(updatedSessionParams.includes(originalRefreshExpiry), false);
69
+ if (result.ok) assert.equal(Date.parse(result.session.refresh_expires_at), new Date(originalRefreshExpiry).getTime());
70
+ });
71
+
72
+ test('AgentAuthRepository refresh replay revokes the whole session fail closed', async () => {
73
+ let sessionRevoked = false;
74
+ let refreshFamilyRevoked = false;
75
+ const row = sessionRow();
76
+ const connection = {
77
+ beginTransaction: async () => undefined,
78
+ commit: async () => undefined,
79
+ rollback: async () => undefined,
80
+ release: () => undefined,
81
+ async query(sql: string) {
82
+ if (sql.startsWith('SELECT * FROM bz_agent_refresh_tokens')) {
83
+ return [[{ token_hash: 'r'.repeat(64), session_id: row.session_id, status: 'used', expires_at: row.refresh_expires_at }], []];
84
+ }
85
+ if (sql.startsWith('SELECT * FROM bz_agent_sessions')) return [[row], []];
86
+ if (sql.startsWith('UPDATE bz_agent_sessions SET revoked_at=')) { sessionRevoked = true; return [{ affectedRows: 1 }, []]; }
87
+ if (sql.startsWith('UPDATE bz_agent_refresh_tokens SET status=CASE')) { refreshFamilyRevoked = true; return [{ affectedRows: 2 }, []]; }
88
+ throw new Error(`unexpected query: ${sql}`);
89
+ },
90
+ };
91
+ const pool = { getConnection: async () => connection } as unknown as Pool;
92
+ const repo = new AgentAuthRepository(() => pool);
93
+ const result = await repo.rotateRefreshToken({
94
+ refreshTokenHash: 'r'.repeat(64),
95
+ clientAppId: 'example-business',
96
+ accessTokenHash: 'b'.repeat(64),
97
+ nextRefreshTokenHash: 'n'.repeat(64),
98
+ accessExpiresAt: '2099-01-01T00:30:00.000Z',
99
+ });
100
+
101
+ assert.deepEqual(result, { ok: false, reason: 'replayed' });
102
+ assert.equal(sessionRevoked, true);
103
+ assert.equal(refreshFamilyRevoked, true);
104
+ });
105
+
106
+ test('AgentAuthRepository rejects an approved authorization after its short code expiry', async () => {
107
+ let insertedSession = false;
108
+ const connection = {
109
+ beginTransaction: async () => undefined,
110
+ commit: async () => undefined,
111
+ rollback: async () => undefined,
112
+ release: () => undefined,
113
+ async query(sql: string) {
114
+ if (sql.startsWith('SELECT * FROM bz_agent_authorizations')) {
115
+ return [[{
116
+ authorization_id: '123e4567-e89b-42d3-a456-426614174000',
117
+ client_app_id: 'example-business',
118
+ redirect_uri: 'http://127.0.0.1:43123/callback',
119
+ code_challenge: 'c'.repeat(43),
120
+ code_expires_at: '2000-01-01 00:00:00',
121
+ status: 'approved',
122
+ principal_json: JSON.stringify({ id: 'user-7', roles: [] }),
123
+ on_behalf_of: 'tenant-2:user-7',
124
+ allowed_routes: JSON.stringify(['orders']),
125
+ }], []];
126
+ }
127
+ if (sql.startsWith('INSERT INTO bz_agent_sessions')) { insertedSession = true; return [{ affectedRows: 1 }, []]; }
128
+ throw new Error(`unexpected query: ${sql}`);
129
+ },
130
+ };
131
+ const pool = { getConnection: async () => connection } as unknown as Pool;
132
+ const repo = new AgentAuthRepository(() => pool);
133
+ const result = await repo.exchangeAuthorizationCode({
134
+ codeHash: 'c'.repeat(64),
135
+ clientAppId: 'example-business',
136
+ redirectUri: 'http://127.0.0.1:43123/callback',
137
+ codeChallenge: 'c'.repeat(43),
138
+ sessionId: '223e4567-e89b-42d3-a456-426614174000',
139
+ accessTokenHash: 'a'.repeat(64),
140
+ refreshTokenHash: 'r'.repeat(64),
141
+ accessExpiresAt: '2099-01-01T00:15:00.000Z',
142
+ refreshExpiresAt: '2099-01-30T00:00:00.000Z',
143
+ });
144
+
145
+ assert.deepEqual(result, { ok: false, reason: 'invalid_grant' });
146
+ assert.equal(insertedSession, false);
147
+ });
148
+
149
+ test('AgentAuthRepository admin session projection filters state and never returns token hashes', async () => {
150
+ const queries: Array<{ sql: string; params: unknown[] }> = [];
151
+ const row = sessionRow({
152
+ access_expires_at: '2026-08-27 01:00:00',
153
+ refresh_expires_at: '2026-09-27 00:00:00',
154
+ created_at: '2026-08-27 00:00:00',
155
+ updated_at: '2026-08-27 00:10:00',
156
+ last_seen_at: '2026-08-27 00:10:00',
157
+ });
158
+ const pool = {
159
+ async query(sql: string, params: unknown[] = []) {
160
+ queries.push({ sql, params });
161
+ if (sql.startsWith('SELECT COUNT(*) AS total,')) {
162
+ return [[{ total: 3, active: 1, expired: 1, revoked: 1 }], []];
163
+ }
164
+ if (sql.startsWith('SELECT COUNT(*) AS total')) return [[{ total: 1 }], []];
165
+ if (sql.startsWith('SELECT session_id,client_app_id')) return [[row], []];
166
+ throw new Error(`unexpected query: ${sql}`);
167
+ },
168
+ } as unknown as Pool;
169
+ const repo = new AgentAuthRepository(() => pool);
170
+ const now = new Date('2026-08-27T00:30:00.000Z');
171
+ const result = await repo.listSessionsForAdmin({
172
+ clientAppId: 'example-business', state: 'active', limit: 25, offset: 5, now,
173
+ });
174
+ assert.equal(result.total, 1);
175
+ assert.equal(result.list[0]?.state, 'active');
176
+ assert.equal(result.list[0]?.last_seen_at, new Date('2026-08-27 00:10:00').toISOString());
177
+ assert.equal(Object.hasOwn(result.list[0]!, 'access_token_hash'), false);
178
+ assert.match(queries[0]!.sql, /client_app_id=\? AND revoked_at IS NULL AND refresh_expires_at>\?/);
179
+ assert.deepEqual(queries[1]!.params.slice(-2), [25, 5]);
180
+
181
+ const summary = await repo.sessionSummaryForAdmin(now);
182
+ assert.deepEqual(summary, { total: 3, active: 1, expired: 1, revoked: 1 });
183
+ });