bailinghub 0.3.4 → 0.5.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/.gitignore +5 -0
- package/README.en.md +6 -1
- package/README.md +6 -0
- package/SECURITY.md +11 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +175 -0
- package/docs/AGENT_AUTH_API.md +190 -0
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +212 -0
- package/docs/AGENT_CLIENT_QUICKSTART.md +206 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
- package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
- package/docs/CHANGELOG.en.md +59 -1
- package/docs/CHANGELOG.md +27 -1
- package/docs/COMPATIBILITY.en.md +25 -0
- package/docs/CONTRACT.en.md +79 -8
- package/docs/CONTRACT.md +36 -6
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/QUICKSTART.en.md +6 -0
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.en.md +8 -0
- package/docs/README.md +8 -0
- package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/docs/STREAMING.en.md +32 -0
- package/docs/STREAMING.md +8 -2
- package/docs/WIDGET_RENDERERS.en.md +123 -6
- package/docs/WIDGET_RENDERERS.md +75 -6
- package/docs/user-guide/console-map.en.md +1 -2
- package/docs/user-guide/console-map.md +2 -2
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
- package/package.json +3 -2
- package/schemas/config/chat-entry.schema.json +2 -1
- package/schemas/config/client.schema.json +7 -0
- package/schemas/config/common.schema.json +30 -0
- package/schemas/config/route.schema.json +11 -0
- package/scripts/check-doc-links.mjs +1 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-release-consistency.test.mjs +5 -5
- package/scripts/e2e-console.mjs +144 -0
- package/scripts/export-oss.mjs +5 -12
- package/scripts/install.sh +1 -1
- package/scripts/public-content-denylist.mjs +82 -0
- package/scripts/public-content-denylist.test.mjs +53 -0
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +8 -12
- package/scripts/sdk-runtime-test.mjs +171 -7
- package/scripts/security-scan.mjs +8 -5
- package/scripts/validate-examples.mjs +3 -1
- package/scripts/verify-github-repo.mjs +7 -11
- package/scripts/verify-oss-export.mjs +6 -12
- package/scripts/widget-renderer-test.mjs +244 -16
- package/sdk/php/README.md +27 -1
- package/sdk/php/src/AgentAuth.php +78 -0
- package/sdk/php/src/HubClient.php +3 -0
- package/sdk/php7/README.md +32 -2
- package/sdk/php7/src/AgentAuth.php +77 -0
- package/sdk/php7/src/HubClient.php +3 -0
- package/sql/055_agent_auth.sql +72 -0
- package/sql/056_agent_client_runtime.sql +60 -0
- package/src/adapters/channels/wecom-api.ts +1 -1
- package/src/app/agent-client-runtime.test.ts +221 -0
- package/src/app/agent-client-runtime.ts +408 -0
- package/src/app/agent-tool-invocations.test.ts +462 -0
- package/src/app/agent-tool-invocations.ts +795 -0
- package/src/app/agent-tool-job.test.ts +62 -0
- package/src/app/agent-tool-job.ts +41 -0
- package/src/app/auth.ts +2 -1
- package/src/app/kernel.ts +2 -0
- package/src/app/runtime-context.ts +8 -0
- package/src/app/tool-approvals.ts +5 -1
- package/src/app/tool-assembly.ts +19 -1
- package/src/app/tool-context.ts +2 -1
- package/src/core/config/config-codec.ts +2 -1
- package/src/core/config/config-models.test.ts +28 -1
- package/src/core/config/config-models.ts +46 -3
- package/src/core/config/config-schema.test.ts +8 -0
- package/src/core/config/route-config.test.ts +15 -0
- package/src/core/config/route-config.ts +36 -0
- package/src/core/config/tools-config.test.ts +58 -1
- package/src/core/config/tools-config.ts +84 -0
- package/src/core/contracts/tools.ts +162 -29
- package/src/core/contracts/types.ts +38 -1
- package/src/core/platform/chat-form.test.ts +147 -0
- package/src/core/platform/chat-form.ts +402 -0
- package/src/core/platform/version.ts +1 -1
- package/src/core/runtime/agent-client-trace.test.ts +154 -0
- package/src/core/runtime/agent-client-trace.ts +288 -0
- package/src/core/runtime/execution-runtime.test.ts +61 -0
- package/src/core/runtime/execution-runtime.ts +17 -0
- package/src/core/runtime/launch-runtime.ts +13 -0
- package/src/core/runtime/trace-runtime.test.ts +18 -1
- package/src/core/runtime/trace-runtime.ts +28 -3
- package/src/core/state/state-codec.ts +2 -0
- package/src/infrastructure/config/config-agent-auth-repository.test.ts +147 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -0
- package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
- package/src/infrastructure/config/config-approval-ledger.ts +16 -0
- package/src/infrastructure/config/config-client-repository.ts +3 -3
- package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
- package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
- package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
- package/src/infrastructure/config/config-observability-ledger.ts +65 -10
- package/src/infrastructure/config/config-route-repository.ts +4 -3
- package/src/infrastructure/config/configstore.ts +14 -3
- package/src/infrastructure/state/state-mysql.ts +2 -2
- package/src/kernel-api/v1/contracts.ts +8 -0
- package/src/routes/admin-runtime.test.ts +214 -0
- package/src/routes/admin-runtime.ts +82 -2
- package/src/routes/agent-api.test.ts +379 -0
- package/src/routes/agent-api.ts +251 -0
- package/src/routes/agent-auth.test.ts +276 -0
- package/src/routes/agent-auth.ts +395 -0
- package/src/routes/approvals.ts +4 -1
- package/src/routes/chat.test.ts +319 -7
- package/src/routes/chat.ts +166 -21
- package/src/routes/critical-routes.test.ts +235 -1
- package/src/routes/private-default.ts +2 -1
- package/src/routes/private.ts +16 -1
- package/src/routes/run.ts +79 -13
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/{Accounts-CAwrtBiS.js → Accounts-D4RRm5D1.js} +1 -1
- package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-CsTTKb8o.js} +1 -1
- package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-BzvZ7JZw.js} +1 -1
- package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-CYcA93wh.js} +1 -1
- package/web/console/assets/{Channels-DTy8ylH-.js → Channels-DRQZggqM.js} +1 -1
- package/web/console/assets/ChatEntries-BUB7BWKU.js +7 -0
- package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
- package/web/console/assets/Clients-CQ_MonGL.css +1 -0
- package/web/console/assets/Clients-HhCyrxfz.js +3 -0
- package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BZgFf1yM.js} +1 -1
- package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-BTe2Q07j.js} +1 -1
- package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-WL-buYli.js} +1 -1
- package/web/console/assets/{Executors-BXoyo28u.js → Executors-CGZ-7Xmp.js} +1 -1
- package/web/console/assets/{Kb-ISbzquab.js → Kb-VVw8oGsT.js} +1 -1
- package/web/console/assets/{Login-Dlu6Wgcf.js → Login-rwvmBBPl.js} +1 -1
- package/web/console/assets/{Projects-DFzmtnqg.js → Projects-CexaCEY1.js} +1 -1
- package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
- package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
- package/web/console/assets/Runs-4zDD9VOC.css +1 -0
- package/web/console/assets/Runs-BzFNPTwD.js +3 -0
- package/web/console/assets/{Setup-CrBAV-b9.js → Setup-Djh5yadQ.js} +1 -1
- package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-kn763smL.js} +1 -1
- package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-CQBR41W1.js} +1 -1
- package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-DgnopekD.js} +1 -1
- package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Bj8-kPt2.js} +1 -1
- package/web/console/assets/{Targets-CtIMa66c.js → Targets-BAfCt_nH.js} +1 -1
- package/web/console/assets/{Tools-BfDZHt01.js → Tools-xjd0NZdE.js} +1 -1
- package/web/console/assets/{index-DBiByFiO.js → index-DfJA7iJS.js} +2 -2
- package/web/console/assets/{request-DY2cxQqZ.js → request-DkNPOweH.js} +1 -1
- package/web/console/assets/{schema-6mCQ7rR5.js → schema-CgPWAu1_.js} +1 -1
- package/web/console/index.html +1 -1
- package/web/widget/widget.js +493 -14
- package/web-admin/src/pages/ChatEntries.vue +18 -6
- package/web-admin/src/pages/Clients.vue +11 -3
- package/web-admin/src/pages/Routes.vue +282 -16
- package/web-admin/src/pages/Runs.vue +159 -38
- package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
- package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
- package/web/console/assets/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DWs9JFr0.js +0 -3
- package/web/console/assets/Routes-B-hm9HGY.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
- package/web/console/assets/Runs-hMRu1im3.js +0 -3
|
@@ -10,15 +10,73 @@ const validPayload = {
|
|
|
10
10
|
kind: 'bar',
|
|
11
11
|
data: [{ label: '已完成', value: 12 }],
|
|
12
12
|
};
|
|
13
|
+
const formPayload = {
|
|
14
|
+
version: 1,
|
|
15
|
+
form_id: 'refund_info',
|
|
16
|
+
title: '请补充退款信息',
|
|
17
|
+
description: '这些内容会作为下一轮用户消息提交。',
|
|
18
|
+
schema: {
|
|
19
|
+
customer: { type: 'text', label: '联系人', required: true, minLength: 2, maxLength: 20, placeholder: '请输入姓名' },
|
|
20
|
+
reason: { type: 'textarea', label: '退款原因', required: true, maxLength: 200 },
|
|
21
|
+
amount: { type: 'number', label: '退款金额', required: true, min: 0, max: 1000 },
|
|
22
|
+
apply_date: { type: 'date', label: '申请日期', required: true, min: '2026-01-01', max: '2026-12-31' },
|
|
23
|
+
confirmed: { type: 'boolean', label: '已确认信息', required: true },
|
|
24
|
+
method: { type: 'single_select', label: '退款方式', required: true, options: [{ label: '原路退回', value: 'original' }, { label: '余额', value: 'balance' }] },
|
|
25
|
+
tags: { type: 'multi_select', label: '需求标记', required: true, options: [{ label: '加急', value: 'urgent' }, { label: '回访', value: 'callback' }] },
|
|
26
|
+
note: { type: 'text', label: '备注 <img src=x onerror="window.__formInjected=1">', maxLength: 80 },
|
|
27
|
+
},
|
|
28
|
+
submit_label: '提交信息',
|
|
29
|
+
};
|
|
30
|
+
const cancelFormPayload = {
|
|
31
|
+
version: 1,
|
|
32
|
+
form_id: 'cancel_form',
|
|
33
|
+
title: '可取消的表单',
|
|
34
|
+
schema: { note: { type: 'text', label: '备注', maxLength: 40 } },
|
|
35
|
+
cancel_label: '暂不填写',
|
|
36
|
+
};
|
|
37
|
+
const invalidFormPayload = {
|
|
38
|
+
version: 1,
|
|
39
|
+
form_id: 'unsafe_remote',
|
|
40
|
+
title: '不应渲染',
|
|
41
|
+
schema: { source: { type: 'remote_select', label: '远程数据', endpoint: 'https://evil.example/data' } },
|
|
42
|
+
};
|
|
43
|
+
const strictInvalidPayloads = [
|
|
44
|
+
{ ...cancelFormPayload, form_id: 'extra_top', unexpected: true },
|
|
45
|
+
{ version: 1, form_id: 'required_string', title: '非法 required', schema: { value: { type: 'text', label: '值', required: 'true' } } },
|
|
46
|
+
{ version: 1, form_id: 'text_over_cap', title: '超限文本', schema: { value: { type: 'text', label: '值', maxLength: 501 } } },
|
|
47
|
+
{ version: 1, form_id: 'number_string', title: '非法数字边界', schema: { value: { type: 'number', label: '值', min: '0' } } },
|
|
48
|
+
{ version: 1, form_id: 'bad_date', title: '非法日期边界', schema: { value: { type: 'date', label: '日期', min: '2026-02-30' } } },
|
|
49
|
+
{ version: 1, form_id: 'sensitive_copy', title: '补充信息', description: '请输入 API Key', schema: { value: { type: 'text', label: '值' } } },
|
|
50
|
+
{ version: 1, form_id: 'option_extra', title: '非法选项', schema: { value: { type: 'single_select', label: '值', options: [{ label: 'A', value: 'a', endpoint: 'https://evil.example' }] } } },
|
|
51
|
+
{ version: 1, form_id: 'control_copy', title: '含\n换行', schema: { value: { type: 'text', label: '值' } } },
|
|
52
|
+
];
|
|
53
|
+
const formBlock = (payload) => `\`\`\`bailing-form\n${JSON.stringify(payload)}\n\`\`\``;
|
|
13
54
|
const history = [
|
|
14
55
|
{ r: 'a', t: `\`\`\`bailing-chart\n${JSON.stringify(validPayload)}\n\`\`\`` },
|
|
15
56
|
{ r: 'a', t: '```unknown-chart\n{"value":1}\n```' },
|
|
16
57
|
{ r: 'a', t: '```bailing-chart\n{"broken":\n```' },
|
|
17
58
|
{ r: 'a', t: '```bailing-chart\n"scalar"\n```' },
|
|
59
|
+
{ r: 'a', t: formBlock(formPayload), j: 'source-form-1' },
|
|
60
|
+
{ r: 'a', t: formBlock(cancelFormPayload), j: 'source-form-2' },
|
|
61
|
+
{ r: 'a', t: formBlock(invalidFormPayload), j: 'source-form-invalid' },
|
|
62
|
+
...strictInvalidPayloads.map((payload, index) => ({ r: 'a', t: formBlock(payload), j: `source-form-strict-invalid-${index}` })),
|
|
63
|
+
{ r: 'a', t: formBlock(cancelFormPayload) },
|
|
18
64
|
];
|
|
19
65
|
|
|
20
|
-
|
|
21
|
-
const
|
|
66
|
+
const submissions = [];
|
|
67
|
+
const submissionWaiters = [];
|
|
68
|
+
function recordSubmission(body) {
|
|
69
|
+
const waiter = submissionWaiters.shift();
|
|
70
|
+
if (waiter) waiter(body);
|
|
71
|
+
else submissions.push(body);
|
|
72
|
+
}
|
|
73
|
+
function nextSubmission() {
|
|
74
|
+
if (submissions.length) return Promise.resolve(submissions.shift());
|
|
75
|
+
return new Promise((resolve) => { submissionWaiters.push(resolve); });
|
|
76
|
+
}
|
|
77
|
+
let serverMessages = [];
|
|
78
|
+
let cancelAttempts = 0;
|
|
79
|
+
let jobSeq = 0;
|
|
22
80
|
|
|
23
81
|
const server = createServer((req, res) => {
|
|
24
82
|
if (req.url === '/widget.js') {
|
|
@@ -28,12 +86,35 @@ const server = createServer((req, res) => {
|
|
|
28
86
|
}
|
|
29
87
|
if (req.url === '/chat/pub_test/config') {
|
|
30
88
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
31
|
-
res.end(JSON.stringify({ enabled: true, title: 'Renderer Test', greeting: '', powered_by_visible: false }));
|
|
89
|
+
res.end(JSON.stringify({ enabled: true, title: 'Renderer Test', greeting: '', default_open: false, powered_by_visible: false }));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (req.url === '/chat/pub_default_open/config') {
|
|
93
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
94
|
+
res.end(JSON.stringify({ enabled: true, title: 'Default Open Test', greeting: '', default_open: true, powered_by_visible: false }));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (req.url === '/chat/pub_default_closed/config') {
|
|
98
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
99
|
+
res.end(JSON.stringify({ enabled: true, title: 'Default Closed Test', greeting: '', default_open: false, powered_by_visible: false }));
|
|
32
100
|
return;
|
|
33
101
|
}
|
|
34
102
|
if (req.url?.startsWith('/chat/pub_test/thread')) {
|
|
35
103
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
36
|
-
res.end(JSON.stringify({ messages:
|
|
104
|
+
res.end(JSON.stringify({ messages: serverMessages }));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (req.url?.startsWith('/chat/pub_test/events/job-refund_info-')) {
|
|
108
|
+
const jobId = req.url.split('/events/')[1].split('?')[0];
|
|
109
|
+
res.writeHead(200, {
|
|
110
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
111
|
+
'cache-control': 'no-cache',
|
|
112
|
+
connection: 'keep-alive',
|
|
113
|
+
});
|
|
114
|
+
setTimeout(() => {
|
|
115
|
+
res.write(`event: done\ndata: ${JSON.stringify({ done: true, job_id: jobId, reply: 'ok:refund_info' })}\n\n`);
|
|
116
|
+
res.end();
|
|
117
|
+
}, 500);
|
|
37
118
|
return;
|
|
38
119
|
}
|
|
39
120
|
if (req.url === '/chat/pub_test' && req.method === 'POST') {
|
|
@@ -41,13 +122,28 @@ const server = createServer((req, res) => {
|
|
|
41
122
|
req.on('data', (chunk) => { chunks.push(chunk); });
|
|
42
123
|
req.on('end', () => {
|
|
43
124
|
const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
44
|
-
|
|
125
|
+
recordSubmission(body);
|
|
126
|
+
if (body.interaction_response?.form_id === 'cancel_form' && cancelAttempts++ === 0) {
|
|
127
|
+
res.writeHead(503, { 'content-type': 'application/json; charset=utf-8' });
|
|
128
|
+
res.end(JSON.stringify({ error: '模拟提交失败' }));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
45
131
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
|
46
|
-
|
|
132
|
+
const suffix = body.interaction_response?.form_id || 'message';
|
|
133
|
+
const jobId = `job-${suffix}-${++jobSeq}`;
|
|
134
|
+
res.end(JSON.stringify({ done: suffix !== 'refund_info', job_id: jobId, visitor_id: 'visitor-12345678', ...(suffix === 'refund_info' ? {} : { reply: `ok:${suffix}` }) }));
|
|
47
135
|
});
|
|
48
136
|
return;
|
|
49
137
|
}
|
|
50
138
|
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
|
|
139
|
+
if (req.url === '/default-open.html') {
|
|
140
|
+
res.end('<!doctype html><html><body><script src="/widget.js" data-entry="pub_default_open"></script></body></html>');
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (req.url === '/default-closed.html') {
|
|
144
|
+
res.end('<!doctype html><html><body><script src="/widget.js" data-entry="pub_default_closed"></script></body></html>');
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
51
147
|
res.end('<!doctype html><html><body><script src="/widget.js" data-entry="pub_test" data-open="1"></script></body></html>');
|
|
52
148
|
});
|
|
53
149
|
|
|
@@ -72,6 +168,18 @@ const executablePath = existsSync(bundledExecutable)
|
|
|
72
168
|
: systemExecutables.find((candidate) => existsSync(candidate));
|
|
73
169
|
const browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) });
|
|
74
170
|
try {
|
|
171
|
+
const defaultOpenPage = await browser.newPage();
|
|
172
|
+
await defaultOpenPage.goto(`http://127.0.0.1:${address.port}/default-open.html`);
|
|
173
|
+
await defaultOpenPage.locator('.panel').waitFor();
|
|
174
|
+
assert.equal(await defaultOpenPage.locator('.panel').evaluate((panel) => panel.classList.contains('open')), true);
|
|
175
|
+
await defaultOpenPage.close();
|
|
176
|
+
|
|
177
|
+
const defaultClosedPage = await browser.newPage();
|
|
178
|
+
await defaultClosedPage.goto(`http://127.0.0.1:${address.port}/default-closed.html`);
|
|
179
|
+
await defaultClosedPage.locator('.panel').waitFor({ state: 'attached' });
|
|
180
|
+
assert.equal(await defaultClosedPage.locator('.panel').evaluate((panel) => panel.classList.contains('open')), false);
|
|
181
|
+
await defaultClosedPage.close();
|
|
182
|
+
|
|
75
183
|
const page = await browser.newPage();
|
|
76
184
|
await page.addInitScript(({ seededHistory }) => {
|
|
77
185
|
window.__rendererMounts = 0;
|
|
@@ -82,10 +190,11 @@ try {
|
|
|
82
190
|
label: 'Test chart',
|
|
83
191
|
contentType: 'application/json',
|
|
84
192
|
mount(context) {
|
|
85
|
-
const { container, payload, signal, theme } = context;
|
|
193
|
+
const { container, payload, signal, theme, message, respond } = context;
|
|
86
194
|
window.__rendererMounts += 1;
|
|
87
195
|
window.__rendererContextKeys = Object.keys(context).sort();
|
|
88
|
-
window.__rendererContextFrozen = Object.isFrozen(context) && Object.isFrozen(theme);
|
|
196
|
+
window.__rendererContextFrozen = Object.isFrozen(context) && Object.isFrozen(theme) && Object.isFrozen(message) && Object.isFrozen(message.responses);
|
|
197
|
+
window.__rendererHasRespond = typeof respond === 'function';
|
|
89
198
|
container.textContent = `${payload.kind}:${payload.data[0].value}`;
|
|
90
199
|
const onAbort = () => { container.dataset.aborted = '1'; };
|
|
91
200
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -96,11 +205,15 @@ try {
|
|
|
96
205
|
},
|
|
97
206
|
}],
|
|
98
207
|
};
|
|
99
|
-
|
|
208
|
+
if (!sessionStorage.getItem('renderer_test_seeded')) {
|
|
209
|
+
localStorage.setItem('bailing_chat_pub_test', JSON.stringify(seededHistory));
|
|
210
|
+
sessionStorage.setItem('renderer_test_seeded', '1');
|
|
211
|
+
}
|
|
100
212
|
}, { seededHistory: history });
|
|
101
213
|
|
|
102
214
|
await page.goto(`http://127.0.0.1:${address.port}/`, { waitUntil: 'networkidle' });
|
|
103
215
|
await page.waitForFunction(() => window.__rendererMounts - window.__rendererDestroys === 1);
|
|
216
|
+
await page.locator('.rich-renderer[data-renderer="bailing-form"][data-form-id="refund_info"] .bailing-form').waitFor();
|
|
104
217
|
|
|
105
218
|
const result = await page.evaluate(() => {
|
|
106
219
|
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
@@ -118,23 +231,40 @@ try {
|
|
|
118
231
|
destroys: window.__rendererDestroys,
|
|
119
232
|
contextKeys: window.__rendererContextKeys,
|
|
120
233
|
contextFrozen: window.__rendererContextFrozen,
|
|
234
|
+
hasRespond: window.__rendererHasRespond,
|
|
121
235
|
richMessageCount: root?.querySelectorAll('.m.rich').length || 0,
|
|
236
|
+
formCount: root?.querySelectorAll('.rich-renderer[data-renderer="bailing-form"] .bailing-form').length || 0,
|
|
237
|
+
formImageCount: root?.querySelectorAll('.rich-renderer[data-form-id="refund_info"] img').length || 0,
|
|
238
|
+
formInjected: window.__formInjected || 0,
|
|
239
|
+
dateMin: root?.querySelector('[data-form-id="refund_info"] input[name="apply_date"]')?.min || '',
|
|
240
|
+
dateMax: root?.querySelector('[data-form-id="refund_info"] input[name="apply_date"]')?.max || '',
|
|
241
|
+
booleanRequired: root?.querySelector('[data-form-id="refund_info"] input[name="confirmed"]')?.required,
|
|
122
242
|
panelWidth: root?.querySelector('.panel')?.getBoundingClientRect().width || 0,
|
|
123
243
|
fallbacks,
|
|
244
|
+
bailingFormFallbackCount: fallbacks.filter((item) => item.language === 'bailing-form').length,
|
|
124
245
|
};
|
|
125
246
|
});
|
|
126
247
|
|
|
127
248
|
assert.equal(result.rendererApiVersion, '1');
|
|
128
|
-
assert.equal(result.activeCount,
|
|
249
|
+
assert.equal(result.activeCount, 3);
|
|
129
250
|
assert.equal(result.activeText, 'bar:12');
|
|
130
251
|
assert.equal(result.mounts - result.destroys, 1);
|
|
131
|
-
assert.deepEqual(result.contextKeys, ['container', 'payload', 'signal', 'source', 'theme', 'type', 'version']);
|
|
252
|
+
assert.deepEqual(result.contextKeys, ['container', 'message', 'payload', 'respond', 'signal', 'source', 'theme', 'type', 'version']);
|
|
132
253
|
assert.equal(result.contextFrozen, true);
|
|
133
|
-
assert.equal(result.
|
|
254
|
+
assert.equal(result.hasRespond, true);
|
|
255
|
+
assert.ok(result.richMessageCount >= 3);
|
|
256
|
+
assert.equal(result.formCount, 2);
|
|
257
|
+
assert.equal(result.formImageCount, 0);
|
|
258
|
+
assert.equal(result.formInjected, 0);
|
|
259
|
+
assert.equal(result.dateMin, '2026-01-01');
|
|
260
|
+
assert.equal(result.dateMax, '2026-12-31');
|
|
261
|
+
assert.equal(result.booleanRequired, false, 'required boolean must still allow submitting false');
|
|
134
262
|
assert.ok(result.panelWidth >= 640, `expected rich content to widen the panel, got ${result.panelWidth}`);
|
|
135
263
|
assert.ok(result.fallbacks.some((item) => item.language === 'unknown-chart' && item.text.includes('{"value":1}')));
|
|
136
264
|
assert.ok(result.fallbacks.some((item) => item.language === 'bailing-chart' && item.text.includes('{"broken":')));
|
|
137
265
|
assert.ok(result.fallbacks.some((item) => item.language === 'bailing-chart' && item.text === '"scalar"'));
|
|
266
|
+
assert.ok(result.fallbacks.some((item) => item.language === 'bailing-form' && item.text.includes('remote_select')));
|
|
267
|
+
assert.equal(result.bailingFormFallbackCount, 2 + strictInvalidPayloads.length, 'invalid and source-less forms must stay inert code blocks');
|
|
138
268
|
|
|
139
269
|
await page.locator('.maximize').click();
|
|
140
270
|
const maximized = await page.evaluate(() => {
|
|
@@ -173,15 +303,89 @@ try {
|
|
|
173
303
|
await page.locator('.bubble').click();
|
|
174
304
|
assert.equal(await page.locator('.panel').evaluate((panel) => panel.classList.contains('open')), true);
|
|
175
305
|
|
|
176
|
-
|
|
306
|
+
const refundForm = page.locator('.rich-renderer[data-form-id="refund_info"]');
|
|
307
|
+
await refundForm.locator('input[name="customer"]').fill('张三');
|
|
308
|
+
await refundForm.locator('textarea[name="reason"]').fill('商品与描述不符');
|
|
309
|
+
await refundForm.locator('input[name="amount"]').fill('88.5');
|
|
310
|
+
await refundForm.locator('input[name="apply_date"]').fill('2026-08-24');
|
|
311
|
+
// required boolean 是 yes/no 数据而非强制同意;故意保持 false 也应可提交。
|
|
312
|
+
await refundForm.locator('select[name="method"]').selectOption('original');
|
|
313
|
+
await refundForm.locator('input[name="tags"][value="urgent"]').check();
|
|
314
|
+
await refundForm.locator('button.primary').click();
|
|
315
|
+
const formSubmitted = await nextSubmission();
|
|
316
|
+
assert.equal(formSubmitted.message, undefined);
|
|
317
|
+
assert.deepEqual(formSubmitted.client_capabilities, { renderers: ['bailing-form', 'bailing-chart'] });
|
|
318
|
+
assert.deepEqual({ ...formSubmitted.interaction_response, submission_id: '<dynamic>' }, {
|
|
319
|
+
type: 'bailing-form',
|
|
320
|
+
version: 1,
|
|
321
|
+
source_job_id: 'source-form-1',
|
|
322
|
+
form_id: 'refund_info',
|
|
323
|
+
submission_id: '<dynamic>',
|
|
324
|
+
action: 'submit',
|
|
325
|
+
values: {
|
|
326
|
+
customer: '张三',
|
|
327
|
+
reason: '商品与描述不符',
|
|
328
|
+
amount: 88.5,
|
|
329
|
+
apply_date: '2026-08-24',
|
|
330
|
+
confirmed: false,
|
|
331
|
+
method: 'original',
|
|
332
|
+
tags: ['urgent'],
|
|
333
|
+
},
|
|
334
|
+
});
|
|
335
|
+
assert.match(formSubmitted.interaction_response.submission_id, /^[a-zA-Z0-9_-]{8,64}$/);
|
|
336
|
+
await refundForm.locator('.bf-status.receipt').waitFor();
|
|
337
|
+
const acknowledgedBeforeDone = await page.evaluate(() => {
|
|
338
|
+
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
339
|
+
const root = host?.shadowRoot;
|
|
340
|
+
return {
|
|
341
|
+
sendDisabled: root?.querySelector('.send')?.disabled,
|
|
342
|
+
hasFinalReply: Array.from(root?.querySelectorAll('.m.a') || []).some((node) => node.textContent?.includes('ok:refund_info')),
|
|
343
|
+
};
|
|
344
|
+
});
|
|
345
|
+
assert.equal(acknowledgedBeforeDone.sendDisabled, true, 'global send stays pending while the next answer streams');
|
|
346
|
+
assert.equal(acknowledgedBeforeDone.hasFinalReply, false, 'form receipt must not wait for the delayed SSE answer');
|
|
347
|
+
await page.waitForFunction(() => {
|
|
348
|
+
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
349
|
+
return host?.shadowRoot?.querySelector('.send')?.disabled === false;
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
const cancelForm = page.locator('.rich-renderer[data-form-id="cancel_form"]');
|
|
353
|
+
await cancelForm.getByRole('button', { name: '暂不填写' }).click();
|
|
354
|
+
const rejectedCancel = await nextSubmission();
|
|
355
|
+
assert.equal(rejectedCancel.interaction_response.action, 'cancel');
|
|
356
|
+
assert.deepEqual(rejectedCancel.interaction_response.values, {});
|
|
357
|
+
await cancelForm.locator('.bf-status.error').waitFor();
|
|
358
|
+
assert.equal(await cancelForm.getByRole('button', { name: '暂不填写' }).isEnabled(), true, 'HTTP rejection must re-enable form controls');
|
|
359
|
+
await cancelForm.getByRole('button', { name: '暂不填写' }).click();
|
|
360
|
+
const acceptedCancel = await nextSubmission();
|
|
361
|
+
assert.equal(acceptedCancel.interaction_response.submission_id, rejectedCancel.interaction_response.submission_id, 'retry keeps one idempotency key');
|
|
362
|
+
assert.equal(acceptedCancel.interaction_response.source_job_id, 'source-form-2');
|
|
363
|
+
await cancelForm.locator('.bf-status.receipt').waitFor();
|
|
364
|
+
await page.waitForFunction(() => {
|
|
365
|
+
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
366
|
+
return host?.shadowRoot?.querySelector('.send')?.disabled === false;
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
await page.locator('.foot textarea').fill('请分析这组数据');
|
|
177
370
|
await page.locator('.send').click();
|
|
178
|
-
const submitted = await
|
|
179
|
-
assert.
|
|
371
|
+
const submitted = await nextSubmission();
|
|
372
|
+
assert.equal(submitted.message, '请分析这组数据');
|
|
373
|
+
assert.deepEqual(submitted.client_capabilities, { renderers: ['bailing-form', 'bailing-chart'] });
|
|
180
374
|
await page.waitForFunction(() => {
|
|
181
375
|
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
182
376
|
return host?.shadowRoot?.querySelector('.send')?.disabled === false;
|
|
183
377
|
});
|
|
184
378
|
|
|
379
|
+
const localInteractions = await page.evaluate(() => JSON.parse(localStorage.getItem('bailing_chat_pub_test') || '[]').filter((item) => item.i).map((item) => item.i));
|
|
380
|
+
assert.equal(localInteractions.length, 2);
|
|
381
|
+
assert.deepEqual(localInteractions.map((item) => item.form_id).sort(), ['cancel_form', 'refund_info']);
|
|
382
|
+
assert.ok(localInteractions.every((item) => !Object.hasOwn(item, 'values')), 'local interaction metadata must not duplicate submitted values');
|
|
383
|
+
await page.reload({ waitUntil: 'networkidle' });
|
|
384
|
+
await page.waitForFunction(() => {
|
|
385
|
+
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
386
|
+
return host?.shadowRoot?.querySelectorAll('.bailing-form .bf-status.receipt').length === 2;
|
|
387
|
+
});
|
|
388
|
+
|
|
185
389
|
await page.evaluate(() => {
|
|
186
390
|
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
187
391
|
host?.shadowRoot?.querySelector('.restart')?.click();
|
|
@@ -199,7 +403,31 @@ try {
|
|
|
199
403
|
assert.equal(afterRestart.activeCount, 0);
|
|
200
404
|
assert.equal(afterRestart.mounts, afterRestart.destroys);
|
|
201
405
|
|
|
202
|
-
|
|
406
|
+
serverMessages = [
|
|
407
|
+
{ r: 'a', t: formBlock(formPayload), j: 'server-source-form' },
|
|
408
|
+
{
|
|
409
|
+
r: 'u',
|
|
410
|
+
t: '用户提交了结构化表单。',
|
|
411
|
+
j: 'server-followup-job',
|
|
412
|
+
interaction: {
|
|
413
|
+
type: 'bailing-form', version: 1, source_job_id: 'server-source-form', form_id: 'refund_info', submission_id: 'sub_server_1234', action: 'submit',
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
];
|
|
417
|
+
const historyPage = await browser.newPage();
|
|
418
|
+
await historyPage.addInitScript(() => {
|
|
419
|
+
localStorage.removeItem('bailing_chat_pub_test');
|
|
420
|
+
localStorage.setItem('bailing_visitor_pub_test', 'visitor-server-history');
|
|
421
|
+
});
|
|
422
|
+
await historyPage.goto(`http://127.0.0.1:${address.port}/`, { waitUntil: 'networkidle' });
|
|
423
|
+
await historyPage.waitForFunction(() => {
|
|
424
|
+
const host = Array.from(document.body.children).find((node) => node.shadowRoot);
|
|
425
|
+
return host?.shadowRoot?.querySelector('[data-form-id="refund_info"] .bf-status.receipt')?.textContent?.includes('已提交');
|
|
426
|
+
});
|
|
427
|
+
assert.equal(await historyPage.locator('[data-form-id="refund_info"] button.primary').isDisabled(), true);
|
|
428
|
+
await historyPage.close();
|
|
429
|
+
|
|
430
|
+
console.log('✓ widget renderers expose safe forms, non-blocking acknowledgements, idempotent recovery, history receipts, capabilities, fallbacks, and cleanup');
|
|
203
431
|
} finally {
|
|
204
432
|
await browser.close();
|
|
205
433
|
await new Promise((resolve) => server.close(resolve));
|
package/sdk/php/README.md
CHANGED
|
@@ -20,7 +20,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php.tgz && tar -xzf baili
|
|
|
20
20
|
}
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
或 ③ 直接拷贝 `src/`
|
|
23
|
+
或 ③ 直接拷贝 `src/` 目录进项目。零依赖,怎么引都行;请保留完整目录结构,避免可选模块 class not found。
|
|
24
24
|
|
|
25
25
|
## 第一步:标注解
|
|
26
26
|
|
|
@@ -195,6 +195,32 @@ $result = $hub->getJob($job['job_id']);
|
|
|
195
195
|
$hub->send('notice_1001', 'team-im', 'user_001', '任务已完成');
|
|
196
196
|
```
|
|
197
197
|
|
|
198
|
+
## 附:本地 Agent 网页授权(可选)
|
|
199
|
+
|
|
200
|
+
`AgentAuth` 是现有 SDK 的可选模块,不是第二套 SDK。业务网页先用自己的登录态确定当前操作人,后端再用接入方 Client Token 调中枢:
|
|
201
|
+
|
|
202
|
+
完整的组件关系、配置归属与非 PHP HTTP 契约分别见
|
|
203
|
+
[Agent Client v1 接入指南](../../docs/AGENT_CLIENT_QUICKSTART.md) 和
|
|
204
|
+
[Agent Auth v1](../../docs/AGENT_AUTH_API.md)。
|
|
205
|
+
|
|
206
|
+
```php
|
|
207
|
+
$agentAuth = new \Bailing\Connect\AgentAuth('https://hub.example.com', $clientToken);
|
|
208
|
+
$context = $agentAuth->context($authorizationId);
|
|
209
|
+
|
|
210
|
+
$result = $agentAuth->approve(
|
|
211
|
+
$authorizationId,
|
|
212
|
+
['id' => (string) $user->id, 'tenant' => (string) $tenantId, 'roles' => $user->roles],
|
|
213
|
+
"tenant_{$tenantId}:user_{$user->id}",
|
|
214
|
+
$context['requested_routes']
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
// 浏览器跳转 $result['redirect_uri'] 完成 loopback 回调。
|
|
218
|
+
// 用户取消时:$agentAuth->deny($authorizationId);
|
|
219
|
+
// 员工离职/设备丢失:$agentAuth->revokeSession($sessionId);
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`principal` 和 `on_behalf_of` 必须由业务后端从当前登录态生成,不得从前端表单原样透传。该协议只绑定业务身份、路由与设备会话,不承载套餐、付费或权益字段。
|
|
223
|
+
|
|
198
224
|
## CI 集成
|
|
199
225
|
|
|
200
226
|
```bash
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
declare(strict_types=1);
|
|
4
|
+
|
|
5
|
+
namespace Bailing\Connect;
|
|
6
|
+
|
|
7
|
+
use InvalidArgumentException;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 业务后端对接 BailingHub Agent Auth v1 的薄客户端。
|
|
11
|
+
*
|
|
12
|
+
* 使用现有接入方 Client Token 读取授权上下文,并在业务系统
|
|
13
|
+
* 已完成登录和权限判定后批准/拒绝。不签发套餐、付费或权益数据。
|
|
14
|
+
*/
|
|
15
|
+
final class AgentAuth
|
|
16
|
+
{
|
|
17
|
+
private HubClient $hub;
|
|
18
|
+
|
|
19
|
+
public function __construct(string $baseUrl, string $clientToken, int $timeoutSeconds = 8)
|
|
20
|
+
{
|
|
21
|
+
$this->hub = new HubClient($baseUrl, $clientToken, $timeoutSeconds);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @return array<string,mixed> */
|
|
25
|
+
public function context(string $authorizationId): array
|
|
26
|
+
{
|
|
27
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
28
|
+
return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param array{id:string,tenant?:string,roles?:array<int,string>,audience?:string,channel?:string} $principal
|
|
33
|
+
* @param array<int,string> $allowedRoutes
|
|
34
|
+
* @return array<string,mixed>
|
|
35
|
+
*/
|
|
36
|
+
public function approve(string $authorizationId, array $principal, string $onBehalfOf, array $allowedRoutes): array
|
|
37
|
+
{
|
|
38
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
39
|
+
if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
|
|
40
|
+
throw new InvalidArgumentException('principal.id 必填');
|
|
41
|
+
}
|
|
42
|
+
if ($onBehalfOf === '') {
|
|
43
|
+
throw new InvalidArgumentException('onBehalfOf 必填');
|
|
44
|
+
}
|
|
45
|
+
if ($allowedRoutes === []) {
|
|
46
|
+
throw new InvalidArgumentException('allowedRoutes 至少包含一条路由');
|
|
47
|
+
}
|
|
48
|
+
if (!isset($principal['roles'])) {
|
|
49
|
+
$principal['roles'] = [];
|
|
50
|
+
}
|
|
51
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', [
|
|
52
|
+
'principal' => $principal,
|
|
53
|
+
'on_behalf_of' => $onBehalfOf,
|
|
54
|
+
'allowed_routes' => array_values($allowedRoutes),
|
|
55
|
+
]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @return array<string,mixed> */
|
|
59
|
+
public function deny(string $authorizationId): array
|
|
60
|
+
{
|
|
61
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
62
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/deny', []);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @return array<string,mixed> */
|
|
66
|
+
public function revokeSession(string $sessionId): array
|
|
67
|
+
{
|
|
68
|
+
self::assertId($sessionId, 'sessionId');
|
|
69
|
+
return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', []);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private static function assertId(string $value, string $name): void
|
|
73
|
+
{
|
|
74
|
+
if (!preg_match('/^[0-9a-f-]{36}$/i', $value)) {
|
|
75
|
+
throw new InvalidArgumentException($name . ' 必须是 UUID');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -98,6 +98,9 @@ final class HubClient
|
|
|
98
98
|
'header' => implode("\r\n", $headers),
|
|
99
99
|
'timeout' => $this->timeoutSeconds,
|
|
100
100
|
'ignore_errors' => true,
|
|
101
|
+
// Bearer 凭证绝不跟随重定向,避免被跨主机 30x 带走。
|
|
102
|
+
'follow_location' => 0,
|
|
103
|
+
'max_redirects' => 0,
|
|
101
104
|
];
|
|
102
105
|
if ($body !== null) {
|
|
103
106
|
$http['content'] = $content;
|
package/sdk/php7/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
和 8.x 注解版**功能完全等价**,区别只在「怎么声明工具」:8.x 用 `#[AiTool]` 属性注解(PHP 8.0+ 语法),本版用 **fluent builder**(纯 PHP,**PHP ≥ 7.3** 即可),产出的 spec 与注解版**逐字段一致**。
|
|
4
4
|
|
|
5
5
|
> 用哪个版本:业务跑 **PHP 8.0+** 用注解版(`sdk/php`,更简洁);跑 **PHP 7.3 / 7.4** 用本版。**不要为了对接去迁 PHP 版本**。
|
|
6
|
-
> 验签 `Verify`、票据 `Ticket`、spec 托管 `SpecServer`
|
|
6
|
+
> 验签 `Verify`、票据 `Ticket`、spec 托管 `SpecServer`、中枢调用 `HubClient` 和本地 Agent 授权 `AgentAuth` 两版 API 与语义完全相同。
|
|
7
7
|
|
|
8
8
|
零依赖。能力声明遵循 ACC,验签与中枢接入约定见 `docs/CONTRACT.md §2.4`。
|
|
9
9
|
|
|
@@ -22,7 +22,7 @@ curl -O https://<中枢域名>/connect/bailing-connect-php7.tgz && tar -xzf bail
|
|
|
22
22
|
}
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
或 ③ 直接拷贝 `src/` 目录进项目——共 **
|
|
25
|
+
或 ③ 直接拷贝 `src/` 目录进项目——共 **7 个文件**(`ToolSpec`/`ToolDef`/`Verify`/`Ticket`/`SpecServer`/`HubClient`/`AgentAuth`)。零依赖,怎么引都行。命名空间同为 `Bailing\Connect`。
|
|
26
26
|
|
|
27
27
|
## 第一步:声明工具(builder,不动你的控制器)
|
|
28
28
|
|
|
@@ -185,6 +185,36 @@ $result = $hub->getJob($job['job_id']);
|
|
|
185
185
|
$hub->send('notice_1001', 'team-im', 'user_001', '任务已完成');
|
|
186
186
|
```
|
|
187
187
|
|
|
188
|
+
## 本地 Agent 网页授权(可选)
|
|
189
|
+
|
|
190
|
+
`AgentAuth` 是现有 PHP 7.3 SDK 的可选模块,不是第二套 SDK。业务网页先用自己的登录态确定当前操作人,后端再用接入方 Client Token 调中枢:
|
|
191
|
+
|
|
192
|
+
```php
|
|
193
|
+
use Bailing\Connect\AgentAuth;
|
|
194
|
+
|
|
195
|
+
$agentAuth = new AgentAuth('https://hub.example.com', $clientToken);
|
|
196
|
+
$context = $agentAuth->context($authorizationId);
|
|
197
|
+
|
|
198
|
+
$result = $agentAuth->approve(
|
|
199
|
+
$authorizationId,
|
|
200
|
+
array(
|
|
201
|
+
'id' => (string) $user->id,
|
|
202
|
+
'tenant' => (string) $tenantId,
|
|
203
|
+
'roles' => $user->roles,
|
|
204
|
+
),
|
|
205
|
+
'tenant_' . $tenantId . ':user_' . $user->id,
|
|
206
|
+
$context['requested_routes']
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
// 浏览器只跳转 $result['redirect_uri'] 完成 loopback 回调。
|
|
210
|
+
// 用户取消时:$agentAuth->deny($authorizationId);
|
|
211
|
+
// 员工离职/设备丢失:$agentAuth->revokeSession($sessionId);
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`principal`、`on_behalf_of` 和 `allowed_routes` 必须由业务后端根据当前登录态与自身权限生成,不得从前端表单原样透传。Client Token 只存业务服务端,不得写进网页 JavaScript、URL、本地 Agent 或插件配置。授权协议只绑定业务身份、路由和设备会话,不承载套餐、付费或权益字段。
|
|
215
|
+
|
|
216
|
+
完整关系与 HTTP 契约见中枢文档 `docs/AGENT_CLIENT_QUICKSTART.md` 和 `docs/AGENT_AUTH_API.md`。
|
|
217
|
+
|
|
188
218
|
## 范例
|
|
189
219
|
|
|
190
220
|
- `examples/build-spec.php`:完整 builder 范例(覆盖全部字段;与 8.x 版同源,跑同一个跨语言契约测试)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
|
|
3
|
+
namespace Bailing\Connect;
|
|
4
|
+
|
|
5
|
+
use InvalidArgumentException;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 业务后端对接 BailingHub Agent Auth v1 的薄客户端。
|
|
9
|
+
*
|
|
10
|
+
* 使用现有接入方 Client Token 读取授权上下文,并在业务系统
|
|
11
|
+
* 已完成登录和权限判定后批准/拒绝。不签发套餐、付费或权益数据。
|
|
12
|
+
* PHP 7.3 兼容版,语义与 8.x SDK 的 AgentAuth 一致。
|
|
13
|
+
*/
|
|
14
|
+
final class AgentAuth
|
|
15
|
+
{
|
|
16
|
+
private $hub;
|
|
17
|
+
|
|
18
|
+
public function __construct($baseUrl, $clientToken, $timeoutSeconds = 8)
|
|
19
|
+
{
|
|
20
|
+
$this->hub = new HubClient($baseUrl, $clientToken, $timeoutSeconds);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @return array */
|
|
24
|
+
public function context($authorizationId)
|
|
25
|
+
{
|
|
26
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
27
|
+
return $this->hub->get('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param array $principal 业务后端从当前登录态推导的主体,必须包含 id
|
|
32
|
+
* @param array $allowedRoutes 本次授权允许的路由标识
|
|
33
|
+
* @return array
|
|
34
|
+
*/
|
|
35
|
+
public function approve($authorizationId, array $principal, $onBehalfOf, array $allowedRoutes)
|
|
36
|
+
{
|
|
37
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
38
|
+
if (!isset($principal['id']) || trim((string) $principal['id']) === '') {
|
|
39
|
+
throw new InvalidArgumentException('principal.id 必填');
|
|
40
|
+
}
|
|
41
|
+
if ($onBehalfOf === '') {
|
|
42
|
+
throw new InvalidArgumentException('onBehalfOf 必填');
|
|
43
|
+
}
|
|
44
|
+
if ($allowedRoutes === array()) {
|
|
45
|
+
throw new InvalidArgumentException('allowedRoutes 至少包含一条路由');
|
|
46
|
+
}
|
|
47
|
+
if (!isset($principal['roles'])) {
|
|
48
|
+
$principal['roles'] = array();
|
|
49
|
+
}
|
|
50
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/approve', array(
|
|
51
|
+
'principal' => $principal,
|
|
52
|
+
'on_behalf_of' => $onBehalfOf,
|
|
53
|
+
'allowed_routes' => array_values($allowedRoutes),
|
|
54
|
+
));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @return array */
|
|
58
|
+
public function deny($authorizationId)
|
|
59
|
+
{
|
|
60
|
+
self::assertId($authorizationId, 'authorizationId');
|
|
61
|
+
return $this->hub->post('/agent-auth/v1/authorizations/' . rawurlencode($authorizationId) . '/deny', array());
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @return array */
|
|
65
|
+
public function revokeSession($sessionId)
|
|
66
|
+
{
|
|
67
|
+
self::assertId($sessionId, 'sessionId');
|
|
68
|
+
return $this->hub->post('/agent-auth/v1/sessions/' . rawurlencode($sessionId) . '/revoke', array());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private static function assertId($value, $name)
|
|
72
|
+
{
|
|
73
|
+
if (!is_string($value) || !preg_match('/^[0-9a-f-]{36}$/i', $value)) {
|
|
74
|
+
throw new InvalidArgumentException($name . ' 必须是 UUID');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -85,6 +85,9 @@ final class HubClient
|
|
|
85
85
|
'header' => implode("\r\n", $headers),
|
|
86
86
|
'timeout' => $this->timeoutSeconds,
|
|
87
87
|
'ignore_errors' => true,
|
|
88
|
+
// Bearer 凭证绝不跟随重定向,避免被跨主机 30x 带走。
|
|
89
|
+
'follow_location' => 0,
|
|
90
|
+
'max_redirects' => 0,
|
|
88
91
|
);
|
|
89
92
|
if ($body !== null) {
|
|
90
93
|
$http['content'] = $content;
|