bailinghub 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitignore +5 -0
- package/README.en.md +5 -2
- package/README.md +6 -2
- package/SECURITY.md +11 -0
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_AUTH_API.en.md +191 -0
- package/docs/AGENT_AUTH_API.md +202 -0
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +263 -0
- package/docs/AGENT_CLIENT_QUICKSTART.md +245 -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 +25 -0
- package/docs/CHANGELOG.md +25 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
- package/docs/INDEPENDENT_VALIDATION.md +4 -4
- package/docs/README.en.md +10 -2
- package/docs/README.md +10 -2
- package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
- package/docs/RELEASE_NOTES_v0.5.1.en.md +45 -0
- package/docs/RELEASE_NOTES_v0.5.1.md +45 -0
- package/package.json +3 -2
- 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 +2 -1
- 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 +9 -13
- 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 +8 -12
- package/scripts/verify-oss-export.mjs +6 -12
- 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/oss-edition.ts +1 -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/agent-direct-console-selection.test.ts +22 -0
- package/src/core/config/config-codec.ts +2 -1
- package/src/core/config/config-models.test.ts +10 -0
- package/src/core/config/config-models.ts +21 -0
- package/src/core/config/config-schema.test.ts +6 -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 +36 -0
- 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/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 +183 -0
- package/src/infrastructure/config/config-agent-auth-repository.ts +453 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.test.ts +38 -0
- package/src/infrastructure/config/config-agent-client-runtime-repository.ts +307 -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-agent-clients.test.ts +120 -0
- package/src/routes/admin-agent-clients.ts +161 -0
- package/src/routes/admin-runtime.test.ts +214 -0
- package/src/routes/admin-runtime.ts +82 -2
- package/src/routes/admin.ts +3 -0
- 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/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-DuUY2UJU.js → Accounts-r10QUjLQ.js} +1 -1
- package/web/console/assets/AgentClients-DsWADpzr.css +1 -0
- package/web/console/assets/AgentClients-UTTqbkjy.js +1 -0
- package/web/console/assets/{Approvals-B11mo1dy.js → Approvals-BGKkYIya.js} +1 -1
- package/web/console/assets/{Audit-CQwJRIJT.js → Audit-CQmjOAoO.js} +1 -1
- package/web/console/assets/{BrandLockup-BIF-h1pi.js → BrandLockup-BF_0pCa3.js} +1 -1
- package/web/console/assets/{Channels-BIploUT-.js → Channels-C4yZE67F.js} +1 -1
- package/web/console/assets/{ChatEntries-Cpg_WV-o.js → ChatEntries-OqsqLjU6.js} +1 -1
- package/web/console/assets/Clients-CNIVs7Qn.css +1 -0
- package/web/console/assets/Clients-Dv3sv51C.js +3 -0
- package/web/console/assets/{Cost-BF52tfU2.js → Cost-C_-kiH59.js} +1 -1
- package/web/console/assets/{Credentials-SwfmQAv6.js → Credentials-CPTEAiV6.js} +1 -1
- package/web/console/assets/{Diagnostics-CJfbI_8p.js → Diagnostics-O-NKFOeI.js} +1 -1
- package/web/console/assets/{Executors-CzlZlznA.js → Executors-GVIAiNgv.js} +1 -1
- package/web/console/assets/{HelpTip-CT07o3kB.js → HelpTip-i-KJhf5s.js} +1 -1
- package/web/console/assets/{Kb-CVX22U4k.js → Kb-BsCWkJI1.js} +2 -2
- package/web/console/assets/{Login-PoUVsBI-.js → Login-VFjkHNMr.js} +1 -1
- package/web/console/assets/{Projects-DYlbjLQy.js → Projects-Ds-sJwfy.js} +1 -1
- package/web/console/assets/Routes-CXGl9SMM.css +1 -0
- package/web/console/assets/Routes-Wwurw2UU.js +124 -0
- package/web/console/assets/Runs-4zDD9VOC.css +1 -0
- package/web/console/assets/Runs-DLPzXmSy.js +3 -0
- package/web/console/assets/{Setup-xiPXit_b.js → Setup-BLelw0_V.js} +1 -1
- package/web/console/assets/Shell-CvaeK4j_.js +1 -0
- package/web/console/assets/Shell-D9Uw-fsa.css +1 -0
- package/web/console/assets/{StorageBuckets-Bjsc3pLd.js → StorageBuckets-Dv6u47yO.js} +1 -1
- package/web/console/assets/{SystemSettings-CcKF2lJ9.js → SystemSettings-B9K7zaDU.js} +1 -1
- package/web/console/assets/{SystemStatus-Oj1xjxJn.js → SystemStatus-H-oKDo-y.js} +1 -1
- package/web/console/assets/{Targets-y1KllVXT.js → Targets-CCFhjPKf.js} +1 -1
- package/web/console/assets/{Tools-DoEP_y9x.js → Tools-D0H9xpFH.js} +1 -1
- package/web/console/assets/index-CuoTgf6q.js +2 -0
- package/web/console/assets/{index-DZEQL_yy.js → index-DyX9Bz3V.js} +1 -1
- package/web/console/assets/{request-CBLNpLth.js → request-F5lXa7Ro.js} +1 -1
- package/web/console/assets/{schema-DzwLpuOy.js → schema-DUWaWqPn.js} +1 -1
- package/web/console/assets/{util-SiQC2MJh.js → util-4bN2dv7B.js} +1 -1
- package/web/console/assets/{vendor-element-D7WRzHhy.js → vendor-element-CZoEjZr8.js} +1 -1
- package/web/console/assets/{vendor-mammoth-DvgsHdlx.js → vendor-mammoth-nXG51Cg7.js} +1 -1
- package/web/console/index.html +2 -2
- package/web-admin/src/agent-direct-selection.ts +21 -0
- package/web-admin/src/layout/Shell.vue +1 -1
- package/web-admin/src/pages/AgentClients.vue +254 -0
- package/web-admin/src/pages/Clients.vue +13 -3
- package/web-admin/src/pages/Routes.vue +331 -16
- package/web-admin/src/pages/Runs.vue +159 -38
- package/web-admin/src/router.ts +2 -0
- package/web/console/assets/Clients--D7NQJKk.css +0 -1
- package/web/console/assets/Clients-DS29eUi2.js +0 -3
- package/web/console/assets/Routes-DSEvGujN.js +0 -124
- package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
- package/web/console/assets/Runs-B-TsYZEt.js +0 -3
- package/web/console/assets/Runs-CUtSsPW-.css +0 -1
- package/web/console/assets/Shell-BVIjmoY8.css +0 -1
- package/web/console/assets/Shell-DNiWZOYB.js +0 -1
- package/web/console/assets/index-CxPIS6G7.js +0 -2
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { AgentToolApiError, listAgentToolsFor, searchAgentToolsFor, type AgentToolAuthContext, type AgentToolCatalog } from './agent-tool-invocations';
|
|
3
|
+
import type { ToolProxyDeps } from './tool-proxy';
|
|
4
|
+
import { routeAgentClientConfig, routeKnowledgeConfig } from '../core/config/route-config';
|
|
5
|
+
import { resolveMemoryConfig } from '../core/runtime/memory';
|
|
6
|
+
import { maxToolCalls } from '../core/config/tools-config';
|
|
7
|
+
import type { Route } from '../core/contracts/types';
|
|
8
|
+
import type { KbService } from '../services/kb';
|
|
9
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
10
|
+
import { AgentClientRuntimeConflictError, type AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
|
|
11
|
+
|
|
12
|
+
export const AGENT_RUNTIME_PROFILE_SCHEMA = 'bailing.agent-runtime-profile.v1';
|
|
13
|
+
export const AGENT_TURN_CONTEXT_SCHEMA = 'bailing.agent-turn-context.v1';
|
|
14
|
+
export const AGENT_WORKSPACES_SCHEMA = 'bailing.agent-workspaces.v1';
|
|
15
|
+
export const AGENT_RUN_COMPLETION_SCHEMA = 'bailing.agent-run-completion.v1';
|
|
16
|
+
|
|
17
|
+
export interface AgentClientRuntimeDeps {
|
|
18
|
+
toolProxyDeps: ToolProxyDeps;
|
|
19
|
+
kbService: KbService | null;
|
|
20
|
+
stateStore: RuntimeStateStore;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface AgentTurnInput {
|
|
24
|
+
client_conversation_id: string;
|
|
25
|
+
client_turn_id: string;
|
|
26
|
+
user_message_id: string;
|
|
27
|
+
user_input: string;
|
|
28
|
+
page_context?: Record<string, unknown>;
|
|
29
|
+
renderers?: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface AgentRunCompleteInput {
|
|
33
|
+
assistant_message_id: string;
|
|
34
|
+
status: 'completed' | 'failed' | 'cancelled';
|
|
35
|
+
content: string;
|
|
36
|
+
model?: string;
|
|
37
|
+
runtime?: string;
|
|
38
|
+
usage?: Record<string, unknown>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
42
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function stableJson(value: unknown): string {
|
|
46
|
+
if (value === null) return 'null';
|
|
47
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
|
|
48
|
+
if (isRecord(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
|
|
49
|
+
return JSON.stringify(value) ?? 'null';
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function hash(value: unknown): string {
|
|
53
|
+
return createHash('sha256').update(stableJson(value), 'utf8').digest('hex');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function safeText(value: unknown, maximum: number): string {
|
|
57
|
+
return typeof value === 'string'
|
|
58
|
+
? value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ').trim().slice(0, maximum)
|
|
59
|
+
: '';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const DISALLOWED_CLIENT_CONTROL_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
|
63
|
+
|
|
64
|
+
/** Client-owned DTO text is never rewritten: invalid input fails closed instead. */
|
|
65
|
+
function strictClientText(value: string, name: string, maximum: number, requireContent = false): string {
|
|
66
|
+
if (value.length > maximum) {
|
|
67
|
+
throw new AgentToolApiError(400, 'invalid_request', `${name} must not exceed ${maximum} characters.`);
|
|
68
|
+
}
|
|
69
|
+
if (DISALLOWED_CLIENT_CONTROL_RE.test(value)) {
|
|
70
|
+
throw new AgentToolApiError(400, 'invalid_request', `${name} contains disallowed control characters.`);
|
|
71
|
+
}
|
|
72
|
+
if (requireContent && !value.trim()) {
|
|
73
|
+
throw new AgentToolApiError(400, 'invalid_request', `${name} must not be empty.`);
|
|
74
|
+
}
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function strictRenderers(value: string[] | undefined): string[] | undefined {
|
|
79
|
+
if (value === undefined) return undefined;
|
|
80
|
+
if (value.length > 20) {
|
|
81
|
+
throw new AgentToolApiError(400, 'invalid_request', 'renderers must not contain more than 20 entries.');
|
|
82
|
+
}
|
|
83
|
+
const seen = new Set<string>();
|
|
84
|
+
for (const renderer of value) {
|
|
85
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/.test(renderer)) {
|
|
86
|
+
throw new AgentToolApiError(400, 'invalid_request', 'renderers contains an invalid renderer name.');
|
|
87
|
+
}
|
|
88
|
+
if (seen.has(renderer)) {
|
|
89
|
+
throw new AgentToolApiError(400, 'invalid_request', 'renderers must not contain duplicate names.');
|
|
90
|
+
}
|
|
91
|
+
seen.add(renderer);
|
|
92
|
+
}
|
|
93
|
+
return [...value];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function safeId(value: string, name: string): string {
|
|
97
|
+
const id = value.trim();
|
|
98
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(id)) {
|
|
99
|
+
throw new AgentToolApiError(400, 'invalid_request', `${name} must be a 1..128 character stable identifier.`);
|
|
100
|
+
}
|
|
101
|
+
return id;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function safeRunId(value: string): string {
|
|
105
|
+
const id = value.trim();
|
|
106
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(id)) {
|
|
107
|
+
throw new AgentToolApiError(400, 'invalid_request', 'run_id must be a UUID.');
|
|
108
|
+
}
|
|
109
|
+
return id;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function publicInstructions(route: Route): string {
|
|
113
|
+
const system = safeText(route.target_config?.['system_prompt'], 40_000);
|
|
114
|
+
const client = safeText(routeAgentClientConfig(route)?.instructions, 20_000);
|
|
115
|
+
return [system ? `【路由系统规则】\n${system}` : '', client ? `【本地 Agent 补充规则】\n${client}` : ''].filter(Boolean).join('\n\n');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function authorizedRuntime(
|
|
119
|
+
deps: AgentClientRuntimeDeps,
|
|
120
|
+
auth: AgentToolAuthContext,
|
|
121
|
+
routeKey: string,
|
|
122
|
+
): Promise<{ route: Route; catalog: AgentToolCatalog; activeLimit: number }> {
|
|
123
|
+
const route = await deps.toolProxyDeps.configStore?.routes.get(routeKey);
|
|
124
|
+
if (!route) throw new AgentToolApiError(404, 'route_unavailable', 'The configured route is unavailable.');
|
|
125
|
+
const client = routeAgentClientConfig(route);
|
|
126
|
+
if (!client) throw new AgentToolApiError(403, 'agent_client_disabled', 'Agent Client Runtime is not enabled for this route.');
|
|
127
|
+
const catalog = await listAgentToolsFor(deps.toolProxyDeps, auth, routeKey);
|
|
128
|
+
return { route, catalog, activeLimit: client.active_tool_limit };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function profileFor(route: Route, catalog: AgentToolCatalog, activeLimit: number): Record<string, unknown> {
|
|
132
|
+
const memory = resolveMemoryConfig(route.memory);
|
|
133
|
+
const knowledge = routeKnowledgeConfig(route.knowledge);
|
|
134
|
+
const workspace = { route: route.route_key, name: safeText(route.name, 128), description: safeText(route.description, 1000) };
|
|
135
|
+
const governance = {
|
|
136
|
+
planner: 'local_agent', execution: 'bailinghub_governed', authorization: 'server_revalidated',
|
|
137
|
+
knowledge_trust: 'reference_only', tool_results_trust: 'untrusted_data', hidden_reasoning_sync: false,
|
|
138
|
+
max_tool_calls: maxToolCalls(route.tools), permission: safeText(route.permission, 64) || null,
|
|
139
|
+
};
|
|
140
|
+
const profileBody = {
|
|
141
|
+
instructions: publicInstructions(route),
|
|
142
|
+
knowledge: knowledge ? {
|
|
143
|
+
enabled: true, sources: knowledge.kb_ids.length, mode: knowledge.inject,
|
|
144
|
+
top_k: knowledge.top_k, max_docs: knowledge.max_docs, page_boost: knowledge.page_boost,
|
|
145
|
+
} : { enabled: false, sources: 0 },
|
|
146
|
+
memory: {
|
|
147
|
+
recent_messages: memory.recent_messages, recent_budget_chars: memory.recent_budget_chars,
|
|
148
|
+
per_message_chars: memory.per_message_chars, summary_enabled: memory.summary_enabled,
|
|
149
|
+
summary_max_chars: memory.summary_max_chars,
|
|
150
|
+
},
|
|
151
|
+
governance,
|
|
152
|
+
};
|
|
153
|
+
const revision = hash({ schema: AGENT_RUNTIME_PROFILE_SCHEMA, workspace, profile: profileBody });
|
|
154
|
+
return {
|
|
155
|
+
schema_version: AGENT_RUNTIME_PROFILE_SCHEMA,
|
|
156
|
+
workspace,
|
|
157
|
+
profile: { revision, ...profileBody },
|
|
158
|
+
capabilities: {
|
|
159
|
+
revision: catalog.capability_revision, authorized_total: catalog.tools.length, active_limit: activeLimit,
|
|
160
|
+
readonly: catalog.tools.filter((tool) => tool.readonly).length,
|
|
161
|
+
writes: catalog.tools.filter((tool) => !tool.readonly).length,
|
|
162
|
+
approval_required: catalog.tools.filter((tool) => tool.approval_required).length,
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function listAgentWorkspacesFor(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext): Promise<Record<string, unknown>> {
|
|
168
|
+
const routes = await deps.toolProxyDeps.configStore?.routes.list() ?? [];
|
|
169
|
+
const workspaces: Record<string, unknown>[] = [];
|
|
170
|
+
for (const route of routes) {
|
|
171
|
+
const client = routeAgentClientConfig(route);
|
|
172
|
+
if (!client) continue;
|
|
173
|
+
try {
|
|
174
|
+
const catalog = await listAgentToolsFor(deps.toolProxyDeps, auth, route.route_key);
|
|
175
|
+
const profile = profileFor(route, catalog, client.active_tool_limit);
|
|
176
|
+
workspaces.push({
|
|
177
|
+
route: route.route_key,
|
|
178
|
+
name: safeText(route.name, 128),
|
|
179
|
+
description: safeText(route.description, 1000),
|
|
180
|
+
profile: safeText(route.profile, 64),
|
|
181
|
+
permission: safeText(route.permission, 64) || null,
|
|
182
|
+
profile_revision: (profile['profile'] as Record<string, unknown>)['revision'],
|
|
183
|
+
capability_revision: catalog.capability_revision,
|
|
184
|
+
authorized_tool_count: catalog.tools.length,
|
|
185
|
+
active_tool_limit: client.active_tool_limit,
|
|
186
|
+
});
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (!(error instanceof AgentToolApiError)) throw error;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { schema_version: AGENT_WORKSPACES_SCHEMA, workspaces };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export async function getAgentWorkspaceBootstrapFor(
|
|
195
|
+
deps: AgentClientRuntimeDeps,
|
|
196
|
+
auth: AgentToolAuthContext,
|
|
197
|
+
routeKey: string,
|
|
198
|
+
): Promise<Record<string, unknown>> {
|
|
199
|
+
const { route, catalog, activeLimit } = await authorizedRuntime(deps, auth, routeKey);
|
|
200
|
+
return profileFor(route, catalog, activeLimit);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function trimRecent(
|
|
204
|
+
rows: Array<{ direction: string; channel: string; content: string; created_at: string }>,
|
|
205
|
+
cfg: ReturnType<typeof resolveMemoryConfig>,
|
|
206
|
+
): Array<Record<string, unknown>> {
|
|
207
|
+
const result: Array<Record<string, unknown>> = [];
|
|
208
|
+
let budget = 0;
|
|
209
|
+
for (let i = rows.length - 1; i >= 0; i--) {
|
|
210
|
+
const row = rows[i]!;
|
|
211
|
+
const content = safeText(row.content, cfg.per_message_chars);
|
|
212
|
+
if (budget + content.length > cfg.recent_budget_chars) break;
|
|
213
|
+
result.unshift({ role: row.direction === 'in' ? 'user' : 'assistant', content, created_at: row.created_at });
|
|
214
|
+
budget += content.length;
|
|
215
|
+
}
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function knowledgeFor(deps: AgentClientRuntimeDeps, route: Route, query: string): Promise<{
|
|
220
|
+
items: Array<Record<string, unknown>>;
|
|
221
|
+
refs: Array<Record<string, unknown>>;
|
|
222
|
+
}> {
|
|
223
|
+
const cfg = routeKnowledgeConfig(route.knowledge);
|
|
224
|
+
if (!cfg || !deps.kbService) return { items: [], refs: [] };
|
|
225
|
+
try {
|
|
226
|
+
if (cfg.inject === 'doc') {
|
|
227
|
+
const docs = await deps.kbService.searchDocsMulti(cfg.kb_ids, query.slice(0, 2000), Math.max(cfg.top_k, 8), cfg.min_score, cfg.max_docs);
|
|
228
|
+
return {
|
|
229
|
+
items: docs.map((doc, index) => ({ ref: `knowledge:${index + 1}`, title: safeText(doc.title, 300), content: safeText(doc.content, 6000) })),
|
|
230
|
+
refs: docs.map((doc, index) => ({ ref: `knowledge:${index + 1}`, doc_id: doc.doc_id, title: safeText(doc.title, 300), score: doc.score })),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
const hits = await deps.kbService.searchMulti(cfg.kb_ids, query.slice(0, 2000), cfg.top_k, cfg.min_score);
|
|
234
|
+
return {
|
|
235
|
+
items: hits.map((hit, index) => ({ ref: `knowledge:${index + 1}`, title: safeText(hit.title, 300), content: safeText(hit.content, 3000) })),
|
|
236
|
+
refs: hits.map((hit, index) => ({ ref: `knowledge:${index + 1}`, doc_id: hit.doc_id, title: safeText(hit.title, 300), score: hit.score })),
|
|
237
|
+
};
|
|
238
|
+
} catch { return { items: [], refs: [] }; }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function queryWithPage(input: AgentTurnInput): string {
|
|
242
|
+
const page = input.page_context ?? {};
|
|
243
|
+
const hint = ['title', 'page_name', 'page_key', 'url'].map((key) => safeText(page[key], 500)).filter(Boolean).join(' ');
|
|
244
|
+
return hint ? `${hint}\n${input.user_input}` : input.user_input;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export async function prepareAgentTurnFor(
|
|
248
|
+
deps: AgentClientRuntimeDeps,
|
|
249
|
+
auth: AgentToolAuthContext,
|
|
250
|
+
routeKey: string,
|
|
251
|
+
raw: AgentTurnInput,
|
|
252
|
+
): Promise<Record<string, unknown>> {
|
|
253
|
+
const renderers = strictRenderers(raw.renderers);
|
|
254
|
+
const input: AgentTurnInput = {
|
|
255
|
+
client_conversation_id: safeId(raw.client_conversation_id, 'client_conversation_id'),
|
|
256
|
+
client_turn_id: safeId(raw.client_turn_id, 'client_turn_id'),
|
|
257
|
+
user_message_id: safeId(raw.user_message_id, 'user_message_id'),
|
|
258
|
+
user_input: strictClientText(raw.user_input, 'user_input', 64_000, true),
|
|
259
|
+
...(raw.page_context ? { page_context: raw.page_context } : {}),
|
|
260
|
+
...(renderers !== undefined ? { renderers } : {}),
|
|
261
|
+
};
|
|
262
|
+
if (Buffer.byteLength(JSON.stringify(input.page_context ?? {}), 'utf8') > 16 * 1024) {
|
|
263
|
+
throw new AgentToolApiError(413, 'page_context_too_large', 'page_context exceeds 16 KiB.');
|
|
264
|
+
}
|
|
265
|
+
const repo = deps.toolProxyDeps.configStore?.agentClientRuntime;
|
|
266
|
+
if (!repo) throw new AgentToolApiError(503, 'agent_runtime_unavailable', 'Agent Client Runtime requires the MySQL control plane.');
|
|
267
|
+
const { route, catalog, activeLimit } = await authorizedRuntime(deps, auth, routeKey);
|
|
268
|
+
const threadId = await repo.resolveConversation({
|
|
269
|
+
session_id: auth.session.session_id, client_app_id: auth.client.app_id, route_key: route.route_key,
|
|
270
|
+
client_conversation_id: input.client_conversation_id, principal_id: safeText(auth.session.principal.id, 64),
|
|
271
|
+
});
|
|
272
|
+
const requestHash = hash({ schema: AGENT_TURN_CONTEXT_SCHEMA, route: route.route_key, ...input });
|
|
273
|
+
let reserved;
|
|
274
|
+
try {
|
|
275
|
+
reserved = await repo.reserveRun({
|
|
276
|
+
session_id: auth.session.session_id, client_app_id: auth.client.app_id, route_key: route.route_key, thread_id: threadId,
|
|
277
|
+
client_conversation_id: input.client_conversation_id, client_turn_id: input.client_turn_id,
|
|
278
|
+
user_message_id: input.user_message_id, request_hash: requestHash, user_input: input.user_input,
|
|
279
|
+
});
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (error instanceof AgentClientRuntimeConflictError) throw new AgentToolApiError(409, 'turn_conflict', error.message);
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
if (reserved.run.context) return reserved.run.context;
|
|
285
|
+
|
|
286
|
+
// 先从总账装配本轮之前的记忆,再追加本轮 user visible message。
|
|
287
|
+
const memoryCfg = resolveMemoryConfig(route.memory);
|
|
288
|
+
const threadMemory = memoryCfg.summary_enabled
|
|
289
|
+
? await deps.toolProxyDeps.configStore!.conversations.getThreadMemory(threadId)
|
|
290
|
+
: { summary: null, summary_upto_id: 0 };
|
|
291
|
+
const recentRaw = await deps.toolProxyDeps.configStore!.conversations.recentMessagesAfter(threadId, threadMemory.summary_upto_id, memoryCfg.recent_messages);
|
|
292
|
+
const recent = trimRecent(recentRaw, memoryCfg);
|
|
293
|
+
const query = queryWithPage(input);
|
|
294
|
+
const [knowledge, selected] = await Promise.all([
|
|
295
|
+
knowledgeFor(deps, route, query),
|
|
296
|
+
searchAgentToolsFor(deps.toolProxyDeps, auth, route.route_key, query, activeLimit),
|
|
297
|
+
]);
|
|
298
|
+
const profile = profileFor(route, catalog, activeLimit);
|
|
299
|
+
const profileBody = profile['profile'] as Record<string, unknown>;
|
|
300
|
+
const context: Record<string, unknown> = {
|
|
301
|
+
schema_version: AGENT_TURN_CONTEXT_SCHEMA,
|
|
302
|
+
run_id: reserved.run.run_id,
|
|
303
|
+
profile_revision: profileBody['revision'],
|
|
304
|
+
capability_revision: selected.capability_revision,
|
|
305
|
+
context: {
|
|
306
|
+
instructions: profileBody['instructions'],
|
|
307
|
+
page_context: input.page_context ?? {},
|
|
308
|
+
renderers: input.renderers ?? [],
|
|
309
|
+
memory: { summary: safeText(threadMemory.summary, memoryCfg.summary_max_chars) || null, recent },
|
|
310
|
+
memory_refs: [{ thread_id: threadId, summary_upto_id: threadMemory.summary_upto_id, prior_messages: recent.length }],
|
|
311
|
+
knowledge: knowledge.items,
|
|
312
|
+
knowledge_refs: knowledge.refs,
|
|
313
|
+
governance: profileBody['governance'],
|
|
314
|
+
},
|
|
315
|
+
active_tools: selected.tools,
|
|
316
|
+
};
|
|
317
|
+
let finalized: AgentClientRunRecord;
|
|
318
|
+
try {
|
|
319
|
+
finalized = await repo.finalizeTurn({
|
|
320
|
+
run_id: reserved.run.run_id, session_id: auth.session.session_id, client_app_id: auth.client.app_id,
|
|
321
|
+
request_hash: requestHash, context, principal_id: safeText(auth.session.principal.id, 64),
|
|
322
|
+
});
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (error instanceof AgentClientRuntimeConflictError) throw new AgentToolApiError(409, 'turn_conflict', error.message);
|
|
325
|
+
throw error;
|
|
326
|
+
}
|
|
327
|
+
await deps.stateStore.appendAudit({
|
|
328
|
+
ts: deps.toolProxyDeps.now(), job_id: finalized.run_id, request_id: input.client_turn_id,
|
|
329
|
+
event: 'agent_client_turn_context_ready',
|
|
330
|
+
detail: { agent_run_id: finalized.run_id, thread_id: finalized.thread_id, route: route.route_key, client_app_id: auth.client.app_id, agent_session_id: auth.session.session_id, active_tools: selected.tools.length },
|
|
331
|
+
}).catch(() => undefined);
|
|
332
|
+
return finalized.context ?? context;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export async function searchAgentCapabilitiesFor(
|
|
336
|
+
deps: AgentClientRuntimeDeps,
|
|
337
|
+
auth: AgentToolAuthContext,
|
|
338
|
+
routeKey: string,
|
|
339
|
+
input: { query?: string; limit?: number; run_id?: string },
|
|
340
|
+
): Promise<Record<string, unknown>> {
|
|
341
|
+
let query = input.query === undefined ? '' : strictClientText(input.query, 'query', 2000);
|
|
342
|
+
if (!query.trim() && !input.run_id) throw new AgentToolApiError(400, 'invalid_request', 'query is required when run_id is not provided.');
|
|
343
|
+
const { activeLimit } = await authorizedRuntime(deps, auth, routeKey);
|
|
344
|
+
if (input.run_id) {
|
|
345
|
+
const runId = safeRunId(input.run_id);
|
|
346
|
+
const run = await deps.toolProxyDeps.configStore?.agentClientRuntime?.getRun(runId, auth.session.session_id, auth.client.app_id);
|
|
347
|
+
if (!run || run.route_key !== routeKey) throw new AgentToolApiError(404, 'run_not_found', 'The run was not found for this Agent Session and route.');
|
|
348
|
+
if (!query.trim()) query = run.user_input;
|
|
349
|
+
}
|
|
350
|
+
if (!query.trim()) throw new AgentToolApiError(400, 'invalid_request', 'The bound run does not contain a usable query.');
|
|
351
|
+
const limit = Math.min(Math.max(Math.round(Number(input.limit) || activeLimit), 1), 12);
|
|
352
|
+
return { ...await searchAgentToolsFor(deps.toolProxyDeps, auth, routeKey, query, limit) };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function safeUsage(value: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
|
|
356
|
+
if (!value) return undefined;
|
|
357
|
+
const known = new Set(['input_tokens', 'cached_input_tokens', 'output_tokens', 'total_tokens', 'tool_calls', 'cost_usd']);
|
|
358
|
+
if (Object.keys(value).some((key) => !known.has(key))) throw new AgentToolApiError(400, 'invalid_request', 'usage contains undeclared fields.');
|
|
359
|
+
const out: Record<string, unknown> = {};
|
|
360
|
+
for (const [key, raw] of Object.entries(value)) {
|
|
361
|
+
const number = Number(raw);
|
|
362
|
+
if (!Number.isFinite(number) || number < 0) throw new AgentToolApiError(400, 'invalid_request', `usage.${key} must be a non-negative number.`);
|
|
363
|
+
out[key] = number;
|
|
364
|
+
}
|
|
365
|
+
return out;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export async function completeAgentRunFor(
|
|
369
|
+
deps: AgentClientRuntimeDeps,
|
|
370
|
+
auth: AgentToolAuthContext,
|
|
371
|
+
runIdRaw: string,
|
|
372
|
+
raw: AgentRunCompleteInput,
|
|
373
|
+
): Promise<Record<string, unknown>> {
|
|
374
|
+
const runId = safeRunId(runIdRaw);
|
|
375
|
+
const assistantMessageId = safeId(raw.assistant_message_id, 'assistant_message_id');
|
|
376
|
+
const output = strictClientText(raw.content, 'content', 64_000, true);
|
|
377
|
+
if (!['completed', 'failed', 'cancelled'].includes(raw.status)) throw new AgentToolApiError(400, 'invalid_request', 'status is invalid.');
|
|
378
|
+
const model = raw.model === undefined ? undefined : strictClientText(raw.model, 'model', 191);
|
|
379
|
+
const runtime = raw.runtime === undefined ? undefined : strictClientText(raw.runtime, 'runtime', 191);
|
|
380
|
+
const usage = safeUsage(raw.usage);
|
|
381
|
+
const completionHash = hash({ schema: AGENT_RUN_COMPLETION_SCHEMA, assistant_message_id: assistantMessageId, status: raw.status, content: output, model: model ?? null, runtime: runtime ?? null, usage: usage ?? null });
|
|
382
|
+
const repo = deps.toolProxyDeps.configStore?.agentClientRuntime;
|
|
383
|
+
if (!repo) throw new AgentToolApiError(503, 'agent_runtime_unavailable', 'Agent Client Runtime requires the MySQL control plane.');
|
|
384
|
+
let completed;
|
|
385
|
+
try {
|
|
386
|
+
completed = await repo.completeRun({
|
|
387
|
+
run_id: runId, session_id: auth.session.session_id, client_app_id: auth.client.app_id,
|
|
388
|
+
completion_hash: completionHash, assistant_message_id: assistantMessageId, status: raw.status,
|
|
389
|
+
assistant_output: output, ...(model !== undefined ? { model } : {}), ...(runtime !== undefined ? { runtime } : {}), ...(usage ? { usage } : {}),
|
|
390
|
+
});
|
|
391
|
+
} catch (error) {
|
|
392
|
+
if (error instanceof AgentClientRuntimeConflictError) throw new AgentToolApiError(409, 'run_completion_conflict', error.message);
|
|
393
|
+
if ((error as { code?: string })?.code === 'ER_DUP_ENTRY') throw new AgentToolApiError(409, 'assistant_message_conflict', 'assistant_message_id is already bound to a different run.');
|
|
394
|
+
throw error;
|
|
395
|
+
}
|
|
396
|
+
await deps.stateStore.appendAudit({
|
|
397
|
+
ts: deps.toolProxyDeps.now(), job_id: runId, request_id: assistantMessageId, event: 'agent_client_run_completed',
|
|
398
|
+
detail: { agent_run_id: runId, thread_id: completed.run.thread_id, route: completed.run.route_key, status: completed.run.status, idempotent_replay: !completed.created },
|
|
399
|
+
}).catch(() => undefined);
|
|
400
|
+
return {
|
|
401
|
+
schema_version: AGENT_RUN_COMPLETION_SCHEMA,
|
|
402
|
+
run_id: runId,
|
|
403
|
+
assistant_message_id: assistantMessageId,
|
|
404
|
+
status: completed.run.status,
|
|
405
|
+
idempotent_replay: !completed.created,
|
|
406
|
+
completed_at: completed.run.completed_at,
|
|
407
|
+
};
|
|
408
|
+
}
|