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
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import test from 'node:test';
|
|
7
|
+
import { readAgentArtifact, uploadAgentArtifact } from './agent-artifacts';
|
|
8
|
+
import type { AgentToolAuthContext } from './agent-tool-invocations';
|
|
9
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
10
|
+
import type { AgentArtifactRecord } from '../infrastructure/config/config-agent-artifact-repository';
|
|
11
|
+
import { AgentArtifactRepository } from '../infrastructure/config/config-agent-artifact-repository';
|
|
12
|
+
import { localStorageBucket, putObject } from '../adapters/storage/object-storage';
|
|
13
|
+
import { rowStorageBucket } from '../core/config/config-codec';
|
|
14
|
+
import { handleAgentArtifacts } from '../routes/agent-artifacts';
|
|
15
|
+
import { Readable } from 'node:stream';
|
|
16
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
17
|
+
|
|
18
|
+
export const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a4mQAAAAASUVORK5CYII=', 'base64');
|
|
19
|
+
const sha256 = createHash('sha256').update(png).digest('hex');
|
|
20
|
+
const uid = 'a'.repeat(64);
|
|
21
|
+
export function artifactFixture() {
|
|
22
|
+
const records = new Map<string, AgentArtifactRecord>();
|
|
23
|
+
const session = { session_id: '123e4567-e89b-42d3-a456-426614174000', client_app_id: 'example-shop', principal: { id: 'operator', roles: [] }, allowed_routes: ['shop'], on_behalf_of: 'tenant:operator' };
|
|
24
|
+
const auth = { session, client: { app_id: 'example-shop', allowed_routes: ['shop'], enabled: true } } as unknown as AgentToolAuthContext;
|
|
25
|
+
const route = { route_key: 'shop', enabled: true, agent_client: { enabled: true, artifact_upload: { enabled: true, bucket: 'media', max_bytes: 6291456 } } };
|
|
26
|
+
const bucket = { ...localStorageBucket('https://hub.example.com'), name: 'media' };
|
|
27
|
+
const counters = { puts: 0, ready: 0, reserves: 0, loseCommit: false };
|
|
28
|
+
const store = { routes: { get: async (key: string) => key === 'shop' ? route : null }, storageBuckets: { get: async () => bucket },
|
|
29
|
+
agentArtifacts: { get: async (s: string, id: string) => records.get(s + id) ?? null,
|
|
30
|
+
reserve: async (r: AgentArtifactRecord) => { counters.reserves++; const key = r.session_id + r.upload_id; if (!records.has(key)) records.set(key, r); return records.get(key)!; },
|
|
31
|
+
ready: async (s: string, id: string, url: string) => { if (counters.loseCommit) throw new Error('simulated commit failure'); counters.ready++; Object.assign(records.get(s + id)!, { state: 'ready', url }); },
|
|
32
|
+
},
|
|
33
|
+
} as unknown as ConfigStoreContract;
|
|
34
|
+
const metadata = { name: 'generated.png', mime: 'image/png', bytes: png.length, sha256, client_conversation_id: 'conversation-one', client_turn_id: 'turn-one' };
|
|
35
|
+
const deps = { configStore: store, put: async (...args: Parameters<typeof putObject>) => { counters.puts++; return `${args[0].public_base_url}/${args[1]}`; } };
|
|
36
|
+
return { auth, route, bucket, store, records, counters, metadata, deps };
|
|
37
|
+
}
|
|
38
|
+
const runId = '123e4567-e89b-42d3-a456-426614174001';
|
|
39
|
+
function setArtifactRun(fx: ReturnType<typeof artifactFixture>, patch: Record<string, unknown> | null = {}) {
|
|
40
|
+
const run = patch === null ? null : { run_id: runId, session_id: fx.auth.session.session_id, client_app_id: fx.auth.client.app_id,
|
|
41
|
+
route_key: 'shop', client_conversation_id: fx.metadata.client_conversation_id, client_turn_id: fx.metadata.client_turn_id, ...patch };
|
|
42
|
+
Object.assign(fx.store, { agentClientRuntime: { getRun: async (id: string, sessionId: string, clientAppId: string) => {
|
|
43
|
+
assert.equal(id, runId); assert.equal(sessionId, fx.auth.session.session_id); assert.equal(clientAppId, fx.auth.client.app_id);
|
|
44
|
+
return run;
|
|
45
|
+
} } });
|
|
46
|
+
}
|
|
47
|
+
test('only a verified turn-only run mismatch is distinguishable before reservation or storage', async t => {
|
|
48
|
+
const cases = [
|
|
49
|
+
{ name: 'another turn in the same original conversation', patch: { client_turn_id: 'earlier-turn' }, code: 'artifact_run_turn_mismatch' },
|
|
50
|
+
{ name: 'missing run', patch: null },
|
|
51
|
+
{ name: 'another run ID', patch: { run_id: '123e4567-e89b-42d3-a456-426614174002' } },
|
|
52
|
+
{ name: 'another Agent Session', patch: { session_id: 'other-session', client_turn_id: 'earlier-turn' } },
|
|
53
|
+
{ name: 'another client', patch: { client_app_id: 'other-client', client_turn_id: 'earlier-turn' } },
|
|
54
|
+
{ name: 'another route', patch: { route_key: 'other-route', client_turn_id: 'earlier-turn' } },
|
|
55
|
+
{ name: 'another conversation', patch: { client_conversation_id: 'other-conversation', client_turn_id: 'earlier-turn' } },
|
|
56
|
+
{ name: 'legacy empty turn', patch: { client_turn_id: '' } },
|
|
57
|
+
{ name: 'invalid stored turn', patch: { client_turn_id: '\u0000' } },
|
|
58
|
+
];
|
|
59
|
+
for (const item of cases) await t.test(item.name, async () => {
|
|
60
|
+
const fx = artifactFixture(); setArtifactRun(fx, item.patch);
|
|
61
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, { ...fx.metadata, run_id: runId }, png),
|
|
62
|
+
{ statusCode: 403, code: item.code ?? 'artifact_run_mismatch' });
|
|
63
|
+
assert.equal(fx.counters.reserves, 0); assert.equal(fx.counters.puts, 0); assert.equal(fx.records.size, 0);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
test('matching run linkage and upload without a business run remain supported', async () => {
|
|
67
|
+
const fx = artifactFixture(); setArtifactRun(fx);
|
|
68
|
+
const linked = await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, { ...fx.metadata, run_id: runId }, png);
|
|
69
|
+
assert.equal(linked.run_id, runId); assert.equal(linked.state, 'ready');
|
|
70
|
+
const direct = artifactFixture();
|
|
71
|
+
Object.assign(direct.store, { agentClientRuntime: { getRun: async () => { throw new Error('upload without a run must not load one'); } } });
|
|
72
|
+
const result = await uploadAgentArtifact(direct.deps, direct.auth, 'shop', uid, direct.metadata, png);
|
|
73
|
+
assert.equal(result.run_id, undefined); assert.equal(result.state, 'ready');
|
|
74
|
+
});
|
|
75
|
+
test('a rejected stale link leaves the original upload ID available without rewriting an existing receipt', async () => {
|
|
76
|
+
const fx = artifactFixture(); setArtifactRun(fx, { client_turn_id: 'earlier-turn' });
|
|
77
|
+
const stale = { ...fx.metadata, run_id: runId };
|
|
78
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, stale, png), { code: 'artifact_run_turn_mismatch' });
|
|
79
|
+
await assert.rejects(readAgentArtifact(fx.deps, fx.auth, 'shop', uid), { code: 'artifact_not_found' });
|
|
80
|
+
const ready = await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
81
|
+
assert.equal(ready.upload_id, uid); assert.equal(ready.client_conversation_id, fx.metadata.client_conversation_id);
|
|
82
|
+
assert.equal(ready.client_turn_id, fx.metadata.client_turn_id); assert.equal(ready.run_id, undefined);
|
|
83
|
+
// A stale retry may still get the precise rejection after another process
|
|
84
|
+
// has saved the object. Only GET establishes whether a receipt now exists.
|
|
85
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, stale, png), { code: 'artifact_run_turn_mismatch' });
|
|
86
|
+
assert.deepEqual(await readAgentArtifact(fx.deps, fx.auth, 'shop', uid), ready);
|
|
87
|
+
assert.equal(fx.records.size, 1); assert.equal(fx.counters.reserves, 1); assert.equal(fx.counters.puts, 1);
|
|
88
|
+
});
|
|
89
|
+
test('HTTP preserves the precise turn-mismatch code without leaking run details', async () => {
|
|
90
|
+
const fx = artifactFixture(); setArtifactRun(fx, { client_turn_id: 'earlier-turn' });
|
|
91
|
+
const req = Object.assign(Readable.from([png]), { method: 'POST', headers: {
|
|
92
|
+
'content-type': 'image/png', 'content-length': String(png.length),
|
|
93
|
+
'x-bailing-artifact': Buffer.from(JSON.stringify({ ...fx.metadata, run_id: runId })).toString('base64url'),
|
|
94
|
+
} }) as unknown as IncomingMessage;
|
|
95
|
+
let status = 0; let body = '';
|
|
96
|
+
const res = { writeHead: (code: number) => { status = code; }, end: (value: string) => { body = value; } } as unknown as ServerResponse;
|
|
97
|
+
assert.equal(await handleAgentArtifacts({ ...fx.deps, isPaused: () => false }, fx.auth, req, res, `/agent-api/v1/workspaces/shop/artifacts/${uid}`), true);
|
|
98
|
+
assert.equal(status, 403); assert.deepEqual(JSON.parse(body), { error: 'artifact_run_turn_mismatch' });
|
|
99
|
+
assert.equal(fx.counters.reserves, 0); assert.equal(fx.counters.puts, 0);
|
|
100
|
+
});
|
|
101
|
+
test('same upload ID recovers saved receipt after lost ACK; no extra object or business write', async () => {
|
|
102
|
+
const fx = artifactFixture();
|
|
103
|
+
const first = await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
104
|
+
const recovered = await readAgentArtifact(fx.deps, fx.auth, 'shop', uid);
|
|
105
|
+
const repeated = await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
106
|
+
assert.deepEqual(first, recovered); assert.deepEqual(first, repeated);
|
|
107
|
+
assert.equal(fx.counters.puts, 1); assert.equal(fx.records.size, 1);
|
|
108
|
+
assert.equal(first.state, 'ready'); assert.ok(first.url); assert.equal('bucket_name' in first, false);
|
|
109
|
+
});
|
|
110
|
+
test('binary saved before receipt commit fails: retry writes only same bytes to same key', async () => {
|
|
111
|
+
const fx = artifactFixture(); fx.counters.loseCommit = true;
|
|
112
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png), { code: 'artifact_upload_pending' });
|
|
113
|
+
const key = [...fx.records.values()][0]!.object_key;
|
|
114
|
+
assert.equal((await readAgentArtifact(fx.deps, fx.auth, 'shop', uid)).state, 'pending');
|
|
115
|
+
fx.counters.loseCommit = false;
|
|
116
|
+
await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
117
|
+
assert.equal([...fx.records.values()][0]!.object_key, key); assert.equal(fx.records.size, 1);
|
|
118
|
+
});
|
|
119
|
+
test('unselected route, another session, disabled upload and changed content fail closed', async () => {
|
|
120
|
+
const fx = artifactFixture();
|
|
121
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'other', uid, fx.metadata, png), { code: 'route_not_allowed' });
|
|
122
|
+
assert.equal(fx.counters.puts, 0);
|
|
123
|
+
fx.route.agent_client.artifact_upload.enabled = false;
|
|
124
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png), { code: 'artifact_upload_disabled' });
|
|
125
|
+
fx.route.agent_client.artifact_upload.enabled = true;
|
|
126
|
+
await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
127
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, { ...fx.metadata, name: 'changed.png' }, png), { code: 'artifact_conflict' });
|
|
128
|
+
await assert.rejects(readAgentArtifact(fx.deps, { ...fx.auth, session: { ...fx.auth.session, session_id: 'different' } }, 'shop', uid), { code: 'artifact_not_found' });
|
|
129
|
+
});
|
|
130
|
+
test('destination changes, disabled storage and invalid bytes never silently choose another bucket', async () => {
|
|
131
|
+
const fx = artifactFixture(); fx.counters.loseCommit = true;
|
|
132
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png));
|
|
133
|
+
fx.bucket.path_prefix = 'changed';
|
|
134
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png), { code: 'artifact_storage_changed' });
|
|
135
|
+
fx.bucket.enabled = false;
|
|
136
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png), { code: 'artifact_storage_unavailable' });
|
|
137
|
+
assert.equal(fx.counters.puts, 1);
|
|
138
|
+
await assert.rejects(uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, Buffer.from('bad')), { code: 'artifact_content_mismatch' });
|
|
139
|
+
});
|
|
140
|
+
test('local storage returns retrievable byte-identical image and keeps local kind when loaded', async () => {
|
|
141
|
+
const fx = artifactFixture(); const root = await mkdtemp(join(tmpdir(), 'artifact-test-'));
|
|
142
|
+
try {
|
|
143
|
+
const result = await uploadAgentArtifact({ configStore: fx.store, root }, fx.auth, 'shop', uid, fx.metadata, png);
|
|
144
|
+
const key = [...fx.records.values()][0]!.object_key;
|
|
145
|
+
assert.deepEqual(await readFile(join(root, 'data/uploads', key)), png);
|
|
146
|
+
assert.match(result.url!, /^https:\/\/hub.example.com\/uploads\//);
|
|
147
|
+
assert.equal(rowStorageBucket({ ...fx.bucket, kind: 'local' }).kind, 'local');
|
|
148
|
+
} finally { await rm(root, { recursive: true, force: true }); }
|
|
149
|
+
});
|
|
150
|
+
test('repository reserves immutable metadata and commits receipt without replacing identity', async () => {
|
|
151
|
+
const queries: string[] = []; let row: any;
|
|
152
|
+
const repo = new AgentArtifactRepository(() => ({ query: async (sql: string, args: any[]) => {
|
|
153
|
+
queries.push(sql);
|
|
154
|
+
if (sql.startsWith('INSERT') && !row) row = { record_json: args[2], state: 'pending', url: null };
|
|
155
|
+
if (sql.startsWith('UPDATE')) { row.state = 'ready'; row.url = args[0]; }
|
|
156
|
+
return [sql.startsWith('SELECT') ? (row ? [row] : []) : {}];
|
|
157
|
+
} }));
|
|
158
|
+
const fx = artifactFixture(); await uploadAgentArtifact(fx.deps, fx.auth, 'shop', uid, fx.metadata, png);
|
|
159
|
+
const original = [...fx.records.values()][0]!;
|
|
160
|
+
await repo.reserve(original); await repo.reserve({ ...original, object_key: 'changed' });
|
|
161
|
+
await repo.ready(original.session_id, uid, 'https://cdn.example.com/image.png');
|
|
162
|
+
assert.equal((await repo.get(original.session_id, uid))!.object_key, original.object_key);
|
|
163
|
+
assert.equal((await repo.get(original.session_id, uid))!.state, 'ready');
|
|
164
|
+
assert.ok(queries.every(q => !q.includes('DELETE')));
|
|
165
|
+
});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { StorageBucket } from '../core/contracts/types';
|
|
3
|
+
import { ARTIFACT_MAX_BYTES, ARTIFACT_MIMES, validateArtifactConfig } from '../core/config/artifact-config';
|
|
4
|
+
import { routeAgentClientConfig } from '../core/config/route-config';
|
|
5
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
|
+
import type { AgentArtifactRecord } from '../infrastructure/config/config-agent-artifact-repository';
|
|
7
|
+
import { objectKey, putObject } from '../adapters/storage/object-storage';
|
|
8
|
+
import { AgentToolApiError, resolveAgentRouteFor, type AgentToolAuthContext } from './agent-tool-invocations';
|
|
9
|
+
|
|
10
|
+
export const ARTIFACT_SCHEMA = 'bailing.agent-artifact.v1';
|
|
11
|
+
export const artifactError = (status: number, code: string): never => { throw new AgentToolApiError(status, code, code); };
|
|
12
|
+
const hash = (s: string | Buffer) => createHash('sha256').update(s).digest('hex');
|
|
13
|
+
const id = (v: unknown, max: number) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\u0000-\u001f\u007f]/.test(v);
|
|
14
|
+
export function artifactMetadata(value: unknown): AgentArtifactRecord['metadata'] {
|
|
15
|
+
const v = value as Record<string, unknown>;
|
|
16
|
+
if (!v || typeof v !== 'object' || Array.isArray(v) || Object.keys(v).some(k => !['client_conversation_id', 'client_turn_id', 'name', 'mime', 'bytes', 'sha256', 'run_id'].includes(k)) ||
|
|
17
|
+
!id(v.client_conversation_id, 128) || !id(v.client_turn_id, 128) || !id(v.name, 128) || /[\\/]/.test(String(v.name)) ||
|
|
18
|
+
!(ARTIFACT_MIMES as readonly unknown[]).includes(v.mime) || !Number.isInteger(v.bytes) || Number(v.bytes) < 1 || Number(v.bytes) > ARTIFACT_MAX_BYTES ||
|
|
19
|
+
typeof v.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(v.sha256) || (v.run_id !== undefined && !/^[a-f0-9-]{36}$/.test(String(v.run_id)))) artifactError(400, 'artifact_invalid_request');
|
|
20
|
+
return { client_conversation_id: String(v.client_conversation_id), client_turn_id: String(v.client_turn_id), name: String(v.name), mime: String(v.mime), bytes: Number(v.bytes), sha256: String(v.sha256), ...(v.run_id ? { run_id: String(v.run_id) } : {}) };
|
|
21
|
+
}
|
|
22
|
+
function storageHash(b: StorageBucket): string {
|
|
23
|
+
return hash(JSON.stringify([b.name, b.kind, b.region, b.bucket, b.endpoint ?? '', b.public_base_url, b.path_prefix]));
|
|
24
|
+
}
|
|
25
|
+
function imageMatches(body: Buffer, mime: string): boolean {
|
|
26
|
+
if (mime === 'image/png') return body.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'));
|
|
27
|
+
if (mime === 'image/jpeg') return body[0] === 255 && body[1] === 216 && body[2] === 255;
|
|
28
|
+
return body.toString('ascii', 0, 4) === 'RIFF' && body.toString('ascii', 8, 12) === 'WEBP';
|
|
29
|
+
}
|
|
30
|
+
function receipt(value: AgentArtifactRecord) {
|
|
31
|
+
return { schema_version: ARTIFACT_SCHEMA, upload_id: value.upload_id, workspace: value.workspace,
|
|
32
|
+
session_id: value.session_id, state: value.state, ...value.metadata, visibility: 'public',
|
|
33
|
+
...(value.state === 'ready' ? { url: value.url } : {}), next_action: value.state === 'ready' ? 'use_url' : 'retry_same_upload' };
|
|
34
|
+
}
|
|
35
|
+
export interface ArtifactDeps { configStore: ConfigStoreContract | null; root?: string; put?: typeof putObject }
|
|
36
|
+
export async function readAgentArtifact(deps: ArtifactDeps, auth: AgentToolAuthContext, workspace: string, uploadId: string) {
|
|
37
|
+
await resolveAgentRouteFor(deps, auth, workspace);
|
|
38
|
+
const repo = deps.configStore?.agentArtifacts;
|
|
39
|
+
if (!repo) return artifactError(501, 'artifact_unsupported');
|
|
40
|
+
const value = await repo.get(auth.session.session_id, uploadId);
|
|
41
|
+
if (!value || value.workspace !== workspace) return artifactError(404, 'artifact_not_found');
|
|
42
|
+
return receipt(value);
|
|
43
|
+
}
|
|
44
|
+
export async function uploadAgentArtifact(deps: ArtifactDeps, auth: AgentToolAuthContext, workspace: string, uploadId: string, input: unknown, body: Buffer) {
|
|
45
|
+
const route = await resolveAgentRouteFor(deps, auth, workspace);
|
|
46
|
+
const repo = deps.configStore?.agentArtifacts;
|
|
47
|
+
if (!repo) return artifactError(501, 'artifact_unsupported');
|
|
48
|
+
const policy = route.agent_client?.artifact_upload;
|
|
49
|
+
if (!routeAgentClientConfig(route) || validateArtifactConfig(policy) || !policy?.enabled || !policy.bucket) return artifactError(403, 'artifact_upload_disabled');
|
|
50
|
+
if (!/^[a-f0-9]{64}$/.test(uploadId)) return artifactError(400, 'artifact_invalid_request');
|
|
51
|
+
const metadata = artifactMetadata(input);
|
|
52
|
+
if (body.length !== metadata.bytes || hash(body) !== metadata.sha256) return artifactError(400, 'artifact_content_mismatch');
|
|
53
|
+
if (!imageMatches(body, metadata.mime) || !(policy.allowed_mimes ?? [...ARTIFACT_MIMES] as readonly string[]).includes(metadata.mime)) return artifactError(415, 'artifact_type_not_allowed');
|
|
54
|
+
if (body.length > (policy.max_bytes ?? ARTIFACT_MAX_BYTES)) return artifactError(413, 'artifact_too_large');
|
|
55
|
+
if (metadata.run_id) {
|
|
56
|
+
const run = await deps.configStore?.agentClientRuntime?.getRun(metadata.run_id, auth.session.session_id, auth.client.app_id);
|
|
57
|
+
if (!run || run.run_id !== metadata.run_id || run.session_id !== auth.session.session_id || run.client_app_id !== auth.client.app_id || run.route_key !== workspace || run.client_conversation_id !== metadata.client_conversation_id) return artifactError(403, 'artifact_run_mismatch');
|
|
58
|
+
// Only a proven turn-only mismatch can repair a stale optional run link.
|
|
59
|
+
// Unknown runs or any identity mismatch remain non-recoverable here.
|
|
60
|
+
if (run.client_turn_id !== metadata.client_turn_id) return artifactError(403, id(run.client_turn_id, 128) ? 'artifact_run_turn_mismatch' : 'artifact_run_mismatch');
|
|
61
|
+
}
|
|
62
|
+
const requestHash = hash(JSON.stringify([workspace, metadata]));
|
|
63
|
+
const old = await repo.get(auth.session.session_id, uploadId);
|
|
64
|
+
if (old && old.request_hash !== requestHash) return artifactError(409, 'artifact_conflict');
|
|
65
|
+
if (old?.state === 'ready') return receipt(old);
|
|
66
|
+
if (old && old.bucket_name !== policy.bucket) return artifactError(409, 'artifact_storage_changed');
|
|
67
|
+
const bucket = await deps.configStore!.storageBuckets.get(policy.bucket);
|
|
68
|
+
if (!bucket?.enabled || !['local', 'cos', 'oss'].includes(bucket.kind)) return artifactError(503, 'artifact_storage_unavailable');
|
|
69
|
+
let publicUrl: URL;
|
|
70
|
+
try { publicUrl = new URL(bucket.public_base_url); } catch { return artifactError(503, 'artifact_storage_unavailable'); }
|
|
71
|
+
if (!['http:', 'https:'].includes(publicUrl.protocol) || publicUrl.username || publicUrl.password || publicUrl.search || publicUrl.hash) return artifactError(503, 'artifact_storage_unavailable');
|
|
72
|
+
if (bucket.kind !== 'local' && (!bucket.access_key || !bucket.secret_key || !bucket.bucket || !bucket.region)) return artifactError(503, 'artifact_storage_unavailable');
|
|
73
|
+
const value = await repo.reserve({ upload_id: uploadId, session_id: auth.session.session_id, workspace, request_hash: requestHash,
|
|
74
|
+
storage_hash: storageHash(bucket), bucket_name: bucket.name, object_key: objectKey(bucket, 'artifacts', metadata.mime), metadata, state: 'pending' });
|
|
75
|
+
if (value.request_hash !== requestHash) return artifactError(409, 'artifact_conflict');
|
|
76
|
+
if (value.state === 'ready') return receipt(value);
|
|
77
|
+
if (value.storage_hash !== storageHash(bucket)) return artifactError(409, 'artifact_storage_changed');
|
|
78
|
+
let url: string;
|
|
79
|
+
try { url = await (deps.put ?? putObject)(bucket, value.object_key, body, metadata.mime, { root: deps.root }); }
|
|
80
|
+
catch { return artifactError(503, 'artifact_upload_pending'); }
|
|
81
|
+
// If this commit or its HTTP ACK is lost, the same immutable upload ID recovers the same object.
|
|
82
|
+
try { await repo.ready(auth.session.session_id, uploadId, url); }
|
|
83
|
+
catch { return artifactError(503, 'artifact_upload_pending'); }
|
|
84
|
+
return receipt({ ...value, state: 'ready', url });
|
|
85
|
+
}
|
|
@@ -102,7 +102,12 @@ function fixture() {
|
|
|
102
102
|
now: () => '2026-01-01T00:00:00.000Z', sleep: async () => undefined,
|
|
103
103
|
};
|
|
104
104
|
const deps: AgentClientRuntimeDeps = { toolProxyDeps, kbService: null, stateStore };
|
|
105
|
-
return {
|
|
105
|
+
return {
|
|
106
|
+
deps, repo,
|
|
107
|
+
setRoute: (value: Route) => { currentRoute = value; },
|
|
108
|
+
setSpec: (value: string) => { provider.spec_json = value; },
|
|
109
|
+
counts: () => ({ userWrites, assistantWrites }),
|
|
110
|
+
};
|
|
106
111
|
}
|
|
107
112
|
|
|
108
113
|
test('Agent Runtime bootstrap 只返回安全字段并声明本地规划治理边界', async () => {
|
|
@@ -219,3 +224,73 @@ test('capability search 空 query 必须绑定合法 run,且可回退到该 ru
|
|
|
219
224
|
assert.equal(fallback['query'], '查询员工 Ada');
|
|
220
225
|
assert.equal((fallback['tools'] as Array<{ name: string }>)[0]?.name, 'staff_list');
|
|
221
226
|
});
|
|
227
|
+
|
|
228
|
+
test('capability search distinguishes empty, bounded and truncated authorized candidate catalogs', async (t) => {
|
|
229
|
+
for (const size of [0, 2, 14]) {
|
|
230
|
+
await t.test(`authorized catalog size ${size}`, async () => {
|
|
231
|
+
const fx = fixture();
|
|
232
|
+
fx.setSpec(JSON.stringify({
|
|
233
|
+
openapi: '3.0.0', info: { title: 'Synthetic inventory', version: '1' },
|
|
234
|
+
paths: Object.fromEntries(Array.from({ length: size }, (_, index) => [`/inventory/${index}`, {
|
|
235
|
+
get: {
|
|
236
|
+
operationId: `inventory_${index}`, summary: 'Read inventory',
|
|
237
|
+
'x-agent-capability': { version: 1, enabled: true, scope: 'inventory.read' },
|
|
238
|
+
},
|
|
239
|
+
}])),
|
|
240
|
+
}));
|
|
241
|
+
const result = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { query: 'inventory', limit: 12 });
|
|
242
|
+
assert.equal((result['tools'] as unknown[]).length, Math.min(size, 12));
|
|
243
|
+
assert.deepEqual(result['discovery'], {
|
|
244
|
+
mode: 'ranked_candidates', scope: 'current_authorization', returned_count: Math.min(size, 12),
|
|
245
|
+
authorized_total: size, matched_total: null, matched_total_exact: false,
|
|
246
|
+
limit: 12, truncated: size > 12, has_more: size > 12,
|
|
247
|
+
truncation_scope: 'authorized_catalog', pagination: 'unsupported',
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test('capability search does not claim exact matches for an unrelated query', async () => {
|
|
254
|
+
const fx = fixture();
|
|
255
|
+
const result = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { query: 'zzz_quasar_999', limit: 8 });
|
|
256
|
+
assert.equal((result['tools'] as unknown[]).length, 2, 'ranked search still includes zero-score authorized candidates');
|
|
257
|
+
const discovery = result['discovery'] as Record<string, unknown>;
|
|
258
|
+
assert.equal(discovery['mode'], 'ranked_candidates');
|
|
259
|
+
assert.equal(discovery['matched_total'], null);
|
|
260
|
+
assert.equal(discovery['matched_total_exact'], false);
|
|
261
|
+
assert.equal(discovery['truncated'], false);
|
|
262
|
+
assert.equal(discovery['authorized_total'], 2);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
test('capability search counts only tools remaining after authorization and direct-tool policy', async () => {
|
|
266
|
+
const fx = fixture();
|
|
267
|
+
const declaration = JSON.parse(spec());
|
|
268
|
+
declaration.paths['/orders'].post = {
|
|
269
|
+
operationId: 'order_update', summary: 'Update order',
|
|
270
|
+
'x-agent-capability': { version: 1, enabled: true, scope: 'tenant.order.write' },
|
|
271
|
+
};
|
|
272
|
+
fx.setSpec(JSON.stringify(declaration));
|
|
273
|
+
const limited = route();
|
|
274
|
+
limited.tools = { ...limited.tools, sources: [{ provider: 'business', allow: ['tenant.order.*'] }] };
|
|
275
|
+
fx.setRoute(limited);
|
|
276
|
+
const result = await searchAgentCapabilitiesFor(fx.deps, auth(), 'tenant-agent', { query: 'order', limit: 1 });
|
|
277
|
+
assert.deepEqual((result['tools'] as Array<{ name: string }>).map((tool) => tool.name), ['order_list']);
|
|
278
|
+
const discovery = result['discovery'] as Record<string, unknown>;
|
|
279
|
+
assert.equal(discovery['authorized_total'], 1, 'scope-excluded reads and direct-policy-excluded writes must not be counted');
|
|
280
|
+
assert.equal(discovery['returned_count'], 1);
|
|
281
|
+
assert.equal(discovery['has_more'], false);
|
|
282
|
+
assert.equal(JSON.stringify(result).includes('staff_list'), false);
|
|
283
|
+
assert.equal(JSON.stringify(result).includes('order_update'), false);
|
|
284
|
+
|
|
285
|
+
const noSubject = auth();
|
|
286
|
+
noSubject.session.on_behalf_of = '';
|
|
287
|
+
const empty = await searchAgentCapabilitiesFor(fx.deps, noSubject, 'tenant-agent', { query: 'order' });
|
|
288
|
+
assert.equal((empty['discovery'] as Record<string, unknown>)['authorized_total'], 0);
|
|
289
|
+
assert.deepEqual(empty['tools'], []);
|
|
290
|
+
const denied = auth();
|
|
291
|
+
denied.session.allowed_routes = [];
|
|
292
|
+
await assert.rejects(
|
|
293
|
+
searchAgentCapabilitiesFor(fx.deps, denied, 'tenant-agent', { query: 'order' }),
|
|
294
|
+
(error) => error instanceof AgentToolApiError && error.code === 'route_not_allowed',
|
|
295
|
+
);
|
|
296
|
+
});
|
|
@@ -8,6 +8,8 @@ import type { Route } from '../core/contracts/types';
|
|
|
8
8
|
import type { KbService } from '../services/kb';
|
|
9
9
|
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
10
10
|
import { AgentClientRuntimeConflictError, type AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
|
|
11
|
+
import { admitAgentTaskTurnFor, bindingForTask, parseAgentTaskBinding, resolveAgentTaskRunFor, assertAgentLegacyTaskAllowedFor } from './agent-task-control';
|
|
12
|
+
import { assertTaskCanDispatch } from '../core/runtime/agent-task-control';
|
|
11
13
|
|
|
12
14
|
export const AGENT_RUNTIME_PROFILE_SCHEMA = 'bailing.agent-runtime-profile.v1';
|
|
13
15
|
export const AGENT_TURN_CONTEXT_SCHEMA = 'bailing.agent-turn-context.v1';
|
|
@@ -27,6 +29,7 @@ export interface AgentTurnInput {
|
|
|
27
29
|
user_input: string;
|
|
28
30
|
page_context?: Record<string, unknown>;
|
|
29
31
|
renderers?: string[];
|
|
32
|
+
task_binding?: unknown;
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
export interface AgentRunCompleteInput {
|
|
@@ -258,12 +261,15 @@ export async function prepareAgentTurnFor(
|
|
|
258
261
|
user_input: strictClientText(raw.user_input, 'user_input', 64_000, true),
|
|
259
262
|
...(raw.page_context ? { page_context: raw.page_context } : {}),
|
|
260
263
|
...(renderers !== undefined ? { renderers } : {}),
|
|
264
|
+
...(raw.task_binding !== undefined ? { task_binding: parseAgentTaskBinding(raw.task_binding) } : {}),
|
|
261
265
|
};
|
|
262
266
|
if (Buffer.byteLength(JSON.stringify(input.page_context ?? {}), 'utf8') > 16 * 1024) {
|
|
263
267
|
throw new AgentToolApiError(413, 'page_context_too_large', 'page_context exceeds 16 KiB.');
|
|
264
268
|
}
|
|
265
269
|
const repo = deps.toolProxyDeps.configStore?.agentClientRuntime;
|
|
266
270
|
if (!repo) throw new AgentToolApiError(503, 'agent_runtime_unavailable', 'Agent Client Runtime requires the MySQL control plane.');
|
|
271
|
+
const managedTask = await admitAgentTaskTurnFor(deps.toolProxyDeps.configStore, auth,
|
|
272
|
+
routeKey, input.client_conversation_id, input.task_binding);
|
|
267
273
|
const { route, catalog, activeLimit } = await authorizedRuntime(deps, auth, routeKey);
|
|
268
274
|
const threadId = await repo.resolveConversation({
|
|
269
275
|
session_id: auth.session.session_id, client_app_id: auth.client.app_id, route_key: route.route_key,
|
|
@@ -281,6 +287,8 @@ export async function prepareAgentTurnFor(
|
|
|
281
287
|
if (error instanceof AgentClientRuntimeConflictError) throw new AgentToolApiError(409, 'turn_conflict', error.message);
|
|
282
288
|
throw error;
|
|
283
289
|
}
|
|
290
|
+
if (managedTask) await deps.toolProxyDeps.configStore!.agentTaskControl!.bindRuntimeRun(
|
|
291
|
+
managedTask.taskId, managedTask.scopeHash, auth.session.session_id, reserved.run.run_id);
|
|
284
292
|
if (reserved.run.context) return reserved.run.context;
|
|
285
293
|
|
|
286
294
|
// 先从总账装配本轮之前的记忆,再追加本轮 user visible message。
|
|
@@ -300,6 +308,7 @@ export async function prepareAgentTurnFor(
|
|
|
300
308
|
const context: Record<string, unknown> = {
|
|
301
309
|
schema_version: AGENT_TURN_CONTEXT_SCHEMA,
|
|
302
310
|
run_id: reserved.run.run_id,
|
|
311
|
+
...(managedTask ? { task_binding: bindingForTask(managedTask) } : {}),
|
|
303
312
|
profile_revision: profileBody['revision'],
|
|
304
313
|
capability_revision: selected.capability_revision,
|
|
305
314
|
context: {
|
|
@@ -340,6 +349,10 @@ export async function searchAgentCapabilitiesFor(
|
|
|
340
349
|
): Promise<Record<string, unknown>> {
|
|
341
350
|
let query = input.query === undefined ? '' : strictClientText(input.query, 'query', 2000);
|
|
342
351
|
if (!query.trim() && !input.run_id) throw new AgentToolApiError(400, 'invalid_request', 'query is required when run_id is not provided.');
|
|
352
|
+
if (input.run_id) {
|
|
353
|
+
const task = await resolveAgentTaskRunFor(deps.toolProxyDeps.configStore, auth, safeRunId(input.run_id), routeKey, true);
|
|
354
|
+
if (task) assertTaskCanDispatch(task, deps.toolProxyDeps.now());
|
|
355
|
+
} else await assertAgentLegacyTaskAllowedFor(deps.toolProxyDeps.configStore, auth.session.session_id);
|
|
343
356
|
const { activeLimit } = await authorizedRuntime(deps, auth, routeKey);
|
|
344
357
|
if (input.run_id) {
|
|
345
358
|
const runId = safeRunId(input.run_id);
|
|
@@ -3,6 +3,8 @@ import type { AgentToolAuthContext } from './agent-tool-invocations';
|
|
|
3
3
|
import {
|
|
4
4
|
auditUuid, parseCreateConversationAudit, parseConversationAuditEvents, ConversationAuditError,
|
|
5
5
|
CONVERSATION_AUDIT_SCHEMA, CONVERSATION_AUDIT_ACK_SCHEMA,
|
|
6
|
+
CONVERSATION_AUDIT_CREATE_V2_SCHEMA, CONVERSATION_AUDIT_CAPABILITIES_SCHEMA,
|
|
7
|
+
CONVERSATION_AUDIT_MEMBER_BINDINGS, parseCreateCrossBindingConversationAudit,
|
|
6
8
|
} from '../core/runtime/agent-conversation-audit';
|
|
7
9
|
|
|
8
10
|
function repository(configStore: ConfigStoreContract | null) {
|
|
@@ -13,10 +15,28 @@ function repository(configStore: ConfigStoreContract | null) {
|
|
|
13
15
|
}
|
|
14
16
|
|
|
15
17
|
export async function createConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, body: unknown) {
|
|
18
|
+
if (body && typeof body === 'object' && 'schema' in body && body.schema === CONVERSATION_AUDIT_CREATE_V2_SCHEMA) {
|
|
19
|
+
const input = parseCreateCrossBindingConversationAudit(body);
|
|
20
|
+
const repo = repository(store);
|
|
21
|
+
if (typeof repo.createCrossBinding !== 'function' || typeof repo.supportsCrossBindingMembers !== 'function' ||
|
|
22
|
+
await repo.supportsCrossBindingMembers() !== true) {
|
|
23
|
+
throw new ConversationAuditError(503, 'conversation_audit_cross_binding_unavailable', 'Cross-binding conversation audit storage is unavailable.');
|
|
24
|
+
}
|
|
25
|
+
return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repo.createCrossBinding(auth, input) };
|
|
26
|
+
}
|
|
16
27
|
const input = parseCreateConversationAudit(body);
|
|
17
28
|
return { schema: CONVERSATION_AUDIT_SCHEMA, ...await repository(store).create(auth, input) };
|
|
18
29
|
}
|
|
19
30
|
|
|
31
|
+
/** No sessions, account names, identifiers or transcript data are discovered here. */
|
|
32
|
+
export async function conversationAuditCapabilitiesFor(store: ConfigStoreContract | null) {
|
|
33
|
+
const repo = store?.agentConversationAudit;
|
|
34
|
+
const supported = typeof repo?.createCrossBinding === 'function' && typeof repo.supportsCrossBindingMembers === 'function' &&
|
|
35
|
+
await repo.supportsCrossBindingMembers() === true;
|
|
36
|
+
return { schema: CONVERSATION_AUDIT_CAPABILITIES_SCHEMA,
|
|
37
|
+
cross_binding_members: supported, member_bindings: CONVERSATION_AUDIT_MEMBER_BINDINGS };
|
|
38
|
+
}
|
|
39
|
+
|
|
20
40
|
export async function confirmConversationAuditFor(store: ConfigStoreContract | null, auth: AgentToolAuthContext, id: string, body: unknown) {
|
|
21
41
|
if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).length) {
|
|
22
42
|
throw new ConversationAuditError(400, 'invalid_request', 'Member confirmation requires an empty object; identity comes from the bearer.');
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import type { Job } from '../core/contracts/types';
|
|
3
|
+
import { argsHash } from '../core/contracts/tools';
|
|
4
|
+
|
|
5
|
+
// A recovery snapshot is private execution material, never plaintext in job metadata or audit output.
|
|
6
|
+
// Rotating the instance token makes pending snapshots unreadable and fails closed.
|
|
7
|
+
function key(secret: string): Buffer {
|
|
8
|
+
if (!secret) throw new Error('invocation_snapshot_key_unavailable');
|
|
9
|
+
return createHash('sha256').update('bailing.agent.invocation.snapshot.v1\0').update(secret).digest();
|
|
10
|
+
}
|
|
11
|
+
function aad(job: Job): Buffer {
|
|
12
|
+
return Buffer.from(JSON.stringify([job.job_id, job.request_id, job.client_app_id, job.agent_session_id,
|
|
13
|
+
job.metadata.agent_run_id, job.metadata.agent_route, job.metadata.agent_tool,
|
|
14
|
+
job.metadata.agent_args_hash, job.metadata.agent_execution_fingerprint]));
|
|
15
|
+
}
|
|
16
|
+
export function sealInvocationArguments(job: Job, args: Record<string, unknown>, secret: string): string {
|
|
17
|
+
const nonce = randomBytes(12);
|
|
18
|
+
const cipher = createCipheriv('aes-256-gcm', key(secret), nonce);
|
|
19
|
+
cipher.setAAD(aad(job));
|
|
20
|
+
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(args), 'utf8'), cipher.final()]);
|
|
21
|
+
return ['v1', nonce.toString('base64url'), cipher.getAuthTag().toString('base64url'), ciphertext.toString('base64url')].join('.');
|
|
22
|
+
}
|
|
23
|
+
export function openInvocationArguments(job: Job, secret: string): Record<string, unknown> | null {
|
|
24
|
+
try {
|
|
25
|
+
const parts = String(job.metadata.agent_frozen_arguments ?? '').split('.');
|
|
26
|
+
if (parts.length !== 4 || parts[0] !== 'v1') return null;
|
|
27
|
+
const decipher = createDecipheriv('aes-256-gcm', key(secret), Buffer.from(parts[1]!, 'base64url'));
|
|
28
|
+
decipher.setAAD(aad(job));
|
|
29
|
+
decipher.setAuthTag(Buffer.from(parts[2]!, 'base64url'));
|
|
30
|
+
const raw = Buffer.concat([decipher.update(Buffer.from(parts[3]!, 'base64url')), decipher.final()]).toString('utf8');
|
|
31
|
+
const args: unknown = JSON.parse(raw);
|
|
32
|
+
if (!args || typeof args !== 'object' || Array.isArray(args) || argsHash(args as Record<string, unknown>) !== job.metadata.agent_args_hash) return null;
|
|
33
|
+
return args as Record<string, unknown>;
|
|
34
|
+
} catch { return null; }
|
|
35
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import type { AgentSystemInfo } from '../core/contracts/types';
|
|
3
|
+
import { routeAgentClientConfig, routeAgentSystemInfo } from '../core/config/route-config';
|
|
4
|
+
import { agentDirectToolsConfig } from '../core/config/tools-config';
|
|
5
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
6
|
+
import { resolveAgentRouteFor, type AgentToolAuthContext } from './agent-tool-invocations';
|
|
7
|
+
|
|
8
|
+
export const AGENT_SYSTEM_INFO_SCHEMA = 'bailing.agent-system-info.v1';
|
|
9
|
+
|
|
10
|
+
export interface AgentSystemInfoResponse {
|
|
11
|
+
schema_version: typeof AGENT_SYSTEM_INFO_SCHEMA;
|
|
12
|
+
binding: { client_app_id: string; session_id: string; workspace: string };
|
|
13
|
+
metadata_status: 'configured' | 'missing';
|
|
14
|
+
revision: string | null;
|
|
15
|
+
system: AgentSystemInfo | null;
|
|
16
|
+
tool_status: 'not_loaded';
|
|
17
|
+
availability: 'unknown' | 'unavailable';
|
|
18
|
+
unavailable_reason?: 'agent_client_disabled' | 'agent_direct_disabled';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Read only the selected route's product description; no tool, context or run services are used. */
|
|
22
|
+
export async function getAgentSystemInfoFor(
|
|
23
|
+
configStore: ConfigStoreContract | null,
|
|
24
|
+
auth: AgentToolAuthContext,
|
|
25
|
+
workspace: string,
|
|
26
|
+
): Promise<AgentSystemInfoResponse> {
|
|
27
|
+
const route = await resolveAgentRouteFor({ configStore }, auth, workspace);
|
|
28
|
+
const system = routeAgentSystemInfo(route);
|
|
29
|
+
const unavailableReason = !routeAgentClientConfig(route) ? 'agent_client_disabled'
|
|
30
|
+
: !agentDirectToolsConfig(route.tools) ? 'agent_direct_disabled' : undefined;
|
|
31
|
+
return {
|
|
32
|
+
schema_version: AGENT_SYSTEM_INFO_SCHEMA,
|
|
33
|
+
binding: { client_app_id: auth.client.app_id, session_id: auth.session.session_id, workspace: route.route_key },
|
|
34
|
+
metadata_status: system ? 'configured' : 'missing',
|
|
35
|
+
revision: system ? createHash('sha256').update(JSON.stringify({ schema_version: AGENT_SYSTEM_INFO_SCHEMA, system })).digest('hex') : null,
|
|
36
|
+
system,
|
|
37
|
+
tool_status: 'not_loaded',
|
|
38
|
+
availability: unavailableReason ? 'unavailable' : 'unknown',
|
|
39
|
+
...(unavailableReason ? { unavailable_reason: unavailableReason } : {}),
|
|
40
|
+
};
|
|
41
|
+
}
|