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.
Files changed (169) hide show
  1. package/.gitignore +5 -0
  2. package/README.en.md +6 -1
  3. package/README.md +6 -0
  4. package/SECURITY.md +11 -0
  5. package/docker-compose.images.yml +2 -2
  6. package/docs/AGENT_AUTH_API.en.md +175 -0
  7. package/docs/AGENT_AUTH_API.md +190 -0
  8. package/docs/AGENT_CLIENT_QUICKSTART.en.md +212 -0
  9. package/docs/AGENT_CLIENT_QUICKSTART.md +206 -0
  10. package/docs/AGENT_CLIENT_RUNTIME_API.en.md +157 -0
  11. package/docs/AGENT_CLIENT_RUNTIME_API.md +107 -0
  12. package/docs/CHANGELOG.en.md +59 -1
  13. package/docs/CHANGELOG.md +27 -1
  14. package/docs/COMPATIBILITY.en.md +25 -0
  15. package/docs/CONTRACT.en.md +79 -8
  16. package/docs/CONTRACT.md +36 -6
  17. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  18. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  19. package/docs/QUICKSTART.en.md +6 -0
  20. package/docs/QUICKSTART.md +1 -1
  21. package/docs/README.en.md +8 -0
  22. package/docs/README.md +8 -0
  23. package/docs/RELEASE_NOTES_v0.4.0.en.md +39 -0
  24. package/docs/RELEASE_NOTES_v0.4.0.md +39 -0
  25. package/docs/RELEASE_NOTES_v0.5.0.en.md +41 -0
  26. package/docs/RELEASE_NOTES_v0.5.0.md +41 -0
  27. package/docs/STREAMING.en.md +32 -0
  28. package/docs/STREAMING.md +8 -2
  29. package/docs/WIDGET_RENDERERS.en.md +123 -6
  30. package/docs/WIDGET_RENDERERS.md +75 -6
  31. package/docs/user-guide/console-map.en.md +1 -2
  32. package/docs/user-guide/console-map.md +2 -2
  33. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +9 -0
  34. package/package.json +3 -2
  35. package/schemas/config/chat-entry.schema.json +2 -1
  36. package/schemas/config/client.schema.json +7 -0
  37. package/schemas/config/common.schema.json +30 -0
  38. package/schemas/config/route.schema.json +11 -0
  39. package/scripts/check-doc-links.mjs +1 -0
  40. package/scripts/check-image-tags.sh +1 -1
  41. package/scripts/check-release-consistency.test.mjs +5 -5
  42. package/scripts/e2e-console.mjs +144 -0
  43. package/scripts/export-oss.mjs +5 -12
  44. package/scripts/install.sh +1 -1
  45. package/scripts/public-content-denylist.mjs +82 -0
  46. package/scripts/public-content-denylist.test.mjs +53 -0
  47. package/scripts/publish-images.sh +1 -1
  48. package/scripts/release-audit.mjs +8 -12
  49. package/scripts/sdk-runtime-test.mjs +171 -7
  50. package/scripts/security-scan.mjs +8 -5
  51. package/scripts/validate-examples.mjs +3 -1
  52. package/scripts/verify-github-repo.mjs +7 -11
  53. package/scripts/verify-oss-export.mjs +6 -12
  54. package/scripts/widget-renderer-test.mjs +244 -16
  55. package/sdk/php/README.md +27 -1
  56. package/sdk/php/src/AgentAuth.php +78 -0
  57. package/sdk/php/src/HubClient.php +3 -0
  58. package/sdk/php7/README.md +32 -2
  59. package/sdk/php7/src/AgentAuth.php +77 -0
  60. package/sdk/php7/src/HubClient.php +3 -0
  61. package/sql/055_agent_auth.sql +72 -0
  62. package/sql/056_agent_client_runtime.sql +60 -0
  63. package/src/adapters/channels/wecom-api.ts +1 -1
  64. package/src/app/agent-client-runtime.test.ts +221 -0
  65. package/src/app/agent-client-runtime.ts +408 -0
  66. package/src/app/agent-tool-invocations.test.ts +462 -0
  67. package/src/app/agent-tool-invocations.ts +795 -0
  68. package/src/app/agent-tool-job.test.ts +62 -0
  69. package/src/app/agent-tool-job.ts +41 -0
  70. package/src/app/auth.ts +2 -1
  71. package/src/app/kernel.ts +2 -0
  72. package/src/app/runtime-context.ts +8 -0
  73. package/src/app/tool-approvals.ts +5 -1
  74. package/src/app/tool-assembly.ts +19 -1
  75. package/src/app/tool-context.ts +2 -1
  76. package/src/core/config/config-codec.ts +2 -1
  77. package/src/core/config/config-models.test.ts +28 -1
  78. package/src/core/config/config-models.ts +46 -3
  79. package/src/core/config/config-schema.test.ts +8 -0
  80. package/src/core/config/route-config.test.ts +15 -0
  81. package/src/core/config/route-config.ts +36 -0
  82. package/src/core/config/tools-config.test.ts +58 -1
  83. package/src/core/config/tools-config.ts +84 -0
  84. package/src/core/contracts/tools.ts +162 -29
  85. package/src/core/contracts/types.ts +38 -1
  86. package/src/core/platform/chat-form.test.ts +147 -0
  87. package/src/core/platform/chat-form.ts +402 -0
  88. package/src/core/platform/version.ts +1 -1
  89. package/src/core/runtime/agent-client-trace.test.ts +154 -0
  90. package/src/core/runtime/agent-client-trace.ts +288 -0
  91. package/src/core/runtime/execution-runtime.test.ts +61 -0
  92. package/src/core/runtime/execution-runtime.ts +17 -0
  93. package/src/core/runtime/launch-runtime.ts +13 -0
  94. package/src/core/runtime/trace-runtime.test.ts +18 -1
  95. package/src/core/runtime/trace-runtime.ts +28 -3
  96. package/src/core/state/state-codec.ts +2 -0
  97. package/src/infrastructure/config/config-agent-auth-repository.test.ts +147 -0
  98. package/src/infrastructure/config/config-agent-auth-repository.ts +356 -0
  99. package/src/infrastructure/config/config-agent-client-runtime-repository.ts +253 -0
  100. package/src/infrastructure/config/config-approval-ledger.test.ts +32 -0
  101. package/src/infrastructure/config/config-approval-ledger.ts +16 -0
  102. package/src/infrastructure/config/config-client-repository.ts +3 -3
  103. package/src/infrastructure/config/config-conversation-ledger.test.ts +69 -0
  104. package/src/infrastructure/config/config-conversation-ledger.ts +8 -7
  105. package/src/infrastructure/config/config-observability-ledger.test.ts +50 -0
  106. package/src/infrastructure/config/config-observability-ledger.ts +65 -10
  107. package/src/infrastructure/config/config-route-repository.ts +4 -3
  108. package/src/infrastructure/config/configstore.ts +14 -3
  109. package/src/infrastructure/state/state-mysql.ts +2 -2
  110. package/src/kernel-api/v1/contracts.ts +8 -0
  111. package/src/routes/admin-runtime.test.ts +214 -0
  112. package/src/routes/admin-runtime.ts +82 -2
  113. package/src/routes/agent-api.test.ts +379 -0
  114. package/src/routes/agent-api.ts +251 -0
  115. package/src/routes/agent-auth.test.ts +276 -0
  116. package/src/routes/agent-auth.ts +395 -0
  117. package/src/routes/approvals.ts +4 -1
  118. package/src/routes/chat.test.ts +319 -7
  119. package/src/routes/chat.ts +166 -21
  120. package/src/routes/critical-routes.test.ts +235 -1
  121. package/src/routes/private-default.ts +2 -1
  122. package/src/routes/private.ts +16 -1
  123. package/src/routes/run.ts +79 -13
  124. package/web/connect/bailing-connect-php.tgz +0 -0
  125. package/web/connect/bailing-connect-php7.tgz +0 -0
  126. package/web/console/assets/{Accounts-CAwrtBiS.js → Accounts-D4RRm5D1.js} +1 -1
  127. package/web/console/assets/{Approvals-C2BZ86T3.js → Approvals-CsTTKb8o.js} +1 -1
  128. package/web/console/assets/{Audit-B-E4Y_Up.js → Audit-BzvZ7JZw.js} +1 -1
  129. package/web/console/assets/{BrandLockup-C18u8Lx5.js → BrandLockup-CYcA93wh.js} +1 -1
  130. package/web/console/assets/{Channels-DTy8ylH-.js → Channels-DRQZggqM.js} +1 -1
  131. package/web/console/assets/ChatEntries-BUB7BWKU.js +7 -0
  132. package/web/console/assets/ChatEntries-DsYtcXN6.css +1 -0
  133. package/web/console/assets/Clients-CQ_MonGL.css +1 -0
  134. package/web/console/assets/Clients-HhCyrxfz.js +3 -0
  135. package/web/console/assets/{Cost-2SSYs1AT.js → Cost-BZgFf1yM.js} +1 -1
  136. package/web/console/assets/{Credentials-B79LtxCE.js → Credentials-BTe2Q07j.js} +1 -1
  137. package/web/console/assets/{Diagnostics-BakcRYvb.js → Diagnostics-WL-buYli.js} +1 -1
  138. package/web/console/assets/{Executors-BXoyo28u.js → Executors-CGZ-7Xmp.js} +1 -1
  139. package/web/console/assets/{Kb-ISbzquab.js → Kb-VVw8oGsT.js} +1 -1
  140. package/web/console/assets/{Login-Dlu6Wgcf.js → Login-rwvmBBPl.js} +1 -1
  141. package/web/console/assets/{Projects-DFzmtnqg.js → Projects-CexaCEY1.js} +1 -1
  142. package/web/console/assets/Routes-B9ZHbQAp.js +124 -0
  143. package/web/console/assets/Routes-BbkFpi6Y.css +1 -0
  144. package/web/console/assets/Runs-4zDD9VOC.css +1 -0
  145. package/web/console/assets/Runs-BzFNPTwD.js +3 -0
  146. package/web/console/assets/{Setup-CrBAV-b9.js → Setup-Djh5yadQ.js} +1 -1
  147. package/web/console/assets/{Shell-B1a8DvXQ.js → Shell-kn763smL.js} +1 -1
  148. package/web/console/assets/{StorageBuckets-BRfL_eHb.js → StorageBuckets-CQBR41W1.js} +1 -1
  149. package/web/console/assets/{SystemSettings-CyirVLbq.js → SystemSettings-DgnopekD.js} +1 -1
  150. package/web/console/assets/{SystemStatus-DZ_OR7sk.js → SystemStatus-Bj8-kPt2.js} +1 -1
  151. package/web/console/assets/{Targets-CtIMa66c.js → Targets-BAfCt_nH.js} +1 -1
  152. package/web/console/assets/{Tools-BfDZHt01.js → Tools-xjd0NZdE.js} +1 -1
  153. package/web/console/assets/{index-DBiByFiO.js → index-DfJA7iJS.js} +2 -2
  154. package/web/console/assets/{request-DY2cxQqZ.js → request-DkNPOweH.js} +1 -1
  155. package/web/console/assets/{schema-6mCQ7rR5.js → schema-CgPWAu1_.js} +1 -1
  156. package/web/console/index.html +1 -1
  157. package/web/widget/widget.js +493 -14
  158. package/web-admin/src/pages/ChatEntries.vue +18 -6
  159. package/web-admin/src/pages/Clients.vue +11 -3
  160. package/web-admin/src/pages/Routes.vue +282 -16
  161. package/web-admin/src/pages/Runs.vue +159 -38
  162. package/web/console/assets/ChatEntries-9xbRiQov.css +0 -1
  163. package/web/console/assets/ChatEntries-DvD-4IeE.js +0 -7
  164. package/web/console/assets/Clients--D7NQJKk.css +0 -1
  165. package/web/console/assets/Clients-DWs9JFr0.js +0 -3
  166. package/web/console/assets/Routes-B-hm9HGY.js +0 -124
  167. package/web/console/assets/Routes-DWGQN5Pv.css +0 -1
  168. package/web/console/assets/Runs-CUtSsPW-.css +0 -1
  169. package/web/console/assets/Runs-hMRu1im3.js +0 -3
