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,143 @@
|
|
|
1
|
+
// 业务主动出站入口:POST /send —— 接入方/admin 带 token 调「把这条消息经渠道X发给用户Y」。
|
|
2
|
+
// 与 /run 是兄弟而非分支:/run=触发大脑(记 in、跑 LLM、闸 allowed_routes);/send=注入一条回复方消息(记 out、不跑大脑、闸 allowed_channels)。
|
|
3
|
+
//
|
|
4
|
+
// 三件事一次做齐:① channelSend 投递;② 作为 out(回复方)轮次写进「该渠道路由下、收件人的那个 thread」(入历史,用户追问时大脑读得到);③ 落一条 job(任务可见)。
|
|
5
|
+
// 纪律:
|
|
6
|
+
// · 先投递、成功才写历史——绝不把"用户没收到的消息"记进会话(否则大脑会引用一条用户从没见过的消息)。
|
|
7
|
+
// · 记 direction='out'(渲染为「回复」),不是 'in'——业务在"对用户说话",记成 in 会让大脑以为是用户自己说的,角色全乱。
|
|
8
|
+
// · scope 走 channelScopeKey 共享函数,与企微入站逐字一致——差一字符就落到别的 thread,等于没接上历史。
|
|
9
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { readBody, send } from '../app/http';
|
|
12
|
+
import { channelScopeKey, channelSendFor, type ChannelMessage, type ChannelCard } from '../app/channels';
|
|
13
|
+
import { type Principal, clientAllowsChannel, rateLimitedFor } from '../app/auth';
|
|
14
|
+
import type { Job } from '../core/contracts/types';
|
|
15
|
+
import type { AppConfig } from '../core/config/config';
|
|
16
|
+
import type { RuntimeActor, RuntimeContext, RuntimeSource } from '../core/edition';
|
|
17
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
18
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
19
|
+
|
|
20
|
+
interface RuntimeContextInput {
|
|
21
|
+
source: RuntimeSource;
|
|
22
|
+
requestId: string;
|
|
23
|
+
principal?: Principal | null;
|
|
24
|
+
actor?: RuntimeActor;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SendApiDeps {
|
|
28
|
+
cfg: Pick<AppConfig, 'defaultProfile'>;
|
|
29
|
+
isPaused: () => boolean;
|
|
30
|
+
runtimeContextFor: (input: RuntimeContextInput) => Promise<RuntimeContext>;
|
|
31
|
+
runtimeStoresFor: (ctx: RuntimeContext) => { state: RuntimeStateStore; config: ConfigStoreContract | null };
|
|
32
|
+
now: () => string;
|
|
33
|
+
channelSendFor: typeof channelSendFor;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const MAX_TEXT = 2000; // 正文上限(企微文本约 2048 字节,留余量;超长直接 400 比让渠道侧报错清楚)
|
|
37
|
+
const MAX_ATTACH = 9; // 单次图片/文件各自条数上限(每个附件一次企微发送,封顶防滥用)
|
|
38
|
+
const MAX_RECIPIENTS = 1000; // 企微 touser 上限;批量通知一次发多人(数组或 "a|b|c"),省 N 次往返与 N 次限速
|
|
39
|
+
|
|
40
|
+
export async function handleSendFor(deps: SendApiDeps, req: IncomingMessage, res: ServerResponse, principal: Principal): Promise<void> {
|
|
41
|
+
if (deps.isPaused()) { send(res, 503, { status: 'paused' }); return; }
|
|
42
|
+
const body = (await readBody(req)) as Partial<{ request_id: string; channel: string; to: unknown; text: string; images: unknown; files: unknown; card: unknown }>;
|
|
43
|
+
const requestId = String(body.request_id ?? '').trim();
|
|
44
|
+
const channelName = String(body.channel ?? '').trim();
|
|
45
|
+
// 收件人:支持单个 / 数组 / "a|b|c"。去重 + 封顶。一次多人 = 渠道原生合并发,一次调用、占一次限速。
|
|
46
|
+
const rawTo = Array.isArray(body.to) ? body.to.map((x) => String(x)) : String(body.to ?? '').split('|');
|
|
47
|
+
const recipients = [...new Set(rawTo.map((x) => x.trim()).filter(Boolean))].slice(0, MAX_RECIPIENTS);
|
|
48
|
+
const text = String(body.text ?? '');
|
|
49
|
+
// 附件(URL 制):images=[url...];files=[{url,name?}...]。中枢拉取→上传渠道→投递。各自封顶 MAX_ATTACH。
|
|
50
|
+
const images = (Array.isArray(body.images) ? body.images.map((u) => String(u).trim()).filter(Boolean) : []).slice(0, MAX_ATTACH);
|
|
51
|
+
const files = (Array.isArray(body.files) ? body.files.filter((f) => f && typeof f === 'object' && (f as { url?: unknown }).url)
|
|
52
|
+
.map((f) => ({ url: String((f as { url: unknown }).url).trim(), name: (f as { name?: unknown }).name ? String((f as { name: unknown }).name).slice(0, 120) : undefined })) : []).slice(0, MAX_ATTACH);
|
|
53
|
+
// 卡片(企微 textcard):仅企微类渠道生效;需 title + url。不支持卡片的渠道回退发 text。
|
|
54
|
+
const cardIn = body.card && typeof body.card === 'object' ? (body.card as Record<string, unknown>) : null;
|
|
55
|
+
let card: ChannelCard | undefined;
|
|
56
|
+
if (cardIn) {
|
|
57
|
+
const ctitle = String(cardIn['title'] ?? '').trim();
|
|
58
|
+
const curl = String(cardIn['url'] ?? '').trim();
|
|
59
|
+
if (!ctitle || !curl) { send(res, 400, { error: 'card 需要 title 和 url' }); return; }
|
|
60
|
+
card = { type: 'textcard', title: ctitle, description: String(cardIn['description'] ?? ''), url: curl, btntxt: cardIn['btntxt'] ? String(cardIn['btntxt']) : undefined };
|
|
61
|
+
}
|
|
62
|
+
if (!requestId || !channelName || !recipients.length) { send(res, 400, { error: 'request_id / channel / to 必填' }); return; }
|
|
63
|
+
if (!text.trim() && !images.length && !files.length && !card) { send(res, 400, { error: 'text / images / files / card 至少给一项' }); return; }
|
|
64
|
+
if (text.length > MAX_TEXT) { send(res, 400, { error: `text 超过 ${MAX_TEXT} 字上限` }); return; }
|
|
65
|
+
|
|
66
|
+
const ctx = await deps.runtimeContextFor({ source: 'send', requestId, principal });
|
|
67
|
+
const { state: store, config: cfgStore } = deps.runtimeStoresFor(ctx);
|
|
68
|
+
if (!cfgStore) { send(res, 400, { error: '出站需要 mysql 后端' }); return; }
|
|
69
|
+
|
|
70
|
+
// 身份闸:仅接入方 token 或管理身份。接入方还要过「渠道白名单 + 限速」(admin 不限,与 /run 的 allowed_routes 一致)。
|
|
71
|
+
const client = principal.kind === 'client' ? principal.client : null;
|
|
72
|
+
if (!client && principal.kind !== 'admin') { send(res, 403, { error: '需接入方 token 或管理身份' }); return; }
|
|
73
|
+
if (client) {
|
|
74
|
+
if (!clientAllowsChannel(client, channelName)) { send(res, 403, { error: `接入方 ${client.app_id} 无权向渠道 ${channelName} 主动推送(需在中枢后台「接入方」授权该渠道)` }); return; }
|
|
75
|
+
if (await rateLimitedFor(cfgStore, client)) { send(res, 429, { error: `超出限速(${client.rate_limit_per_min}/分钟),请稍后重试同 request_id` }); return; }
|
|
76
|
+
}
|
|
77
|
+
const source = client ? client.app_id : 'admin';
|
|
78
|
+
|
|
79
|
+
// 幂等:同一 request_id 不重发(撞自己的 id 才认;失败后请换新 request_id 重试,不会复发旧的)
|
|
80
|
+
const existing = await store.findByRequestId(requestId);
|
|
81
|
+
if (existing) {
|
|
82
|
+
if (client && existing.client_app_id !== client.app_id) { send(res, 409, { error: 'request_id 与其他接入方冲突,请换用带自身前缀的 request_id' }); return; }
|
|
83
|
+
send(res, 200, { ok: existing.status === 'done', job_id: existing.job_id, status: existing.status, request_id: requestId, deduped: true });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const ch = await cfgStore.channels.get(channelName);
|
|
88
|
+
if (!ch || !ch.enabled) { send(res, 400, { error: `渠道 ${channelName} 不存在或已停用` }); return; }
|
|
89
|
+
|
|
90
|
+
// 入历史的内容:文字(无文字则用卡片标题作降级)+ 图片(markdown 图,控制台可渲染、大脑能"看见"发过图) + 文件(链接)。投递成功才写。
|
|
91
|
+
const histParts: string[] = [];
|
|
92
|
+
if (text.trim()) histParts.push(text);
|
|
93
|
+
else if (card) histParts.push(card.title);
|
|
94
|
+
for (const u of images) histParts.push(``);
|
|
95
|
+
for (const f of files) histParts.push(`[附件:${f.name || '文件'}](${f.url})`);
|
|
96
|
+
const content = histParts.join('\n') || '(空)';
|
|
97
|
+
const message: ChannelMessage = { text: text.trim() || undefined, images, files, card };
|
|
98
|
+
|
|
99
|
+
// 先投递——成功才入历史。多收件人用渠道原生 "a|b|c" 合并,一次调用。channelSend 内校验凭证、拉取上传附件、发卡片/文字/附件。
|
|
100
|
+
const r = await deps.channelSendFor(cfgStore, channelName, recipients.join('|'), message).catch((e) => ({ ok: false, error: String(e) } as { ok: boolean; error?: string }));
|
|
101
|
+
|
|
102
|
+
const jobId = randomUUID();
|
|
103
|
+
const ts = deps.now();
|
|
104
|
+
let threadId: number | undefined;
|
|
105
|
+
if (r.ok) {
|
|
106
|
+
// 入历史:每个收件人各自的 thread 都记一条 out(谁回复大脑都接得上)。并发写,总账故障不回滚已送达、降级审计即可。
|
|
107
|
+
try {
|
|
108
|
+
const tids = await Promise.all(recipients.map(async (rcpt) => {
|
|
109
|
+
const scope = channelScopeKey(ch.kind, ch.name, rcpt);
|
|
110
|
+
const pid = (ch.kind === 'wecom' ? `wxuid:${rcpt}` : `${ch.kind}:${rcpt}`).slice(0, 64);
|
|
111
|
+
const tid = await cfgStore.conversations.resolveThread(ch.route_key, scope, pid);
|
|
112
|
+
await cfgStore.conversations.appendMessage({ thread_id: tid, direction: 'out', channel: source, principal_id: pid, job_id: jobId, content });
|
|
113
|
+
return tid;
|
|
114
|
+
}));
|
|
115
|
+
threadId = tids[0];
|
|
116
|
+
} catch (e) {
|
|
117
|
+
await store.appendAudit({ ts, job_id: jobId, request_id: requestId, event: 'ledger_error', detail: { stage: 'outbound', error: String(e).slice(0, 200) } }).catch(() => undefined);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const single = recipients.length === 1;
|
|
122
|
+
const job: Job = {
|
|
123
|
+
job_id: jobId, request_id: requestId,
|
|
124
|
+
status: r.ok ? 'done' : 'error',
|
|
125
|
+
target: 'channel-send', profile: deps.cfg.defaultProfile, project: '',
|
|
126
|
+
source, client_app_id: client?.app_id, thread_id: threadId,
|
|
127
|
+
input_preview: content.slice(0, 200), input: content,
|
|
128
|
+
result: r.ok ? { text, channel: channelName, to: single ? recipients[0] : recipients, ...(card ? { card: true } : {}), ...(images.length ? { images } : {}), ...(files.length ? { files } : {}) } : undefined,
|
|
129
|
+
error: r.ok ? undefined : (r.error ?? '送达失败'),
|
|
130
|
+
metadata: { outbound: true, via: 'send', channel: channelName, recipients: recipients.length, ...(single ? { recipient: recipients[0] } : {}), ...(card ? { card: card.type } : {}), ...(images.length ? { images: images.length } : {}), ...(files.length ? { files: files.length } : {}) },
|
|
131
|
+
created_at: ts, updated_at: ts,
|
|
132
|
+
};
|
|
133
|
+
await store.createJob(job).catch(() => undefined);
|
|
134
|
+
await store.appendAudit({
|
|
135
|
+
ts, job_id: jobId, request_id: requestId,
|
|
136
|
+
event: r.ok ? 'outbound_sent' : 'outbound_send_error',
|
|
137
|
+
detail: { channel: channelName, to: single ? recipients[0] : `${recipients.length}人`, source, ...(card ? { card: card.type } : {}), ...(images.length ? { images: images.length } : {}), ...(files.length ? { files: files.length } : {}), ...(r.ok ? { thread_id: threadId ?? null } : { error: r.error }) },
|
|
138
|
+
}).catch(() => undefined);
|
|
139
|
+
if (client) void cfgStore.clients.touch(client.app_id).catch(() => undefined);
|
|
140
|
+
|
|
141
|
+
if (r.ok) send(res, 200, { ok: true, job_id: jobId, request_id: requestId, thread_id: threadId ?? null, recipients: recipients.length });
|
|
142
|
+
else send(res, 502, { ok: false, job_id: jobId, request_id: requestId, error: r.error ?? '送达失败' });
|
|
143
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// OSS 默认企微入站包装:这里才绑定 app/runtime 单组织单例。
|
|
2
|
+
// 自定义部署应使用 wecom.ts 的 handleWecomInboundFor(deps, ...)。
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import { cfg, isPaused, targetRegistry } from '../app/runtime';
|
|
5
|
+
import { resolveProjectPathFor, runtimeContextFor, runtimeStoresFor } from '../app/runtime-context-default';
|
|
6
|
+
import { now } from '../app/http';
|
|
7
|
+
import type { EngineRuntime } from '../app/engine';
|
|
8
|
+
import { launchJob, waitForJob } from '../app/engine-default';
|
|
9
|
+
import type { RuntimeContext } from '../core/edition';
|
|
10
|
+
import { handleWecomInboundFor, type WecomApiDeps } from './wecom';
|
|
11
|
+
|
|
12
|
+
export function defaultWecomApiDeps(): WecomApiDeps {
|
|
13
|
+
return {
|
|
14
|
+
cfg,
|
|
15
|
+
isPaused,
|
|
16
|
+
runtimeContextFor,
|
|
17
|
+
runtimeStoresFor,
|
|
18
|
+
resolveProjectPathFor,
|
|
19
|
+
now,
|
|
20
|
+
engineForContext: (_ctx: RuntimeContext): Pick<EngineRuntime, 'launchJob' | 'waitForJob'> => ({ launchJob, waitForJob }),
|
|
21
|
+
targetRegistry,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function handleWecomInbound(req: IncomingMessage, res: ServerResponse, accountId: string, url: URL): Promise<void> {
|
|
26
|
+
return handleWecomInboundFor(defaultWecomApiDeps(), req, res, accountId, url);
|
|
27
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
// 企业微信入站(公开面):自建应用「接收消息」回调 → 中枢当回调地址 → 走路由 → 被动加密回复 + 超窗 qyapi 主动推。
|
|
2
|
+
// 自带验签(无需 admin/接入方鉴权);短窗口聚合(WECOM_COALESCE)把连发的图+文合成一轮;身份=解密报文 FromUserName。
|
|
3
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { normalizeHttpMountPath, readRawBody } from '../app/http';
|
|
6
|
+
import type { EngineRuntime } from '../app/engine';
|
|
7
|
+
import { UPLOAD_MIME, objectKey, putObject, storageBucketForRuntime } from '../adapters/storage/object-storage';
|
|
8
|
+
import { resolveTargetDef } from '../core/targets/resolve';
|
|
9
|
+
import { wecomBuildReply, wecomDecrypt, wecomSign, wecomVerifyUrl, wecomXmlField } from '../adapters/channels/wecom-crypto';
|
|
10
|
+
import { WECOM_TEXT_SAFE_BYTES, getWecomMedia, sendWecomText, type WecomAccessTokenCache } from '../adapters/channels/wecom-api';
|
|
11
|
+
import { channelScopeKey } from '../app/channels';
|
|
12
|
+
import type { RuntimeActor, RuntimeContext, RuntimeSource } from '../core/edition';
|
|
13
|
+
import type { RuntimeStateStore } from '../core/state/state-contracts';
|
|
14
|
+
import type { AppConfig } from '../core/config/config';
|
|
15
|
+
import type { ConfigStoreContract } from '../infrastructure/config/configstore';
|
|
16
|
+
import type { TargetRegistry } from '../core/targets/registry';
|
|
17
|
+
|
|
18
|
+
// ---- 企业微信入站(公开面):自建应用「接收消息」回调 → 中枢当回调地址 → 走 llm 路由 → 被动加密回复 ----
|
|
19
|
+
// v1 只做被动回复(回复随回调 HTTP 响应返回,无需 qyapi/可信IP);慢回答靠企微自身重试(同 MsgId 复用任务)兜一程。
|
|
20
|
+
// 后续增量:注册 wecom-notify 送达 + 中枢 qyapi 主动推,覆盖 >5s 的长回答与执行器大脑。身份纪律:企微解密报文里的 FromUserName 即可信操作主体。
|
|
21
|
+
function wecomActor(accountId: string): RuntimeActor {
|
|
22
|
+
return { kind: 'channel', id: `wecom:${accountId}`, roles: ['channel'], displayName: accountId };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface WecomApiDeps {
|
|
26
|
+
cfg: AppConfig;
|
|
27
|
+
/** Trusted public prefix owned by an embedding host. */
|
|
28
|
+
httpMountPath?: string;
|
|
29
|
+
isPaused: () => boolean;
|
|
30
|
+
runtimeContextFor: (input: RuntimeContextInput) => Promise<RuntimeContext>;
|
|
31
|
+
runtimeStoresFor: (ctx: RuntimeContext) => { state: RuntimeStateStore; config: ConfigStoreContract | null };
|
|
32
|
+
resolveProjectPathFor: (config: ConfigStoreContract | null, name: string) => Promise<string | null>;
|
|
33
|
+
now: () => string;
|
|
34
|
+
engineForContext: (ctx: RuntimeContext) => Pick<EngineRuntime, 'launchJob' | 'waitForJob'>;
|
|
35
|
+
targetRegistry?: TargetRegistry;
|
|
36
|
+
runtimeState?: WecomRuntimeState;
|
|
37
|
+
/** Kernel-owned credential cache; embedded hosts must inject and dispose it with the Kernel. */
|
|
38
|
+
accessTokenCache?: WecomAccessTokenCache;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface RuntimeContextInput {
|
|
42
|
+
source: RuntimeSource;
|
|
43
|
+
requestId: string;
|
|
44
|
+
actor?: RuntimeActor;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function wecomRuntime(deps: WecomApiDeps, accountId: string, requestId: string) {
|
|
48
|
+
const ctx = await deps.runtimeContextFor({ source: 'channel', requestId, actor: wecomActor(accountId) });
|
|
49
|
+
return { ctx, ...deps.runtimeStoresFor(ctx) };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// 异步主动推(送达超出 5s 被动窗口的慢回答):任务完成后中枢经 qyapi 把回复推回企微用户。
|
|
53
|
+
// 与被动回复互斥——被动只在"首攻 done"分支发,主动推只在"首攻超窗"分支排;企微重试一律空 ack,绝不重复发。
|
|
54
|
+
// 凭证由触发那条消息当场解析好传入(corpid 来自密文 receiveId),不依赖持久化。
|
|
55
|
+
function scheduleWecomPush(deps: WecomApiDeps, accountId: string, corpid: string, secret: string, agentid: string, touser: string, jobId: string): void {
|
|
56
|
+
void (async () => {
|
|
57
|
+
const { ctx, state: store } = await wecomRuntime(deps, accountId, jobId);
|
|
58
|
+
const engine = deps.engineForContext(ctx);
|
|
59
|
+
const j = await engine.waitForJob(jobId, 110_000);
|
|
60
|
+
if (!j || j.status !== 'done') return; // 失败不推人渠道(与送达策略一致)
|
|
61
|
+
if (!secret || !corpid || !agentid) {
|
|
62
|
+
await store.appendAudit({ ts: deps.now(), job_id: jobId, request_id: j.request_id, event: 'wecom_push_skipped', detail: { reason: '缺 secret/corpid/agentid,无法主动推(快答仍走被动回复)' } }).catch(() => { /* 审计失败不影响 */ });
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const r = (j.result ?? {}) as Record<string, unknown>;
|
|
66
|
+
const text = typeof r['text'] === 'string' && r['text'] ? (r['text'] as string) : (j.raw_result || '');
|
|
67
|
+
if (!text) return;
|
|
68
|
+
try {
|
|
69
|
+
const res = await sendWecomText(corpid, secret, agentid, touser, String(text), deps.accessTokenCache);
|
|
70
|
+
await store.appendAudit({ ts: deps.now(), job_id: jobId, request_id: j.request_id, event: res.ok ? 'wecom_push' : 'wecom_push_error', detail: { to: touser, errcode: res.errcode, errmsg: res.errmsg } }).catch(() => { /* 审计失败不影响 */ });
|
|
71
|
+
} catch (e) {
|
|
72
|
+
await store.appendAudit({ ts: deps.now(), job_id: jobId, request_id: j.request_id, event: 'wecom_push_error', detail: { to: touser, error: String(e).slice(0, 200) } }).catch(() => { /* 审计失败不影响 */ });
|
|
73
|
+
}
|
|
74
|
+
})();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---- 入站消息短窗口聚合 ----
|
|
78
|
+
// 企微把「图片+文字」永远拆成多条几乎同时到达的消息(无法合并发)。中枢按 (账号+用户) 攒一个小窗口,
|
|
79
|
+
// 把这一连串合成「一轮」再喂大脑(图+问题一起),否则文字那条会先于图单独跑、答「没收到图」。
|
|
80
|
+
// 首条 hold 住回调用于被动快回复(零依赖、不要求配 agentid/secret);后续条立即空 ack;
|
|
81
|
+
// 合并轮答得慢(含图基本都慢)则空 ack + 异步主动推。窗口 < 企微 5s,留出大脑时间。
|
|
82
|
+
type WecomPart = { kind: 'text'; text: string } | { kind: 'image'; mediaId: string; picUrl: string };
|
|
83
|
+
interface WecomBuf {
|
|
84
|
+
parts: WecomPart[]; msgIds: string[]; timer: ReturnType<typeof setTimeout> | null; firstMs: number;
|
|
85
|
+
held: { res: ServerResponse; token: string; aesKey: string; corpid: string; fromUser: string } | null;
|
|
86
|
+
accountId: string; routeKey: string; secret: string; agentId: string; corpid: string; fromUser: string;
|
|
87
|
+
runtimeScopeKey: string;
|
|
88
|
+
cc: Record<string, unknown>; replyWaitMs: number; publicBaseUrl: string;
|
|
89
|
+
deps: WecomApiDeps;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Kernel-owned 企微瞬态状态;dispose 后不会残留跨 Kernel 的 held response 或定时器。 */
|
|
93
|
+
export class WecomRuntimeState {
|
|
94
|
+
readonly seen = new Map<string, { jobId: string; ts: number }>();
|
|
95
|
+
readonly buffers = new Map<string, WecomBuf>();
|
|
96
|
+
|
|
97
|
+
pruneSeen(): void {
|
|
98
|
+
const cut = Date.now() - 5 * 60_000;
|
|
99
|
+
for (const [key, value] of this.seen) if (value.ts < cut) this.seen.delete(key);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
dispose(): void {
|
|
103
|
+
for (const buffer of this.buffers.values()) {
|
|
104
|
+
if (buffer.timer) clearTimeout(buffer.timer);
|
|
105
|
+
try {
|
|
106
|
+
if (buffer.held && !buffer.held.res.writableEnded) {
|
|
107
|
+
buffer.held.res.writeHead(503, { 'content-type': 'text/plain' });
|
|
108
|
+
buffer.held.res.end('');
|
|
109
|
+
}
|
|
110
|
+
} catch { /* best effort */ }
|
|
111
|
+
}
|
|
112
|
+
this.buffers.clear();
|
|
113
|
+
this.seen.clear();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const defaultWecomRuntimeState = new WecomRuntimeState();
|
|
118
|
+
const WECOM_COALESCE_MS = 1500; // 攒消息窗口:同一用户这段时间内连发的合成一轮
|
|
119
|
+
const WECOM_COALESCE_MAX_MS = 3000; // 窗口上限:连发不断也不无限等,到顶就发(给大脑留时间)
|
|
120
|
+
// 企微聊天窗不渲染 Markdown:默认给大脑注入"纯文本、无 emoji"输出风格(随任务 metadata.reply_hint 透传,llm 适配器据此追加进系统提示)。
|
|
121
|
+
// 渠道配置里显式设 reply_hint 可覆盖文案、设为空串可关闭;网页嵌入聊天组件等能渲染 md 的入口不走这条路径、行为不变。
|
|
122
|
+
const WECOM_PLAINTEXT_HINT = '【输出格式·企业微信】你的回复会发送到企业微信聊天窗口,它不渲染 Markdown:请用纯文本回答,不要使用任何 Markdown 语法——不要用 #/## 标题、* 或 ** 加粗、`代码`/```代码块```、| 表格、- 或 * 列表符号、> 引用。需要分条时用「1. 2. 3.」加换行;需要呈现表格类信息时改用「字段:值」逐行罗列。也不要使用 emoji 表情符号。用简洁的文字和换行组织内容,确保在纯文本里清晰易读。';
|
|
123
|
+
|
|
124
|
+
export function wecomPublicBaseUrl(req: IncomingMessage, mountPath = ''): string {
|
|
125
|
+
const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? '').split(',')[0]!.trim();
|
|
126
|
+
const protoHeader = String(req.headers['x-forwarded-proto'] ?? '').split(',')[0]!.trim();
|
|
127
|
+
const proto = protoHeader || (/^(localhost|127\.|0\.0\.0\.0)/.test(host) ? 'http' : 'https');
|
|
128
|
+
return `${proto}://${host || 'localhost'}${normalizeHttpMountPath(mountPath)}`;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 窗口结束:把缓冲里的多条消息合成一轮 → 下载/落桶图片 → 起一个任务 → 首条回调被动回复 or 异步推。永不抛。 */
|
|
132
|
+
async function flushWecom(runtimeState: WecomRuntimeState, key: string): Promise<void> {
|
|
133
|
+
const buf = runtimeState.buffers.get(key);
|
|
134
|
+
if (!buf) return;
|
|
135
|
+
runtimeState.buffers.delete(key);
|
|
136
|
+
if (buf.timer) clearTimeout(buf.timer);
|
|
137
|
+
let auditStore: RuntimeStateStore | null = null;
|
|
138
|
+
const held = buf.held;
|
|
139
|
+
const replyHeld = (text: string): void => {
|
|
140
|
+
if (!held) return;
|
|
141
|
+
try { held.res.writeHead(200, { 'content-type': 'application/xml; charset=utf-8' }); held.res.end(wecomBuildReply(held.token, held.aesKey, held.corpid, held.fromUser, text)); } catch { /* res 可能已关 */ }
|
|
142
|
+
};
|
|
143
|
+
const ackHeld = (): void => { if (!held) return; try { held.res.writeHead(200, { 'content-type': 'text/plain' }); held.res.end(''); } catch { /* ignore */ } };
|
|
144
|
+
try {
|
|
145
|
+
const { ctx, state: store, config: cfgStore } = await wecomRuntime(buf.deps, buf.accountId, buf.msgIds[0] ?? `wecom:${key}`);
|
|
146
|
+
const engine = buf.deps.engineForContext(ctx);
|
|
147
|
+
auditStore = store;
|
|
148
|
+
if (!cfgStore) { ackHeld(); return; }
|
|
149
|
+
// 合成正文:文字原样,图片在此统一下载落桶取永久 URL(失败回退企微临时 PicUrl)→ markdown 图
|
|
150
|
+
const segments: string[] = [];
|
|
151
|
+
let hasImage = false, hasText = false;
|
|
152
|
+
const bucketName = String(buf.cc['bucket'] ?? '').trim();
|
|
153
|
+
const configuredBucket = bucketName ? await cfgStore.storageBuckets.get(bucketName).catch(() => null) : null;
|
|
154
|
+
const bucket = storageBucketForRuntime(configuredBucket, buf.publicBaseUrl);
|
|
155
|
+
for (const part of buf.parts) {
|
|
156
|
+
if (part.kind === 'text') { if (part.text) { segments.push(part.text); hasText = true; } continue; }
|
|
157
|
+
hasImage = true;
|
|
158
|
+
let imgUrl = '';
|
|
159
|
+
if (part.mediaId && bucket.enabled && buf.corpid && buf.secret) {
|
|
160
|
+
const media = await getWecomMedia(buf.corpid, buf.secret, part.mediaId, buf.deps.accessTokenCache);
|
|
161
|
+
if (media.ok && media.buf) {
|
|
162
|
+
try {
|
|
163
|
+
const mime = UPLOAD_MIME.test(media.mime ?? '') ? media.mime! : 'image/jpeg';
|
|
164
|
+
const okey = objectKey(bucket, `wecom_${buf.accountId}`, mime);
|
|
165
|
+
imgUrl = await putObject(bucket, okey, media.buf, mime, { root: buf.deps.cfg.runtimeRoot ?? buf.deps.cfg.root });
|
|
166
|
+
await store.appendAudit({ ts: buf.deps.now(), job_id: '-', request_id: buf.msgIds[0] ?? '-', event: 'wecom_image_rehosted', detail: { account: buf.accountId, bucket: bucket.name, storage: bucket.kind, key: okey, bytes: media.buf.length, mime } }).catch(() => undefined);
|
|
167
|
+
} catch (e) { await store.appendAudit({ ts: buf.deps.now(), job_id: '-', request_id: buf.msgIds[0] ?? '-', event: 'wecom_image_rehost_failed', detail: { account: buf.accountId, error: String(e).slice(0, 300) } }).catch(() => undefined); }
|
|
168
|
+
} else { await store.appendAudit({ ts: buf.deps.now(), job_id: '-', request_id: buf.msgIds[0] ?? '-', event: 'wecom_image_rehost_failed', detail: { account: buf.accountId, error: media.error ?? 'media/get 失败' } }).catch(() => undefined); }
|
|
169
|
+
}
|
|
170
|
+
if (!imgUrl) imgUrl = part.picUrl;
|
|
171
|
+
if (imgUrl) segments.push(``);
|
|
172
|
+
}
|
|
173
|
+
if (hasImage && !hasText && !segments.some((s) => s.startsWith('!['))) { replyHeld('图片没收到(拿不到图片地址),请重发或改用文字描述。'); return; }
|
|
174
|
+
let fullInput = segments.join('\n').trim();
|
|
175
|
+
if (!fullInput) { ackHeld(); return; }
|
|
176
|
+
if (hasImage && !hasText) fullInput += '\n[用户发来一张图片]'; // 纯图无文字:给大脑一句中性引导
|
|
177
|
+
|
|
178
|
+
const route = await cfgStore.routes.get(buf.routeKey);
|
|
179
|
+
const targetDef = route ? await resolveTargetDef(cfgStore, route.target, buf.deps.targetRegistry) : null;
|
|
180
|
+
if (!route || !route.enabled || !targetDef || targetDef.enabled === false) { replyHeld('该渠道尚未配置好(路由缺失或未启用),请联系管理员。'); return; }
|
|
181
|
+
const projectPath = route.project ? await buf.deps.resolveProjectPathFor(cfgStore, route.project) : null;
|
|
182
|
+
const scopeKey = channelScopeKey('wecom', buf.accountId, buf.fromUser); // 出站 /send 复用同一函数,杜绝 scope 漂移
|
|
183
|
+
const sess = await cfgStore.conversations.sessionForScope(route.route_key, scopeKey);
|
|
184
|
+
// 渠道输出风格:默认注入企微纯文本提示;渠道配置 reply_hint 可覆盖文案,显式空串则关闭。
|
|
185
|
+
const replyHint = (buf.cc['reply_hint'] !== undefined ? String(buf.cc['reply_hint']) : WECOM_PLAINTEXT_HINT).trim();
|
|
186
|
+
const job = await engine.launchJob({
|
|
187
|
+
requestId: `wecom_${randomUUID()}`, fullInput,
|
|
188
|
+
route, routeKey: route.route_key, target: route.target, project: route.project ?? null, projectPath,
|
|
189
|
+
profileName: route.profile, permission: route.permission, source: `wecom:${buf.accountId}`,
|
|
190
|
+
metadata: { wecom_account: buf.accountId, wecom_userid: buf.fromUser, wecom_msgtype: hasImage ? (hasText ? 'image+text' : 'image') : 'text', wecom_msg_count: buf.parts.length, ...(buf.agentId ? { wecom_agentid: buf.agentId } : {}), wecom_msgid: buf.msgIds.join(','), no_delivery: true, ...(replyHint ? { reply_hint: replyHint } : {}) },
|
|
191
|
+
session: { sessionId: sess.sessionId, isContinue: sess.isContinue },
|
|
192
|
+
threadScope: scopeKey, principalId: `wxuid:${buf.fromUser}`.slice(0, 64), channel: `wecom:${buf.accountId}`,
|
|
193
|
+
});
|
|
194
|
+
for (const mid of buf.msgIds) runtimeState.seen.set(`${buf.runtimeScopeKey}:${mid}`, { jobId: job.job_id, ts: Date.now() });
|
|
195
|
+
// 5s 窗口余额:用掉了 攒窗口+图片下载 的时间,剩下的给大脑;够则被动回复,不够则空 ack + 异步推
|
|
196
|
+
const budget = Math.max(300, Math.min(buf.replyWaitMs, 4500) - (Date.now() - buf.firstMs));
|
|
197
|
+
const fin = await engine.waitForJob(job.job_id, budget);
|
|
198
|
+
if (fin && fin.status === 'done') {
|
|
199
|
+
const r = (fin.result ?? {}) as Record<string, unknown>;
|
|
200
|
+
const text = typeof r['text'] === 'string' && r['text'] ? (r['text'] as string) : (fin.raw_result || '(无内容)');
|
|
201
|
+
// 被动回复(单条 XML)无法分条:超企微字节上限会被客户端截断。长回复改走异步主动推(sendWecomText 会按字节分条发全)。
|
|
202
|
+
// 需出站凭证;缺凭证时只能退回被动回复(截断,但已是无凭证下最优)。
|
|
203
|
+
if (Buffer.byteLength(String(text), 'utf8') > WECOM_TEXT_SAFE_BYTES && buf.corpid && buf.secret && buf.agentId) {
|
|
204
|
+
ackHeld();
|
|
205
|
+
scheduleWecomPush(buf.deps, buf.accountId, buf.corpid, buf.secret, buf.agentId, buf.fromUser, job.job_id);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
replyHeld(String(text)); return;
|
|
209
|
+
}
|
|
210
|
+
if (fin && (fin.status === 'error' || fin.status === 'rejected')) { replyHeld('抱歉,本次处理失败,请稍后再试。'); return; }
|
|
211
|
+
ackHeld();
|
|
212
|
+
scheduleWecomPush(buf.deps, buf.accountId, buf.corpid, buf.secret, buf.agentId, buf.fromUser, job.job_id);
|
|
213
|
+
} catch (e) {
|
|
214
|
+
ackHeld();
|
|
215
|
+
await auditStore?.appendAudit({ ts: buf.deps.now(), job_id: '-', request_id: buf.msgIds[0] ?? '-', event: 'wecom_flush_error', detail: { account: buf.accountId, error: String(e).slice(0, 300) } }).catch(() => undefined);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export async function handleWecomInboundFor(deps: WecomApiDeps, req: IncomingMessage, res: ServerResponse, accountId: string, url: URL): Promise<void> {
|
|
220
|
+
const runtimeState = deps.runtimeState ?? defaultWecomRuntimeState;
|
|
221
|
+
const { ctx, config: cfgStore } = await wecomRuntime(deps, accountId, `wecom:${accountId}:${url.searchParams.get('timestamp') ?? Date.now()}`);
|
|
222
|
+
const runtimeScopeKey = `${ctx.scope.kind}:${ctx.scope.id}`;
|
|
223
|
+
if (!cfgStore) { res.writeHead(503, { 'content-type': 'text/plain' }); res.end('service not ready'); return; }
|
|
224
|
+
// 渠道配置来自后台「渠道」注册表(bz_channels),不再写死 config.json
|
|
225
|
+
const channel = await cfgStore.channels.get(accountId);
|
|
226
|
+
if (!channel || !channel.enabled || channel.kind !== 'wecom') { res.writeHead(404, { 'content-type': 'text/plain' }); res.end('unknown wecom channel'); return; }
|
|
227
|
+
const cc = channel.config as Record<string, unknown>;
|
|
228
|
+
const token = String(cc['token'] ?? '');
|
|
229
|
+
const aesKey = String(cc['aes_key'] ?? '');
|
|
230
|
+
const cfgCorpid = String(cc['corpid'] ?? '').trim();
|
|
231
|
+
const secret = String(cc['secret'] ?? '').trim();
|
|
232
|
+
const cfgAgentId = String(cc['agentid'] ?? '').trim();
|
|
233
|
+
const replyWaitMs = Number(cc['reply_wait_ms'] ?? 4000) || 4000;
|
|
234
|
+
if (!token || !aesKey) { res.writeHead(404, { 'content-type': 'text/plain' }); res.end('channel not configured'); return; }
|
|
235
|
+
const sig = url.searchParams.get('msg_signature') ?? '';
|
|
236
|
+
const ts = url.searchParams.get('timestamp') ?? '';
|
|
237
|
+
const nonce = url.searchParams.get('nonce') ?? '';
|
|
238
|
+
|
|
239
|
+
// GET:企微后台「保存」时的 URL 验证(解密 echostr 原样回显)
|
|
240
|
+
if (req.method === 'GET') {
|
|
241
|
+
const plain = wecomVerifyUrl(token, aesKey, sig, ts, nonce, url.searchParams.get('echostr') ?? '', cfgCorpid || undefined);
|
|
242
|
+
if (plain == null) { res.writeHead(401, { 'content-type': 'text/plain' }); res.end('invalid signature'); return; }
|
|
243
|
+
res.writeHead(200, { 'content-type': 'text/plain' }); res.end(plain); return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// POST:加密消息
|
|
247
|
+
let xml = '';
|
|
248
|
+
try { xml = await readRawBody(req); } catch { res.writeHead(413, { 'content-type': 'text/plain' }); res.end(''); return; }
|
|
249
|
+
const encrypt = wecomXmlField(xml, 'Encrypt');
|
|
250
|
+
if (!encrypt || wecomSign(token, ts, nonce, encrypt) !== sig) { res.writeHead(401, { 'content-type': 'text/plain' }); res.end('invalid signature'); return; }
|
|
251
|
+
let inner: { message: string; receiveId: string };
|
|
252
|
+
try { inner = wecomDecrypt(aesKey, encrypt); } catch { res.writeHead(400, { 'content-type': 'text/plain' }); res.end(''); return; }
|
|
253
|
+
if (cfgCorpid && inner.receiveId && inner.receiveId !== cfgCorpid) { res.writeHead(401, { 'content-type': 'text/plain' }); res.end(''); return; }
|
|
254
|
+
|
|
255
|
+
const msg = inner.message;
|
|
256
|
+
const fromUser = wecomXmlField(msg, 'FromUserName');
|
|
257
|
+
const msgType = wecomXmlField(msg, 'MsgType');
|
|
258
|
+
const msgId = wecomXmlField(msg, 'MsgId') || `${fromUser}:${wecomXmlField(msg, 'CreateTime')}`;
|
|
259
|
+
const agentId = cfgAgentId || wecomXmlField(msg, 'AgentID');
|
|
260
|
+
// corpid:优先配置,缺省取密文尾部 receiveId(企微自建应用即 corpid);被动回复 receiveid 与主动推 gettoken 都用它
|
|
261
|
+
const corpid = (cfgCorpid || inner.receiveId || '').trim();
|
|
262
|
+
const replyText = (text: string): void => { res.writeHead(200, { 'content-type': 'application/xml; charset=utf-8' }); res.end(wecomBuildReply(token, aesKey, corpid, fromUser, text)); };
|
|
263
|
+
const ackEmpty = (): void => { res.writeHead(200, { 'content-type': 'text/plain' }); res.end(''); };
|
|
264
|
+
|
|
265
|
+
if (msgType === 'event') { ackEmpty(); return; } // 关注/进入应用等事件:静默 ack
|
|
266
|
+
if (deps.isPaused()) { replyText('服务暂停中,请稍后再试。'); return; }
|
|
267
|
+
|
|
268
|
+
// 企微 5s 无响应会重试同一 MsgId:占位去重(提前到入缓冲前,避免重试重复并入/重复处理)
|
|
269
|
+
runtimeState.pruneSeen();
|
|
270
|
+
const seenKey = `${runtimeScopeKey}:${msgId}`;
|
|
271
|
+
if (runtimeState.seen.has(seenKey)) { ackEmpty(); return; }
|
|
272
|
+
runtimeState.seen.set(seenKey, { jobId: '', ts: Date.now() });
|
|
273
|
+
|
|
274
|
+
// 解析这条消息为一个 part;图片此刻只记 MediaId/PicUrl,下载落桶推迟到窗口结束统一做(见 flushWecom)
|
|
275
|
+
let part: WecomPart;
|
|
276
|
+
if (msgType === 'text') {
|
|
277
|
+
const text = wecomXmlField(msg, 'Content').trim();
|
|
278
|
+
if (!text) { ackEmpty(); return; }
|
|
279
|
+
part = { kind: 'text', text };
|
|
280
|
+
} else if (msgType === 'image') {
|
|
281
|
+
part = { kind: 'image', mediaId: wecomXmlField(msg, 'MediaId').trim(), picUrl: wecomXmlField(msg, 'PicUrl').trim() };
|
|
282
|
+
} else {
|
|
283
|
+
replyText('我目前只看得懂文字和图片消息哦,请用文字或图片描述你的问题。'); return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 短窗口聚合:同一 (账号+用户) 的连发合成一轮。首条 hold 住回调(被动回复),后续条立即空 ack。
|
|
287
|
+
const key = `${runtimeScopeKey}:${accountId}:${fromUser}`;
|
|
288
|
+
const coalesceMs = Math.min(Math.max(Number(cc['coalesce_ms'] ?? WECOM_COALESCE_MS) || WECOM_COALESCE_MS, 0), WECOM_COALESCE_MAX_MS);
|
|
289
|
+
const existing = runtimeState.buffers.get(key);
|
|
290
|
+
if (existing) {
|
|
291
|
+
existing.parts.push(part); existing.msgIds.push(msgId);
|
|
292
|
+
if (existing.timer) clearTimeout(existing.timer);
|
|
293
|
+
const wait = Math.max(0, Math.min(coalesceMs, WECOM_COALESCE_MAX_MS - (Date.now() - existing.firstMs)));
|
|
294
|
+
existing.timer = setTimeout(() => { void flushWecom(runtimeState, key); }, wait);
|
|
295
|
+
ackEmpty(); return; // 后续条:正文已并入缓冲,立即空 ack
|
|
296
|
+
}
|
|
297
|
+
const buf: WecomBuf = {
|
|
298
|
+
parts: [part], msgIds: [msgId], timer: null, firstMs: Date.now(),
|
|
299
|
+
held: { res, token, aesKey, corpid, fromUser }, // 首条 hold 住 res,窗口结束由 flushWecom 统一回复
|
|
300
|
+
accountId, routeKey: channel.route_key, secret, agentId, corpid, fromUser, runtimeScopeKey, cc, replyWaitMs,
|
|
301
|
+
publicBaseUrl: wecomPublicBaseUrl(req, deps.httpMountPath),
|
|
302
|
+
deps,
|
|
303
|
+
};
|
|
304
|
+
buf.timer = setTimeout(() => { void flushWecom(runtimeState, key); }, coalesceMs);
|
|
305
|
+
runtimeState.buffers.set(key, buf);
|
|
306
|
+
// 首条不立即响应:res 已交给 buf.held,连接保持到 flushWecom 写回
|
|
307
|
+
}
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// OSS 默认进程也走公开 Kernel Host API,确保独立部署与外部宿主复用同一条装配路径。
|
|
2
|
+
import { createBailingHubKernel } from './app/kernel';
|
|
3
|
+
import { loadConfig } from './core/config/config';
|
|
4
|
+
|
|
5
|
+
const kernel = createBailingHubKernel({
|
|
6
|
+
instanceKey: 'oss:default',
|
|
7
|
+
config: loadConfig(),
|
|
8
|
+
schedulerMode: 'standalone',
|
|
9
|
+
});
|
|
10
|
+
const appServer = kernel.createStandaloneServer();
|
|
11
|
+
|
|
12
|
+
await appServer.start();
|
|
13
|
+
appServer.registerSignalHandlers();
|