bailinghub 0.9.4 → 0.10.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/README.en.md +6 -6
- package/README.md +6 -6
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/docker-compose.images.yml +2 -2
- package/docs/AGENT_CLIENT_QUICKSTART.en.md +1 -3
- package/docs/AGENT_CLIENT_QUICKSTART.md +1 -1
- package/docs/AGENT_CLIENT_RUNTIME_API.en.md +87 -2
- package/docs/AGENT_CLIENT_RUNTIME_API.md +36 -2
- package/docs/AGENT_KNOWLEDGE_API.en.md +77 -0
- package/docs/AGENT_KNOWLEDGE_API.md +86 -0
- package/docs/AGENT_TASK_CONTROL.md +4 -4
- package/docs/AGENT_TASK_CONTROL_FOUNDATION.md +1 -1
- package/docs/ARCHITECTURE.md +4 -0
- package/docs/CHANGELOG.en.md +24 -1
- package/docs/CHANGELOG.md +24 -1
- package/docs/COMPATIBILITY.en.md +27 -1
- package/docs/CONTRACT.en.md +1 -1
- package/docs/CONTRACT.md +1 -1
- package/docs/IMPLEMENTATION_STATUS.en.md +28 -15
- package/docs/IMPLEMENTATION_STATUS.md +28 -15
- package/docs/INDEPENDENT_VALIDATION.en.md +6 -4
- package/docs/INDEPENDENT_VALIDATION.md +6 -4
- package/docs/INTEGRATION_WALKTHROUGH.md +65 -0
- package/docs/MODEL_BILLING.en.md +2 -0
- package/docs/MODEL_BILLING.md +6 -2
- package/docs/MODEL_CONTINUATION.en.md +54 -0
- package/docs/MODEL_CONTINUATION.md +54 -0
- package/docs/MODEL_OUTPUT_BUDGET.en.md +69 -0
- package/docs/MODEL_OUTPUT_BUDGET.md +69 -0
- package/docs/OPERATIONS.en.md +16 -4
- package/docs/OPERATIONS.md +16 -4
- package/docs/QUICKSTART.md +1 -1
- package/docs/README.en.md +7 -0
- package/docs/README.md +7 -0
- package/docs/RELEASE_NOTES_NEXT.en.md +3 -3
- package/docs/RELEASE_NOTES_NEXT.md +3 -3
- package/docs/RELEASE_NOTES_v0.10.0.en.md +58 -0
- package/docs/RELEASE_NOTES_v0.10.0.md +58 -0
- package/docs/RELEASE_NOTES_v0.10.1.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.10.1.md +41 -0
- package/docs/UPGRADE_PLAN.en.md +118 -0
- package/docs/UPGRADE_PLAN.md +124 -0
- package/docs/UPGRADE_v0.10.0.en.md +47 -0
- package/docs/UPGRADE_v0.10.0.md +47 -0
- package/docs/UPGRADE_v0.10.1.en.md +66 -0
- package/docs/UPGRADE_v0.10.1.md +66 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +38 -22
- package/package.json +10 -5
- package/schemas/tool-definition.schema.json +13 -0
- package/scripts/check-doc-links.mjs +6 -0
- package/scripts/check-image-tags.sh +1 -1
- package/scripts/check-php-sdk-artifacts.mjs +152 -0
- package/scripts/check-php-sdk-artifacts.test.mjs +99 -0
- package/scripts/check-release-consistency.test.mjs +2 -2
- package/scripts/doctor-upgrade-plan.test.ts +205 -0
- package/scripts/doctor-upgrade-plan.ts +276 -0
- package/scripts/doctor.ts +4 -1
- package/scripts/e2e-console-approval-details.mjs +134 -0
- package/scripts/e2e-console-config-races.mjs +180 -0
- package/scripts/e2e-console-kb-audit.mjs +170 -0
- package/scripts/e2e-console-operations-audit.mjs +152 -0
- package/scripts/e2e-console-runtime-audit.mjs +179 -0
- package/scripts/e2e-console-settings-audit.mjs +125 -0
- package/scripts/e2e-console-troubleshooting-extra.mjs +267 -0
- package/scripts/e2e-console.mjs +476 -7
- package/scripts/install.sh +1 -1
- package/scripts/publish-images.sh +1 -1
- package/scripts/release-audit.mjs +9 -1
- package/scripts/sdk-declaration-contract-test.ts +34 -0
- package/scripts/sdk-p1-check.mjs +62 -26
- package/scripts/verify-github-repo.mjs +8 -0
- package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +4 -4
- package/sdk/dotnet/README.md +8 -0
- package/sdk/dotnet/tests/Declaration/Declaration.csproj +11 -0
- package/sdk/dotnet/tests/Declaration/Program.cs +74 -0
- package/sdk/go/README.md +8 -0
- package/sdk/go/bailingconnect/connect.go +5 -5
- package/sdk/go/bailingconnect/declaration_test.go +107 -0
- package/sdk/java/README.md +13 -0
- package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +4 -4
- package/sdk/java/tests/DeclarationTest.java +70 -0
- package/sdk/node/README.md +8 -0
- package/sdk/node/src/index.mjs +4 -4
- package/sdk/node/tests/declaration.test.mjs +41 -0
- package/sdk/php/README.md +16 -0
- package/sdk/php/src/Attributes/AiTool.php +4 -4
- package/sdk/php/src/SpecBuilder.php +8 -8
- package/sdk/php/tests/declaration-serialization.php +103 -0
- package/sdk/php7/README.md +14 -0
- package/sdk/php7/src/ToolDef.php +3 -3
- package/sdk/php7/src/ToolSpec.php +8 -13
- package/sdk/php7/tests/declaration-serialization.php +103 -0
- package/sdk/python/README.md +8 -0
- package/sdk/python/bailing_connect/__init__.py +6 -6
- package/sdk/python/tests/test_declaration.py +61 -0
- package/src/app/agent-client-runtime.test.ts +115 -2
- package/src/app/agent-client-runtime.ts +40 -11
- package/src/app/agent-knowledge.test.ts +171 -0
- package/src/app/agent-knowledge.ts +233 -0
- package/src/app/agent-tool-catalog-revision.test.ts +31 -0
- package/src/app/agent-tool-invocations.test.ts +7 -2
- package/src/app/agent-tool-invocations.ts +67 -7
- package/src/app/approval-continuations.test.ts +49 -1
- package/src/app/http.test.ts +16 -1
- package/src/app/http.ts +3 -3
- package/src/app/kernel-boot-recovery.mysql.test.ts +132 -0
- package/src/app/kernel-boot-recovery.test.ts +157 -0
- package/src/app/kernel.ts +12 -8
- package/src/app/readiness.mysql.test.ts +120 -0
- package/src/app/readiness.test.ts +111 -26
- package/src/app/readiness.ts +26 -22
- package/src/app/runtime-lifecycle.ts +34 -3
- package/src/app/tool-approvals.test.ts +83 -0
- package/src/app/tool-approvals.ts +25 -7
- package/src/app/tool-proxy-payload.test.ts +81 -0
- package/src/app/tool-proxy.ts +24 -2
- package/src/core/config/console-diagnostic-location.test.ts +36 -0
- package/src/core/config/console-form-guard.test.ts +69 -0
- package/src/core/config/console-task-location.test.ts +64 -0
- package/src/core/contracts/explicit-capability-values.test.ts +62 -0
- package/src/core/contracts/openapi-tools.ts +18 -7
- package/src/core/contracts/schema-readiness.ts +11 -0
- package/src/core/contracts/tool-annotations.ts +4 -4
- package/src/core/contracts/tool-definition.ts +26 -0
- package/src/core/contracts/tool-guidance.test.ts +77 -0
- package/src/core/contracts/tool-guidance.ts +31 -0
- package/src/core/contracts/tool-input-limits.ts +15 -0
- package/src/core/contracts/tools-idempotency.test.ts +90 -0
- package/src/core/contracts/tools.ts +52 -9
- package/src/core/runtime/agent-execution-memory.test.ts +64 -0
- package/src/core/runtime/agent-execution-memory.ts +63 -0
- package/src/core/state/state-contracts.ts +3 -0
- package/src/infrastructure/config/config-observability-ledger.ts +2 -0
- package/src/infrastructure/schema/schema-readiness.ts +29 -0
- package/src/infrastructure/state/state-mysql.ts +3 -0
- package/src/modules/usage/contracts.ts +7 -0
- package/src/modules/usage/http.ts +2 -0
- package/src/modules/usage/model-continuation.test.ts +109 -0
- package/src/modules/usage/model-gateway.ts +5 -1
- package/src/modules/usage/output-budget.mysql.test.ts +84 -0
- package/src/modules/usage/output-budget.test.ts +167 -0
- package/src/modules/usage/output-budget.ts +73 -0
- package/src/modules/usage/provider-stream.test.ts +22 -0
- package/src/modules/usage/provider.ts +2 -3
- package/src/modules/usage/repository.ts +6 -0
- package/src/modules/usage/test-harness.ts +4 -2
- package/src/routes/admin-approval-view.test.ts +109 -0
- package/src/routes/admin-approval-view.ts +36 -0
- package/src/routes/admin-readiness.test.ts +52 -0
- package/src/routes/admin-runtime-ux.test.ts +51 -0
- package/src/routes/admin-runtime-ux.ts +25 -0
- package/src/routes/admin-runtime.ts +36 -8
- package/src/routes/admin.ts +9 -0
- package/src/routes/agent-api.test.ts +80 -1
- package/src/routes/agent-api.ts +63 -4
- package/src/routes/agent-tool-detail.test.ts +140 -0
- package/src/routes/public-default.ts +1 -1
- package/src/services/kb-agent.test.ts +84 -0
- package/src/services/kb.ts +73 -0
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/console/assets/Accounts-CjIBO3sU.css +1 -0
- package/web/console/assets/Accounts-Dhyw-7wF.js +3 -0
- package/web/console/assets/AgentClients-BA0M26-I.css +1 -0
- package/web/console/assets/AgentClients-DWxb8-ko.js +1 -0
- package/web/console/assets/AgentTasks-DOyxANnx.css +1 -0
- package/web/console/assets/AgentTasks-DUHD4dzr.js +2 -0
- package/web/console/assets/Approvals-Brl-2uJq.css +1 -0
- package/web/console/assets/Approvals-CQx1YWxW.js +1 -0
- package/web/console/assets/Audit--QcdVlMh.js +1 -0
- package/web/console/assets/Audit-DAdmOnIs.css +1 -0
- package/web/console/assets/{BrandLockup-CffORQse.js → BrandLockup-DQcaW4Nt.js} +1 -1
- package/web/console/assets/Channels-DJJU3ksE.css +1 -0
- package/web/console/assets/Channels-cGS5WfQ-.js +105 -0
- package/web/console/assets/ChatEntries-BYpji27B.css +1 -0
- package/web/console/assets/ChatEntries-nh23Iz5O.js +7 -0
- package/web/console/assets/Clients-CX5EeYio.js +3 -0
- package/web/console/assets/Clients-CbZAou8E.css +1 -0
- package/web/console/assets/Cost-C6oQvz9P.css +1 -0
- package/web/console/assets/Cost-DOZfdNS9.js +1 -0
- package/web/console/assets/Credentials--aHs57yV.css +1 -0
- package/web/console/assets/Credentials-sy6W9Sac.js +1 -0
- package/web/console/assets/Diagnostics-CKs27Dnv.css +1 -0
- package/web/console/assets/Diagnostics-CyoM1XrZ.js +1 -0
- package/web/console/assets/Executors-2Upi6bOS.css +1 -0
- package/web/console/assets/Executors-BQqqiFwt.js +1 -0
- package/web/console/assets/HelpTip-DLlhaGQp.js +1 -0
- package/web/console/assets/HelpTip-bbDEyuqV.css +1 -0
- package/web/console/assets/Kb-5R3ce4UU.js +5 -0
- package/web/console/assets/Kb-BM_PYi11.css +1 -0
- package/web/console/assets/{Login-CGgLGTE1.js → Login-YKeUwdgo.js} +1 -1
- package/web/console/assets/Projects-DHwHrPT9.css +1 -0
- package/web/console/assets/Projects-Grgb6fOv.js +1 -0
- package/web/console/assets/Routes-DR_Yf02e.css +1 -0
- package/web/console/assets/Routes-DYgrXlRJ.js +138 -0
- package/web/console/assets/Runs-CwTddJJj.js +3 -0
- package/web/console/assets/Runs-D4FOvNfu.css +1 -0
- package/web/console/assets/Setup-Ca0b1d1-.css +1 -0
- package/web/console/assets/Setup-D_xUPNDq.js +1 -0
- package/web/console/assets/Shell-BTg8Vw_L.css +1 -0
- package/web/console/assets/Shell-Dfam2Uoj.js +1 -0
- package/web/console/assets/StorageBuckets-7QLBpV4a.css +1 -0
- package/web/console/assets/StorageBuckets-CP6e50wI.js +1 -0
- package/web/console/assets/SystemSettings-BRYKyJNa.js +1 -0
- package/web/console/assets/SystemSettings-HsXGx0aH.css +1 -0
- package/web/console/assets/SystemStatus-B-VfRsQd.css +1 -0
- package/web/console/assets/SystemStatus-CbPsDsGt.js +1 -0
- package/web/console/assets/Targets-1j4-g6rC.css +1 -0
- package/web/console/assets/Targets-C2LkR2AF.js +1 -0
- package/web/console/assets/Tools-C9HPJqJb.css +1 -0
- package/web/console/assets/Tools-C9JNJUS0.js +2 -0
- package/web/console/assets/Usage-D1Mv6vGY.js +1 -0
- package/web/console/assets/Usage-DMOzUsqh.css +1 -0
- package/web/console/assets/UsageAccess-77LmGCm6.js +1 -0
- package/web/console/assets/UsageAccess-C6ZGxEgJ.css +1 -0
- package/web/console/assets/{UsageHelp-CzS2gI40.js → UsageHelp-BmuiE1Ew.js} +1 -1
- package/web/console/assets/client-route-draft-DxZRxKPT.js +1 -0
- package/web/console/assets/console-location-Csv-xsnl.js +1 -0
- package/web/console/assets/form-guard-8GrFpry0.js +1 -0
- package/web/console/assets/{index-65JiiUr4.js → index-B_5UfiTw.js} +1 -1
- package/web/console/assets/index-MjZJEFIN.js +2 -0
- package/web/console/assets/{request-DKycpD7z.js → request-rqm6MT0s.js} +1 -1
- package/web/console/assets/runtime-feedback-gPfZVNvY.js +1 -0
- package/web/console/assets/{schema-SCiNxBlR.js → schema-o3mK4mid.js} +1 -1
- package/web/console/assets/task-page-location-DWiGtAln.js +1 -0
- package/web/console/assets/use-list-location-FvLFt0Tq.css +1 -0
- package/web/console/assets/use-list-location-cIPy2cKM.js +1 -0
- package/web/console/assets/use-unsaved-form-DScKD0h9.js +1 -0
- package/web/console/assets/{util-DZYfJ5Zo.js → util-B40VqOwl.js} +1 -1
- package/web/console/assets/{vendor-element-8cVcdt5T.js → vendor-element-BT8tHCFk.js} +1 -1
- package/web/console/assets/{vendor-mammoth-CnDA23N0.js → vendor-mammoth-CVIXVxTN.js} +1 -1
- package/web/console/assets/{vendor-vue-Co7x2FW6.js → vendor-vue-DhbG0vd4.js} +7 -7
- package/web/console/index.html +3 -3
- package/web-admin/package-lock.json +4 -4
- package/web-admin/package.json +1 -1
- package/web-admin/src/client-route-draft.ts +25 -0
- package/web-admin/src/components/AgentSetupPanel.vue +54 -41
- package/web-admin/src/components/HelpTip.vue +4 -1
- package/web-admin/src/components/ListLocationBar.vue +22 -0
- package/web-admin/src/components/NotificationOutboxPanel.vue +35 -7
- package/web-admin/src/console-entry.test.ts +26 -0
- package/web-admin/src/console-entry.ts +20 -0
- package/web-admin/src/console-location.ts +35 -0
- package/web-admin/src/form-guard.ts +35 -0
- package/web-admin/src/layout/Shell.vue +18 -65
- package/web-admin/src/onboarding-state.test.ts +174 -0
- package/web-admin/src/onboarding-state.ts +122 -0
- package/web-admin/src/pages/Accounts.vue +44 -24
- package/web-admin/src/pages/AgentClients.vue +47 -29
- package/web-admin/src/pages/AgentTasks.vue +57 -12
- package/web-admin/src/pages/Approvals.vue +105 -25
- package/web-admin/src/pages/Audit.vue +15 -6
- package/web-admin/src/pages/Channels.vue +136 -43
- package/web-admin/src/pages/ChatEntries.vue +96 -41
- package/web-admin/src/pages/Clients.vue +87 -26
- package/web-admin/src/pages/Cost.vue +15 -4
- package/web-admin/src/pages/Credentials.vue +63 -32
- package/web-admin/src/pages/Diagnostics.vue +103 -54
- package/web-admin/src/pages/Executors.vue +103 -40
- package/web-admin/src/pages/Kb.vue +278 -128
- package/web-admin/src/pages/Projects.vue +44 -16
- package/web-admin/src/pages/Routes.vue +168 -247
- package/web-admin/src/pages/Runs.vue +163 -91
- package/web-admin/src/pages/Setup.vue +182 -291
- package/web-admin/src/pages/StorageBuckets.vue +61 -25
- package/web-admin/src/pages/SystemSettings.vue +76 -51
- package/web-admin/src/pages/SystemStatus.vue +54 -30
- package/web-admin/src/pages/Targets.vue +45 -17
- package/web-admin/src/pages/Tools.vue +133 -68
- package/web-admin/src/pages/Usage.vue +64 -25
- package/web-admin/src/pages/UsageAccess.vue +11 -8
- package/web-admin/src/route-call-snippets.test.ts +82 -0
- package/web-admin/src/route-call-snippets.ts +178 -0
- package/web-admin/src/router.ts +11 -29
- package/web-admin/src/runtime-feedback.ts +43 -0
- package/web-admin/src/task-page-location.ts +66 -0
- package/web-admin/src/usage-output-budget.test.ts +26 -0
- package/web-admin/src/usage-output-budget.ts +46 -0
- package/web-admin/src/use-list-location.ts +24 -0
- package/web-admin/src/use-unsaved-form.ts +38 -0
- package/web-admin/tests/model-output-budget.browser.mjs +69 -0
- package/web/console/assets/Accounts-Bervi5JU.css +0 -1
- package/web/console/assets/Accounts-Dhj6PjXP.js +0 -3
- package/web/console/assets/AgentClients-CMy8StAH.js +0 -1
- package/web/console/assets/AgentClients-i52AI6YV.css +0 -1
- package/web/console/assets/AgentTasks-BsG850Il.css +0 -1
- package/web/console/assets/AgentTasks-DA1xZdmP.js +0 -2
- package/web/console/assets/Approvals-DIsd7R8N.js +0 -1
- package/web/console/assets/Approvals-DlTSHl_7.css +0 -1
- package/web/console/assets/Audit-AUDABLTX.js +0 -1
- package/web/console/assets/Audit-CSu6_3oD.css +0 -1
- package/web/console/assets/Channels-B8rjsM0S.js +0 -105
- package/web/console/assets/Channels-CCn0L1jg.css +0 -1
- package/web/console/assets/ChatEntries-DsYtcXN6.css +0 -1
- package/web/console/assets/ChatEntries-iZjJMEUZ.js +0 -7
- package/web/console/assets/Clients-CSHIsaWU.css +0 -1
- package/web/console/assets/Clients-CwgpGCSD.js +0 -3
- package/web/console/assets/Cost-B2tNxu71.js +0 -1
- package/web/console/assets/Cost-CjT39DSZ.css +0 -1
- package/web/console/assets/Credentials-BuwFB-fV.js +0 -1
- package/web/console/assets/Credentials-ioLP0qYN.css +0 -1
- package/web/console/assets/Diagnostics-Ya05PTDp.css +0 -1
- package/web/console/assets/Diagnostics-z5glms11.js +0 -1
- package/web/console/assets/Executors-Bc4SvjeH.js +0 -1
- package/web/console/assets/Executors-CjhEM54c.css +0 -1
- package/web/console/assets/HelpTip-CA6Bm7Nx.css +0 -1
- package/web/console/assets/HelpTip-Dtdt2tKR.js +0 -1
- package/web/console/assets/Kb-BRbRHxLy.js +0 -5
- package/web/console/assets/Kb-CzIzd9xr.css +0 -1
- package/web/console/assets/Projects-Bm8AjsNx.css +0 -1
- package/web/console/assets/Projects-CPWw3con.js +0 -1
- package/web/console/assets/Routes-CMIaE0Bx.js +0 -124
- package/web/console/assets/Routes-CyXV4Pba.css +0 -1
- package/web/console/assets/Runs-B8HuE700.js +0 -3
- package/web/console/assets/Runs-Bv6CV_Hk.css +0 -1
- package/web/console/assets/Setup-D7nxgn-9.css +0 -1
- package/web/console/assets/Setup-G8RKzliR.js +0 -1
- package/web/console/assets/Shell-DimHgraJ.js +0 -1
- package/web/console/assets/Shell-ykb-tUfo.css +0 -1
- package/web/console/assets/StorageBuckets-CVgpZRWY.css +0 -1
- package/web/console/assets/StorageBuckets-CiVYXIE2.js +0 -1
- package/web/console/assets/SystemSettings-BjiHyrXO.css +0 -1
- package/web/console/assets/SystemSettings-DF8sZNen.js +0 -1
- package/web/console/assets/SystemStatus-BlHywK13.js +0 -1
- package/web/console/assets/SystemStatus-I11I67rw.css +0 -1
- package/web/console/assets/Targets-BXaoPoAJ.js +0 -1
- package/web/console/assets/Targets-DTb5tn6z.css +0 -1
- package/web/console/assets/Tools-B22lNHXq.js +0 -2
- package/web/console/assets/Tools-DU8ei6sd.css +0 -1
- package/web/console/assets/Usage-C02EzoI2.js +0 -1
- package/web/console/assets/Usage-CAeDGjrb.css +0 -1
- package/web/console/assets/UsageAccess-CGGaWTuj.css +0 -1
- package/web/console/assets/UsageAccess-DOb-cyPE.js +0 -1
- package/web/console/assets/index-CK0ZCTZv.js +0 -2
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import type { AgentClientRuntimeDeps } from './agent-client-runtime';
|
|
3
|
+
import { AgentToolApiError, resolveAgentRouteFor, type AgentToolAuthContext } from './agent-tool-invocations';
|
|
4
|
+
import { routeAgentClientConfig, routeKnowledgeConfig } from '../core/config/route-config';
|
|
5
|
+
import { assertAgentLegacyTaskAllowedFor, resolveAgentTaskRunFor } from './agent-task-control';
|
|
6
|
+
import { assertTaskCanDispatch } from '../core/runtime/agent-task-control';
|
|
7
|
+
import { requireServerToken } from '../core/platform/server-token';
|
|
8
|
+
import type { Route } from '../core/contracts/types';
|
|
9
|
+
import type { AgentKnowledgeDocument } from '../services/kb';
|
|
10
|
+
|
|
11
|
+
export const AGENT_KNOWLEDGE_PROTOCOL = 'bailing.agent-knowledge.v1';
|
|
12
|
+
export const AGENT_KNOWLEDGE_LIMITS = Object.freeze({ search_max_results: 3, search_max_bytes: 4096,
|
|
13
|
+
read_default_bytes: 16384, read_max_bytes: 32768, reference_ttl_seconds: 300, read_chain_max_bytes: 131072 });
|
|
14
|
+
|
|
15
|
+
export interface AgentKnowledgeSearchInput { query: string; limit?: number; run_id?: string }
|
|
16
|
+
export interface AgentKnowledgeReadInput { ref: string; run_id?: string; cursor?: string; max_bytes?: number }
|
|
17
|
+
|
|
18
|
+
interface ReferencePayload {
|
|
19
|
+
v: 1; c: string; s: string; p: string; w: string; g: string; k: string; d: number; r: string; e: number; u?: string;
|
|
20
|
+
}
|
|
21
|
+
interface CursorPayload { v: 1; f: string; r: string; o: number; e: number }
|
|
22
|
+
type JsonRecord = Record<string, unknown>;
|
|
23
|
+
|
|
24
|
+
function stable(value: unknown): string {
|
|
25
|
+
if (value === null) return 'null';
|
|
26
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
|
|
27
|
+
if (typeof value === 'object' && value) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable((value as JsonRecord)[key])}`).join(',')}}`;
|
|
28
|
+
return JSON.stringify(value) ?? 'null';
|
|
29
|
+
}
|
|
30
|
+
function hash(value: unknown): string { return createHash('sha256').update(stable(value), 'utf8').digest('hex'); }
|
|
31
|
+
function bytes(value: unknown): number { return Buffer.byteLength(JSON.stringify(value), 'utf8'); }
|
|
32
|
+
function now(deps: AgentClientRuntimeDeps): number { return new Date(deps.toolProxyDeps.now()).getTime(); }
|
|
33
|
+
function invalid(message = 'The knowledge reference is invalid; search again.'): never {
|
|
34
|
+
throw new AgentToolApiError(400, 'knowledge_reference_invalid', message);
|
|
35
|
+
}
|
|
36
|
+
function changed(): never { throw new AgentToolApiError(409, 'knowledge_changed', 'The referenced knowledge changed; search again.'); }
|
|
37
|
+
function scopeChanged(): never { throw new AgentToolApiError(409, 'knowledge_scope_changed', 'The knowledge scope changed; search again.'); }
|
|
38
|
+
function unavailable(): never { throw new AgentToolApiError(503, 'knowledge_unavailable', 'Knowledge is unavailable. Try searching later.'); }
|
|
39
|
+
function checkRunId(value: string | undefined): string | undefined {
|
|
40
|
+
if (value !== undefined && (typeof value !== 'string' || !/^[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(value))) {
|
|
41
|
+
throw new AgentToolApiError(400, 'invalid_request', 'run_id must be a UUID.');
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
function principalHash(auth: AgentToolAuthContext): string {
|
|
46
|
+
return hash({ principal: auth.session.principal, on_behalf_of: auth.session.on_behalf_of });
|
|
47
|
+
}
|
|
48
|
+
function scopeRevision(route: Route): string {
|
|
49
|
+
// profile_revision deliberately exposes only the KB count. This separate revision binds
|
|
50
|
+
// the exact server-owned sources, so swapping two equally sized KB sets invalidates refs.
|
|
51
|
+
return hash({ protocol: AGENT_KNOWLEDGE_PROTOCOL, route: route.route_key, knowledge: route.knowledge ?? null,
|
|
52
|
+
enabled: route.enabled, agent_client: routeAgentClientConfig(route), audience: route.audience ?? null });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function authorize(deps: AgentClientRuntimeDeps, original: AgentToolAuthContext, routeKey: string, runId?: string,
|
|
56
|
+
options: { preparing?: boolean; capabilities?: boolean } = {}) {
|
|
57
|
+
const store = deps.toolProxyDeps.configStore;
|
|
58
|
+
// HTTP authentication already checks the bearer. Recheck mutable authorization after
|
|
59
|
+
// asynchronous embedding / storage reads without retaining or logging the bearer.
|
|
60
|
+
const client = store?.clients?.get ? await store.clients.get(original.client.app_id) : original.client;
|
|
61
|
+
const session = store?.agentAuth?.getBusinessSession
|
|
62
|
+
? await store.agentAuth.getBusinessSession(original.client.app_id, original.session.session_id) : original.session;
|
|
63
|
+
if (!client?.enabled || !session || session.revoked_at
|
|
64
|
+
|| new Date(session.access_expires_at).getTime() <= now(deps)
|
|
65
|
+
|| new Date(session.refresh_expires_at).getTime() <= now(deps)
|
|
66
|
+
|| session.session_id !== original.session.session_id || session.client_app_id !== original.client.app_id
|
|
67
|
+
|| principalHash({ client, session }) !== principalHash(original)) {
|
|
68
|
+
throw new AgentToolApiError(401, 'unauthorized', 'The Agent Session is unavailable.');
|
|
69
|
+
}
|
|
70
|
+
const auth = { client, session };
|
|
71
|
+
const route = await resolveAgentRouteFor(deps.toolProxyDeps, auth, routeKey);
|
|
72
|
+
if (!routeAgentClientConfig(route)) throw new AgentToolApiError(403, 'agent_client_disabled', 'Agent Client Runtime is not enabled for this route.');
|
|
73
|
+
if (runId) {
|
|
74
|
+
const run = await store?.agentClientRuntime?.getRun(runId, session.session_id, client.app_id);
|
|
75
|
+
if (!run || run.route_key !== routeKey || (run.status !== 'context_ready' && !(options.preparing && run.status === 'preparing')) || run.completed_at) {
|
|
76
|
+
throw new AgentToolApiError(404, 'run_not_found', 'The active run was not found for this Agent Session and route.');
|
|
77
|
+
}
|
|
78
|
+
const task = await resolveAgentTaskRunFor(store, auth, runId, routeKey, !options.preparing);
|
|
79
|
+
if (task) assertTaskCanDispatch(task, deps.toolProxyDeps.now());
|
|
80
|
+
} else if (!options.capabilities) await assertAgentLegacyTaskAllowedFor(store, session.session_id);
|
|
81
|
+
return { auth, route, cfg: routeKnowledgeConfig(route.knowledge), revision: scopeRevision(route) };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function signingKey(deps: AgentClientRuntimeDeps, kind: 'ref' | 'cursor'): Buffer {
|
|
85
|
+
try {
|
|
86
|
+
return createHmac('sha256', requireServerToken(deps.toolProxyDeps.cfg.server?.token ?? '', '签署 Agent 知识引用'))
|
|
87
|
+
.update(`bailing.agent-knowledge.${kind}.key.v1`).digest();
|
|
88
|
+
} catch { return unavailable(); }
|
|
89
|
+
}
|
|
90
|
+
function sign(deps: AgentClientRuntimeDeps, kind: 'ref' | 'cursor', payload: ReferencePayload | CursorPayload): string {
|
|
91
|
+
const body = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
|
|
92
|
+
const prefix = kind === 'ref' ? 'bkr1' : 'bkc1';
|
|
93
|
+
const signature = createHmac('sha256', signingKey(deps, kind)).update(`${prefix}.${body}`).digest('base64url');
|
|
94
|
+
return `${prefix}.${body}.${signature}`;
|
|
95
|
+
}
|
|
96
|
+
function open(deps: AgentClientRuntimeDeps, kind: 'ref' | 'cursor', token: string): JsonRecord {
|
|
97
|
+
if (typeof token !== 'string' || token.length > 2048) return invalid();
|
|
98
|
+
const parts = token.split('.'); const prefix = kind === 'ref' ? 'bkr1' : 'bkc1';
|
|
99
|
+
if (parts.length !== 3 || parts[0] !== prefix || !/^[A-Za-z0-9_-]+$/.test(parts[1]!) || !/^[A-Za-z0-9_-]{43}$/.test(parts[2]!)) return invalid();
|
|
100
|
+
const expected = createHmac('sha256', signingKey(deps, kind)).update(`${prefix}.${parts[1]}`).digest();
|
|
101
|
+
const actual = Buffer.from(parts[2]!, 'base64url');
|
|
102
|
+
if (actual.toString('base64url') !== parts[2] || actual.length !== expected.length || !timingSafeEqual(actual, expected)) return invalid();
|
|
103
|
+
let value: unknown;
|
|
104
|
+
try { value = JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')); } catch { return invalid(); }
|
|
105
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid();
|
|
106
|
+
const record = value as JsonRecord;
|
|
107
|
+
if (record.v !== 1 || !Number.isSafeInteger(record.e)) return invalid();
|
|
108
|
+
if (Number(record.e) <= now(deps)) throw new AgentToolApiError(410, 'knowledge_reference_expired', 'The knowledge reference expired; search again.');
|
|
109
|
+
if (Number(record.e) > now(deps) + AGENT_KNOWLEDGE_LIMITS.reference_ttl_seconds * 1000) return invalid();
|
|
110
|
+
return record;
|
|
111
|
+
}
|
|
112
|
+
function prefixChars(value: string, maximum: number): string {
|
|
113
|
+
let end = Math.min(value.length, maximum);
|
|
114
|
+
if (end > 0 && end < value.length && /[\uD800-\uDBFF]/.test(value[end - 1]!)) end--;
|
|
115
|
+
return value.slice(0, end);
|
|
116
|
+
}
|
|
117
|
+
function prefixBytes(value: string, maximum: number): string {
|
|
118
|
+
if (Buffer.byteLength(value, 'utf8') <= maximum) return value;
|
|
119
|
+
let low = 0; let high = value.length;
|
|
120
|
+
while (low < high) {
|
|
121
|
+
const middle = Math.ceil((low + high) / 2);
|
|
122
|
+
if (Buffer.byteLength(prefixChars(value, middle), 'utf8') <= maximum) low = middle;
|
|
123
|
+
else high = middle - 1;
|
|
124
|
+
}
|
|
125
|
+
return prefixChars(value, low);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function getAgentKnowledgeCapabilitiesFor(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext, routeKey: string): Promise<JsonRecord> {
|
|
129
|
+
const current = await authorize(deps, auth, routeKey, undefined, { capabilities: true });
|
|
130
|
+
return { schema_version: 'bailing.agent-knowledge-capabilities.v1', protocol: AGENT_KNOWLEDGE_PROTOCOL,
|
|
131
|
+
supported: true, route: routeKey, enabled: Boolean(current.cfg && deps.kbService),
|
|
132
|
+
knowledge_scope_revision: current.revision, delivery_modes: ['inline', 'on_demand'], limits: AGENT_KNOWLEDGE_LIMITS };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function searchKnowledge(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext, routeKey: string, input: AgentKnowledgeSearchInput,
|
|
136
|
+
preparing = false): Promise<JsonRecord> {
|
|
137
|
+
if (typeof input.query !== 'string' || !input.query.trim() || input.query.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(input.query)
|
|
138
|
+
|| (input.limit !== undefined && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 3))) {
|
|
139
|
+
throw new AgentToolApiError(400, 'invalid_request', 'Knowledge search requires a non-empty query up to 2000 characters and a limit from 1 to 3.');
|
|
140
|
+
}
|
|
141
|
+
const runId = checkRunId(input.run_id); const current = await authorize(deps, auth, routeKey, runId, { preparing });
|
|
142
|
+
const base: JsonRecord = { schema_version: 'bailing.agent-knowledge-search.v1', route: routeKey,
|
|
143
|
+
...(runId ? { run_id: runId } : {}), knowledge_scope_revision: current.revision,
|
|
144
|
+
status: current.cfg ? 'unavailable' : 'disabled', trust: 'reference_only', hints: [], truncated: false };
|
|
145
|
+
if (!current.cfg || !deps.kbService) return base;
|
|
146
|
+
// Fail closed if signing is unavailable before spending embedding work.
|
|
147
|
+
signingKey(deps, 'ref');
|
|
148
|
+
let result;
|
|
149
|
+
try { result = await deps.kbService.searchForAgent(current.cfg.kb_ids, input.query, Math.max(current.cfg.top_k, 8), current.cfg.min_score, input.limit ?? 3); }
|
|
150
|
+
catch { return base; }
|
|
151
|
+
const after = await authorize(deps, auth, routeKey, runId, { preparing });
|
|
152
|
+
if (after.revision !== current.revision) return scopeChanged();
|
|
153
|
+
const hints: JsonRecord[] = []; const expiry = now(deps) + AGENT_KNOWLEDGE_LIMITS.reference_ttl_seconds * 1000;
|
|
154
|
+
base.status = result.status; base.hints = hints; base.truncated = result.truncated;
|
|
155
|
+
for (const doc of result.documents) {
|
|
156
|
+
if (!after.cfg?.kb_ids.includes(doc.kb_id)) continue;
|
|
157
|
+
let fresh: AgentKnowledgeDocument | null;
|
|
158
|
+
try { fresh = await deps.kbService.getAgentDocumentSnapshot(doc.kb_id, doc.doc_id); }
|
|
159
|
+
catch { base.status = hints.length ? 'partial' : 'unavailable'; base.truncated = true; continue; }
|
|
160
|
+
if (!fresh || fresh.revision !== doc.revision) { base.truncated = true; continue; }
|
|
161
|
+
const payload: ReferencePayload = { v: 1, c: after.auth.client.app_id, s: after.auth.session.session_id,
|
|
162
|
+
p: principalHash(after.auth), w: routeKey, g: after.revision, k: doc.kb_id, d: doc.doc_id, r: doc.revision, e: expiry,
|
|
163
|
+
...(runId ? { u: runId } : {}) };
|
|
164
|
+
const hint = { ref: sign(deps, 'ref', payload), title: prefixChars(doc.title, 100),
|
|
165
|
+
summary: prefixChars(doc.summary, 200), revision: doc.revision, score: doc.score, expires_at: new Date(expiry).toISOString() };
|
|
166
|
+
hints.push(hint);
|
|
167
|
+
if (bytes(base) > AGENT_KNOWLEDGE_LIMITS.search_max_bytes) {
|
|
168
|
+
hints.pop(); base.truncated = true; break;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return base;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function searchAgentKnowledgeFor(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext, routeKey: string,
|
|
175
|
+
input: AgentKnowledgeSearchInput): Promise<JsonRecord> {
|
|
176
|
+
return searchKnowledge(deps, auth, routeKey, input);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Server-only turn assembly may issue run-bound hints before finalizeTurn. Not a public search mode. */
|
|
180
|
+
export async function prepareAgentKnowledgeFor(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext, routeKey: string,
|
|
181
|
+
input: { query: string; run_id: string }): Promise<JsonRecord> {
|
|
182
|
+
checkRunId(input.run_id);
|
|
183
|
+
return searchKnowledge(deps, auth, routeKey, { ...input, limit: 3 }, true);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function readAgentKnowledgeFor(deps: AgentClientRuntimeDeps, auth: AgentToolAuthContext, routeKey: string, input: AgentKnowledgeReadInput): Promise<JsonRecord> {
|
|
187
|
+
const max = input.max_bytes ?? AGENT_KNOWLEDGE_LIMITS.read_default_bytes;
|
|
188
|
+
if (!Number.isInteger(max) || max < 4096 || max > AGENT_KNOWLEDGE_LIMITS.read_max_bytes) {
|
|
189
|
+
throw new AgentToolApiError(400, 'invalid_request', 'max_bytes must be from 4096 to 32768.');
|
|
190
|
+
}
|
|
191
|
+
const runId = checkRunId(input.run_id); const current = await authorize(deps, auth, routeKey, runId);
|
|
192
|
+
const ref = open(deps, 'ref', input.ref);
|
|
193
|
+
if (ref.c !== current.auth.client.app_id || ref.s !== current.auth.session.session_id || ref.p !== principalHash(current.auth)
|
|
194
|
+
|| ref.w !== routeKey || ref.u !== runId || typeof ref.k !== 'string' || !Number.isSafeInteger(ref.d) || Number(ref.d) < 1 || typeof ref.r !== 'string') return invalid();
|
|
195
|
+
if (ref.g !== current.revision) return scopeChanged();
|
|
196
|
+
if (!current.cfg?.kb_ids.includes(ref.k)) return scopeChanged();
|
|
197
|
+
if (!deps.kbService) return unavailable();
|
|
198
|
+
let doc: AgentKnowledgeDocument | null;
|
|
199
|
+
try { doc = await deps.kbService.getAgentDocumentSnapshot(ref.k, Number(ref.d)); } catch { return unavailable(); }
|
|
200
|
+
if (!doc || doc.revision !== ref.r) return changed();
|
|
201
|
+
const after = await authorize(deps, auth, routeKey, runId);
|
|
202
|
+
if (after.revision !== current.revision) return scopeChanged();
|
|
203
|
+
// Authorization storage itself is asynchronous. Fence content again after that await,
|
|
204
|
+
// so an update/deletion/disable observed in that window cannot return the old snapshot.
|
|
205
|
+
try { doc = await deps.kbService.getAgentDocumentSnapshot(ref.k, Number(ref.d)); } catch { return unavailable(); }
|
|
206
|
+
if (!doc || doc.revision !== ref.r) return changed();
|
|
207
|
+
const limited = prefixBytes(doc.content, AGENT_KNOWLEDGE_LIMITS.read_chain_max_bytes);
|
|
208
|
+
let offset = 0;
|
|
209
|
+
if (input.cursor !== undefined) {
|
|
210
|
+
const cursor = open(deps, 'cursor', input.cursor);
|
|
211
|
+
if (cursor.f !== hash(input.ref) || cursor.r !== doc.revision || cursor.e !== ref.e
|
|
212
|
+
|| !Number.isSafeInteger(cursor.o) || Number(cursor.o) < 0 || Number(cursor.o) > limited.length) return invalid();
|
|
213
|
+
offset = Number(cursor.o);
|
|
214
|
+
if (offset > 0 && /[\uD800-\uDBFF]/.test(limited[offset - 1]!) && /[\uDC00-\uDFFF]/.test(limited[offset] ?? '')) return invalid();
|
|
215
|
+
}
|
|
216
|
+
const response = (end: number): JsonRecord => ({ schema_version: 'bailing.agent-knowledge-read.v1', route: routeKey,
|
|
217
|
+
...(runId ? { run_id: runId } : {}), knowledge_scope_revision: current.revision, ref: input.ref,
|
|
218
|
+
revision: doc!.revision, title: prefixChars(doc!.title, 300), content: limited.slice(offset, end), trust: 'reference_only',
|
|
219
|
+
next_cursor: end < limited.length ? sign(deps, 'cursor', { v: 1, f: hash(input.ref), r: doc!.revision, o: end, e: Number(ref.e) }) : null,
|
|
220
|
+
truncated: end < doc!.content.length, budget_exhausted: end === limited.length && limited.length < doc!.content.length,
|
|
221
|
+
total_content_bytes: Buffer.byteLength(doc!.content, 'utf8'), read_chain_max_bytes: AGENT_KNOWLEDGE_LIMITS.read_chain_max_bytes });
|
|
222
|
+
let low = offset; let high = limited.length;
|
|
223
|
+
while (low < high) {
|
|
224
|
+
const middle = Math.ceil((low + high) / 2); const end = prefixChars(limited, middle).length;
|
|
225
|
+
if (bytes(response(end)) <= max) low = middle;
|
|
226
|
+
else high = middle - 1;
|
|
227
|
+
}
|
|
228
|
+
const end = prefixChars(limited, low).length;
|
|
229
|
+
if (end <= offset && offset < limited.length) return unavailable();
|
|
230
|
+
const result = response(end);
|
|
231
|
+
if (bytes(result) > max) return unavailable();
|
|
232
|
+
return result;
|
|
233
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { compileOpenApiTools } from '../core/contracts/openapi-tools';
|
|
4
|
+
import type { ToolDefinition } from '../core/contracts/tool-definition';
|
|
5
|
+
import type { Route, ToolProvider } from '../core/contracts/types';
|
|
6
|
+
import type { AllowedToolContext } from './tool-context';
|
|
7
|
+
import { agentToolCatalogRevisionFor } from './agent-tool-invocations';
|
|
8
|
+
|
|
9
|
+
test('same raw spec gets a new catalog revision when compiler discovery or guidance projection changes', () => {
|
|
10
|
+
const spec = JSON.stringify({ paths: { '/page': { get: { operationId: 'page_get', summary: '读取页面', description: '必须先核对页面绑定。',
|
|
11
|
+
'x-agent-capability': { enabled: true, scope: 'page.read' } } } } });
|
|
12
|
+
const tool = compileOpenApiTools(spec).tools[0]!;
|
|
13
|
+
const provider: ToolProvider = { name: 'pages', enabled: true, base_url: 'https://pages.invalid', secret: 'not-part-of-revision',
|
|
14
|
+
spec_source: 'inline', spec_json: spec, timeout_ms: 1000, rate_limit_per_min: 0, auto_refresh_min: 0, log_payload: false };
|
|
15
|
+
const route: Route = { route_key: 'page-agent', name: 'Pages', enabled: true, target: 'llm', target_config: {}, profile: 'general',
|
|
16
|
+
session_policy: 'new', tools: { sources: [{ provider: provider.name, allow: ['*'] }], agent_direct: { enabled: true } } };
|
|
17
|
+
const revision = (compiled: ToolDefinition) => {
|
|
18
|
+
const context: AllowedToolContext = { allowed: [compiled], sources: [{ provider, allowed: [compiled],
|
|
19
|
+
sourceCfg: { provider: provider.name, allow: ['*'] }, onBehalfOf: 't1:u1', lockedBySubject: 0 }], toolsCfg: route.tools!, lockedBySubject: 0 };
|
|
20
|
+
return agentToolCatalogRevisionFor(route, context);
|
|
21
|
+
};
|
|
22
|
+
const current = revision(tool);
|
|
23
|
+
assert.equal(revision(structuredClone(tool)), current, 'same raw spec and same compiled output stay stable');
|
|
24
|
+
const historical = { ...tool, usageGuidance: undefined, descriptionTruncated: undefined };
|
|
25
|
+
assert.notEqual(revision(historical), current, 'the same spec compiled before detail preservation must not reuse the new revision');
|
|
26
|
+
assert.notEqual(revision({ ...tool, description: '读取页面并核对绑定' }), current, 'public short-description changes invalidate the catalog');
|
|
27
|
+
assert.notEqual(revision({ ...tool, descriptionTruncated: true }), current, 'public truncation flags participate in the revision');
|
|
28
|
+
assert.notEqual(revision({ ...tool, usageGuidance: { ...tool.usageGuidance!, text: '其他指导', sourceChars: 4, sourceBytes: 12 } }), current,
|
|
29
|
+
'full guidance changes invalidate detail caches even when public summaries remain identical');
|
|
30
|
+
assert.equal(provider.spec_json, spec, 'all compiler-output variants use byte-identical source spec');
|
|
31
|
+
});
|
|
@@ -429,8 +429,13 @@ test('Agent direct: 路由精确列出的写工具额外强制审批并可续执
|
|
|
429
429
|
assert.equal(fx.approvals.length, 1);
|
|
430
430
|
|
|
431
431
|
fx.approvals[0]!.status = 'approved';
|
|
432
|
-
//
|
|
433
|
-
|
|
432
|
+
// 当前工具的发现文案/按需指导变化会改变 catalog revision,但不改变已冻结的执行契约。
|
|
433
|
+
const changedSpec = JSON.parse(spec());
|
|
434
|
+
changedSpec.paths['/staff/edit'].post.description = '先核对原员工修订;冲突时重新读取,不要自动重放。';
|
|
435
|
+
fx.setSpec(JSON.stringify(changedSpec));
|
|
436
|
+
const refreshedCatalog = await listAgentToolsFor(fx.deps, auth(), 'tenant-agent');
|
|
437
|
+
assert.notEqual(refreshedCatalog.capability_revision, catalog.capability_revision);
|
|
438
|
+
assert.equal(refreshedCatalog.tools.find((item) => item.name === 'staff_edit')?.usage_guidance_available, true);
|
|
434
439
|
const completed = await resumeAgentToolFor(fx.deps, auth(), {
|
|
435
440
|
invocation_id: invocationId('8'),
|
|
436
441
|
});
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { openInvocationArguments, sealInvocationArguments } from './agent-invocation-snapshot';
|
|
2
2
|
import { bindingForTask, resolveAgentTaskRunFor } from './agent-task-control';
|
|
3
3
|
import { taskAssert } from '../core/runtime/agent-task-control';
|
|
4
|
+
import { TOOL_ARGUMENTS_MAX_BYTES, type ToolInputLimitDetails } from '../core/contracts/tool-input-limits';
|
|
4
5
|
import type { ToolRateLimitFeedback } from '../core/contracts/tools';
|
|
5
6
|
import { createHash, randomUUID } from 'node:crypto';
|
|
6
7
|
import { agentDirectToolsConfig } from '../core/config/tools-config';
|
|
7
|
-
import type
|
|
8
|
+
import { TOOL_NAME_RE, type ToolDefinition } from '../core/contracts/tool-definition';
|
|
9
|
+
import { boundedToolText, TOOL_USAGE_GUIDANCE_MAX_BYTES, TOOL_USAGE_GUIDANCE_MAX_CHARS } from '../core/contracts/tool-guidance';
|
|
8
10
|
import { argsHash, type ToolExecutionJournalEntry } from '../core/contracts/tools';
|
|
9
11
|
import type { AgentSession, Client, Job, Route } from '../core/contracts/types';
|
|
10
12
|
import { audienceAllows } from '../core/runtime/identity-runtime';
|
|
@@ -25,10 +27,10 @@ const ROUTE_RE = /^[a-z0-9][a-z0-9_-]{1,63}$/;
|
|
|
25
27
|
const INVOCATION_RE = /^[a-f0-9]{64}$/;
|
|
26
28
|
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;
|
|
27
29
|
const REVISION_RE = /^[a-f0-9]{64}$/;
|
|
28
|
-
const ARGUMENTS_MAX_BYTES = 4096;
|
|
29
30
|
const INVOCATION_LOCK_TTL_MS = 15 * 60_000;
|
|
30
31
|
|
|
31
32
|
export const AGENT_TOOL_CATALOG_SCHEMA = 'bailing.agent-tool-catalog.v1';
|
|
33
|
+
export const AGENT_TOOL_DETAIL_SCHEMA = 'bailing.agent-tool-detail.v1';
|
|
32
34
|
export const AGENT_TOOL_INVOCATION_SCHEMA = 'bailing.agent-tool-invocation.v1';
|
|
33
35
|
export const AGENT_INVOCATION_RECEIPT_SCHEMA = 'bailing.agent-invocation-receipt.v1';
|
|
34
36
|
export const AGENT_INVOCATION_INSPECTION_SCHEMA = 'bailing.agent-invocation-inspection-capabilities.v1';
|
|
@@ -51,6 +53,8 @@ export interface AgentToolAuthContext {
|
|
|
51
53
|
export interface AgentToolCatalogItem {
|
|
52
54
|
name: string;
|
|
53
55
|
description: string;
|
|
56
|
+
description_truncated?: boolean;
|
|
57
|
+
usage_guidance_available?: boolean;
|
|
54
58
|
input_schema: Record<string, unknown>;
|
|
55
59
|
scope: string;
|
|
56
60
|
risk: string;
|
|
@@ -66,6 +70,21 @@ export interface AgentToolCatalog {
|
|
|
66
70
|
tools: AgentToolCatalogItem[];
|
|
67
71
|
}
|
|
68
72
|
|
|
73
|
+
export interface AgentToolDetail {
|
|
74
|
+
schema_version: typeof AGENT_TOOL_DETAIL_SCHEMA;
|
|
75
|
+
route: string;
|
|
76
|
+
capability_revision: string;
|
|
77
|
+
tool: AgentToolCatalogItem;
|
|
78
|
+
usage_guidance: {
|
|
79
|
+
text: string;
|
|
80
|
+
truncated: boolean;
|
|
81
|
+
source_chars: number;
|
|
82
|
+
max_chars: number;
|
|
83
|
+
source_bytes: number;
|
|
84
|
+
max_bytes: number;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
69
88
|
export const AGENT_TOOL_SEARCH_SCHEMA = 'bailing.agent-capability-search.v1';
|
|
70
89
|
export interface AgentToolDiscovery {
|
|
71
90
|
mode: 'ranked_candidates';
|
|
@@ -136,6 +155,7 @@ export class AgentToolApiError extends Error {
|
|
|
136
155
|
readonly statusCode: number,
|
|
137
156
|
readonly code: string,
|
|
138
157
|
message: string,
|
|
158
|
+
readonly details?: ToolInputLimitDetails,
|
|
139
159
|
) {
|
|
140
160
|
super(message);
|
|
141
161
|
this.name = 'AgentToolApiError';
|
|
@@ -247,6 +267,8 @@ function publicTool(tool: ToolDefinition): AgentToolCatalogItem {
|
|
|
247
267
|
return {
|
|
248
268
|
name: tool.name,
|
|
249
269
|
description: safeDescription(tool.description),
|
|
270
|
+
...(tool.descriptionTruncated ? { description_truncated: true } : {}),
|
|
271
|
+
...(tool.usageGuidance ? { usage_guidance_available: true } : {}),
|
|
250
272
|
input_schema: safeInputSchema(tool.inputSchema),
|
|
251
273
|
scope: tool.scope,
|
|
252
274
|
risk: tool.risk,
|
|
@@ -256,7 +278,8 @@ function publicTool(tool: ToolDefinition): AgentToolCatalogItem {
|
|
|
256
278
|
};
|
|
257
279
|
}
|
|
258
280
|
|
|
259
|
-
|
|
281
|
+
/** @internal Pure revision builder: compiled discovery changes invalidate client caches even for the same raw spec. */
|
|
282
|
+
export function agentToolCatalogRevisionFor(route: Route, context: AllowedToolContext): string {
|
|
260
283
|
return sha256(stableJson({
|
|
261
284
|
schema: AGENT_TOOL_CATALOG_SCHEMA,
|
|
262
285
|
route: route.route_key,
|
|
@@ -282,6 +305,8 @@ function fingerprint(route: Route, context: AllowedToolContext): string {
|
|
|
282
305
|
idempotent: tool.idempotent,
|
|
283
306
|
input_schema: tool.inputSchema,
|
|
284
307
|
param_in: tool.paramIn,
|
|
308
|
+
discovery: publicTool(tool),
|
|
309
|
+
usage_guidance: tool.usageGuidance ?? null,
|
|
285
310
|
})),
|
|
286
311
|
})),
|
|
287
312
|
}));
|
|
@@ -383,7 +408,7 @@ async function resolveSurface(deps: ToolProxyDeps, auth: AgentToolAuthContext, r
|
|
|
383
408
|
const resolved = await resolveAllowedToolsFor(deps.configStore, probeJob(auth, route, deps.now()), route);
|
|
384
409
|
if (!resolved) {
|
|
385
410
|
const empty: AllowedToolContext = { sources: [], allowed: [], toolsCfg: route.tools ?? {}, lockedBySubject: 0 };
|
|
386
|
-
return { route, revision:
|
|
411
|
+
return { route, revision: agentToolCatalogRevisionFor(route, empty), context: empty, tools: [] };
|
|
387
412
|
}
|
|
388
413
|
const writeNames = new Set(direct.write_tools ?? []);
|
|
389
414
|
const forceApproval = new Set(direct.force_approval_tools ?? []);
|
|
@@ -395,7 +420,7 @@ async function resolveSurface(deps: ToolProxyDeps, auth: AgentToolAuthContext, r
|
|
|
395
420
|
})).filter((source) => source.allowed.length);
|
|
396
421
|
const allowed = sources.flatMap((source) => source.allowed).sort((a, b) => a.name.localeCompare(b.name));
|
|
397
422
|
const context: AllowedToolContext = { ...resolved, sources, allowed };
|
|
398
|
-
return { route, revision:
|
|
423
|
+
return { route, revision: agentToolCatalogRevisionFor(route, context), context, tools: allowed.map(publicTool) };
|
|
399
424
|
}
|
|
400
425
|
|
|
401
426
|
export async function listAgentToolsFor(deps: ToolProxyDeps, auth: AgentToolAuthContext, route: string): Promise<AgentToolCatalog> {
|
|
@@ -408,6 +433,37 @@ export async function listAgentToolsFor(deps: ToolProxyDeps, auth: AgentToolAuth
|
|
|
408
433
|
};
|
|
409
434
|
}
|
|
410
435
|
|
|
436
|
+
/** A named, current-authority read: no job, approval, invocation or business dispatch is created. */
|
|
437
|
+
export async function getAgentToolDetailFor(
|
|
438
|
+
deps: ToolProxyDeps,
|
|
439
|
+
auth: AgentToolAuthContext,
|
|
440
|
+
route: string,
|
|
441
|
+
name: string,
|
|
442
|
+
capabilityRevision: string,
|
|
443
|
+
): Promise<AgentToolDetail> {
|
|
444
|
+
if (!TOOL_NAME_RE.test(name)) throw new AgentToolApiError(400, 'invalid_request', 'The tool name is invalid.');
|
|
445
|
+
if (!REVISION_RE.test(capabilityRevision)) throw new AgentToolApiError(400, 'invalid_request', 'A current capability_revision is required.');
|
|
446
|
+
const surface = await resolveSurface(deps, auth, route);
|
|
447
|
+
if (surface.revision !== capabilityRevision) throw new AgentToolApiError(409, 'capability_changed', 'The capability catalog changed; refresh tools before reading usage guidance.');
|
|
448
|
+
const definition = surface.context.allowed.find((tool) => tool.name === name);
|
|
449
|
+
if (!definition) throw new AgentToolApiError(404, 'tool_not_found', 'The tool is not available in the current capability catalog.');
|
|
450
|
+
const guidance = definition.usageGuidance ?? boundedToolText(definition.description, TOOL_USAGE_GUIDANCE_MAX_CHARS, TOOL_USAGE_GUIDANCE_MAX_BYTES);
|
|
451
|
+
return {
|
|
452
|
+
schema_version: AGENT_TOOL_DETAIL_SCHEMA,
|
|
453
|
+
route: surface.route.route_key,
|
|
454
|
+
capability_revision: surface.revision,
|
|
455
|
+
tool: publicTool(definition),
|
|
456
|
+
usage_guidance: {
|
|
457
|
+
text: guidance.text,
|
|
458
|
+
truncated: guidance.truncated,
|
|
459
|
+
source_chars: guidance.sourceChars,
|
|
460
|
+
max_chars: TOOL_USAGE_GUIDANCE_MAX_CHARS,
|
|
461
|
+
source_bytes: guidance.sourceBytes,
|
|
462
|
+
max_bytes: TOOL_USAGE_GUIDANCE_MAX_BYTES,
|
|
463
|
+
},
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
|
|
411
467
|
function lexicalToolOrder(tools: AgentToolCatalogItem[], query: string): AgentToolCatalogItem[] {
|
|
412
468
|
const normalized = query.toLowerCase().replace(/[^\p{L}\p{N}_]+/gu, ' ').trim();
|
|
413
469
|
const words = [...new Set(normalized.split(/\s+/).filter(Boolean))];
|
|
@@ -574,8 +630,12 @@ function assertInvocationInput(input: InvokeAgentToolInput): void {
|
|
|
574
630
|
throw new AgentToolApiError(400, 'invalid_request', 'The Agent tool invocation request is invalid.');
|
|
575
631
|
}
|
|
576
632
|
const encoded = JSON.stringify(input.arguments);
|
|
577
|
-
|
|
578
|
-
|
|
633
|
+
const actualBytes = Buffer.byteLength(encoded, 'utf8');
|
|
634
|
+
if (actualBytes > TOOL_ARGUMENTS_MAX_BYTES) {
|
|
635
|
+
throw new AgentToolApiError(413, 'arguments_too_large', `Tool arguments exceed ${TOOL_ARGUMENTS_MAX_BYTES} bytes.`, {
|
|
636
|
+
origin: 'core', dispatch: 'not_dispatched', limit_scope: 'arguments',
|
|
637
|
+
actual_bytes: actualBytes, max_bytes: TOOL_ARGUMENTS_MAX_BYTES,
|
|
638
|
+
});
|
|
579
639
|
}
|
|
580
640
|
}
|
|
581
641
|
|
|
@@ -66,6 +66,7 @@ async function fixture(status: Job['status'] = 'done', direct = false) {
|
|
|
66
66
|
};
|
|
67
67
|
const ledger = {
|
|
68
68
|
get: async () => ({ ...approval }), getByDecisionId: async () => null,
|
|
69
|
+
list: async () => [{ ...approval }],
|
|
69
70
|
decideWithContinuation: async (_id: number, decision: 'approved' | 'denied', by: string, opts: ApprovalContinuationDecisionOptions) => {
|
|
70
71
|
if (approval.status !== 'pending') return approval.status === decision && approval.decision_id === opts.decision_id ? 'same' : 'conflict';
|
|
71
72
|
approval.status = decision; approval.decision_id = opts.decision_id;
|
|
@@ -114,7 +115,17 @@ async function fixture(status: Job['status'] = 'done', direct = false) {
|
|
|
114
115
|
{ kind: 'admin', via: 'session', role: 'admin', username: 'fixture-operator' });
|
|
115
116
|
return res;
|
|
116
117
|
}
|
|
117
|
-
|
|
118
|
+
async function consoleRead(pathname: string) {
|
|
119
|
+
const req = Object.assign(Readable.from([]), { method: 'GET', headers: {}, url: pathname });
|
|
120
|
+
const res = new Response();
|
|
121
|
+
await handleAdminRuntimeApiFor({ configStore, stateStore: store, now, isPaused: () => false,
|
|
122
|
+
queueStats: () => ({}), channelSend: async () => ({ ok: true }),
|
|
123
|
+
engineRuntime: { ...deps.engineRuntime, requeueForRerun: async () => { throw new Error('read must not requeue'); } },
|
|
124
|
+
}, 'GET', pathname.split('?')[0]!, req as IncomingMessage, res as unknown as ServerResponse,
|
|
125
|
+
{ kind: 'admin', via: 'session', role: 'admin', username: 'fixture-operator' });
|
|
126
|
+
return res;
|
|
127
|
+
}
|
|
128
|
+
return { directory, path, store, job, approval, ledger, deps, faults, call, consoleCall, consoleRead,
|
|
118
129
|
intent: () => intent, kicks: () => kicks,
|
|
119
130
|
close: () => rm(directory, { recursive: true, force: true }) };
|
|
120
131
|
}
|
|
@@ -297,6 +308,43 @@ test('manual Agent continuation preserves original invocation without Core infer
|
|
|
297
308
|
} finally { await h.close(); }
|
|
298
309
|
});
|
|
299
310
|
|
|
311
|
+
test('console approval responses explain manual continuation and never offer a model rerun for Agent jobs', async () => {
|
|
312
|
+
const h = await fixture('done', true);
|
|
313
|
+
try {
|
|
314
|
+
const listed = await h.consoleRead('/admin/api/tool-approvals?status=all');
|
|
315
|
+
assert.equal(listed.body[0].continuation_mode, 'manual');
|
|
316
|
+
assert.equal(listed.body[0].continuation_pending, false);
|
|
317
|
+
const decision = await h.consoleCall();
|
|
318
|
+
assert.equal(decision.body.continuation_mode, 'manual');
|
|
319
|
+
assert.equal(decision.body.rerun, false);
|
|
320
|
+
assert.equal(decision.body.continuation_pending, false);
|
|
321
|
+
const { consoleExecution } = await import('../routes/admin-runtime-ux');
|
|
322
|
+
assert.deepEqual(consoleExecution((await h.store.getJob(h.job.job_id))!), { kind: 'agent_tool', rerun: { available: false, reason: 'original_client' } });
|
|
323
|
+
assert.equal((await h.store.getJob(h.job.job_id))?.status, 'done');
|
|
324
|
+
assert.equal(h.kicks(), 0);
|
|
325
|
+
} finally { await h.close(); }
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
test('console lists persisted decisions as pending recovery after a queue failure and then queued after recovery', async () => {
|
|
329
|
+
const h = await fixture();
|
|
330
|
+
try {
|
|
331
|
+
h.faults.queue = true;
|
|
332
|
+
const failure = await h.consoleCall();
|
|
333
|
+
assert.equal(failure.statusCode, 503);
|
|
334
|
+
assert.equal(failure.body.decision_recorded, true);
|
|
335
|
+
assert.equal(failure.body.continuation_mode, 'rerun');
|
|
336
|
+
const pending = (await h.consoleRead('/admin/api/tool-approvals?status=all')).body[0];
|
|
337
|
+
assert.equal(pending.status, 'approved');
|
|
338
|
+
assert.equal(pending.continuation_pending, true);
|
|
339
|
+
assert.equal(pending.job_status, 'done');
|
|
340
|
+
h.faults.queue = false;
|
|
341
|
+
await reconcileApprovalContinuationsFor(h.deps);
|
|
342
|
+
const queued = (await h.consoleRead('/admin/api/tool-approvals?status=all')).body[0];
|
|
343
|
+
assert.equal(queued.continuation_pending, false);
|
|
344
|
+
assert.equal(queued.job_status, 'queued');
|
|
345
|
+
} finally { await h.close(); }
|
|
346
|
+
});
|
|
347
|
+
|
|
300
348
|
test('missing state continuation port blocks a new decision rather than silently falling back', async () => {
|
|
301
349
|
const h = await fixture();
|
|
302
350
|
try {
|
package/src/app/http.test.ts
CHANGED
|
@@ -11,10 +11,25 @@ function req(body: string): IncomingMessage {
|
|
|
11
11
|
test('readBody: 默认 JSON 读取支持显式上限并在超限时拒绝', async () => {
|
|
12
12
|
await assert.rejects(
|
|
13
13
|
() => readBody(req(JSON.stringify({ text: 'abcdef' })), 8),
|
|
14
|
-
(e) => e instanceof PayloadTooLargeError && e.statusCode === 413 && e.maxBytes === 8,
|
|
14
|
+
(e) => e instanceof PayloadTooLargeError && e.statusCode === 413 && e.maxBytes === 8 && e.observedBytes === 17,
|
|
15
15
|
);
|
|
16
16
|
});
|
|
17
17
|
|
|
18
|
+
test('readBody: stream overflow reports observed UTF-8 bytes and stops before reading the remainder', async () => {
|
|
19
|
+
let chunksRead = 0;
|
|
20
|
+
async function* chunks() {
|
|
21
|
+
for (const text of ['{"value":"', '中文😀', 'private-unread-remainder"}']) {
|
|
22
|
+
chunksRead++;
|
|
23
|
+
yield Buffer.from(text, 'utf8');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
await assert.rejects(
|
|
27
|
+
() => readBody(chunks() as unknown as IncomingMessage, 16),
|
|
28
|
+
(e) => e instanceof PayloadTooLargeError && e.maxBytes === 16 && e.observedBytes === 20,
|
|
29
|
+
);
|
|
30
|
+
assert.equal(chunksRead, 2);
|
|
31
|
+
});
|
|
32
|
+
|
|
18
33
|
test('readBody: 限内 JSON 正常解析', async () => {
|
|
19
34
|
assert.deepEqual(await readBody(req(JSON.stringify({ ok: true })), 64), { ok: true });
|
|
20
35
|
});
|
package/src/app/http.ts
CHANGED
|
@@ -10,7 +10,7 @@ export function errMsg(e: unknown): string { return e instanceof Error ? e.messa
|
|
|
10
10
|
|
|
11
11
|
export class PayloadTooLargeError extends Error {
|
|
12
12
|
readonly statusCode = 413;
|
|
13
|
-
constructor(readonly maxBytes: number) {
|
|
13
|
+
constructor(readonly maxBytes: number, readonly observedBytes?: number) {
|
|
14
14
|
super(`payload too large: max ${maxBytes} bytes`);
|
|
15
15
|
this.name = 'PayloadTooLargeError';
|
|
16
16
|
}
|
|
@@ -28,7 +28,7 @@ export async function readBodyCapped(req: IncomingMessage, maxBytes: number): Pr
|
|
|
28
28
|
let total = 0;
|
|
29
29
|
for await (const c of req) {
|
|
30
30
|
total += (c as Buffer).length;
|
|
31
|
-
if (total > maxBytes) throw new PayloadTooLargeError(maxBytes);
|
|
31
|
+
if (total > maxBytes) throw new PayloadTooLargeError(maxBytes, total);
|
|
32
32
|
chunks.push(c as Buffer);
|
|
33
33
|
}
|
|
34
34
|
const raw = Buffer.concat(chunks).toString('utf8');
|
|
@@ -44,7 +44,7 @@ export async function readRawBody(req: IncomingMessage, maxBytes = 256 * 1024):
|
|
|
44
44
|
let total = 0;
|
|
45
45
|
for await (const c of req) {
|
|
46
46
|
total += (c as Buffer).length;
|
|
47
|
-
if (total > maxBytes) throw new PayloadTooLargeError(maxBytes);
|
|
47
|
+
if (total > maxBytes) throw new PayloadTooLargeError(maxBytes, total);
|
|
48
48
|
chunks.push(c as Buffer);
|
|
49
49
|
}
|
|
50
50
|
return Buffer.concat(chunks).toString('utf8');
|