@@ -0,0 +1,795 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { agentDirectToolsConfig } from '../core/config/tools-config';
3
+ import type { ToolDefinition } from '../core/contracts/tool-definition';
4
+ import { argsHash, type ToolExecutionJournalEntry } from '../core/contracts/tools';
5
+ import type { AgentSession, Client, Job, Route } from '../core/contracts/types';
6
+ import { audienceAllows } from '../core/runtime/identity-runtime';
7
+ import type { ConfigStoreContract } from '../infrastructure/config/configstore';
8
+ import { clientAllowsRoute, rateLimitedFor } from './auth';
9
+ import { assembleResolvedToolRuntimeFor } from './tool-assembly';
10
+ import { embedConfigOf, resolveAllowedToolsFor, retrievalOptsOf, type AllowedToolContext } from './tool-context';
11
+ import type { AgentClientRunRecord } from '../infrastructure/config/config-agent-client-runtime-repository';
12
+ import type { ToolProxyDeps } from './tool-proxy';
13
+ import {
14
+ AGENT_TOOL_JOB_MARKER,
15
+ AGENT_TOOL_JOB_SOURCE_PREFIX,
16
+ AGENT_TOOL_JOB_TARGET,
17
+ isAgentToolInvocationJob,
18
+ } from './agent-tool-job';
19
+
20
+ const ROUTE_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/;
21
+ const INVOCATION_RE = /^[a-f0-9]{64}$/;
22
+ const AGENT_RUN_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
23
+ const REVISION_RE = /^[a-f0-9]{64}$/;
24
+ const ARGUMENTS_MAX_BYTES = 4096;
25
+ const INVOCATION_LOCK_TTL_MS = 15 * 60_000;
26
+
27
+ export const AGENT_TOOL_CATALOG_SCHEMA = 'bailing.agent-tool-catalog.v1';
28
+ export const AGENT_TOOL_INVOCATION_SCHEMA = 'bailing.agent-tool-invocation.v1';
29
+ const AGENT_TOOL_EXECUTION_FINGERPRINT_SCHEMA = 'bailing.agent-tool-execution.v1';
30
+
31
+ export type AgentToolInvocationState =
32
+ | 'executed'
33
+ | 'business_rejected'
34
+ | 'awaiting_approval'
35
+ | 'denied'
36
+ | 'rejected_before_dispatch'
37
+ | 'reconciliation_required'
38
+ | 'in_progress';
39
+
40
+ export interface AgentToolAuthContext {
41
+ session: AgentSession;
42
+ client: Client;
43
+ }
44
+
45
+ export interface AgentToolCatalogItem {
46
+ name: string;
47
+ description: string;
48
+ input_schema: Record<string, unknown>;
49
+ scope: string;
50
+ risk: string;
51
+ approval_required: boolean;
52
+ readonly: boolean;
53
+ idempotent: boolean;
54
+ }
55
+
56
+ export interface AgentToolCatalog {
57
+ schema_version: typeof AGENT_TOOL_CATALOG_SCHEMA;
58
+ route: string;
59
+ capability_revision: string;
60
+ tools: AgentToolCatalogItem[];
61
+ }
62
+
63
+ export const AGENT_TOOL_SEARCH_SCHEMA = 'bailing.agent-capability-search.v1';
64
+ export interface AgentToolSearchResult {
65
+ schema_version: typeof AGENT_TOOL_SEARCH_SCHEMA;
66
+ route: string;
67
+ capability_revision: string;
68
+ query: string;
69
+ tools: AgentToolCatalogItem[];
70
+ }
71
+
72
+ export interface AgentToolInvocationResult {
73
+ schema_version: typeof AGENT_TOOL_INVOCATION_SCHEMA;
74
+ invocation_id: string;
75
+ route: string;
76
+ tool: string;
77
+ state: AgentToolInvocationState;
78
+ ok: boolean;
79
+ auto_retry_allowed: boolean;
80
+ text: string;
81
+ business_status?: number;
82
+ approval_id?: number;
83
+ }
84
+
85
+ export class AgentToolApiError extends Error {
86
+ constructor(
87
+ readonly statusCode: number,
88
+ readonly code: string,
89
+ message: string,
90
+ ) {
91
+ super(message);
92
+ this.name = 'AgentToolApiError';
93
+ }
94
+ }
95
+
96
+ interface AgentToolSurface {
97
+ route: Route;
98
+ revision: string;
99
+ context: AllowedToolContext;
100
+ tools: AgentToolCatalogItem[];
101
+ }
102
+
103
+ export interface InvokeAgentToolInput {
104
+ invocation_id: string;
105
+ route: string;
106
+ capability_revision: string;
107
+ agent_run_id: string;
108
+ tool: string;
109
+ arguments: Record<string, unknown>;
110
+ }
111
+
112
+ export interface ResumeAgentToolInput {
113
+ invocation_id: string;
114
+ }
115
+
116
+ interface FrozenInvocationCoordinates extends ResumeAgentToolInput {
117
+ route: string;
118
+ capability_revision: string;
119
+ }
120
+
121
+ function isRecord(value: unknown): value is Record<string, unknown> {
122
+ return !!value && typeof value === 'object' && !Array.isArray(value);
123
+ }
124
+
125
+ function stableJson(value: unknown): string {
126
+ if (value === null) return 'null';
127
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
128
+ if (isRecord(value)) {
129
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(',')}}`;
130
+ }
131
+ return JSON.stringify(value) ?? 'null';
132
+ }
133
+
134
+ function sha256(value: string): string {
135
+ return createHash('sha256').update(value, 'utf8').digest('hex');
136
+ }
137
+
138
+ function sessionAllowsRoute(session: AgentSession, route: string): boolean {
139
+ return session.allowed_routes.includes('*') || session.allowed_routes.includes(route);
140
+ }
141
+
142
+ function invocationRequestId(sessionId: string, invocationId: string): string {
143
+ return `agent-tool:${sha256(`bailing.agent-tool.v1\0${sessionId}\0${invocationId}`)}`;
144
+ }
145
+
146
+ function safeText(value: string, maximum: number): string {
147
+ return value.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ').trim().slice(0, maximum);
148
+ }
149
+
150
+ function safeDescription(value: string): string {
151
+ return safeText(value, 1200);
152
+ }
153
+
154
+ const SAFE_SCHEMA_KEYS = new Set([
155
+ 'type', 'properties', 'required', 'items', 'description', 'enum', 'const', 'oneOf', 'anyOf', 'allOf',
156
+ 'nullable', 'format', 'pattern', 'minLength', 'maxLength', 'minimum', 'maximum', 'exclusiveMinimum',
157
+ 'exclusiveMaximum', 'minItems', 'maxItems', 'additionalProperties',
158
+ ]);
159
+
160
+ function safeInputSchema(value: unknown, depth = 0): Record<string, unknown> {
161
+ if (!isRecord(value) || depth > 16) return { type: 'object', properties: {} };
162
+ const out: Record<string, unknown> = {};
163
+ for (const [key, raw] of Object.entries(value)) {
164
+ if (!SAFE_SCHEMA_KEYS.has(key)) continue;
165
+ if (key === 'properties' && isRecord(raw)) {
166
+ out[key] = Object.fromEntries(Object.entries(raw).map(([name, schema]) => [name, safeInputSchema(schema, depth + 1)]));
167
+ } else if (key === 'items' && isRecord(raw)) {
168
+ out[key] = safeInputSchema(raw, depth + 1);
169
+ } else if ((key === 'oneOf' || key === 'anyOf' || key === 'allOf') && Array.isArray(raw)) {
170
+ out[key] = raw.slice(0, 20).map((schema) => safeInputSchema(schema, depth + 1));
171
+ } else if (key === 'additionalProperties' && isRecord(raw)) {
172
+ out[key] = safeInputSchema(raw, depth + 1);
173
+ } else if (key === 'description' && typeof raw === 'string') {
174
+ out[key] = safeDescription(raw);
175
+ } else {
176
+ out[key] = raw;
177
+ }
178
+ }
179
+ if (depth === 0) {
180
+ out['type'] = 'object';
181
+ if (!isRecord(out['properties'])) out['properties'] = {};
182
+ }
183
+ return out;
184
+ }
185
+
186
+ function directPermissionAllows(route: Route, tool: ToolDefinition, writeNames: Set<string>): boolean {
187
+ if (tool.readonly) return true;
188
+ if (route.permission !== 'readwrite' && route.permission !== 'full') return false;
189
+ return writeNames.has(tool.name);
190
+ }
191
+
192
+ function directToolDefinition(tool: ToolDefinition, forceApproval: Set<string>): ToolDefinition {
193
+ if (tool.readonly || !forceApproval.has(tool.name)) return tool;
194
+ return { ...tool, confirmRequired: true };
195
+ }
196
+
197
+ function publicTool(tool: ToolDefinition): AgentToolCatalogItem {
198
+ return {
199
+ name: tool.name,
200
+ description: safeDescription(tool.description),
201
+ input_schema: safeInputSchema(tool.inputSchema),
202
+ scope: tool.scope,
203
+ risk: tool.risk,
204
+ approval_required: tool.risk === 'high' || tool.confirmRequired || !!tool.confirmWhen?.length,
205
+ readonly: tool.readonly,
206
+ idempotent: tool.idempotent,
207
+ };
208
+ }
209
+
210
+ function fingerprint(route: Route, context: AllowedToolContext): string {
211
+ return sha256(stableJson({
212
+ schema: AGENT_TOOL_CATALOG_SCHEMA,
213
+ route: route.route_key,
214
+ permission: route.permission ?? null,
215
+ audience: route.audience ?? null,
216
+ direct: agentDirectToolsConfig(route.tools),
217
+ sources: context.sources.map((source) => ({
218
+ provider: source.provider.name,
219
+ provider_enabled: source.provider.enabled,
220
+ provider_base: sha256(source.provider.base_url),
221
+ provider_spec: sha256(source.provider.spec_json ?? ''),
222
+ allow: source.sourceCfg.allow,
223
+ tools: source.allowed.map((tool) => ({
224
+ name: tool.name,
225
+ method: tool.method,
226
+ path: tool.path,
227
+ scope: tool.scope,
228
+ risk: tool.risk,
229
+ confirm_required: tool.confirmRequired,
230
+ confirm_when: tool.confirmWhen ?? [],
231
+ requires_subject: tool.requiresSubject,
232
+ readonly: tool.readonly,
233
+ idempotent: tool.idempotent,
234
+ input_schema: tool.inputSchema,
235
+ param_in: tool.paramIn,
236
+ })),
237
+ })),
238
+ }));
239
+ }
240
+
241
+ /**
242
+ * 只冻结当前这一个工具的出站与治理语义。其他工具或文案变更会使
243
+ * catalog revision 漂移,但不应阻断这次 invocation 的结果回放/审批续执行。
244
+ * Provider secret 也不入指纹,允许安全轮换;实际业务目标 base URL 必须冻结。
245
+ */
246
+ function executionFingerprint(surface: AgentToolSurface, toolName: string): string | null {
247
+ const owners = surface.context.sources.flatMap((source) => source.allowed
248
+ .filter((tool) => tool.name === toolName)
249
+ .map((tool) => ({ source, tool })));
250
+ if (owners.length !== 1) return null;
251
+ const { source, tool } = owners[0]!;
252
+ return sha256(stableJson({
253
+ schema: AGENT_TOOL_EXECUTION_FINGERPRINT_SCHEMA,
254
+ route: surface.route.route_key,
255
+ provider: {
256
+ name: source.provider.name,
257
+ base: sha256(source.provider.base_url),
258
+ },
259
+ tool: {
260
+ name: tool.name,
261
+ method: tool.method,
262
+ path: tool.path,
263
+ scope: tool.scope,
264
+ risk: tool.risk,
265
+ confirm_required: tool.confirmRequired,
266
+ confirm_when: tool.confirmWhen ?? [],
267
+ requires_subject: tool.requiresSubject,
268
+ sensitive: tool.sensitive,
269
+ readonly: tool.readonly,
270
+ idempotent: tool.idempotent,
271
+ input_schema: tool.inputSchema,
272
+ param_in: tool.paramIn,
273
+ },
274
+ }));
275
+ }
276
+
277
+ function probeJob(auth: AgentToolAuthContext, route: Route, now: string): Job {
278
+ return {
279
+ job_id: '00000000-0000-4000-8000-000000000000',
280
+ request_id: 'agent-tool-catalog',
281
+ status: 'done',
282
+ target: AGENT_TOOL_JOB_TARGET,
283
+ profile: route.profile,
284
+ project: route.project ?? '',
285
+ source: `${AGENT_TOOL_JOB_SOURCE_PREFIX}${auth.client.app_id}`,
286
+ client_app_id: auth.client.app_id,
287
+ agent_session_id: auth.session.session_id,
288
+ on_behalf_of: auth.session.on_behalf_of,
289
+ session_id: auth.session.session_id,
290
+ input_preview: '',
291
+ metadata: { agent_tool_call_v1: true },
292
+ dispatch: { route_key: route.route_key, route_name: route.name, tools: route.tools },
293
+ created_at: now,
294
+ updated_at: now,
295
+ };
296
+ }
297
+
298
+ async function resolveDirectRoute(deps: ToolProxyDeps, auth: AgentToolAuthContext, routeKey: string): Promise<Route> {
299
+ if (!deps.configStore) throw new AgentToolApiError(503, 'agent_tools_unavailable', 'Agent tools require the MySQL control plane.');
300
+ if (!ROUTE_RE.test(routeKey) || routeKey === 'auto') throw new AgentToolApiError(400, 'invalid_route', 'The configured route is invalid.');
301
+ if (!clientAllowsRoute(auth.client, routeKey) || !sessionAllowsRoute(auth.session, routeKey)) {
302
+ throw new AgentToolApiError(403, 'route_not_allowed', 'The Agent Session is not allowed to use this route.');
303
+ }
304
+ const route = await deps.configStore.routes.get(routeKey);
305
+ if (!route?.enabled) throw new AgentToolApiError(404, 'route_unavailable', 'The configured route is unavailable.');
306
+ const direct = agentDirectToolsConfig(route.tools);
307
+ if (!direct) throw new AgentToolApiError(403, 'agent_direct_disabled', 'Direct Agent tools are not enabled for this route.');
308
+ const principal = {
309
+ ...auth.session.principal,
310
+ roles: [...auth.session.principal.roles],
311
+ client_app_id: auth.client.app_id,
312
+ channel: auth.session.principal.channel ?? `agent:${auth.client.app_id}`,
313
+ };
314
+ const audience = audienceAllows(route.audience, principal);
315
+ if (!audience.ok) throw new AgentToolApiError(403, 'audience_not_allowed', 'The business identity is not allowed to use this route.');
316
+ return route;
317
+ }
318
+
319
+ async function resolveSurface(deps: ToolProxyDeps, auth: AgentToolAuthContext, routeKey: string): Promise<AgentToolSurface> {
320
+ const route = await resolveDirectRoute(deps, auth, routeKey);
321
+ const direct = agentDirectToolsConfig(route.tools)!;
322
+ const resolved = await resolveAllowedToolsFor(deps.configStore, probeJob(auth, route, deps.now()), route);
323
+ if (!resolved) {
324
+ const empty: AllowedToolContext = { sources: [], allowed: [], toolsCfg: route.tools ?? {}, lockedBySubject: 0 };
325
+ return { route, revision: fingerprint(route, empty), context: empty, tools: [] };
326
+ }
327
+ const writeNames = new Set(direct.write_tools ?? []);
328
+ const forceApproval = new Set(direct.force_approval_tools ?? []);
329
+ const sources = resolved.sources.map((source) => ({
330
+ ...source,
331
+ allowed: source.allowed
332
+ .filter((tool) => directPermissionAllows(route, tool, writeNames))
333
+ .map((tool) => directToolDefinition(tool, forceApproval)),
334
+ })).filter((source) => source.allowed.length);
335
+ const allowed = sources.flatMap((source) => source.allowed).sort((a, b) => a.name.localeCompare(b.name));
336
+ const context: AllowedToolContext = { ...resolved, sources, allowed };
337
+ return { route, revision: fingerprint(route, context), context, tools: allowed.map(publicTool) };
338
+ }
339
+
340
+ export async function listAgentToolsFor(deps: ToolProxyDeps, auth: AgentToolAuthContext, route: string): Promise<AgentToolCatalog> {
341
+ const surface = await resolveSurface(deps, auth, route);
342
+ return {
343
+ schema_version: AGENT_TOOL_CATALOG_SCHEMA,
344
+ route: surface.route.route_key,
345
+ capability_revision: surface.revision,
346
+ tools: surface.tools,
347
+ };
348
+ }
349
+
350
+ function lexicalToolOrder(tools: AgentToolCatalogItem[], query: string): AgentToolCatalogItem[] {
351
+ const normalized = query.toLowerCase().replace(/[^\p{L}\p{N}_]+/gu, ' ').trim();
352
+ const words = [...new Set(normalized.split(/\s+/).filter(Boolean))];
353
+ const grams = normalized.replace(/\s+/g, '').length > 1
354
+ ? [...new Set(Array.from({ length: normalized.replace(/\s+/g, '').length - 1 }, (_, i) => normalized.replace(/\s+/g, '').slice(i, i + 2)))]
355
+ : [];
356
+ const score = (tool: AgentToolCatalogItem): number => {
357
+ const name = tool.name.toLowerCase();
358
+ const scope = tool.scope.toLowerCase();
359
+ const description = tool.description.toLowerCase();
360
+ const haystack = `${name} ${scope} ${description}`;
361
+ let value = normalized && name === normalized ? 10_000 : normalized && name.includes(normalized) ? 2_000 : 0;
362
+ if (normalized && haystack.includes(normalized)) value += 1_000;
363
+ for (const word of words) {
364
+ if (name.includes(word)) value += 240;
365
+ if (scope.includes(word)) value += 120;
366
+ if (description.includes(word)) value += 60;
367
+ }
368
+ for (const gram of grams) if (haystack.includes(gram)) value += 2;
369
+ return value;
370
+ };
371
+ return [...tools].sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
372
+ }
373
+
374
+ /** 授权面内的渐进发现:所有 provider 的向量检索都可用才采用语义排序,否则整体确定性 lexical 回退。 */
375
+ export async function searchAgentToolsFor(
376
+ deps: ToolProxyDeps,
377
+ auth: AgentToolAuthContext,
378
+ route: string,
379
+ query: string,
380
+ requestedLimit = 8,
381
+ ): Promise<AgentToolSearchResult> {
382
+ const surface = await resolveSurface(deps, auth, route);
383
+ const limit = Math.min(Math.max(Math.round(Number(requestedLimit) || 8), 1), 12);
384
+ const cleanQuery = safeText(query, 2000);
385
+ let ordered = lexicalToolOrder(surface.tools, cleanQuery);
386
+ if (cleanQuery && deps.toolIndex && surface.context.sources.length) {
387
+ const semantic = new Map<string, number>();
388
+ let allSourcesAvailable = true;
389
+ for (const source of surface.context.sources) {
390
+ const ec = embedConfigOf(source.provider);
391
+ const opts = retrievalOptsOf(source.sourceCfg);
392
+ if (!ec || !opts.enabled) { allSourcesAvailable = false; break; }
393
+ try {
394
+ const hits = await deps.toolIndex.retrieve(
395
+ source.provider.name,
396
+ new Set(source.allowed.map((tool) => tool.name)),
397
+ cleanQuery,
398
+ ec,
399
+ { minScore: opts.minScore, maxTools: Math.min(limit, opts.maxTools) },
400
+ );
401
+ if (!hits) { allSourcesAvailable = false; break; }
402
+ for (const hit of hits) semantic.set(hit.name, Math.max(semantic.get(hit.name) ?? -Infinity, hit.score));
403
+ } catch {
404
+ allSourcesAvailable = false;
405
+ break;
406
+ }
407
+ }
408
+ if (allSourcesAvailable && semantic.size) {
409
+ const lexical = lexicalToolOrder(surface.tools, cleanQuery);
410
+ const fallbackOrder = new Map(lexical.map((tool, index) => [tool.name, index]));
411
+ ordered = [...surface.tools].sort((a, b) =>
412
+ (semantic.get(b.name) ?? -Infinity) - (semantic.get(a.name) ?? -Infinity)
413
+ || (fallbackOrder.get(a.name) ?? 0) - (fallbackOrder.get(b.name) ?? 0)
414
+ || a.name.localeCompare(b.name));
415
+ }
416
+ }
417
+ return {
418
+ schema_version: AGENT_TOOL_SEARCH_SCHEMA,
419
+ route: surface.route.route_key,
420
+ capability_revision: surface.revision,
421
+ query: cleanQuery,
422
+ tools: ordered.slice(0, limit),
423
+ };
424
+ }
425
+
426
+ function parseInvocationResult(job: Job): AgentToolInvocationResult | null {
427
+ const value = job.result;
428
+ if (!isRecord(value) || value['schema_version'] !== AGENT_TOOL_INVOCATION_SCHEMA) return null;
429
+ const state = String(value['state'] ?? '') as AgentToolInvocationState;
430
+ const states: AgentToolInvocationState[] = ['executed', 'business_rejected', 'awaiting_approval', 'denied', 'rejected_before_dispatch', 'reconciliation_required', 'in_progress'];
431
+ const metadata = job.metadata ?? {};
432
+ if (!states.includes(state)
433
+ || value['invocation_id'] !== metadata['agent_invocation_id']
434
+ || value['route'] !== metadata['agent_route']
435
+ || value['tool'] !== metadata['agent_tool']
436
+ || typeof value['ok'] !== 'boolean'
437
+ || typeof value['auto_retry_allowed'] !== 'boolean'
438
+ || typeof value['text'] !== 'string'
439
+ || value['text'].length > 8192
440
+ || (value['business_status'] !== undefined && (!Number.isInteger(value['business_status']) || Number(value['business_status']) < 1))
441
+ || (value['approval_id'] !== undefined && (!Number.isInteger(value['approval_id']) || Number(value['approval_id']) < 1))) return null;
442
+ return value as unknown as AgentToolInvocationResult;
443
+ }
444
+
445
+ function publicResult(input: {
446
+ invocationId: string;
447
+ route: string;
448
+ tool: string;
449
+ state: AgentToolInvocationState;
450
+ ok: boolean;
451
+ text: string;
452
+ autoRetryAllowed?: boolean;
453
+ businessStatus?: number;
454
+ approvalId?: number;
455
+ }): AgentToolInvocationResult {
456
+ return {
457
+ schema_version: AGENT_TOOL_INVOCATION_SCHEMA,
458
+ invocation_id: input.invocationId,
459
+ route: input.route,
460
+ tool: input.tool,
461
+ state: input.state,
462
+ ok: input.ok,
463
+ auto_retry_allowed: input.autoRetryAllowed ?? false,
464
+ text: safeText(input.text, 8192),
465
+ ...(input.businessStatus !== undefined ? { business_status: input.businessStatus } : {}),
466
+ ...(input.approvalId !== undefined ? { approval_id: input.approvalId } : {}),
467
+ };
468
+ }
469
+
470
+ function isStableInvocationResult(result: AgentToolInvocationResult | null): result is AgentToolInvocationResult {
471
+ return !!result
472
+ && !['in_progress', 'awaiting_approval'].includes(result.state)
473
+ && result.auto_retry_allowed !== true;
474
+ }
475
+
476
+ function assertCurrentToolAuthorized(surface: AgentToolSurface, tool: string): void {
477
+ if (!surface.context.allowed.some((candidate) => candidate.name === tool)) {
478
+ throw new AgentToolApiError(409, 'capability_changed', 'The tool is no longer authorized for this Agent Session and route.');
479
+ }
480
+ }
481
+
482
+ function assertCurrentToolExecution(job: Job, surface: AgentToolSurface, tool: string): void {
483
+ assertCurrentToolAuthorized(surface, tool);
484
+ const frozen = String(job.metadata?.['agent_execution_fingerprint'] ?? '');
485
+ const current = executionFingerprint(surface, tool);
486
+ if (!current || current !== frozen) {
487
+ throw new AgentToolApiError(409, 'capability_changed', 'The selected tool execution contract changed; start a new invocation from the refreshed catalog.');
488
+ }
489
+ }
490
+
491
+ function assertInvocationInput(input: InvokeAgentToolInput): void {
492
+ if (!INVOCATION_RE.test(input.invocation_id) || !ROUTE_RE.test(input.route) || !REVISION_RE.test(input.capability_revision) ||
493
+ !AGENT_RUN_RE.test(input.agent_run_id) || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(input.tool) || !isRecord(input.arguments)) {
494
+ throw new AgentToolApiError(400, 'invalid_request', 'The Agent tool invocation request is invalid.');
495
+ }
496
+ const encoded = JSON.stringify(input.arguments);
497
+ if (Buffer.byteLength(encoded, 'utf8') > ARGUMENTS_MAX_BYTES) {
498
+ throw new AgentToolApiError(413, 'arguments_too_large', `Tool arguments exceed ${ARGUMENTS_MAX_BYTES} bytes.`);
499
+ }
500
+ }
501
+
502
+ function assertResumeInput(input: ResumeAgentToolInput): void {
503
+ if (!INVOCATION_RE.test(input.invocation_id)) {
504
+ throw new AgentToolApiError(400, 'invalid_request', 'The Agent tool resume request is invalid.');
505
+ }
506
+ }
507
+
508
+ function sameInvocation(job: Job, auth: AgentToolAuthContext, input: {
509
+ invocation_id: string;
510
+ route: string;
511
+ tool?: string;
512
+ args_hash?: string;
513
+ capability_revision: string;
514
+ agent_run_id?: string;
515
+ }): boolean {
516
+ const meta = job.metadata ?? {};
517
+ return isAgentToolInvocationJob(job) &&
518
+ job.agent_session_id === auth.session.session_id &&
519
+ job.client_app_id === auth.client.app_id &&
520
+ meta['agent_invocation_id'] === input.invocation_id &&
521
+ meta['agent_route'] === input.route &&
522
+ meta['agent_capability_revision'] === input.capability_revision &&
523
+ (input.agent_run_id === undefined || meta['agent_run_id'] === input.agent_run_id) &&
524
+ (input.tool === undefined || meta['agent_tool'] === input.tool) &&
525
+ (input.args_hash === undefined || meta['agent_args_hash'] === input.args_hash);
526
+ }
527
+
528
+ function syntheticJob(
529
+ auth: AgentToolAuthContext,
530
+ surface: AgentToolSurface,
531
+ input: InvokeAgentToolInput,
532
+ hash: string,
533
+ toolFingerprint: string,
534
+ runtimeRun: AgentClientRunRecord | null,
535
+ now: string,
536
+ ): Job {
537
+ const initial = publicResult({
538
+ invocationId: input.invocation_id,
539
+ route: input.route,
540
+ tool: input.tool,
541
+ state: 'in_progress',
542
+ ok: false,
543
+ text: 'The governed tool invocation is in progress.',
544
+ });
545
+ return {
546
+ job_id: randomUUID(),
547
+ request_id: invocationRequestId(auth.session.session_id, input.invocation_id),
548
+ status: 'done',
549
+ target: AGENT_TOOL_JOB_TARGET,
550
+ profile: surface.route.profile,
551
+ project: surface.route.project ?? '',
552
+ source: `${AGENT_TOOL_JOB_SOURCE_PREFIX}${auth.client.app_id}`,
553
+ client_app_id: auth.client.app_id,
554
+ agent_session_id: auth.session.session_id,
555
+ on_behalf_of: auth.session.on_behalf_of,
556
+ session_id: input.agent_run_id,
557
+ ...(runtimeRun ? { thread_id: runtimeRun.thread_id } : {}),
558
+ input_preview: `Agent tool ${input.tool}`.slice(0, 200),
559
+ result: { ...initial },
560
+ metadata: {
561
+ agent_tool_job_marker: AGENT_TOOL_JOB_MARKER,
562
+ agent_tool_call_v1: true,
563
+ agent_invocation_id: input.invocation_id,
564
+ agent_run_id: input.agent_run_id,
565
+ agent_route: input.route,
566
+ agent_tool: input.tool,
567
+ agent_args_hash: hash,
568
+ agent_capability_revision: input.capability_revision,
569
+ agent_execution_fingerprint: toolFingerprint,
570
+ ...(runtimeRun ? { agent_thread_id: runtimeRun.thread_id, agent_client_runtime_v1: true } : {}),
571
+ principal: { ...auth.session.principal },
572
+ },
573
+ dispatch: { route_key: surface.route.route_key, route_name: surface.route.name, tools: surface.route.tools },
574
+ created_at: now,
575
+ updated_at: now,
576
+ };
577
+ }
578
+
579
+ async function currentApproval(config: ConfigStoreContract, job: Job, tool: string, hash: string) {
580
+ const rows = await config.approvals.forJob(job.job_id);
581
+ return [...rows].reverse().find((row) => row.tool === tool && row.args_hash === hash) ?? null;
582
+ }
583
+
584
+ function fromJournal(input: FrozenInvocationCoordinates, tool: string, entry: ToolExecutionJournalEntry): AgentToolInvocationResult {
585
+ if (entry.state !== 'completed') {
586
+ return publicResult({
587
+ invocationId: input.invocation_id,
588
+ route: input.route,
589
+ tool,
590
+ state: 'reconciliation_required',
591
+ ok: false,
592
+ text: `The tool execution is unresolved (${entry.state}). Use idempotency key ${entry.idempotencyKey} for manual reconciliation; do not replay it.`,
593
+ });
594
+ }
595
+ return publicResult({
596
+ invocationId: input.invocation_id,
597
+ route: input.route,
598
+ tool,
599
+ state: entry.ok ? 'executed' : 'business_rejected',
600
+ ok: entry.ok,
601
+ text: entry.text,
602
+ businessStatus: entry.status,
603
+ });
604
+ }
605
+
606
+ async function persistResult(deps: ToolProxyDeps, job: Job, result: AgentToolInvocationResult): Promise<void> {
607
+ await deps.stateStore.updateJob(job.job_id, { status: 'done', result: { ...result }, error: undefined });
608
+ await deps.stateStore.appendAudit({
609
+ ts: deps.now(), job_id: job.job_id, request_id: job.request_id, event: 'agent_tool_invocation_state',
610
+ detail: { invocation_id: result.invocation_id, route: result.route, tool: result.tool, state: result.state, ok: result.ok, business_status: result.business_status ?? null },
611
+ }).catch(() => undefined);
612
+ }
613
+
614
+ async function invokeExisting(
615
+ deps: ToolProxyDeps,
616
+ auth: AgentToolAuthContext,
617
+ surface: AgentToolSurface,
618
+ job: Job,
619
+ input: FrozenInvocationCoordinates,
620
+ tool: string,
621
+ hash: string,
622
+ args: Record<string, unknown> | null,
623
+ ): Promise<AgentToolInvocationResult> {
624
+ const cached = parseInvocationResult(job);
625
+ if (isStableInvocationResult(cached)) return cached;
626
+ if (!surface.context.allowed.some((candidate) => candidate.name === tool)) {
627
+ throw new AgentToolApiError(409, 'capability_changed', 'The tool is no longer available; refresh the capability catalog.');
628
+ }
629
+ const journal = await deps.configStore!.toolCalls.get(job.job_id, tool, hash).catch(() => null);
630
+ if (journal) {
631
+ const result = fromJournal(input, tool, journal);
632
+ await persistResult(deps, job, result);
633
+ return result;
634
+ }
635
+ const approval = await currentApproval(deps.configStore!, job, tool, hash);
636
+ if (approval?.status === 'denied') {
637
+ const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'denied', ok: false, text: 'The governed tool invocation was denied.' });
638
+ await persistResult(deps, job, result);
639
+ return result;
640
+ }
641
+ if (approval?.status === 'pending') {
642
+ const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'awaiting_approval', ok: false, text: 'The governed tool invocation is awaiting approval.', approvalId: approval.id });
643
+ await persistResult(deps, job, result);
644
+ return result;
645
+ }
646
+ if (!args && approval?.status === 'approved' && approval.args_json) {
647
+ try {
648
+ const parsed: unknown = JSON.parse(approval.args_json);
649
+ if (isRecord(parsed) && argsHash(parsed) === hash) args = parsed;
650
+ } catch { /* 损坏的审批快照不执行 */ }
651
+ }
652
+ if (!args) {
653
+ const result = publicResult({ invocationId: input.invocation_id, route: input.route, tool, state: 'rejected_before_dispatch', ok: false, text: 'The exact frozen arguments are unavailable; the invocation was not dispatched.' });
654
+ await persistResult(deps, job, result);
655
+ return result;
656
+ }
657
+
658
+ const runtime = await assembleResolvedToolRuntimeFor(
659
+ deps.configStore, deps.stateStore, deps.toolIndex, job, surface.context,
660
+ deps.cfg, deps.now, deps.sleep, deps.targetRegistry,
661
+ );
662
+ if (!runtime || runtime === 'subject_locked') {
663
+ throw new AgentToolApiError(409, 'capability_changed', 'The tool surface is no longer available; refresh the capability catalog.');
664
+ }
665
+ const out = await runtime.invoke(tool, args);
666
+ const uncertainty = runtime.executionUncertainty();
667
+ const state: AgentToolInvocationState = uncertainty || out.governance_state === 'reconciliation_required'
668
+ ? 'reconciliation_required'
669
+ : out.governance_state === 'awaiting_approval'
670
+ ? 'awaiting_approval'
671
+ : out.governance_state === 'rejected_before_dispatch'
672
+ ? 'rejected_before_dispatch'
673
+ : out.status > 0
674
+ ? (out.ok ? 'executed' : 'business_rejected')
675
+ : 'rejected_before_dispatch';
676
+ const result = publicResult({
677
+ invocationId: input.invocation_id,
678
+ route: input.route,
679
+ tool,
680
+ state,
681
+ ok: out.ok,
682
+ text: out.text,
683
+ autoRetryAllowed: out.auto_retry_allowed ?? false,
684
+ ...(out.status > 0 && out.governance_state !== 'rejected_before_dispatch' ? { businessStatus: out.status } : {}),
685
+ ...(out.approval_id !== undefined ? { approvalId: out.approval_id } : {}),
686
+ });
687
+ await persistResult(deps, job, result);
688
+ return result;
689
+ }
690
+
691
+ export async function invokeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAuthContext, input: InvokeAgentToolInput): Promise<AgentToolInvocationResult> {
692
+ assertInvocationInput(input);
693
+ const runtimeRun = await deps.configStore?.agentClientRuntime?.findRunForInvocation(input.agent_run_id) ?? null;
694
+ if (runtimeRun && (
695
+ runtimeRun.session_id !== auth.session.session_id
696
+ || runtimeRun.client_app_id !== auth.client.app_id
697
+ || runtimeRun.route_key !== input.route
698
+ )) {
699
+ throw new AgentToolApiError(409, 'agent_run_conflict', 'The agent_run_id belongs to a different Agent Session or route.');
700
+ }
701
+ const hash = argsHash(input.arguments);
702
+ const requestId = invocationRequestId(auth.session.session_id, input.invocation_id);
703
+ const lockKey = `agent-tool:${requestId}`;
704
+ const owner = randomUUID();
705
+ if (!await deps.stateStore.acquireRuntimeLock(lockKey, owner, INVOCATION_LOCK_TTL_MS)) {
706
+ return publicResult({ invocationId: input.invocation_id, route: input.route, tool: input.tool, state: 'in_progress', ok: false, text: 'The same governed invocation is already in progress.', autoRetryAllowed: true });
707
+ }
708
+ try {
709
+ let job = await deps.stateStore.findByRequestId(requestId);
710
+ if (job && !sameInvocation(job, auth, { ...input, args_hash: hash })) {
711
+ throw new AgentToolApiError(409, 'invocation_conflict', 'The invocation_id is already bound to a different call.');
712
+ }
713
+ if (job) await resolveDirectRoute(deps, auth, input.route);
714
+ const cached = job ? parseInvocationResult(job) : null;
715
+ let surface: AgentToolSurface | null = null;
716
+ if (isStableInvocationResult(cached)) {
717
+ surface = await resolveSurface(deps, auth, input.route);
718
+ assertCurrentToolAuthorized(surface, input.tool);
719
+ return cached;
720
+ }
721
+ surface = await resolveSurface(deps, auth, input.route);
722
+ if (!job) {
723
+ if (await rateLimitedFor(deps.configStore, auth.client)) {
724
+ return publicResult({ invocationId: input.invocation_id, route: input.route, tool: input.tool, state: 'rejected_before_dispatch', ok: false, text: 'The Agent client rate limit was exceeded.', autoRetryAllowed: true });
725
+ }
726
+ if (surface.revision !== input.capability_revision) {
727
+ throw new AgentToolApiError(409, 'capability_changed', 'The capability catalog changed; refresh tools before calling.');
728
+ }
729
+ const definition = surface.context.allowed.find((tool) => tool.name === input.tool);
730
+ const toolFingerprint = executionFingerprint(surface, input.tool);
731
+ if (!definition || !toolFingerprint) {
732
+ throw new AgentToolApiError(404, 'tool_not_found', 'The tool is not available in the current capability catalog.');
733
+ }
734
+ job = syntheticJob(auth, surface, input, hash, toolFingerprint, runtimeRun, deps.now());
735
+ await deps.stateStore.createJob(job);
736
+ await deps.stateStore.appendAudit({
737
+ ts: deps.now(), job_id: job.job_id, request_id: job.request_id, event: 'agent_tool_invocation_created',
738
+ detail: { invocation_id: input.invocation_id, agent_run_id: input.agent_run_id, agent_thread_id: runtimeRun?.thread_id ?? null, route: input.route, tool: input.tool, args_hash: hash, execution_fingerprint: toolFingerprint, client_app_id: auth.client.app_id, agent_session_id: auth.session.session_id },
739
+ });
740
+ } else {
741
+ assertCurrentToolExecution(job, surface, input.tool);
742
+ if (await rateLimitedFor(deps.configStore, auth.client)) {
743
+ return publicResult({ invocationId: input.invocation_id, route: input.route, tool: input.tool, state: 'rejected_before_dispatch', ok: false, text: 'The Agent client rate limit was exceeded.', autoRetryAllowed: true });
744
+ }
745
+ }
746
+ return await invokeExisting(deps, auth, surface, job, input, input.tool, hash, input.arguments);
747
+ } finally {
748
+ await deps.stateStore.releaseRuntimeLock(lockKey, owner).catch(() => undefined);
749
+ }
750
+ }
751
+
752
+ export async function resumeAgentToolFor(deps: ToolProxyDeps, auth: AgentToolAuthContext, input: ResumeAgentToolInput): Promise<AgentToolInvocationResult> {
753
+ assertResumeInput(input);
754
+ const requestId = invocationRequestId(auth.session.session_id, input.invocation_id);
755
+ const lockKey = `agent-tool:${requestId}`;
756
+ const owner = randomUUID();
757
+ if (!await deps.stateStore.acquireRuntimeLock(lockKey, owner, INVOCATION_LOCK_TTL_MS)) {
758
+ const current = await deps.stateStore.findByRequestId(requestId);
759
+ const route = String(current?.metadata?.['agent_route'] ?? 'unknown');
760
+ const tool = String(current?.metadata?.['agent_tool'] ?? 'unknown');
761
+ return publicResult({ invocationId: input.invocation_id, route, tool, state: 'in_progress', ok: false, text: 'The governed invocation is already in progress.', autoRetryAllowed: true });
762
+ }
763
+ try {
764
+ const job = await deps.stateStore.findByRequestId(requestId);
765
+ if (!job || !isAgentToolInvocationJob(job) || job.agent_session_id !== auth.session.session_id || job.client_app_id !== auth.client.app_id) {
766
+ throw new AgentToolApiError(404, 'invocation_not_found', 'The governed invocation was not found.');
767
+ }
768
+ const route = String(job.metadata['agent_route'] ?? '');
769
+ const capabilityRevision = String(job.metadata['agent_capability_revision'] ?? '');
770
+ const tool = String(job.metadata['agent_tool'] ?? '');
771
+ const hash = String(job.metadata['agent_args_hash'] ?? '');
772
+ const frozen: FrozenInvocationCoordinates = {
773
+ invocation_id: input.invocation_id,
774
+ route,
775
+ capability_revision: capabilityRevision,
776
+ };
777
+ if (!sameInvocation(job, auth, { ...frozen, tool, args_hash: hash })) {
778
+ throw new AgentToolApiError(409, 'invocation_conflict', 'The invocation no longer matches this Agent Session and catalog.');
779
+ }
780
+ await resolveDirectRoute(deps, auth, route);
781
+ const cached = parseInvocationResult(job);
782
+ const surface = await resolveSurface(deps, auth, route);
783
+ if (isStableInvocationResult(cached)) {
784
+ assertCurrentToolAuthorized(surface, tool);
785
+ return cached;
786
+ }
787
+ assertCurrentToolExecution(job, surface, tool);
788
+ if (await rateLimitedFor(deps.configStore, auth.client)) {
789
+ return publicResult({ invocationId: input.invocation_id, route, tool, state: 'rejected_before_dispatch', ok: false, text: 'The Agent client rate limit was exceeded.', autoRetryAllowed: true });
790
+ }
791
+ return await invokeExisting(deps, auth, surface, job, frozen, tool, hash, null);
792
+ } finally {
793
+ await deps.stateStore.releaseRuntimeLock(lockKey, owner).catch(() => undefined);
794
+ }
795
+ }