bailinghub 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.dockerignore +42 -0
- package/.env.example +83 -0
- package/.gitignore +44 -0
- package/.npmignore +56 -0
- package/CODE_OF_CONDUCT.md +24 -0
- package/CONTRIBUTING.md +74 -0
- package/Dockerfile +16 -0
- package/LICENSE +176 -0
- package/LICENSING.md +9 -0
- package/NOTICE +23 -0
- package/README.en.md +264 -0
- package/README.md +279 -0
- package/SECURITY.md +30 -0
- package/THIRD_PARTY_NOTICES.md +254 -0
- package/VISION.md +41 -0
- package/assets/architecture-overview.en-dark.png +0 -0
- package/assets/architecture-overview.en-dark.svg +57 -0
- package/assets/architecture-overview.en.png +0 -0
- package/assets/architecture-overview.en.svg +57 -0
- package/assets/architecture-overview.zh-CN-dark.png +0 -0
- package/assets/architecture-overview.zh-CN-dark.svg +57 -0
- package/assets/architecture-overview.zh-CN.png +0 -0
- package/assets/architecture-overview.zh-CN.svg +57 -0
- package/assets/bailinghub-lockup-dark.png +0 -0
- package/assets/bailinghub-lockup-dark.svg +8 -0
- package/assets/bailinghub-lockup.png +0 -0
- package/assets/bailinghub-lockup.svg +8 -0
- package/brain/README.en.md +23 -0
- package/brain/README.md +45 -0
- package/brain/agents/code-review.md +41 -0
- package/brain/agents/triage.md +37 -0
- package/brain/profiles.json +114 -0
- package/brain/runbooks/ticket-triage.md +24 -0
- package/config.example.json +58 -0
- package/contracts/client-api/consumers.json +28 -0
- package/contracts/client-api/v1/error-response.schema.json +21 -0
- package/contracts/client-api/v1/health-response.schema.json +13 -0
- package/contracts/client-api/v1/job-response.schema.json +49 -0
- package/contracts/client-api/v1/manifest.json +63 -0
- package/contracts/client-api/v1/run-request.schema.json +42 -0
- package/contracts/client-api/v1/submit-response.schema.json +35 -0
- package/contracts/client-api/v1/vectors.json +153 -0
- package/demo/business/Dockerfile +8 -0
- package/demo/business/server.mjs +483 -0
- package/docker-compose.images.yml +67 -0
- package/docker-compose.yml +79 -0
- package/docs/AI_FRIENDLY_TOOLS.en.md +69 -0
- package/docs/AI/345/217/213/345/245/275/345/267/245/345/205/267/350/256/276/350/256/241/346/214/207/345/215/227.md +198 -0
- package/docs/ARCHITECTURE.en.md +81 -0
- package/docs/ARCHITECTURE.md +795 -0
- package/docs/CHANGELOG.en.md +275 -0
- package/docs/CHANGELOG.md +279 -0
- package/docs/CHANNELS.en.md +35 -0
- package/docs/CHANNELS.md +72 -0
- package/docs/CLIENT_API.md +89 -0
- package/docs/COMPATIBILITY.en.md +103 -0
- package/docs/CONTRACT.en.md +254 -0
- package/docs/CONTRACT.md +653 -0
- package/docs/DEMO.en.md +90 -0
- package/docs/DEMO.md +297 -0
- package/docs/ECOSYSTEM.en.md +39 -0
- package/docs/ECOSYSTEM.md +39 -0
- package/docs/INDEPENDENT_VALIDATION.en.md +184 -0
- package/docs/INDEPENDENT_VALIDATION.md +184 -0
- package/docs/INTEGRATION.en.md +120 -0
- package/docs/KERNEL_HOST_API.en.md +59 -0
- package/docs/KERNEL_HOST_API.md +59 -0
- package/docs/OPERATIONS.en.md +182 -0
- package/docs/OPERATIONS.md +231 -0
- package/docs/PIPELINE.en.md +74 -0
- package/docs/PIPELINE.md +67 -0
- package/docs/QUICKSTART.en.md +297 -0
- package/docs/QUICKSTART.md +152 -0
- package/docs/README.en.md +103 -0
- package/docs/README.md +119 -0
- package/docs/RELEASE_NOTES_v0.1.0.en.md +46 -0
- package/docs/RELEASE_NOTES_v0.1.0.md +66 -0
- package/docs/RELEASE_NOTES_v0.1.1.en.md +38 -0
- package/docs/RELEASE_NOTES_v0.1.1.md +38 -0
- package/docs/RELEASE_NOTES_v0.1.10.en.md +102 -0
- package/docs/RELEASE_NOTES_v0.1.10.md +102 -0
- package/docs/RELEASE_NOTES_v0.1.11.en.md +99 -0
- package/docs/RELEASE_NOTES_v0.1.11.md +99 -0
- package/docs/RELEASE_NOTES_v0.1.12.en.md +64 -0
- package/docs/RELEASE_NOTES_v0.1.12.md +64 -0
- package/docs/RELEASE_NOTES_v0.1.13.en.md +46 -0
- package/docs/RELEASE_NOTES_v0.1.13.md +46 -0
- package/docs/RELEASE_NOTES_v0.1.14.en.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.14.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.15.en.md +50 -0
- package/docs/RELEASE_NOTES_v0.1.15.md +50 -0
- package/docs/RELEASE_NOTES_v0.1.16.en.md +106 -0
- package/docs/RELEASE_NOTES_v0.1.16.md +105 -0
- package/docs/RELEASE_NOTES_v0.1.2.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.1.2.md +39 -0
- package/docs/RELEASE_NOTES_v0.1.3.en.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.3.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.4.en.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.4.md +55 -0
- package/docs/RELEASE_NOTES_v0.1.5.en.md +49 -0
- package/docs/RELEASE_NOTES_v0.1.5.md +49 -0
- package/docs/RELEASE_NOTES_v0.1.6.en.md +41 -0
- package/docs/RELEASE_NOTES_v0.1.6.md +41 -0
- package/docs/RELEASE_NOTES_v0.1.7.en.md +39 -0
- package/docs/RELEASE_NOTES_v0.1.7.md +39 -0
- package/docs/RELEASE_NOTES_v0.1.8.en.md +88 -0
- package/docs/RELEASE_NOTES_v0.1.8.md +88 -0
- package/docs/RELEASE_NOTES_v0.1.9.en.md +127 -0
- package/docs/RELEASE_NOTES_v0.1.9.md +127 -0
- package/docs/RELEASE_NOTES_v0.2.0.en.md +95 -0
- package/docs/RELEASE_NOTES_v0.2.0.md +96 -0
- package/docs/RELEASE_NOTES_v0.3.0.en.md +77 -0
- package/docs/RELEASE_NOTES_v0.3.0.md +77 -0
- package/docs/SDK.en.md +177 -0
- package/docs/STREAMING.en.md +78 -0
- package/docs/STREAMING.md +109 -0
- package/docs/TOOLS.en.md +205 -0
- package/docs/TOOLS_DESIGN.en.md +142 -0
- package/docs/TOOLS_DESIGN.md +466 -0
- package/docs/TOOLS_MODEL.en.md +56 -0
- package/docs/TOOLS_MODEL.md +903 -0
- package/docs/WIDGET_RENDERERS.en.md +133 -0
- package/docs/WIDGET_RENDERERS.md +139 -0
- package/docs/examples/bailing-tool-verify.mjs +94 -0
- package/docs/examples/bailing-tool-verify.php +154 -0
- package/docs/examples/bailing-tool-verify.py +107 -0
- package/docs/examples/custom-streaming-chat-client.mjs +108 -0
- package/docs/examples/widget-chart-renderer-adapter.mjs +44 -0
- package/docs/integrations/bailian/README.en.md +181 -0
- package/docs/integrations/bailian/README.md +165 -0
- package/docs/integrations/bailian/bailian-mcp-config.json +17 -0
- package/docs/integrations/bailian/verify_recipe.py +97 -0
- package/docs/integrations/deepseek/README.en.md +225 -0
- package/docs/integrations/deepseek/README.md +225 -0
- package/docs/integrations/deepseek/verify_e2e.py +131 -0
- package/docs/integrations/dify/README.en.md +131 -0
- package/docs/integrations/dify/README.md +131 -0
- package/docs/integrations/dify/bailinghub-control-plane.openapi.json +129 -0
- package/docs/integrations/dify/verify_contract.py +88 -0
- package/docs/integrations/dify/verify_e2e.py +117 -0
- package/docs/integrations/jeecgboot/README.en.md +193 -0
- package/docs/integrations/jeecgboot/README.md +161 -0
- package/docs/integrations/jeecgboot/adapter-contract.v1.json +94 -0
- package/docs/integrations/jeecgboot/jeecgboot-user-adapter.openapi.json +183 -0
- package/docs/integrations/jeecgboot/verify_recipe.mjs +97 -0
- package/docs/integrations/ruoyi-vue-pro/README.en.md +91 -0
- package/docs/integrations/ruoyi-vue-pro/README.md +155 -0
- package/docs/integrations/ruoyi-vue-pro/adapter-contract.v1.json +71 -0
- package/docs/integrations/ruoyi-vue-pro/ruoyi-vue-pro-trade-adapter.openapi.json +148 -0
- package/docs/integrations/ruoyi-vue-pro/verify_recipe.mjs +71 -0
- package/docs/user-guide/README.en.md +39 -0
- package/docs/user-guide/README.md +40 -0
- package/docs/user-guide/concepts.en.md +69 -0
- package/docs/user-guide/concepts.md +225 -0
- package/docs/user-guide/console-map.en.md +58 -0
- package/docs/user-guide/console-map.md +473 -0
- package/docs/user-guide/overview.en.md +61 -0
- package/docs/user-guide/overview.md +156 -0
- package/docs/user-guide/scenarios.en.md +70 -0
- package/docs/user-guide/scenarios.md +398 -0
- package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +134 -0
- package/docs//347/254/254/344/270/211/346/226/271/345/257/271/346/216/245/346/214/207/345/215/227.md +625 -0
- package/package.json +119 -0
- package/schemas/agent-capability-contract.schema.json +104 -0
- package/schemas/api/approval-decision.schema.json +28 -0
- package/schemas/api/approval-request.schema.json +31 -0
- package/schemas/api/delivery-callback.schema.json +28 -0
- package/schemas/api/job-response.schema.json +6 -0
- package/schemas/api/kb-doc-upsert.schema.json +21 -0
- package/schemas/api/run-request.schema.json +6 -0
- package/schemas/api/run-response.schema.json +6 -0
- package/schemas/api/tool-spec.schema.json +38 -0
- package/schemas/config/alert-rule.schema.json +22 -0
- package/schemas/config/channel.schema.json +91 -0
- package/schemas/config/chat-entry.schema.json +47 -0
- package/schemas/config/client.schema.json +56 -0
- package/schemas/config/common.schema.json +215 -0
- package/schemas/config/credential.schema.json +48 -0
- package/schemas/config/executor-token.schema.json +20 -0
- package/schemas/config/page-context.schema.json +21 -0
- package/schemas/config/route.schema.json +152 -0
- package/schemas/config/storage-bucket.schema.json +31 -0
- package/schemas/config/target.schema.json +17 -0
- package/schemas/config/tool-provider.schema.json +60 -0
- package/schemas/tool-definition.schema.json +188 -0
- package/scripts/check-client-api-ecosystem.mjs +69 -0
- package/scripts/check-doc-links.mjs +136 -0
- package/scripts/check-image-tags.sh +43 -0
- package/scripts/check-package-artifact.mjs +185 -0
- package/scripts/check-release-consistency.mjs +199 -0
- package/scripts/check-release-consistency.test.mjs +63 -0
- package/scripts/client-api-contract-test.ts +127 -0
- package/scripts/create-admin.ts +27 -0
- package/scripts/demo-e2e.ts +133 -0
- package/scripts/docker-entrypoint.sh +33 -0
- package/scripts/doctor.ts +107 -0
- package/scripts/e2e-console.mjs +214 -0
- package/scripts/export-oss.mjs +204 -0
- package/scripts/generate-readme-assets.mjs +181 -0
- package/scripts/generate-third-party-notices.mjs +93 -0
- package/scripts/image-release-policy.mjs +75 -0
- package/scripts/image-release-policy.test.mjs +58 -0
- package/scripts/init-db.ts +21 -0
- package/scripts/install.sh +461 -0
- package/scripts/oss-boundary-check.mjs +183 -0
- package/scripts/publish-images.sh +63 -0
- package/scripts/publish-mysql-image.sh +41 -0
- package/scripts/release-audit.mjs +348 -0
- package/scripts/sdk-contract-test.ts +62 -0
- package/scripts/sdk-p1-check.mjs +58 -0
- package/scripts/sdk-runtime-test.mjs +106 -0
- package/scripts/security-scan.mjs +110 -0
- package/scripts/seed-demo.ts +116 -0
- package/scripts/selftest.ts +226 -0
- package/scripts/smoke.ts +31 -0
- package/scripts/validate-examples.mjs +93 -0
- package/scripts/verify-bootstrap-admin-restart.ts +66 -0
- package/scripts/verify-github-repo.mjs +195 -0
- package/scripts/verify-oss-export.mjs +192 -0
- package/scripts/verify-routing.ts +29 -0
- package/scripts/widget-renderer-test.mjs +206 -0
- package/scripts/write-build-info.mjs +29 -0
- package/sdk/dotnet/Bailing.Connect/Bailing.Connect.csproj +12 -0
- package/sdk/dotnet/Bailing.Connect/BailingConnect.cs +260 -0
- package/sdk/dotnet/README.md +32 -0
- package/sdk/dotnet/examples/BuildSpec/BuildSpec.csproj +11 -0
- package/sdk/dotnet/examples/BuildSpec/Program.cs +36 -0
- package/sdk/go/README.md +33 -0
- package/sdk/go/bailingconnect/connect.go +367 -0
- package/sdk/go/examples/build-spec/main.go +39 -0
- package/sdk/go/go.mod +3 -0
- package/sdk/java/README.md +43 -0
- package/sdk/java/examples/BuildSpec.java +31 -0
- package/sdk/java/src/main/java/com/bailing/connect/BailingConnect.java +376 -0
- package/sdk/node/README.md +107 -0
- package/sdk/node/examples/build-spec.mjs +84 -0
- package/sdk/node/package.json +22 -0
- package/sdk/node/src/index.mjs +250 -0
- package/sdk/php/README.md +204 -0
- package/sdk/php/composer.json +18 -0
- package/sdk/php/examples/DemoStaffController.php +108 -0
- package/sdk/php/examples/build-spec.php +27 -0
- package/sdk/php/examples/thinkphp-integration.php +81 -0
- package/sdk/php/src/Attributes/AiParam.php +40 -0
- package/sdk/php/src/Attributes/AiTool.php +75 -0
- package/sdk/php/src/HubClient.php +122 -0
- package/sdk/php/src/SpecBuilder.php +328 -0
- package/sdk/php/src/SpecServer.php +209 -0
- package/sdk/php/src/Ticket.php +37 -0
- package/sdk/php/src/Verify.php +178 -0
- package/sdk/php7/README.md +191 -0
- package/sdk/php7/composer.json +18 -0
- package/sdk/php7/examples/build-spec.php +68 -0
- package/sdk/php7/examples/well-known.php +33 -0
- package/sdk/php7/src/HubClient.php +111 -0
- package/sdk/php7/src/SpecServer.php +203 -0
- package/sdk/php7/src/Ticket.php +33 -0
- package/sdk/php7/src/ToolDef.php +169 -0
- package/sdk/php7/src/ToolSpec.php +334 -0
- package/sdk/php7/src/Verify.php +165 -0
- package/sdk/python/README.md +107 -0
- package/sdk/python/bailing_connect/__init__.py +307 -0
- package/sdk/python/examples/build_spec.py +90 -0
- package/sdk/python/pyproject.toml +24 -0
- package/sql/001_init_state.sql +66 -0
- package/sql/002_routes.sql +44 -0
- package/sql/003_executor.sql +15 -0
- package/sql/004_clients.sql +22 -0
- package/sql/005_admins.sql +25 -0
- package/sql/006_ledger.sql +57 -0
- package/sql/007_delivery.sql +8 -0
- package/sql/008_kb.sql +66 -0
- package/sql/009_rbac.sql +5 -0
- package/sql/010_targets.sql +28 -0
- package/sql/011_observability.sql +11 -0
- package/sql/012_generic.sql +5 -0
- package/sql/013_tools.sql +24 -0
- package/sql/014_approvals.sql +27 -0
- package/sql/015_chat.sql +21 -0
- package/sql/016_chat_feedback.sql +19 -0
- package/sql/017_provider_autorefresh.sql +6 -0
- package/sql/018_kb_ingest.sql +11 -0
- package/sql/019_kb_datasources.sql +32 -0
- package/sql/022_storage_buckets.sql +25 -0
- package/sql/024_channels.sql +15 -0
- package/sql/025_chat_appearance.sql +7 -0
- package/sql/026_thread_memory.sql +10 -0
- package/sql/027_page_contexts.sql +23 -0
- package/sql/028_executor_capabilities.sql +4 -0
- package/sql/029_executor_tokens.sql +13 -0
- package/sql/030_route_permission.sql +5 -0
- package/sql/031_tool_embeddings.sql +20 -0
- package/sql/032_tool_provider_embed.sql +7 -0
- package/sql/033_alert_rules.sql +21 -0
- package/sql/034_client_allowed_channels.sql +6 -0
- package/sql/035_tool_idempotency.sql +15 -0
- package/sql/036_delivery_dlq.sql +15 -0
- package/sql/038_audit_trace_shape.sql +15 -0
- package/sql/039_runtime_locks.sql +9 -0
- package/sql/040_budget_policy.sql +3 -0
- package/sql/041_approval_intent.sql +14 -0
- package/sql/042_approval_decision_contract.sql +11 -0
- package/sql/043_rate_limits.sql +7 -0
- package/sql/044_job_run_after.sql +3 -0
- package/sql/045_job_claim_lease.sql +7 -0
- package/sql/046_tool_authz_probe.sql +5 -0
- package/sql/047_route_audience.sql +4 -0
- package/sql/048_llm_target.sql +17 -0
- package/sql/049_llm_input_shape.sql +11 -0
- package/sql/050_operational_metrics_indexes.sql +8 -0
- package/sql/051_instance_branding.sql +17 -0
- package/sql/052_tool_execution_journal.sql +19 -0
- package/sql/053_tool_spec_access_policy.sql +9 -0
- package/sql/README.en.md +41 -0
- package/sql/README.md +40 -0
- package/src/adapters/channels/wecom-api.test.ts +77 -0
- package/src/adapters/channels/wecom-api.ts +224 -0
- package/src/adapters/channels/wecom-crypto.test.ts +85 -0
- package/src/adapters/channels/wecom-crypto.ts +77 -0
- package/src/adapters/executors/claudecode.ts +39 -0
- package/src/adapters/executors/profiles.ts +86 -0
- package/src/adapters/executors/report.ts +35 -0
- package/src/adapters/executors/runner.ts +114 -0
- package/src/adapters/executors/wecomnotify.ts +63 -0
- package/src/adapters/llm/file.test.ts +81 -0
- package/src/adapters/llm/file.ts +250 -0
- package/src/adapters/llm/openai-chat-stream.test.ts +74 -0
- package/src/adapters/llm/openai-chat-stream.ts +154 -0
- package/src/adapters/llm/perception.ts +159 -0
- package/src/adapters/llm/speech.test.ts +75 -0
- package/src/adapters/llm/speech.ts +146 -0
- package/src/adapters/storage/object-storage.test.ts +38 -0
- package/src/adapters/storage/object-storage.ts +140 -0
- package/src/adapters/targets/demo-agent.ts +88 -0
- package/src/adapters/targets/llm.test.ts +733 -0
- package/src/adapters/targets/llm.ts +862 -0
- package/src/app/admin-bootstrap.test.ts +112 -0
- package/src/app/admin-bootstrap.ts +48 -0
- package/src/app/auth-default.ts +26 -0
- package/src/app/auth.test.ts +57 -0
- package/src/app/auth.ts +207 -0
- package/src/app/builtin-tools-default.ts +17 -0
- package/src/app/builtin-tools.test.ts +202 -0
- package/src/app/builtin-tools.ts +380 -0
- package/src/app/channels-default.ts +8 -0
- package/src/app/channels.ts +141 -0
- package/src/app/delivery-default.ts +14 -0
- package/src/app/delivery.test.ts +46 -0
- package/src/app/delivery.ts +215 -0
- package/src/app/engine-default.ts +54 -0
- package/src/app/engine.ts +427 -0
- package/src/app/http-mount.test.ts +27 -0
- package/src/app/http-server.test.ts +114 -0
- package/src/app/http-server.ts +127 -0
- package/src/app/http.test.ts +27 -0
- package/src/app/http.ts +118 -0
- package/src/app/kernel.test.ts +191 -0
- package/src/app/kernel.ts +544 -0
- package/src/app/monitor-default.ts +9 -0
- package/src/app/monitor.ts +46 -0
- package/src/app/operational-metrics.test.ts +73 -0
- package/src/app/operational-metrics.ts +124 -0
- package/src/app/oss-edition.test.ts +71 -0
- package/src/app/oss-edition.ts +108 -0
- package/src/app/outbound-default.ts +57 -0
- package/src/app/outbound.ts +133 -0
- package/src/app/readiness.test.ts +37 -0
- package/src/app/readiness.ts +39 -0
- package/src/app/runtime-composition.test.ts +51 -0
- package/src/app/runtime-composition.ts +73 -0
- package/src/app/runtime-context-default.ts +30 -0
- package/src/app/runtime-context.test.ts +60 -0
- package/src/app/runtime-context.ts +79 -0
- package/src/app/runtime-lifecycle-default.ts +48 -0
- package/src/app/runtime-lifecycle.test.ts +322 -0
- package/src/app/runtime-lifecycle.ts +440 -0
- package/src/app/runtime.ts +36 -0
- package/src/app/tool-approvals-default.ts +16 -0
- package/src/app/tool-approvals.ts +214 -0
- package/src/app/tool-assembly-default.ts +11 -0
- package/src/app/tool-assembly.test.ts +112 -0
- package/src/app/tool-assembly.ts +83 -0
- package/src/app/tool-context-default.ts +7 -0
- package/src/app/tool-context.test.ts +82 -0
- package/src/app/tool-context.ts +109 -0
- package/src/app/tool-debug.test.ts +111 -0
- package/src/app/tool-debug.ts +152 -0
- package/src/app/tool-proxy-default.ts +35 -0
- package/src/app/tool-proxy.ts +173 -0
- package/src/app/tool-specs-default.ts +33 -0
- package/src/app/tool-specs.test.ts +322 -0
- package/src/app/tool-specs.ts +555 -0
- package/src/app/tools-runtime-default.ts +14 -0
- package/src/app/tools-runtime.ts +23 -0
- package/src/architecture-boundary.test.ts +119 -0
- package/src/core/config/config-codec.test.ts +105 -0
- package/src/core/config/config-codec.ts +231 -0
- package/src/core/config/config-diagnostics.test.ts +285 -0
- package/src/core/config/config-diagnostics.ts +436 -0
- package/src/core/config/config-models.test.ts +584 -0
- package/src/core/config/config-models.ts +392 -0
- package/src/core/config/config-schema.test.ts +153 -0
- package/src/core/config/config.test.ts +314 -0
- package/src/core/config/config.ts +324 -0
- package/src/core/config/route-config.test.ts +232 -0
- package/src/core/config/route-config.ts +246 -0
- package/src/core/config/target-config.test.ts +139 -0
- package/src/core/config/target-config.ts +219 -0
- package/src/core/config/tools-config.test.ts +124 -0
- package/src/core/config/tools-config.ts +126 -0
- package/src/core/contracts/approval-decision.test.ts +67 -0
- package/src/core/contracts/approval-decision.ts +93 -0
- package/src/core/contracts/openapi-tools.ts +201 -0
- package/src/core/contracts/tool-annotations.ts +121 -0
- package/src/core/contracts/tool-definition.test.ts +147 -0
- package/src/core/contracts/tool-definition.ts +304 -0
- package/src/core/contracts/tools-idempotency.test.ts +435 -0
- package/src/core/contracts/tools.test.ts +487 -0
- package/src/core/contracts/tools.ts +831 -0
- package/src/core/contracts/types.ts +408 -0
- package/src/core/edition/capabilities.ts +6 -0
- package/src/core/edition/context.test.ts +20 -0
- package/src/core/edition/context.ts +78 -0
- package/src/core/edition/index.ts +4 -0
- package/src/core/edition/scope-resolver.ts +24 -0
- package/src/core/edition/store-factory.ts +6 -0
- package/src/core/observability/openmetrics.test.ts +57 -0
- package/src/core/observability/openmetrics.ts +103 -0
- package/src/core/platform/content.test.ts +46 -0
- package/src/core/platform/content.ts +90 -0
- package/src/core/platform/fence.test.ts +31 -0
- package/src/core/platform/fence.ts +11 -0
- package/src/core/platform/instance-branding.test.ts +65 -0
- package/src/core/platform/instance-branding.ts +202 -0
- package/src/core/platform/metrics-token.test.ts +31 -0
- package/src/core/platform/metrics-token.ts +42 -0
- package/src/core/platform/pagecontext.ts +0 -0
- package/src/core/platform/password.test.ts +13 -0
- package/src/core/platform/password.ts +38 -0
- package/src/core/platform/queue.test.ts +59 -0
- package/src/core/platform/queue.ts +75 -0
- package/src/core/platform/serial.test.ts +73 -0
- package/src/core/platform/serial.ts +64 -0
- package/src/core/platform/server-token.test.ts +46 -0
- package/src/core/platform/server-token.ts +60 -0
- package/src/core/platform/signing.test.ts +24 -0
- package/src/core/platform/signing.ts +22 -0
- package/src/core/platform/time.ts +73 -0
- package/src/core/platform/version.test.ts +19 -0
- package/src/core/platform/version.ts +90 -0
- package/src/core/runtime/budget-runtime.test.ts +93 -0
- package/src/core/runtime/budget-runtime.ts +110 -0
- package/src/core/runtime/context-runtime.test.ts +106 -0
- package/src/core/runtime/context-runtime.ts +95 -0
- package/src/core/runtime/credential-resolver.test.ts +129 -0
- package/src/core/runtime/credential-resolver.ts +93 -0
- package/src/core/runtime/credential-verify.test.ts +76 -0
- package/src/core/runtime/credential-verify.ts +161 -0
- package/src/core/runtime/debug-report.test.ts +20 -0
- package/src/core/runtime/debug-report.ts +100 -0
- package/src/core/runtime/execution-runtime.test.ts +350 -0
- package/src/core/runtime/execution-runtime.ts +197 -0
- package/src/core/runtime/finish-runtime.test.ts +168 -0
- package/src/core/runtime/finish-runtime.ts +83 -0
- package/src/core/runtime/identity-runtime.test.ts +38 -0
- package/src/core/runtime/identity-runtime.ts +104 -0
- package/src/core/runtime/inhub-runtime.test.ts +297 -0
- package/src/core/runtime/inhub-runtime.ts +198 -0
- package/src/core/runtime/job-stream.test.ts +55 -0
- package/src/core/runtime/job-stream.ts +187 -0
- package/src/core/runtime/knowledge-runtime.test.ts +120 -0
- package/src/core/runtime/knowledge-runtime.ts +98 -0
- package/src/core/runtime/launch-runtime.test.ts +187 -0
- package/src/core/runtime/launch-runtime.ts +182 -0
- package/src/core/runtime/memory-runtime.test.ts +85 -0
- package/src/core/runtime/memory-runtime.ts +32 -0
- package/src/core/runtime/memory.ts +141 -0
- package/src/core/runtime/redaction-runtime.test.ts +35 -0
- package/src/core/runtime/redaction-runtime.ts +60 -0
- package/src/core/runtime/routing-runtime.test.ts +89 -0
- package/src/core/runtime/routing-runtime.ts +146 -0
- package/src/core/runtime/smoke-runtime.test.ts +65 -0
- package/src/core/runtime/smoke-runtime.ts +237 -0
- package/src/core/runtime/summary-runtime.test.ts +234 -0
- package/src/core/runtime/summary-runtime.ts +153 -0
- package/src/core/runtime/trace-runtime.test.ts +234 -0
- package/src/core/runtime/trace-runtime.ts +330 -0
- package/src/core/state/audit-observability.test.ts +51 -0
- package/src/core/state/audit-observability.ts +74 -0
- package/src/core/state/state-codec.ts +44 -0
- package/src/core/state/state-contracts.ts +59 -0
- package/src/core/targets/adapter.ts +69 -0
- package/src/core/targets/registry.test.ts +65 -0
- package/src/core/targets/registry.ts +153 -0
- package/src/core/targets/resolve.ts +21 -0
- package/src/executor.ts +201 -0
- package/src/extension-api.test.ts +84 -0
- package/src/extension-api.ts +194 -0
- package/src/infrastructure/config/config-admin-repository.test.ts +193 -0
- package/src/infrastructure/config/config-admin-repository.ts +175 -0
- package/src/infrastructure/config/config-alert-rule-repository.ts +38 -0
- package/src/infrastructure/config/config-approval-ledger.ts +74 -0
- package/src/infrastructure/config/config-channel-repository.ts +31 -0
- package/src/infrastructure/config/config-chat-repository.ts +83 -0
- package/src/infrastructure/config/config-client-repository.ts +46 -0
- package/src/infrastructure/config/config-conversation-ledger.ts +222 -0
- package/src/infrastructure/config/config-credential-repository.test.ts +32 -0
- package/src/infrastructure/config/config-credential-repository.ts +47 -0
- package/src/infrastructure/config/config-delivery-dlq-ledger.ts +49 -0
- package/src/infrastructure/config/config-executor-ledger.ts +30 -0
- package/src/infrastructure/config/config-executor-token-repository.ts +44 -0
- package/src/infrastructure/config/config-instance-branding-repository.ts +75 -0
- package/src/infrastructure/config/config-knowledge-repository.ts +249 -0
- package/src/infrastructure/config/config-observability-ledger.ts +262 -0
- package/src/infrastructure/config/config-project-repository.ts +30 -0
- package/src/infrastructure/config/config-rate-limit-ledger.ts +56 -0
- package/src/infrastructure/config/config-route-repository.ts +41 -0
- package/src/infrastructure/config/config-storage-bucket-repository.ts +43 -0
- package/src/infrastructure/config/config-target-repository.ts +25 -0
- package/src/infrastructure/config/config-tool-call-ledger.ts +142 -0
- package/src/infrastructure/config/config-tool-embedding-repository.test.ts +124 -0
- package/src/infrastructure/config/config-tool-embedding-repository.ts +78 -0
- package/src/infrastructure/config/config-tool-provider-repository.test.ts +71 -0
- package/src/infrastructure/config/config-tool-provider-repository.ts +50 -0
- package/src/infrastructure/config/configstore.ts +130 -0
- package/src/infrastructure/config/local-instance-branding-provider.test.ts +94 -0
- package/src/infrastructure/config/local-instance-branding-provider.ts +79 -0
- package/src/infrastructure/mysql/pool-owner.test.ts +36 -0
- package/src/infrastructure/mysql/pool-owner.ts +56 -0
- package/src/infrastructure/schema/core-schema-migrator.test.ts +340 -0
- package/src/infrastructure/schema/core-schema-migrator.ts +461 -0
- package/src/infrastructure/schema/migration-files.test.ts +18 -0
- package/src/infrastructure/schema/migration-files.ts +27 -0
- package/src/infrastructure/schema/retired-migrations.ts +35 -0
- package/src/infrastructure/state/operational-metrics-storage.test.ts +107 -0
- package/src/infrastructure/state/state-jsonl.ts +268 -0
- package/src/infrastructure/state/state-mysql-update-plan.test.ts +54 -0
- package/src/infrastructure/state/state-mysql-update-plan.ts +63 -0
- package/src/infrastructure/state/state-mysql.ts +359 -0
- package/src/infrastructure/state/state.test.ts +319 -0
- package/src/infrastructure/state/state.ts +11 -0
- package/src/kernel-api/v1/artifact.test.ts +46 -0
- package/src/kernel-api/v1/artifact.ts +71 -0
- package/src/kernel-api/v1/contracts.ts +168 -0
- package/src/kernel-api/v1/execution-gate.test.ts +25 -0
- package/src/kernel-api/v1/execution-gate.ts +18 -0
- package/src/kernel-api/v1/index.ts +51 -0
- package/src/openclaw-stdio.test.ts +60 -0
- package/src/routes/admin-access-default.ts +20 -0
- package/src/routes/admin-access.ts +94 -0
- package/src/routes/admin-branding.test.ts +116 -0
- package/src/routes/admin-branding.ts +48 -0
- package/src/routes/admin-chat-default.ts +12 -0
- package/src/routes/admin-chat.ts +84 -0
- package/src/routes/admin-default.ts +35 -0
- package/src/routes/admin-dispatch-config-default.ts +13 -0
- package/src/routes/admin-dispatch-config.ts +121 -0
- package/src/routes/admin-format.ts +12 -0
- package/src/routes/admin-host.test.ts +56 -0
- package/src/routes/admin-infra-default.ts +12 -0
- package/src/routes/admin-infra.ts +142 -0
- package/src/routes/admin-kb-default.ts +13 -0
- package/src/routes/admin-kb.ts +160 -0
- package/src/routes/admin-runtime-default.ts +31 -0
- package/src/routes/admin-runtime.ts +444 -0
- package/src/routes/admin-tool-providers-default.ts +20 -0
- package/src/routes/admin-tool-providers.test.ts +114 -0
- package/src/routes/admin-tool-providers.ts +186 -0
- package/src/routes/admin.ts +246 -0
- package/src/routes/approvals-default.ts +32 -0
- package/src/routes/approvals.ts +120 -0
- package/src/routes/chat-default.ts +61 -0
- package/src/routes/chat-mount.test.ts +58 -0
- package/src/routes/chat.test.ts +222 -0
- package/src/routes/chat.ts +478 -0
- package/src/routes/critical-routes.test.ts +292 -0
- package/src/routes/executor-default.ts +45 -0
- package/src/routes/executor.ts +226 -0
- package/src/routes/kb-default.ts +23 -0
- package/src/routes/kb.ts +92 -0
- package/src/routes/private-default.ts +38 -0
- package/src/routes/private-host-auth.test.ts +84 -0
- package/src/routes/private.ts +210 -0
- package/src/routes/public-default.ts +46 -0
- package/src/routes/public.test.ts +504 -0
- package/src/routes/public.ts +313 -0
- package/src/routes/run-default.ts +25 -0
- package/src/routes/run.ts +188 -0
- package/src/routes/send-default.ts +24 -0
- package/src/routes/send.ts +143 -0
- package/src/routes/wecom-default.ts +27 -0
- package/src/routes/wecom.ts +307 -0
- package/src/server.ts +13 -0
- package/src/services/embedding.test.ts +185 -0
- package/src/services/embedding.ts +138 -0
- package/src/services/kb-repository.ts +79 -0
- package/src/services/kb.ts +328 -0
- package/src/services/kbsync.ts +166 -0
- package/src/services/tool-index-repository.ts +50 -0
- package/src/services/tools-index.test.ts +756 -0
- package/src/services/tools-index.ts +427 -0
- package/tsconfig.json +17 -0
- package/web/connect/bailing-connect-php.tgz +0 -0
- package/web/connect/bailing-connect-php7.tgz +0 -0
- package/web/connect/executor.mjs +152 -0
- package/web/connect/openclaw-stdio.mjs +145 -0
- package/web/connect/skills/connect-bailinghub-executor/SKILL.md +97 -0
- package/web/connect/skills/connect-bailinghub-executor/agents/openai.yaml +4 -0
- package/web/connect/skills/connect-bailinghub-executor/references/direct-protocol.md +99 -0
- package/web/connect/skills/connect-bailinghub-executor/references/openclaw.md +39 -0
- package/web/console/assets/Accounts-B4ePH5jp.css +1 -0
- package/web/console/assets/Accounts-Dwzm4D_V.js +3 -0
- package/web/console/assets/Approvals-BxhuI0ku.js +1 -0
- package/web/console/assets/Approvals-DlTSHl_7.css +1 -0
- package/web/console/assets/Audit-CSu6_3oD.css +1 -0
- package/web/console/assets/Audit-dFAbGynl.js +1 -0
- package/web/console/assets/BrandLockup-BtZyvkM5.js +1 -0
- package/web/console/assets/BrandLockup-DKYBYzKU.css +1 -0
- package/web/console/assets/Channels-CCn0L1jg.css +1 -0
- package/web/console/assets/Channels-Dqg4-_yr.js +105 -0
- package/web/console/assets/ChatEntries-BweMx_CU.css +1 -0
- package/web/console/assets/ChatEntries-CEGZ3NnJ.js +7 -0
- package/web/console/assets/Clients-C0QD1x7g.js +3 -0
- package/web/console/assets/Clients-DcTYN-Js.css +1 -0
- package/web/console/assets/Cost-BAJqLhpK.js +1 -0
- package/web/console/assets/Cost-CjT39DSZ.css +1 -0
- package/web/console/assets/Credentials-D_GDRgWi.js +1 -0
- package/web/console/assets/Credentials-ioLP0qYN.css +1 -0
- package/web/console/assets/Diagnostics-BWYnDxRj.js +1 -0
- package/web/console/assets/Diagnostics-Ya05PTDp.css +1 -0
- package/web/console/assets/Executors-CjhEM54c.css +1 -0
- package/web/console/assets/Executors-Cmryk4Vk.js +1 -0
- package/web/console/assets/HelpTip-CA6Bm7Nx.css +1 -0
- package/web/console/assets/HelpTip-CT07o3kB.js +1 -0
- package/web/console/assets/Kb-BSXQE0Fa.js +5 -0
- package/web/console/assets/Kb-CzIzd9xr.css +1 -0
- package/web/console/assets/Login-BnBPqC8Z.js +1 -0
- package/web/console/assets/Login-xtPwDB5_.css +1 -0
- package/web/console/assets/Projects-Bm8AjsNx.css +1 -0
- package/web/console/assets/Projects-CNHx4L_7.js +1 -0
- package/web/console/assets/Routes-DWGQN5Pv.css +1 -0
- package/web/console/assets/Routes-u5cEAEXQ.js +124 -0
- package/web/console/assets/Runs-BeFUR77_.js +3 -0
- package/web/console/assets/Runs-CUtSsPW-.css +1 -0
- package/web/console/assets/Setup-BjZfrmfN.js +1 -0
- package/web/console/assets/Setup-QjlHZKdB.css +1 -0
- package/web/console/assets/Shell-CbGNTN91.css +1 -0
- package/web/console/assets/Shell-EJuYf3OO.js +1 -0
- package/web/console/assets/StorageBuckets-DMXRJxUA.js +1 -0
- package/web/console/assets/StorageBuckets-GnXnVvF0.css +1 -0
- package/web/console/assets/SystemSettings-B72F-loY.js +1 -0
- package/web/console/assets/SystemSettings-BjiHyrXO.css +1 -0
- package/web/console/assets/SystemStatus-I11I67rw.css +1 -0
- package/web/console/assets/SystemStatus-hOj_TPYE.js +1 -0
- package/web/console/assets/Targets-DTb5tn6z.css +1 -0
- package/web/console/assets/Targets-UVVf7twC.js +1 -0
- package/web/console/assets/Tools-A20oaMaQ.css +1 -0
- package/web/console/assets/Tools-ihkr9R9x.js +2 -0
- package/web/console/assets/_plugin-vue_export-helper-DlAUqK2U.js +1 -0
- package/web/console/assets/docs-DPUOCa7R.js +1 -0
- package/web/console/assets/index-DZEQL_yy.js +1 -0
- package/web/console/assets/index-DxvruykG.js +2 -0
- package/web/console/assets/index-Fi9gkGxV.css +1 -0
- package/web/console/assets/llm-catalog-HwRIrS94.js +1 -0
- package/web/console/assets/request-BisL2T9B.js +1 -0
- package/web/console/assets/schema-CzpUpoLk.js +1 -0
- package/web/console/assets/util-SiQC2MJh.js +1 -0
- package/web/console/assets/vendor-element-D7WRzHhy.js +37 -0
- package/web/console/assets/vendor-mammoth-DvgsHdlx.js +231 -0
- package/web/console/assets/vendor-turndown-kLzRgxYD.js +61 -0
- package/web/console/assets/vendor-vue-B2uhHUfE.js +29 -0
- package/web/console/index.html +16 -0
- package/web/widget/widget.js +1490 -0
- package/web-admin/index.html +13 -0
- package/web-admin/package-lock.json +1854 -0
- package/web-admin/package.json +25 -0
- package/web-admin/src/App.vue +9 -0
- package/web-admin/src/branding.ts +90 -0
- package/web-admin/src/components/BrandLockup.vue +40 -0
- package/web-admin/src/components/HelpTip.vue +51 -0
- package/web-admin/src/components/RichText.vue +35 -0
- package/web-admin/src/docs.ts +16 -0
- package/web-admin/src/layout/Shell.vue +356 -0
- package/web-admin/src/llm-catalog.ts +129 -0
- package/web-admin/src/main.ts +116 -0
- package/web-admin/src/pages/Accounts.vue +162 -0
- package/web-admin/src/pages/Approvals.vue +179 -0
- package/web-admin/src/pages/Audit.vue +110 -0
- package/web-admin/src/pages/Channels.vue +738 -0
- package/web-admin/src/pages/ChatEntries.vue +778 -0
- package/web-admin/src/pages/Clients.vue +353 -0
- package/web-admin/src/pages/Cost.vue +314 -0
- package/web-admin/src/pages/Credentials.vue +418 -0
- package/web-admin/src/pages/Diagnostics.vue +440 -0
- package/web-admin/src/pages/Executors.vue +398 -0
- package/web-admin/src/pages/Kb.vue +698 -0
- package/web-admin/src/pages/Login.vue +314 -0
- package/web-admin/src/pages/Projects.vue +106 -0
- package/web-admin/src/pages/Routes.vue +1661 -0
- package/web-admin/src/pages/Runs.vue +1113 -0
- package/web-admin/src/pages/Setup.vue +354 -0
- package/web-admin/src/pages/StorageBuckets.vue +182 -0
- package/web-admin/src/pages/SystemSettings.vue +281 -0
- package/web-admin/src/pages/SystemStatus.vue +185 -0
- package/web-admin/src/pages/Targets.vue +193 -0
- package/web-admin/src/pages/Tools.vue +1051 -0
- package/web-admin/src/request.ts +18 -0
- package/web-admin/src/router.ts +142 -0
- package/web-admin/src/runtime-path.ts +27 -0
- package/web-admin/src/schema.ts +52 -0
- package/web-admin/src/store.ts +35 -0
- package/web-admin/src/styles/base.css +272 -0
- package/web-admin/src/table-widths.ts +603 -0
- package/web-admin/src/util.ts +16 -0
- package/web-admin/tsconfig.json +15 -0
- package/web-admin/vite.config.ts +35 -0
|
@@ -0,0 +1,831 @@
|
|
|
1
|
+
// 工具插座运行时治理核心——设计与安全边界见 docs/TOOLS_DESIGN.md
|
|
2
|
+
// 职责:消费 ToolDefinition → 白名单/主体/审批/限流/审计/签名 → 给大脑可调用的运行时句柄。
|
|
3
|
+
// 中枢只做 reach(白名单/风险闸/限流/签名/审计);authority(这个人能不能做)永远由业务侧验签后裁决。
|
|
4
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
5
|
+
import type { ToolProvider } from './types';
|
|
6
|
+
import { schemaAtPath, schemaTypes, valueMatchesSchemaType, type ToolConfirmCondition, type ToolDefinition } from './tool-definition';
|
|
7
|
+
import { toolSummary } from './tool-definition';
|
|
8
|
+
|
|
9
|
+
/** 路由 allow 白名单匹配:精确 scope 或前缀通配("tenant.staff.*")。 */
|
|
10
|
+
export function scopeAllowed(scope: string, allow: string[]): boolean {
|
|
11
|
+
for (const a of allow) {
|
|
12
|
+
if (a === scope) return true;
|
|
13
|
+
if (a.endsWith('.*') && scope.startsWith(a.slice(0, -1))) return true;
|
|
14
|
+
if (a === '*') return true;
|
|
15
|
+
}
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 工具通道唯一签名(工具调用 + spec 拉取共用同一套构造):
|
|
21
|
+
* `sha256=` + HMAC_SHA256(secret, "<ts>.<METHOD>.<path?query>.<sha256hex(body)>.<On-Behalf-Of>.<Job-Id>")
|
|
22
|
+
* 返回值已含方案标签前缀 `sha256=`,可直接作 X-Bailing-Signature 头值。
|
|
23
|
+
*
|
|
24
|
+
* - 标签 `sha256` 是【算法名】不是版本号(GitHub webhook 同款约定);构造细节见 CONTRACT §2.4b。
|
|
25
|
+
* - On-Behalf-Of + Job-Id 并入签名材料,杜绝"窗口内重放合法请求、只改这两个头换租户/绕幂等"。
|
|
26
|
+
* - spec 拉取无操作主体/任务:onBehalfOf/jobId 传空串即可(同一套构造、尾部为空)。
|
|
27
|
+
*/
|
|
28
|
+
export function signToolCall(secret: string, ts: number, method: string, pathWithQuery: string, body: string, onBehalfOf = '', jobId = ''): string {
|
|
29
|
+
const bodyHash = createHash('sha256').update(body, 'utf8').digest('hex');
|
|
30
|
+
const mac = createHmac('sha256', secret).update(`${ts}.${method}.${pathWithQuery}.${bodyHash}.${onBehalfOf}.${jobId}`).digest('hex');
|
|
31
|
+
return `sha256=${mac}`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 调用参数的规范化哈希:递归按键名排序后 JSON 化再 sha256。审批单按它精确匹配"当时那个调用"(键序不同不算换动作)。 */
|
|
35
|
+
export function argsHash(args: Record<string, unknown>): string {
|
|
36
|
+
return createHash('sha256').update(canonicalJson(args ?? {}), 'utf8').digest('hex');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type ToolExecutionJournalState =
|
|
40
|
+
| 'dispatching'
|
|
41
|
+
| 'response_recorded'
|
|
42
|
+
| 'completed'
|
|
43
|
+
| 'uncertain'
|
|
44
|
+
| 'evidence_degraded';
|
|
45
|
+
|
|
46
|
+
export interface ToolExecutionJournalEntry {
|
|
47
|
+
state: ToolExecutionJournalState;
|
|
48
|
+
ok: boolean;
|
|
49
|
+
status: number;
|
|
50
|
+
text: string;
|
|
51
|
+
idempotencyKey: string;
|
|
52
|
+
error?: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ToolExecutionJournalRecord extends ToolExecutionJournalEntry {
|
|
56
|
+
jobId: string;
|
|
57
|
+
tool: string;
|
|
58
|
+
scope: string;
|
|
59
|
+
argsHash: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ToolExecutionUncertainty {
|
|
63
|
+
state: Exclude<ToolExecutionJournalState, 'completed'>;
|
|
64
|
+
tool: string;
|
|
65
|
+
scope: string;
|
|
66
|
+
idempotency_key: string;
|
|
67
|
+
reason: string;
|
|
68
|
+
message: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 稳定的下游幂等键。业务系统可据此去重,但仍必须独立完成鉴权与业务授权。 */
|
|
72
|
+
export function toolCallIdempotencyKey(jobId: string, tool: string, hash: string, onBehalfOf = ''): string {
|
|
73
|
+
return createHash('sha256')
|
|
74
|
+
.update(canonicalJson({ job_id: jobId, tool, args_hash: hash, on_behalf_of: onBehalfOf }), 'utf8')
|
|
75
|
+
.digest('hex');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function canonicalJson(v: unknown): string {
|
|
79
|
+
if (v === null) return 'null';
|
|
80
|
+
if (Array.isArray(v)) return `[${v.map((item) => canonicalJsonArrayValue(item)).join(',')}]`;
|
|
81
|
+
if (typeof v === 'object') {
|
|
82
|
+
const record = v as Record<string, unknown>;
|
|
83
|
+
const keys = Object.keys(record).filter((key) => !isJsonOmitted(record[key])).sort();
|
|
84
|
+
return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`;
|
|
85
|
+
}
|
|
86
|
+
return JSON.stringify(v) ?? 'null';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function canonicalJsonArrayValue(v: unknown): string {
|
|
90
|
+
return isJsonOmitted(v) ? 'null' : canonicalJson(v);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isJsonOmitted(v: unknown): boolean {
|
|
94
|
+
return v === undefined || typeof v === 'function' || typeof v === 'symbol';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function normalizeToolArgs(args: Record<string, unknown>): { ok: true; args: Record<string, unknown> } | { ok: false; error: string } {
|
|
98
|
+
try {
|
|
99
|
+
// 以实际 HTTP JSON 语义为准:对象中的 undefined 被省略、数组中的 undefined 变为 null。
|
|
100
|
+
// 审批快照、幂等哈希和外发请求必须消费同一份规范化参数。
|
|
101
|
+
const encoded = JSON.stringify(args);
|
|
102
|
+
if (!encoded) return { ok: false, error: 'tool_args_not_json_object' };
|
|
103
|
+
const decoded: unknown = JSON.parse(encoded);
|
|
104
|
+
if (!isRecord(decoded)) return { ok: false, error: 'tool_args_not_json_object' };
|
|
105
|
+
return { ok: true, args: decoded };
|
|
106
|
+
} catch {
|
|
107
|
+
return { ok: false, error: 'tool_args_not_json_serializable' };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
112
|
+
return !!value && typeof value === 'object' && !Array.isArray(value);
|
|
113
|
+
}
|
|
114
|
+
function escapeRegExp(s: string): string {
|
|
115
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 工具响应给模型的视图与审计证据分离:
|
|
120
|
+
* - 成功响应保持原有上下文预算;
|
|
121
|
+
* - 失败响应不把整页 HTML/代理错误页灌进后续模型轮次;
|
|
122
|
+
* - 完整响应仍由 tool_result 审计按独立上限留存。
|
|
123
|
+
*/
|
|
124
|
+
function modelFacingToolResponse(fullText: string, status: number, truncateBytes: number, contentType: string): string {
|
|
125
|
+
const limit = Math.max(0, truncateBytes);
|
|
126
|
+
if (status >= 200 && status < 300) return fullText.slice(0, limit);
|
|
127
|
+
if (status === 0) return fullText.slice(0, limit);
|
|
128
|
+
|
|
129
|
+
const looksLikeHtml = /text\/html/i.test(contentType)
|
|
130
|
+
|| /^\s*(?:<!doctype\s+html|<html\b)/i.test(fullText);
|
|
131
|
+
if (looksLikeHtml) {
|
|
132
|
+
return `HTTP ${status}:业务工具返回 HTML 错误页(${fullText.length} 字符)。完整响应已保留在审计记录中。`
|
|
133
|
+
.slice(0, limit);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const errorText = fullText.trim().slice(0, Math.min(limit, 2048));
|
|
137
|
+
return (errorText ? `HTTP ${status}:${errorText}` : `HTTP ${status} 空响应`).slice(0, limit);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ---- 限流(进程内滑窗,三层:每任务 max_calls 由调用方计数 / 每工具 ACC execution.rate_limit / 工具源总闸)----
|
|
141
|
+
export class LocalSlidingWindowRateLimiter {
|
|
142
|
+
private readonly buckets = new Map<string, number[]>();
|
|
143
|
+
private lastSweepAt = 0;
|
|
144
|
+
|
|
145
|
+
constructor(private readonly now: () => number = Date.now) {}
|
|
146
|
+
|
|
147
|
+
consume(key: string, perMin: number): boolean {
|
|
148
|
+
if (perMin <= 0) return false;
|
|
149
|
+
const now = this.now();
|
|
150
|
+
this.sweep(now);
|
|
151
|
+
const timestamps = (this.buckets.get(key) ?? []).filter((timestamp) => now - timestamp < 60_000);
|
|
152
|
+
if (timestamps.length >= perMin) {
|
|
153
|
+
this.buckets.set(key, timestamps);
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
timestamps.push(now);
|
|
157
|
+
this.buckets.set(key, timestamps);
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
bucketCount(): number {
|
|
162
|
+
return this.buckets.size;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
private sweep(now: number): void {
|
|
166
|
+
if (now - this.lastSweepAt < 60_000) return;
|
|
167
|
+
this.lastSweepAt = now;
|
|
168
|
+
for (const [key, timestamps] of this.buckets) {
|
|
169
|
+
const active = timestamps.filter((timestamp) => now - timestamp < 60_000);
|
|
170
|
+
if (active.length) this.buckets.set(key, active);
|
|
171
|
+
else this.buckets.delete(key);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const localRateLimiter = new LocalSlidingWindowRateLimiter();
|
|
177
|
+
function allowRate(key: string, perMin: number): boolean {
|
|
178
|
+
return !localRateLimiter.consume(key, perMin);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 渐进式披露阈值:白名单内工具数 ≤ 此值全量内联(省一次往返);超过则目录+按需取定义(防几百个工具定义灌爆上下文)。 */
|
|
182
|
+
export const TOOL_INLINE_MAX = 12;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 审计落库单字段封顶(字节)。log_payload 打开且非敏感工具时,工具入参/响应**全量**入审计(远高于回流给模型的 truncateBytes,
|
|
186
|
+
* 二者是不同关注点:truncateBytes 控"喂模型的上下文预算",这里控"可追溯的审计留存")。封顶仅防异常大响应撑爆 bz_audit;
|
|
187
|
+
* 真实字节数始终另记 resp_bytes/args_bytes,超封顶记 *_truncated=true,绝不静默丢。64KB 覆盖绝大多数业务响应。
|
|
188
|
+
*/
|
|
189
|
+
export const AUDIT_MAX_BYTES = 65536;
|
|
190
|
+
|
|
191
|
+
/** 大脑可用的工具运行时:清单(喂 LLM)+ 受治理的调用句柄。由 server 在派发时装配并注入 AdapterContext。 */
|
|
192
|
+
export interface ToolRuntime {
|
|
193
|
+
/** OpenAI function-calling 形态的工具清单 */
|
|
194
|
+
llmTools: Array<{ type: 'function'; function: { name: string; description: string; parameters: Record<string, unknown> } }>;
|
|
195
|
+
maxCalls: number;
|
|
196
|
+
/** 工具数 > TOOL_INLINE_MAX 时启用渐进披露:大脑先看目录,用哪个再取完整定义 */
|
|
197
|
+
progressive: boolean;
|
|
198
|
+
/** 工具语义检索可用(工具源配了 embedding 凭证且已建索引):装配方注入了 retrieveNames,retrieve() 可用。
|
|
199
|
+
* 优先级高于 progressive——适配器有它就按用户问题预载相关工具 + search_tools 检索更多,而不是甩一份目录让模型自己翻。 */
|
|
200
|
+
retrievalMode: boolean;
|
|
201
|
+
/** 轻目录(渐进披露第一段):每条 ~20 token,无参数 schema */
|
|
202
|
+
catalog: Array<{ name: string; summary: string; scope: string; risk: string; confirm_required: boolean }>;
|
|
203
|
+
/** 重跑时的"已批准调用清单"提示(审批车道 B:批准后自动重跑,大脑须按原样执行批准的调用);无则 undefined */
|
|
204
|
+
approvedNote?: string;
|
|
205
|
+
/** 渐进披露第二段:按名取完整定义(看菜单不点菜:不计入 max_calls,审计 tool_lookup)。未知名忽略。 */
|
|
206
|
+
lookup(names: string[]): Promise<ToolRuntime['llmTools']>;
|
|
207
|
+
/** 工具语义检索:按一句自然语言意图召回最相关的工具定义(双闸内排序,不计 max_calls)。
|
|
208
|
+
* 返回 null = 检索运行时不可用(索引未建/凭证不可用/embedding 临时挂)→ 调用方应降级回 progressive。retrievalMode=false 时不存在。 */
|
|
209
|
+
retrieve?(query: string): Promise<ToolRuntime['llmTools'] | null>;
|
|
210
|
+
/** 受闸调用:白名单复核→风险闸→限流→审计(fail-closed)→签名外发。返回回流 LLM 的文本(错误也以文本回流)。 */
|
|
211
|
+
invoke(name: string, args: Record<string, unknown>): Promise<{ ok: boolean; text: string; status: number }>;
|
|
212
|
+
/** 下游是否已经进入“不允许自动重试、必须人工对账”的执行边界。 */
|
|
213
|
+
executionUncertainty(): ToolExecutionUncertainty | null;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 多工具源组合器:模型只看到一份工具面,调用时按工具名路由回所属工具源。
|
|
218
|
+
* 工具名必须在路由内全局唯一;上下文装配层会在运行前拒绝冲突,避免误调到错误业务系统。
|
|
219
|
+
*/
|
|
220
|
+
export function composeToolRuntimes(runtimes: ToolRuntime[], maxCalls: number, approvedNote?: string): ToolRuntime {
|
|
221
|
+
const owner = new Map<string, ToolRuntime>();
|
|
222
|
+
for (const runtime of runtimes) {
|
|
223
|
+
for (const tool of runtime.llmTools) {
|
|
224
|
+
const name = tool.function.name;
|
|
225
|
+
if (owner.has(name)) throw new Error(`工具名冲突 ${name}:同一路由的多工具源必须使用全局唯一 operationId`);
|
|
226
|
+
owner.set(name, runtime);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const llmTools = runtimes.flatMap((runtime) => runtime.llmTools);
|
|
230
|
+
const catalog = runtimes.flatMap((runtime) => runtime.catalog);
|
|
231
|
+
const retrievalMode = runtimes.length > 0 && runtimes.every((runtime) => runtime.retrievalMode && !!runtime.retrieve);
|
|
232
|
+
return {
|
|
233
|
+
llmTools,
|
|
234
|
+
maxCalls,
|
|
235
|
+
progressive: llmTools.length > TOOL_INLINE_MAX,
|
|
236
|
+
retrievalMode,
|
|
237
|
+
catalog,
|
|
238
|
+
approvedNote,
|
|
239
|
+
async lookup(names) {
|
|
240
|
+
const wanted = [...new Set(names.map(String))].slice(0, 20);
|
|
241
|
+
const groups = await Promise.all(runtimes.map((runtime) => runtime.lookup(wanted)));
|
|
242
|
+
return groups.flat();
|
|
243
|
+
},
|
|
244
|
+
...(retrievalMode ? {
|
|
245
|
+
async retrieve(query: string) {
|
|
246
|
+
const groups = await Promise.all(runtimes.map((runtime) => runtime.retrieve!(query).catch(() => null)));
|
|
247
|
+
if (groups.some((group) => group === null)) return null;
|
|
248
|
+
const seen = new Set<string>();
|
|
249
|
+
return groups.flatMap((group) => group ?? []).filter((tool) => {
|
|
250
|
+
if (seen.has(tool.function.name)) return false;
|
|
251
|
+
seen.add(tool.function.name);
|
|
252
|
+
return true;
|
|
253
|
+
});
|
|
254
|
+
},
|
|
255
|
+
} : {}),
|
|
256
|
+
async invoke(name, args) {
|
|
257
|
+
const runtime = owner.get(name);
|
|
258
|
+
if (!runtime) return { ok: false, text: `工具 ${name} 不在本路由白名单内,调用被拒。`, status: 0 };
|
|
259
|
+
return runtime.invoke(name, args);
|
|
260
|
+
},
|
|
261
|
+
executionUncertainty() {
|
|
262
|
+
for (const runtime of runtimes) {
|
|
263
|
+
const uncertainty = runtime.executionUncertainty();
|
|
264
|
+
if (uncertainty) return uncertainty;
|
|
265
|
+
}
|
|
266
|
+
return null;
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 审批车道句柄:由 server 接到 bz_tool_approvals + 送达插座。不注入时风险闸按未配置审批承接处理(一律拦)。 */
|
|
272
|
+
export interface ApprovalDeps {
|
|
273
|
+
/** 查"已批准且未消费"的同快照审批单并原子消费;消费成功返回单号,否则 null */
|
|
274
|
+
consumeApproved(tool: string, hash: string): Promise<number | null>;
|
|
275
|
+
/** 查同快照 pending 单(去重:同一调用别重复开单) */
|
|
276
|
+
findPending(tool: string, hash: string): Promise<number | null>;
|
|
277
|
+
/** 查本任务同工具"已批准未消费"单(不限参数)——重跑时大脑参数漂移的纠偏依据 */
|
|
278
|
+
findApprovedAnyArgs(tool: string): Promise<{ id: number; args_json: string } | null>;
|
|
279
|
+
/** 开 pending 单,返回单号 */
|
|
280
|
+
create(snap: ApprovalIntentSnap): Promise<number>;
|
|
281
|
+
/** 推送审批人(送达插座);失败不阻塞——单已在库里,控制台照样能批。summary=ACC approval.prompt 渲染后的人话动作描述 */
|
|
282
|
+
notify(approvalId: number, snap: ApprovalIntentSnap): Promise<void>;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export interface ApprovalIntentSnap {
|
|
286
|
+
tool: string;
|
|
287
|
+
scope: string;
|
|
288
|
+
risk: string;
|
|
289
|
+
policy: string;
|
|
290
|
+
reason: string;
|
|
291
|
+
method: string;
|
|
292
|
+
path: string;
|
|
293
|
+
args_json: string;
|
|
294
|
+
args_hash: string;
|
|
295
|
+
summary?: string;
|
|
296
|
+
confirm_when?: ConfirmHit;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export interface ToolRuntimeDeps {
|
|
300
|
+
provider: ToolProvider;
|
|
301
|
+
allowedTools: ToolDefinition[]; // 已过双闸的清单
|
|
302
|
+
maxCalls: number;
|
|
303
|
+
onBehalfOf: string; // metadata[subject_field],可空串
|
|
304
|
+
conversation?: string; // 来源会话坐标 <渠道名>:<收件人>(X-Bailing-Conversation),供业务批准后 /send 回流;可空
|
|
305
|
+
jobId: string;
|
|
306
|
+
clientAppId: string;
|
|
307
|
+
truncateBytes: number; // 工具结果回流截断(默认 8192)
|
|
308
|
+
approvedNote?: string; // 重跑时已批准调用清单提示
|
|
309
|
+
approvals?: ApprovalDeps; // 不注入 = high/confirm 一律拦
|
|
310
|
+
audit(event: string, detail: Record<string, unknown>): Promise<void>; // 写审计;抛错=调用不放行(fail-closed)
|
|
311
|
+
/** 工具语义检索(装配层注入;不注入 = 不启用检索,退回 progressive):一句意图 → 召回工具名(已是双闸内、按相关度排序)。
|
|
312
|
+
* 返回 null = 检索运行时不可用(索引/凭证/embedding 临时挂)→ retrieve() 透传 null 让适配器降级。本层不碰 embedding,只收名单。 */
|
|
313
|
+
retrieveNames?: (query: string) => Promise<string[] | null>;
|
|
314
|
+
/** 多工具源聚合后总工具数超过阈值时,装配层可强制小工具源也开启检索句柄。 */
|
|
315
|
+
retrievalMode?: boolean;
|
|
316
|
+
/** 副作用工具执行日志。请求发出前必须先占位;任何未完成状态都禁止自动重放。 */
|
|
317
|
+
idempotency?: {
|
|
318
|
+
get(tool: string, argsHash: string): Promise<ToolExecutionJournalEntry | null>;
|
|
319
|
+
reserve(tool: string, scope: string, argsHash: string, idempotencyKey: string): Promise<{ inserted: boolean; entry: ToolExecutionJournalEntry }>;
|
|
320
|
+
recordResponse(tool: string, argsHash: string, res: { ok: boolean; status: number; text: string }): Promise<void>;
|
|
321
|
+
complete(tool: string, argsHash: string): Promise<void>;
|
|
322
|
+
markUncertain(tool: string, argsHash: string, error: string): Promise<void>;
|
|
323
|
+
markEvidenceDegraded(tool: string, argsHash: string, error: string): Promise<void>;
|
|
324
|
+
};
|
|
325
|
+
/** 集中限速器:返回 true = 已触发限流;不注入时退回进程内滑窗。 */
|
|
326
|
+
rateLimit?: (bucket: string, limit: number, windowSec: number) => Promise<boolean>;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function buildToolRuntime(d: ToolRuntimeDeps): ToolRuntime {
|
|
330
|
+
const byName = new Map(d.allowedTools.map((t) => [t.name, t]));
|
|
331
|
+
const llmTools = d.allowedTools.map((t) => ({
|
|
332
|
+
type: 'function' as const,
|
|
333
|
+
function: { name: t.name, description: `${t.description}(scope:${t.scope}${t.readonly ? ',只读' : ''}${hasConditionalConfirm(t) ? ',部分参数需审批' : ''})`, parameters: t.inputSchema },
|
|
334
|
+
}));
|
|
335
|
+
// 检索模式:工具数超内联阈值 + 装配层注入了 retrieveNames(工具源配了 embedding 且有索引)才启用。
|
|
336
|
+
const retrievalMode = !!d.retrieveNames && (d.retrievalMode ?? d.allowedTools.length > TOOL_INLINE_MAX);
|
|
337
|
+
let executionUncertainty: ToolExecutionUncertainty | null = null;
|
|
338
|
+
return {
|
|
339
|
+
llmTools,
|
|
340
|
+
maxCalls: d.maxCalls,
|
|
341
|
+
progressive: d.allowedTools.length > TOOL_INLINE_MAX,
|
|
342
|
+
retrievalMode,
|
|
343
|
+
catalog: d.allowedTools.map((t) => ({ name: t.name, summary: toolSummary(t), scope: t.scope, risk: t.risk, confirm_required: t.confirmRequired || hasConditionalConfirm(t) })),
|
|
344
|
+
approvedNote: d.approvedNote,
|
|
345
|
+
async lookup(names) {
|
|
346
|
+
const want = new Set(names.map(String).slice(0, 20));
|
|
347
|
+
const found = llmTools.filter((x) => want.has(x.function.name));
|
|
348
|
+
// 看菜单不点菜:不计 max_calls;审计留痕但非 fail-closed(只读元操作)
|
|
349
|
+
try { void Promise.resolve(d.audit('tool_lookup', { names: [...want], found: found.map((x) => x.function.name) })).catch(() => undefined); } catch { /* best-effort 元审计 */ }
|
|
350
|
+
return found;
|
|
351
|
+
},
|
|
352
|
+
...(retrievalMode ? {
|
|
353
|
+
async retrieve(query: string) {
|
|
354
|
+
const names = await d.retrieveNames!(query).catch(() => null);
|
|
355
|
+
if (names === null) return null; // 检索运行时不可用 → 透传降级信号
|
|
356
|
+
// 保留相关度顺序(retrieveNames 已按分数排序),映射回完整定义
|
|
357
|
+
const found = names.map((n) => llmTools.find((x) => x.function.name === n)).filter(Boolean) as ToolRuntime['llmTools'];
|
|
358
|
+
try { void Promise.resolve(d.audit('tools_retrieved', { query: query.slice(0, 120), picked: found.map((x) => x.function.name) })).catch(() => undefined); } catch { /* best-effort 元审计 */ }
|
|
359
|
+
return found;
|
|
360
|
+
},
|
|
361
|
+
} : {}),
|
|
362
|
+
executionUncertainty() {
|
|
363
|
+
return executionUncertainty;
|
|
364
|
+
},
|
|
365
|
+
async invoke(name, args) {
|
|
366
|
+
if (executionUncertainty) {
|
|
367
|
+
return {
|
|
368
|
+
ok: false,
|
|
369
|
+
status: 0,
|
|
370
|
+
text: `前序工具 ${executionUncertainty.tool} 的执行结果尚未完成可信确认,本任务已冻结,禁止继续调用业务工具;请按幂等键 ${executionUncertainty.idempotency_key} 人工对账。`,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
const t = byName.get(name);
|
|
374
|
+
// 闸1:白名单复核(与清单装配解耦的独立校验——清单多吐了也走不到执行)
|
|
375
|
+
if (!t) return { ok: false, text: `工具 ${name} 不在本路由白名单内,调用被拒。`, status: 0 };
|
|
376
|
+
const normalized = normalizeToolArgs(args);
|
|
377
|
+
if (!normalized.ok) {
|
|
378
|
+
await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: normalized.error }).catch(() => undefined);
|
|
379
|
+
return { ok: false, text: `工具 ${name} 参数不是合法 JSON 对象,调用已拒绝。请按工具参数 schema 重新传参。`, status: 0 };
|
|
380
|
+
}
|
|
381
|
+
const callArgs = normalized.args;
|
|
382
|
+
// 闸1.5:主体闸——ACC subject.required 的工具必须有操作主体(装配层已过滤看不见,这里防绕过双闸兜底)
|
|
383
|
+
if (t.requiresSubject && !d.onBehalfOf) {
|
|
384
|
+
await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: 'requires-subject:任务无操作主体' }).catch(() => undefined);
|
|
385
|
+
return { ok: false, text: `工具 ${name} 需要明确的操作主体,当前任务没有可信身份(如匿名访客)。请告知用户登录后再操作或走人工流程。`, status: 0 };
|
|
386
|
+
}
|
|
387
|
+
// 闸1.8:幂等账本——同 job 内"副作用工具"(非只读、非声明幂等)已执行过的相同调用,重试/崩溃恢复重跑时直接返回上次结果,
|
|
388
|
+
// 不重复执行(防写操作重复扣款)。放在审批闸之前:否则重跑时已消费的审批单会被当成"无批准"再次触发待审批,把重跑卡死。
|
|
389
|
+
const sideEffecting = !t.readonly && !t.idempotent;
|
|
390
|
+
if (sideEffecting && !d.idempotency) {
|
|
391
|
+
await d.audit('tool_blocked', {
|
|
392
|
+
tool: name,
|
|
393
|
+
scope: t.scope,
|
|
394
|
+
reason: '副作用工具缺少持久化执行日志,请求未发出',
|
|
395
|
+
}).catch(() => undefined);
|
|
396
|
+
return {
|
|
397
|
+
ok: false,
|
|
398
|
+
status: 0,
|
|
399
|
+
text: `工具 ${name} 会产生业务副作用,但当前运行时未配置持久化执行日志,请求未发出。`,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
const idemHash = sideEffecting ? argsHash(callArgs) : '';
|
|
403
|
+
const idemKey = idemHash ? toolCallIdempotencyKey(d.jobId, name, idemHash, d.onBehalfOf) : '';
|
|
404
|
+
if (idemHash) {
|
|
405
|
+
let existing: ToolExecutionJournalEntry | null;
|
|
406
|
+
try {
|
|
407
|
+
existing = await d.idempotency!.get(name, idemHash);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
await d.audit('tool_blocked', {
|
|
410
|
+
tool: name,
|
|
411
|
+
scope: t.scope,
|
|
412
|
+
reason: '执行日志查询不可用,请求未发出',
|
|
413
|
+
error: String(error).slice(0, 500),
|
|
414
|
+
}).catch(() => undefined);
|
|
415
|
+
return {
|
|
416
|
+
ok: false,
|
|
417
|
+
status: 0,
|
|
418
|
+
text: `工具 ${name} 的执行日志当前不可用,请求未发出,也未消费审批。请稍后重新发起。`,
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
if (existing?.state === 'completed') {
|
|
422
|
+
await d.audit('tool_call_deduped', { tool: name, scope: t.scope, status: existing.status, idempotency_key: existing.idempotencyKey, reason: '同 job 已完成相同调用,返回已确认结果(防重试/恢复重复副作用)' }).catch(() => undefined);
|
|
423
|
+
return { ok: existing.ok, text: existing.text, status: existing.status };
|
|
424
|
+
}
|
|
425
|
+
if (existing) {
|
|
426
|
+
executionUncertainty = toolExecutionUncertaintyFromJournal(name, t.scope, existing);
|
|
427
|
+
await d.audit('tool_reconciliation_required', {
|
|
428
|
+
tool: name,
|
|
429
|
+
scope: t.scope,
|
|
430
|
+
state: existing.state,
|
|
431
|
+
idempotency_key: existing.idempotencyKey,
|
|
432
|
+
reason: existing.error ?? '检测到未完成的执行日志,禁止自动重放',
|
|
433
|
+
}).catch(() => undefined);
|
|
434
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
// 闸2:风险闸 + 审批车道(B 方案:先撤再来)。high / confirm-required 的调用:
|
|
438
|
+
// 有"已批准未消费"的同快照单 → 原子消费后放行;没有 → 开 pending 单推审批人,本次调用拒绝(任务正常收尾,批准后自动重跑)。
|
|
439
|
+
// 批准按 job+tool+args_hash 精确匹配——批的是"那一次调用",重跑换参数/换动作 = 重新走审批。
|
|
440
|
+
let approvalId: number | null = null;
|
|
441
|
+
const confirmCheck = firstConfirmHit(t, callArgs);
|
|
442
|
+
if (confirmCheck.error) {
|
|
443
|
+
await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: confirmCheck.error }).catch(() => undefined);
|
|
444
|
+
return { ok: false, text: `工具 ${name} 的审批条件参数类型不符合声明,调用已拒绝。请按工具参数 schema 重新传参。`, status: 0 };
|
|
445
|
+
}
|
|
446
|
+
const confirmHit = confirmCheck.hit;
|
|
447
|
+
const needsApproval = t.risk === 'high' || t.confirmRequired || !!confirmHit;
|
|
448
|
+
if (needsApproval) {
|
|
449
|
+
if (!d.approvals) { // 未接审批车道(理论不发生,server 总会注入):一律拦
|
|
450
|
+
await d.audit('tool_blocked', { tool: name, scope: t.scope, reason: approvalReason(t, confirmHit) }).catch(() => undefined);
|
|
451
|
+
return { ok: false, text: `工具 ${name} 属于需人工确认的高风险操作,当前不允许自动执行。请告知用户走人工流程。`, status: 0 };
|
|
452
|
+
}
|
|
453
|
+
const hash = argsHash(callArgs);
|
|
454
|
+
approvalId = await d.approvals.consumeApproved(name, hash);
|
|
455
|
+
if (approvalId === null) {
|
|
456
|
+
const pendingId = await d.approvals.findPending(name, hash);
|
|
457
|
+
if (pendingId !== null) {
|
|
458
|
+
return { ok: false, text: `该操作已有待审批单(编号 ${pendingId}),请勿重复提交。请结束任务并告知用户:操作待人工审批。`, status: 0 };
|
|
459
|
+
}
|
|
460
|
+
// 参数漂移纠偏:同工具已有"已批准未消费"单但参数对不上(大脑重跑没按原样发,如 {id:25} 漂成 {name:"周杰伦"})。
|
|
461
|
+
// 不开新单空转审批——把批准的精确参数怼回去让大脑当场重发;安全零降级:执行仍只认精确匹配的原子消费。
|
|
462
|
+
const drifted = await d.approvals.findApprovedAnyArgs(name);
|
|
463
|
+
if (drifted) {
|
|
464
|
+
await d.audit('tool_args_drift', { tool: name, approval_id: drifted.id, got_args: JSON.stringify(callArgs).slice(0, 500) }).catch(() => undefined);
|
|
465
|
+
return { ok: false, text: `该工具已有人工批准的调用(审批单 ${drifted.id}),但你本次的参数与批准的不一致。请立即按批准的参数原样重新调用:${name} 参数 ${drifted.args_json}(一字不改,不要再确认)。`, status: 0 };
|
|
466
|
+
}
|
|
467
|
+
const argsJson = JSON.stringify(callArgs);
|
|
468
|
+
const reason = approvalReason(t, confirmHit);
|
|
469
|
+
const summary = t.confirmPrompt ? t.confirmPrompt.replace(/\{(\w+)\}/g, (_, k) => String(callArgs[k] ?? `{${k}}`)) : undefined;
|
|
470
|
+
const snap: ApprovalIntentSnap = {
|
|
471
|
+
tool: name, scope: t.scope, risk: t.risk, policy: approvalPolicy(t, confirmHit), reason,
|
|
472
|
+
method: t.method, path: t.path, args_json: argsJson.slice(0, 4096), args_hash: hash,
|
|
473
|
+
...(summary ? { summary } : {}),
|
|
474
|
+
...(confirmHit ? { confirm_when: confirmHit } : {}),
|
|
475
|
+
};
|
|
476
|
+
const id = await d.approvals.create(snap);
|
|
477
|
+
await d.audit('tool_approval_pending', { approval_id: id, tool: name, scope: t.scope, risk: t.risk, confirm_required: t.confirmRequired, ...(confirmHit ? { confirm_when: confirmHit } : {}) }).catch(() => undefined);
|
|
478
|
+
await d.approvals.notify(id, { ...snap, args_json: argsJson.slice(0, 1000) }).catch(() => undefined);
|
|
479
|
+
return { ok: false, text: `工具 ${name} 属于需人工审批的操作,已提交审批单(编号 ${id})。请结束本次任务并告知用户:该操作已提交人工审批,批准后系统会自动继续执行。`, status: 0 };
|
|
480
|
+
}
|
|
481
|
+
// 走到这 = 批准单已消费,放行执行(审计带 approval_id 闭环留痕)
|
|
482
|
+
}
|
|
483
|
+
// 闸3:限流(每工具 + 工具源总闸)
|
|
484
|
+
const toolLimited = d.rateLimit
|
|
485
|
+
? await d.rateLimit(`tool:${d.provider.name}:${name}`, t.rateLimitPerMin, 60)
|
|
486
|
+
: !allowRate(`tool:${d.provider.name}:${name}`, t.rateLimitPerMin);
|
|
487
|
+
const providerLimited = d.rateLimit
|
|
488
|
+
? await d.rateLimit(`provider:${d.provider.name}`, d.provider.rate_limit_per_min, 60)
|
|
489
|
+
: !allowRate(`provider:${d.provider.name}`, d.provider.rate_limit_per_min);
|
|
490
|
+
if (toolLimited || providerLimited) {
|
|
491
|
+
return { ok: false, text: `工具 ${name} 触发限流,稍后再试。`, status: 429 };
|
|
492
|
+
}
|
|
493
|
+
// 组装请求:path/header/query/body 各归其位;GET 未标位置的参数仍回落 query。
|
|
494
|
+
const query = new URLSearchParams();
|
|
495
|
+
const bodyObj: Record<string, unknown> = {};
|
|
496
|
+
const headers: Record<string, string> = {};
|
|
497
|
+
let path = t.path;
|
|
498
|
+
for (const [k, v] of Object.entries(callArgs)) {
|
|
499
|
+
if (v === undefined || v === null) continue;
|
|
500
|
+
const where = t.paramIn[k] ?? (t.method === 'GET' ? 'query' : 'body');
|
|
501
|
+
if (where === 'path') path = path.replace(new RegExp(`\\{${escapeRegExp(k)}\\}`, 'g'), encodeURIComponent(String(v)));
|
|
502
|
+
else if (where === 'header') headers[k] = String(v);
|
|
503
|
+
else if (where === 'query') query.set(k, String(v));
|
|
504
|
+
else bodyObj[k] = v;
|
|
505
|
+
}
|
|
506
|
+
const qs = query.toString();
|
|
507
|
+
const pathWithQuery = path + (qs ? `?${qs}` : '');
|
|
508
|
+
const body = t.method === 'GET' ? '' : JSON.stringify(bodyObj);
|
|
509
|
+
const ts = Math.floor(Date.now() / 1000);
|
|
510
|
+
// 工具调用签名(把 On-Behalf-Of + Job-Id 钉进 HMAC)。签名材料里的主体/任务必须与下面实际发出的头逐字一致(同源)。
|
|
511
|
+
const subjectHeader = d.onBehalfOf || '';
|
|
512
|
+
const sigHeader = signToolCall(d.provider.secret, ts, t.method, pathWithQuery, body, subjectHeader, d.jobId); // 已含 sha256= 前缀
|
|
513
|
+
|
|
514
|
+
// 闸4:审计 fail-closed——账记不下来就不放行。ACC audit.sensitive 工具强制只记键名(优先级高于工具源 log_payload)。
|
|
515
|
+
// logFull 时入参全量入审计(封顶 AUDIT_MAX_BYTES,超出记 args_truncated;真实字节数 args_bytes 始终记)。
|
|
516
|
+
const logFull = d.provider.log_payload && !t.sensitive;
|
|
517
|
+
const argsStr = JSON.stringify(callArgs);
|
|
518
|
+
const argsLog = logFull
|
|
519
|
+
? { args: argsStr.slice(0, AUDIT_MAX_BYTES), args_bytes: argsStr.length, ...(argsStr.length > AUDIT_MAX_BYTES ? { args_truncated: true } : {}) }
|
|
520
|
+
: { args: JSON.stringify(Object.keys(callArgs)) };
|
|
521
|
+
await d.audit('tool_call', {
|
|
522
|
+
provider: d.provider.name, tool: name, scope: t.scope, method: t.method, path: t.path,
|
|
523
|
+
on_behalf_of: d.onBehalfOf || null, signature_scheme: 'sha256=', idempotency_key: idemKey || null, ...argsLog,
|
|
524
|
+
...(approvalId !== null ? { approval_id: approvalId } : {}),
|
|
525
|
+
});
|
|
526
|
+
|
|
527
|
+
if (idemHash) {
|
|
528
|
+
let reserved: { inserted: boolean; entry: ToolExecutionJournalEntry };
|
|
529
|
+
try {
|
|
530
|
+
reserved = await d.idempotency!.reserve(name, t.scope, idemHash, idemKey);
|
|
531
|
+
} catch (error) {
|
|
532
|
+
await d.audit('tool_blocked', {
|
|
533
|
+
tool: name,
|
|
534
|
+
scope: t.scope,
|
|
535
|
+
reason: '执行日志不可用,请求未发出',
|
|
536
|
+
error: String(error).slice(0, 500),
|
|
537
|
+
}).catch(() => undefined);
|
|
538
|
+
return { ok: false, text: `工具 ${name} 的执行日志当前不可用,请求未发出。请稍后重新发起并重新完成必要审批。`, status: 0 };
|
|
539
|
+
}
|
|
540
|
+
if (!reserved.inserted) {
|
|
541
|
+
if (reserved.entry.state === 'completed') {
|
|
542
|
+
await d.audit('tool_call_deduped', {
|
|
543
|
+
tool: name,
|
|
544
|
+
scope: t.scope,
|
|
545
|
+
status: reserved.entry.status,
|
|
546
|
+
idempotency_key: reserved.entry.idempotencyKey,
|
|
547
|
+
reason: '并发调用已完成,返回已确认结果',
|
|
548
|
+
}).catch(() => undefined);
|
|
549
|
+
return { ok: reserved.entry.ok, text: reserved.entry.text, status: reserved.entry.status };
|
|
550
|
+
}
|
|
551
|
+
executionUncertainty = toolExecutionUncertaintyFromJournal(name, t.scope, reserved.entry);
|
|
552
|
+
await d.audit('tool_reconciliation_required', {
|
|
553
|
+
tool: name,
|
|
554
|
+
scope: t.scope,
|
|
555
|
+
state: reserved.entry.state,
|
|
556
|
+
idempotency_key: reserved.entry.idempotencyKey,
|
|
557
|
+
reason: reserved.entry.error ?? '并发或恢复路径检测到未完成执行日志',
|
|
558
|
+
}).catch(() => undefined);
|
|
559
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const started = Date.now();
|
|
564
|
+
const timeoutMs = t.timeoutMs || d.provider.timeout_ms || 10000; // ACC execution.timeout_ms 单工具覆盖(慢接口放宽),缺省工具源超时
|
|
565
|
+
let status = 0; let fullText = '';
|
|
566
|
+
let responseContentType = '';
|
|
567
|
+
try {
|
|
568
|
+
const r = await fetch(d.provider.base_url.replace(/\/+$/, '') + pathWithQuery, {
|
|
569
|
+
method: t.method,
|
|
570
|
+
headers: {
|
|
571
|
+
...(body ? { 'content-type': 'application/json' } : {}),
|
|
572
|
+
'x-bailing-timestamp': String(ts),
|
|
573
|
+
'x-bailing-signature': sigHeader,
|
|
574
|
+
'x-bailing-job-id': d.jobId,
|
|
575
|
+
'x-bailing-client': d.clientAppId,
|
|
576
|
+
...(idemKey ? { 'x-bailing-idempotency-key': idemKey } : {}),
|
|
577
|
+
...(subjectHeader ? { 'x-bailing-on-behalf-of': subjectHeader } : {}),
|
|
578
|
+
// 来源会话坐标(非签名材料):业务侧自审批批准后据此 /send 回流到原会话;收件人权威仍以已验签的 on-behalf-of 为准
|
|
579
|
+
...(d.conversation ? { 'x-bailing-conversation': d.conversation } : {}),
|
|
580
|
+
'x-bailing-tool-scope': t.scope,
|
|
581
|
+
...headers,
|
|
582
|
+
},
|
|
583
|
+
body: body || undefined,
|
|
584
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
585
|
+
});
|
|
586
|
+
status = r.status;
|
|
587
|
+
responseContentType = r.headers?.get?.('content-type') ?? '';
|
|
588
|
+
fullText = await r.text();
|
|
589
|
+
} catch (e) {
|
|
590
|
+
const error = e instanceof Error && e.name === 'TimeoutError' ? `超时(${timeoutMs}ms)` : String(e);
|
|
591
|
+
fullText = `调用结果不确定:${error}`;
|
|
592
|
+
if (idemHash) {
|
|
593
|
+
await d.idempotency!.markUncertain(name, idemHash, error).catch(() => undefined);
|
|
594
|
+
executionUncertainty = {
|
|
595
|
+
state: 'uncertain',
|
|
596
|
+
tool: name,
|
|
597
|
+
scope: t.scope,
|
|
598
|
+
idempotency_key: idemKey,
|
|
599
|
+
reason: error,
|
|
600
|
+
message: `工具 ${name} 的请求可能已经到达业务系统,但未取得可信响应。为避免重复业务后果,本任务已禁止自动重试;请使用幂等键 ${idemKey} 人工对账。`,
|
|
601
|
+
};
|
|
602
|
+
await d.audit('tool_reconciliation_required', {
|
|
603
|
+
tool: name,
|
|
604
|
+
scope: t.scope,
|
|
605
|
+
state: 'uncertain',
|
|
606
|
+
idempotency_key: idemKey,
|
|
607
|
+
reason: error,
|
|
608
|
+
}).catch(() => undefined);
|
|
609
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
// 回流给模型的:受上下文预算 truncateBytes 截断(与审计留存解耦)
|
|
613
|
+
const text = modelFacingToolResponse(fullText, status, d.truncateBytes, responseContentType);
|
|
614
|
+
const ok = status >= 200 && status < 300;
|
|
615
|
+
const retText = text || `(HTTP ${status} 空响应)`;
|
|
616
|
+
if (idemHash) {
|
|
617
|
+
try {
|
|
618
|
+
await d.idempotency!.recordResponse(name, idemHash, { ok, status, text: retText });
|
|
619
|
+
} catch (error) {
|
|
620
|
+
executionUncertainty = {
|
|
621
|
+
state: 'uncertain',
|
|
622
|
+
tool: name,
|
|
623
|
+
scope: t.scope,
|
|
624
|
+
idempotency_key: idemKey,
|
|
625
|
+
reason: `响应已收到但执行日志写入失败:${String(error).slice(0, 300)}`,
|
|
626
|
+
message: `工具 ${name} 已收到业务响应,但未能持久化执行结果。为避免重复业务后果,本任务已禁止自动重试;请使用幂等键 ${idemKey} 人工对账。`,
|
|
627
|
+
};
|
|
628
|
+
await d.audit('tool_reconciliation_required', {
|
|
629
|
+
tool: name,
|
|
630
|
+
scope: t.scope,
|
|
631
|
+
state: 'uncertain',
|
|
632
|
+
idempotency_key: idemKey,
|
|
633
|
+
reason: executionUncertainty.reason,
|
|
634
|
+
}).catch(() => undefined);
|
|
635
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// 审计留存:logFull 记全量响应(封顶 AUDIT_MAX_BYTES,超出记 resp_truncated);resp_bytes 始终记真实字节数。
|
|
639
|
+
const respLog = logFull
|
|
640
|
+
? { resp: fullText.slice(0, AUDIT_MAX_BYTES), resp_bytes: fullText.length, ...(fullText.length > AUDIT_MAX_BYTES ? { resp_truncated: true } : {}) }
|
|
641
|
+
: { resp: `<${fullText.length} bytes>`, resp_bytes: fullText.length };
|
|
642
|
+
try {
|
|
643
|
+
await d.audit('tool_result', {
|
|
644
|
+
tool: name,
|
|
645
|
+
status,
|
|
646
|
+
ok,
|
|
647
|
+
duration_ms: Date.now() - started,
|
|
648
|
+
idempotency_key: idemKey || null,
|
|
649
|
+
...respLog,
|
|
650
|
+
});
|
|
651
|
+
} catch (error) {
|
|
652
|
+
if (idemHash) {
|
|
653
|
+
const reason = `业务响应已收到,但结果审计写入失败:${String(error).slice(0, 300)}`;
|
|
654
|
+
await d.idempotency!.markEvidenceDegraded(name, idemHash, reason).catch(() => undefined);
|
|
655
|
+
executionUncertainty = {
|
|
656
|
+
state: 'evidence_degraded',
|
|
657
|
+
tool: name,
|
|
658
|
+
scope: t.scope,
|
|
659
|
+
idempotency_key: idemKey,
|
|
660
|
+
reason,
|
|
661
|
+
message: `工具 ${name} 已产生业务响应,但审计证据不完整。为避免重复业务后果,本任务已禁止自动重试;请使用幂等键 ${idemKey} 人工对账。`,
|
|
662
|
+
};
|
|
663
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
if (idemHash) {
|
|
668
|
+
try {
|
|
669
|
+
await d.idempotency!.complete(name, idemHash);
|
|
670
|
+
} catch (error) {
|
|
671
|
+
executionUncertainty = {
|
|
672
|
+
state: 'response_recorded',
|
|
673
|
+
tool: name,
|
|
674
|
+
scope: t.scope,
|
|
675
|
+
idempotency_key: idemKey,
|
|
676
|
+
reason: `响应与审计已记录,但执行日志未能确认完成:${String(error).slice(0, 300)}`,
|
|
677
|
+
message: `工具 ${name} 已产生业务响应,但执行日志未完成最终确认。为避免重复业务后果,本任务已禁止自动重试;请使用幂等键 ${idemKey} 人工对账。`,
|
|
678
|
+
};
|
|
679
|
+
await d.audit('tool_reconciliation_required', {
|
|
680
|
+
tool: name,
|
|
681
|
+
scope: t.scope,
|
|
682
|
+
state: 'response_recorded',
|
|
683
|
+
idempotency_key: idemKey,
|
|
684
|
+
reason: executionUncertainty.reason,
|
|
685
|
+
}).catch(() => undefined);
|
|
686
|
+
return { ok: false, text: executionUncertainty.message, status: 0 };
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return { ok, text: retText, status };
|
|
690
|
+
},
|
|
691
|
+
};
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
export function toolExecutionUncertaintyFromJournal(
|
|
695
|
+
tool: string,
|
|
696
|
+
scope: string,
|
|
697
|
+
entry: ToolExecutionJournalEntry,
|
|
698
|
+
): ToolExecutionUncertainty {
|
|
699
|
+
const state = entry.state === 'completed' ? 'response_recorded' : entry.state;
|
|
700
|
+
const reason = entry.error ?? `检测到执行日志状态 ${state}`;
|
|
701
|
+
return {
|
|
702
|
+
state,
|
|
703
|
+
tool,
|
|
704
|
+
scope,
|
|
705
|
+
idempotency_key: entry.idempotencyKey,
|
|
706
|
+
reason,
|
|
707
|
+
message: `工具 ${tool} 已存在未完成的执行记录(${state})。系统不能确认是否已经产生业务后果,因此禁止自动重放;请使用幂等键 ${entry.idempotencyKey} 人工对账。`,
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function hasConditionalConfirm(t: ToolDefinition): boolean {
|
|
712
|
+
return Array.isArray(t.confirmWhen) && t.confirmWhen.length > 0;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function approvalReason(t: ToolDefinition, hit: ConfirmHit | null): string {
|
|
716
|
+
if (t.risk === 'high') return 'risk=high';
|
|
717
|
+
if (t.confirmRequired) return 'confirm-required';
|
|
718
|
+
return hit?.reason ?? 'confirm-when';
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function approvalPolicy(t: ToolDefinition, hit: ConfirmHit | null): string {
|
|
722
|
+
if (t.risk === 'high') return 'risk_high';
|
|
723
|
+
if (t.confirmRequired) return 'confirm_required';
|
|
724
|
+
if (hit) return 'confirm_when';
|
|
725
|
+
return 'unknown';
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
export interface ConfirmHit {
|
|
729
|
+
param: string;
|
|
730
|
+
op: string;
|
|
731
|
+
value?: unknown;
|
|
732
|
+
actual?: unknown;
|
|
733
|
+
reason: string;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
interface ConfirmCheck {
|
|
737
|
+
hit: ConfirmHit | null;
|
|
738
|
+
error?: string;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
function firstConfirmHit(tool: ToolDefinition, args: Record<string, unknown>): ConfirmCheck {
|
|
742
|
+
for (const cond of tool.confirmWhen ?? []) {
|
|
743
|
+
const result = matchConfirmCondition(cond, args, tool.inputSchema);
|
|
744
|
+
if (result && 'error' in result) return { hit: null, error: result.error };
|
|
745
|
+
if (result) return { hit: result };
|
|
746
|
+
}
|
|
747
|
+
return { hit: null };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function matchConfirmCondition(
|
|
751
|
+
cond: ToolConfirmCondition,
|
|
752
|
+
args: Record<string, unknown>,
|
|
753
|
+
inputSchema: Record<string, unknown>,
|
|
754
|
+
): ConfirmHit | { error: string } | null {
|
|
755
|
+
const actual = valueAtPath(args, cond.param);
|
|
756
|
+
const exists = actual !== undefined && actual !== null;
|
|
757
|
+
const schema = schemaAtPath(inputSchema, cond.param);
|
|
758
|
+
if (!schema) return { error: `confirm_when_missing_schema:${cond.param}` };
|
|
759
|
+
if (!schemaTypes(schema).length) return { error: `confirm_when_untyped_schema:${cond.param}` };
|
|
760
|
+
if (actual !== undefined && !valueMatchesSchemaType(actual, schema)) {
|
|
761
|
+
return { error: `confirm_when_argument_type:${cond.param}` };
|
|
762
|
+
}
|
|
763
|
+
const base = (): ConfirmHit => ({
|
|
764
|
+
param: cond.param,
|
|
765
|
+
op: cond.op,
|
|
766
|
+
...('value' in cond ? { value: cond.value } : {}),
|
|
767
|
+
...(exists ? { actual } : {}),
|
|
768
|
+
reason: cond.label || `confirm_when: ${cond.param} ${cond.op}${'value' in cond ? ` ${String(cond.value)}` : ''}`,
|
|
769
|
+
});
|
|
770
|
+
switch (cond.op) {
|
|
771
|
+
case 'exists': return exists ? base() : null;
|
|
772
|
+
case '>': return numericMatch(actual, cond.value, (a, b) => a > b, cond.param, base);
|
|
773
|
+
case '>=': return numericMatch(actual, cond.value, (a, b) => a >= b, cond.param, base);
|
|
774
|
+
case '<': return numericMatch(actual, cond.value, (a, b) => a < b, cond.param, base);
|
|
775
|
+
case '<=': return numericMatch(actual, cond.value, (a, b) => a <= b, cond.param, base);
|
|
776
|
+
case '==': return valueEquals(actual, cond.value) ? base() : null;
|
|
777
|
+
case '!=': return !valueEquals(actual, cond.value) ? base() : null;
|
|
778
|
+
case 'in': {
|
|
779
|
+
if (!Array.isArray(cond.value)) return { error: `confirm_when_invalid_in:${cond.param}` };
|
|
780
|
+
if (actual !== undefined && !cond.value.some((value) => sameJsonType(actual, value))) return { error: `confirm_when_argument_type:${cond.param}` };
|
|
781
|
+
return cond.value.some((value) => valueEquals(actual, value)) ? base() : null;
|
|
782
|
+
}
|
|
783
|
+
case 'contains': {
|
|
784
|
+
const contained = containsValue(actual, cond.value, cond.param);
|
|
785
|
+
if (typeof contained === 'object') return contained;
|
|
786
|
+
return contained ? base() : null;
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
return null;
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function valueAtPath(obj: Record<string, unknown>, path: string): unknown {
|
|
793
|
+
let cur: unknown = obj;
|
|
794
|
+
for (const part of path.split('.').filter(Boolean)) {
|
|
795
|
+
if (!cur || typeof cur !== 'object' || Array.isArray(cur)) return undefined;
|
|
796
|
+
cur = (cur as Record<string, unknown>)[part];
|
|
797
|
+
}
|
|
798
|
+
return cur;
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function numericMatch(
|
|
802
|
+
a: unknown,
|
|
803
|
+
b: unknown,
|
|
804
|
+
cmp: (x: number, y: number) => boolean,
|
|
805
|
+
param: string,
|
|
806
|
+
onMatch: () => ConfirmHit,
|
|
807
|
+
): ConfirmHit | { error: string } | null {
|
|
808
|
+
if (a === undefined) return null;
|
|
809
|
+
if (typeof a !== 'number' || !Number.isFinite(a) || typeof b !== 'number' || !Number.isFinite(b)) {
|
|
810
|
+
return { error: `confirm_when_argument_type:${param}` };
|
|
811
|
+
}
|
|
812
|
+
return cmp(a, b) ? onMatch() : null;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function valueEquals(a: unknown, b: unknown): boolean {
|
|
816
|
+
if (a === undefined || b === undefined) return a === b;
|
|
817
|
+
return canonicalJson(a) === canonicalJson(b);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
function sameJsonType(a: unknown, b: unknown): boolean {
|
|
821
|
+
if (a === null || b === null) return a === null && b === null;
|
|
822
|
+
if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b);
|
|
823
|
+
return typeof a === typeof b;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function containsValue(actual: unknown, expected: unknown, param: string): boolean | { error: string } {
|
|
827
|
+
if (Array.isArray(actual)) return actual.some((v) => valueEquals(v, expected));
|
|
828
|
+
if (actual === undefined) return false;
|
|
829
|
+
if (typeof actual !== 'string' || typeof expected !== 'string') return { error: `confirm_when_argument_type:${param}` };
|
|
830
|
+
return actual.includes(expected);
|
|
831
|
+
}
|