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,74 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { readOpenAiChatCompletion } from './openai-chat-stream';
|
|
4
|
+
|
|
5
|
+
function sseResponse(chunks: Uint8Array[]): Response {
|
|
6
|
+
return new Response(new ReadableStream<Uint8Array>({
|
|
7
|
+
start(controller) {
|
|
8
|
+
chunks.forEach((chunk) => controller.enqueue(chunk));
|
|
9
|
+
controller.close();
|
|
10
|
+
},
|
|
11
|
+
}), { headers: { 'content-type': 'text/event-stream; charset=utf-8' } });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
test('openai stream: decodes split UTF-8 and aggregates content', async () => {
|
|
15
|
+
const bytes = new TextEncoder().encode('data: {"choices":[{"delta":{"role":"assistant","content":"你"}}]}\r\n\r\ndata: {"choices":[{"delta":{"content":"好"},"finish_reason":"stop"}]}\r\n\r\ndata: [DONE]\r\n\r\n');
|
|
16
|
+
const deltas: string[] = [];
|
|
17
|
+
const result = await readOpenAiChatCompletion(sseResponse([
|
|
18
|
+
bytes.slice(0, 63),
|
|
19
|
+
bytes.slice(63, 66),
|
|
20
|
+
bytes.slice(66),
|
|
21
|
+
]), { onDelta: (text) => deltas.push(text) });
|
|
22
|
+
|
|
23
|
+
assert.equal(result.message['content'], '你好');
|
|
24
|
+
assert.deepEqual(deltas, ['你', '好']);
|
|
25
|
+
assert.equal(result.finishReason, 'stop');
|
|
26
|
+
assert.equal(result.streamed, true);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test('openai stream: aggregates fragmented tool calls by index', async () => {
|
|
30
|
+
const source = [
|
|
31
|
+
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_","type":"function","function":{"name":"order_","arguments":"{\\"id\\":"}}]}}]}\n\n',
|
|
32
|
+
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"1","function":{"name":"get","arguments":"\\"42\\"}"}}]},"finish_reason":"tool_calls"}]}\n\n',
|
|
33
|
+
'data: [DONE]\n\n',
|
|
34
|
+
].join('');
|
|
35
|
+
const result = await readOpenAiChatCompletion(sseResponse([new TextEncoder().encode(source)]));
|
|
36
|
+
const calls = result.message['tool_calls'] as Array<Record<string, unknown>>;
|
|
37
|
+
|
|
38
|
+
assert.equal(calls.length, 1);
|
|
39
|
+
assert.equal(calls[0]?.['id'], 'call_1');
|
|
40
|
+
assert.deepEqual(calls[0]?.['function'], { name: 'order_get', arguments: '{"id":"42"}' });
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('openai stream: preserves reasoning_content for a later tool-call round without exposing it as answer text', async () => {
|
|
44
|
+
const source = [
|
|
45
|
+
'data: {"choices":[{"delta":{"role":"assistant","reasoning_content":"need "}}]}\n\n',
|
|
46
|
+
'data: {"choices":[{"delta":{"reasoning_content":"lookup","tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"lookup_order","arguments":"{}"}}]},"finish_reason":"tool_calls"}]}\n\n',
|
|
47
|
+
'data: [DONE]\n\n',
|
|
48
|
+
].join('');
|
|
49
|
+
const deltas: string[] = [];
|
|
50
|
+
const result = await readOpenAiChatCompletion(
|
|
51
|
+
sseResponse([new TextEncoder().encode(source)]),
|
|
52
|
+
{ onDelta: (text) => deltas.push(text) },
|
|
53
|
+
);
|
|
54
|
+
|
|
55
|
+
assert.equal(result.message['reasoning_content'], 'need lookup');
|
|
56
|
+
assert.equal(result.message['content'], null);
|
|
57
|
+
assert.deepEqual(deltas, []);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('openai stream: accepts a JSON fallback response', async () => {
|
|
61
|
+
const response = new Response(JSON.stringify({
|
|
62
|
+
choices: [{ message: { role: 'assistant', content: 'fallback' }, finish_reason: 'stop' }],
|
|
63
|
+
usage: { total_tokens: 7 },
|
|
64
|
+
}), { headers: { 'content-type': 'application/json' } });
|
|
65
|
+
const result = await readOpenAiChatCompletion(response);
|
|
66
|
+
assert.equal(result.message['content'], 'fallback');
|
|
67
|
+
assert.equal(result.totalTokens, 7);
|
|
68
|
+
assert.equal(result.streamed, false);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('openai stream: rejects a truncated response without completion evidence', async () => {
|
|
72
|
+
const response = sseResponse([new TextEncoder().encode('data: {"choices":[{"delta":{"content":"partial"}}]}\n\n')]);
|
|
73
|
+
await assert.rejects(() => readOpenAiChatCompletion(response), /提前结束/);
|
|
74
|
+
});
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
export interface OpenAiChatStreamResult {
|
|
2
|
+
message: Record<string, unknown>;
|
|
3
|
+
totalTokens: number;
|
|
4
|
+
finishReason: string | null;
|
|
5
|
+
streamed: boolean;
|
|
6
|
+
chunkCount: number;
|
|
7
|
+
contentChars: number;
|
|
8
|
+
firstTokenMs?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface OpenAiChatStreamOptions {
|
|
12
|
+
onDelta?: (text: string) => void;
|
|
13
|
+
startedAt?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface ToolCallAccumulator {
|
|
17
|
+
id: string;
|
|
18
|
+
type: string;
|
|
19
|
+
function: { name: string; arguments: string };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function record(value: unknown): Record<string, unknown> | null {
|
|
23
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function contentText(value: unknown): string {
|
|
27
|
+
if (typeof value === 'string') return value;
|
|
28
|
+
if (!Array.isArray(value)) return '';
|
|
29
|
+
return value.map((part) => {
|
|
30
|
+
if (typeof part === 'string') return part;
|
|
31
|
+
const item = record(part);
|
|
32
|
+
return typeof item?.['text'] === 'string' ? item['text'] : '';
|
|
33
|
+
}).join('');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function completionFromJson(data: unknown): OpenAiChatStreamResult {
|
|
37
|
+
const root = record(data);
|
|
38
|
+
const choices = Array.isArray(root?.['choices']) ? root['choices'] : [];
|
|
39
|
+
const choice = record(choices[0]);
|
|
40
|
+
const message = record(choice?.['message']);
|
|
41
|
+
if (!message) throw new Error('LLM JSON 响应缺少 choices[0].message');
|
|
42
|
+
const usage = record(root?.['usage']);
|
|
43
|
+
const content = contentText(message['content']);
|
|
44
|
+
return {
|
|
45
|
+
message: { ...message, ...(content ? { content } : {}) },
|
|
46
|
+
totalTokens: Number(usage?.['total_tokens'] ?? 0) || 0,
|
|
47
|
+
finishReason: typeof choice?.['finish_reason'] === 'string' ? choice['finish_reason'] : null,
|
|
48
|
+
streamed: false,
|
|
49
|
+
chunkCount: 0,
|
|
50
|
+
contentChars: content.length,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function appendToolCalls(target: Map<number, ToolCallAccumulator>, value: unknown): void {
|
|
55
|
+
if (!Array.isArray(value)) return;
|
|
56
|
+
value.forEach((raw, position) => {
|
|
57
|
+
const part = record(raw);
|
|
58
|
+
if (!part) return;
|
|
59
|
+
const indexValue = Number(part['index']);
|
|
60
|
+
const index = Number.isInteger(indexValue) && indexValue >= 0 ? indexValue : position;
|
|
61
|
+
const current = target.get(index) ?? { id: '', type: 'function', function: { name: '', arguments: '' } };
|
|
62
|
+
const fn = record(part['function']);
|
|
63
|
+
if (typeof part['id'] === 'string') current.id += part['id'];
|
|
64
|
+
if (typeof part['type'] === 'string') current.type = part['type'];
|
|
65
|
+
if (typeof fn?.['name'] === 'string') current.function.name += fn['name'];
|
|
66
|
+
if (typeof fn?.['arguments'] === 'string') current.function.arguments += fn['arguments'];
|
|
67
|
+
target.set(index, current);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseSseData(block: string): string | null {
|
|
72
|
+
const data = block.split(/\r?\n/)
|
|
73
|
+
.filter((line) => line.startsWith('data:'))
|
|
74
|
+
.map((line) => line.slice(5).replace(/^ /, ''));
|
|
75
|
+
return data.length ? data.join('\n') : null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function readOpenAiChatCompletion(response: Response, options: OpenAiChatStreamOptions = {}): Promise<OpenAiChatStreamResult> {
|
|
79
|
+
const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
|
|
80
|
+
if (!contentType.includes('text/event-stream')) {
|
|
81
|
+
return completionFromJson(await response.json());
|
|
82
|
+
}
|
|
83
|
+
if (!response.body) throw new Error('LLM 流式响应没有响应体');
|
|
84
|
+
|
|
85
|
+
const reader = response.body.getReader();
|
|
86
|
+
const decoder = new TextDecoder();
|
|
87
|
+
const toolCalls = new Map<number, ToolCallAccumulator>();
|
|
88
|
+
let buffer = '';
|
|
89
|
+
let content = '';
|
|
90
|
+
let reasoningContent = '';
|
|
91
|
+
let role = '';
|
|
92
|
+
let totalTokens = 0;
|
|
93
|
+
let finishReason: string | null = null;
|
|
94
|
+
let chunkCount = 0;
|
|
95
|
+
let firstTokenMs: number | undefined;
|
|
96
|
+
let doneMarker = false;
|
|
97
|
+
|
|
98
|
+
const consume = (block: string) => {
|
|
99
|
+
const raw = parseSseData(block);
|
|
100
|
+
if (raw === null) return;
|
|
101
|
+
if (raw.trim() === '[DONE]') { doneMarker = true; return; }
|
|
102
|
+
let payload: unknown;
|
|
103
|
+
try { payload = JSON.parse(raw); }
|
|
104
|
+
catch { throw new Error('LLM 流式响应包含无效 JSON 事件'); }
|
|
105
|
+
chunkCount++;
|
|
106
|
+
const root = record(payload);
|
|
107
|
+
const usage = record(root?.['usage']);
|
|
108
|
+
totalTokens = Math.max(totalTokens, Number(usage?.['total_tokens'] ?? 0) || 0);
|
|
109
|
+
const choices = Array.isArray(root?.['choices']) ? root['choices'] : [];
|
|
110
|
+
const choice = record(choices[0]);
|
|
111
|
+
if (!choice) return;
|
|
112
|
+
if (typeof choice['finish_reason'] === 'string') finishReason = choice['finish_reason'];
|
|
113
|
+
const delta = record(choice['delta']) ?? record(choice['message']);
|
|
114
|
+
if (!delta) return;
|
|
115
|
+
if (typeof delta['role'] === 'string') role = delta['role'];
|
|
116
|
+
appendToolCalls(toolCalls, delta['tool_calls']);
|
|
117
|
+
if (typeof delta['reasoning_content'] === 'string') reasoningContent += delta['reasoning_content'];
|
|
118
|
+
const text = contentText(delta['content']);
|
|
119
|
+
if (!text) return;
|
|
120
|
+
if (firstTokenMs === undefined) firstTokenMs = Math.max(0, Date.now() - (options.startedAt ?? Date.now()));
|
|
121
|
+
content += text;
|
|
122
|
+
options.onDelta?.(text);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
for (;;) {
|
|
126
|
+
const part = await reader.read();
|
|
127
|
+
buffer += decoder.decode(part.value, { stream: !part.done });
|
|
128
|
+
let match: RegExpExecArray | null;
|
|
129
|
+
while ((match = /\r?\n\r?\n/.exec(buffer))) {
|
|
130
|
+
const block = buffer.slice(0, match.index);
|
|
131
|
+
buffer = buffer.slice(match.index + match[0].length);
|
|
132
|
+
consume(block);
|
|
133
|
+
}
|
|
134
|
+
if (part.done) break;
|
|
135
|
+
}
|
|
136
|
+
if (buffer.trim()) consume(buffer);
|
|
137
|
+
if (!doneMarker && finishReason === null) throw new Error('LLM 流式响应提前结束,未收到完成标记');
|
|
138
|
+
|
|
139
|
+
const orderedToolCalls = [...toolCalls.entries()].sort((a, b) => a[0] - b[0]).map(([, call]) => call);
|
|
140
|
+
return {
|
|
141
|
+
message: {
|
|
142
|
+
role: role || 'assistant',
|
|
143
|
+
content: content || null,
|
|
144
|
+
...(reasoningContent ? { reasoning_content: reasoningContent } : {}),
|
|
145
|
+
...(orderedToolCalls.length ? { tool_calls: orderedToolCalls } : {}),
|
|
146
|
+
},
|
|
147
|
+
totalTokens,
|
|
148
|
+
finishReason,
|
|
149
|
+
streamed: true,
|
|
150
|
+
chunkCount,
|
|
151
|
+
contentChars: content.length,
|
|
152
|
+
...(firstTokenMs === undefined ? {} : { firstTokenMs }),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// 感知层(多模态解耦)—— 设计与边界见 docs/TOOLS_DESIGN.md「感知层」。
|
|
2
|
+
//
|
|
3
|
+
// 为什么解耦:中枢的「大脑」(brain,target_config.model)是编排者,最重要的能力是**可靠地调用工具**;
|
|
4
|
+
// 而「看图」是另一种能力。把两者绑在同一个模型上很脆——很多最强的工具模型不识图(如纯文本的
|
|
5
|
+
// qwen-plus / deepseek),很多识图模型又不会调工具(实测 qwen-vl-max 在工具调用上 0 命中)。
|
|
6
|
+
// 本模块把「看图」拆成一个独立可配的**视觉模型**,通过两条路接入,让 brain 用纯文本工具模型也能间接看图:
|
|
7
|
+
// - tool 模式:给 brain 一个内置工具 see_image,它按需对「图 + 问题」做一次视觉子调用,结果回流;
|
|
8
|
+
// - prepass 模式:派发前先把图识别成文字,前置注入,brain 纯文本+工具正常跑。
|
|
9
|
+
// 这样开发者(含海外)可以任意搭配「最强工具模型 + 任意视觉模型」,不被「又能看图又能调工具的独角兽模型」绑架。
|
|
10
|
+
|
|
11
|
+
/** 解析后的模型凭证(base_url + key,可选默认模型)。与 config.ts 的 LlmCredential、bz_credentials 行兼容。 */
|
|
12
|
+
export interface ResolvedCredential {
|
|
13
|
+
base_url: string;
|
|
14
|
+
api_key: string;
|
|
15
|
+
default_model?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 路由 target_config.input.image:图片输入策略(全可选)。 */
|
|
19
|
+
export interface VisionConfig {
|
|
20
|
+
/** 视觉模型凭证名(「模型凭证」注册表);留空复用 brain 凭证(同一把 key 调不同模型) */
|
|
21
|
+
credential?: string;
|
|
22
|
+
/** 视觉模型;留空用凭证默认模型 */
|
|
23
|
+
model?: string;
|
|
24
|
+
/** 图片接入方式:tool=见图工具(推荐,最解耦)/ prepass=前置识图 / inline=直送 brain(brain 须多模态)/ off=忽略图片 */
|
|
25
|
+
mode?: 'tool' | 'prepass' | 'inline' | 'off';
|
|
26
|
+
/** 单次任务的视觉调用次数上限(tool 模式防刷;不占业务工具的 max_calls)。默认 VISION_MAX_CALLS_DEFAULT */
|
|
27
|
+
max_calls?: number;
|
|
28
|
+
/** 派发时由中枢注入的已解析凭证(key 只进本次调用内存,不落 job 快照/日志)。 */
|
|
29
|
+
_db_credential?: ResolvedCredential;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 无显式 mode 且视觉模型可用时的默认接入方式:见图工具(最解耦、最 agentic)。 */
|
|
33
|
+
export const VISION_MODE_DEFAULT: 'tool' = 'tool';
|
|
34
|
+
/** tool 模式单任务视觉调用次数上限缺省值。 */
|
|
35
|
+
export const VISION_MAX_CALLS_DEFAULT = 6;
|
|
36
|
+
/** 视觉子调用超时(ms)。识图通常比纯文本慢,给足。 */
|
|
37
|
+
export const VISION_TIMEOUT_MS = 60000;
|
|
38
|
+
|
|
39
|
+
/** see_image 内置工具定义(OpenAI function-calling 形态)。imageCount 写进描述,让 brain 知道有几张可看。 */
|
|
40
|
+
export function seeImageTool(imageCount: number): {
|
|
41
|
+
type: 'function';
|
|
42
|
+
function: { name: string; description: string; parameters: Record<string, unknown> };
|
|
43
|
+
} {
|
|
44
|
+
const range = imageCount > 1 ? `序号 0..${imageCount - 1}` : '序号 0';
|
|
45
|
+
return {
|
|
46
|
+
type: 'function',
|
|
47
|
+
function: {
|
|
48
|
+
name: 'see_image',
|
|
49
|
+
description:
|
|
50
|
+
`查看用户本次附带的图片并回答关于图片的问题(用户共附带 ${imageCount} 张,${range})。` +
|
|
51
|
+
'需要图片里的信息时调用本工具:question 精确描述你要看什么' +
|
|
52
|
+
'(如"图中员工的工号是多少""识别这张小票的金额与商品""图里的二维码内容");' +
|
|
53
|
+
'indexes 可选,只看指定序号的图,默认看全部。返回文字描述,你可据此继续调用业务工具或作答。' +
|
|
54
|
+
'不要凭空臆测图片内容——要图片信息就调用本工具拿真实识别结果。',
|
|
55
|
+
parameters: {
|
|
56
|
+
type: 'object',
|
|
57
|
+
properties: {
|
|
58
|
+
question: { type: 'string', description: '要从图片中获取的具体信息或问题' },
|
|
59
|
+
indexes: { type: 'array', items: { type: 'integer' }, description: '只看这些序号的图(从 0 开始);省略=看全部' },
|
|
60
|
+
},
|
|
61
|
+
required: ['question'],
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 按 indexes 过滤图片 URL(越界/非法忽略);indexes 为空或缺省返回全部。 */
|
|
68
|
+
export function selectImages(all: string[], indexes?: unknown): string[] {
|
|
69
|
+
if (!Array.isArray(indexes) || !indexes.length) return all;
|
|
70
|
+
const picked: string[] = [];
|
|
71
|
+
for (const i of indexes) {
|
|
72
|
+
const n = Number(i);
|
|
73
|
+
if (Number.isInteger(n) && n >= 0 && n < all.length && !picked.includes(all[n]!)) picked.push(all[n]!);
|
|
74
|
+
}
|
|
75
|
+
return picked.length ? picked : all;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface VisionResult {
|
|
79
|
+
ok: boolean;
|
|
80
|
+
text: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 用视觉模型对「图片 + 问题」做一次 OpenAI 兼容多模态子调用(无工具、非流式),返回文字。
|
|
85
|
+
* 失败(HTTP 错误/超时/空响应)以 ok=false + 文本回传,由调用方决定如何回流——绝不抛错炸断整条任务。
|
|
86
|
+
*/
|
|
87
|
+
export async function runVision(opts: {
|
|
88
|
+
cred: ResolvedCredential;
|
|
89
|
+
model: string;
|
|
90
|
+
images: string[];
|
|
91
|
+
question: string;
|
|
92
|
+
timeoutMs?: number;
|
|
93
|
+
}): Promise<VisionResult> {
|
|
94
|
+
const { cred, model, images, question } = opts;
|
|
95
|
+
if (!images.length) return { ok: false, text: '(没有可查看的图片)' };
|
|
96
|
+
const url = cred.base_url.replace(/\/+$/, '') + '/chat/completions';
|
|
97
|
+
const content: Array<Record<string, unknown>> = [
|
|
98
|
+
{ type: 'text', text: question || '请客观、详细地描述这些图片中的全部可见内容与文字。' },
|
|
99
|
+
...images.map((u) => ({ type: 'image_url', image_url: { url: u } })),
|
|
100
|
+
];
|
|
101
|
+
const body = {
|
|
102
|
+
model,
|
|
103
|
+
stream: false,
|
|
104
|
+
messages: [
|
|
105
|
+
{
|
|
106
|
+
role: 'system',
|
|
107
|
+
content:
|
|
108
|
+
'你是图像识别助手。只如实描述图片中**可见**的内容与文字(含 OCR),不要臆测看不到的信息;' +
|
|
109
|
+
'信息不足以回答时明确说明"图中看不到"。回答简洁、准确、面向下游助手使用。',
|
|
110
|
+
},
|
|
111
|
+
{ role: 'user', content },
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
try {
|
|
115
|
+
const resp = await fetch(url, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${cred.api_key}` },
|
|
118
|
+
body: JSON.stringify(body),
|
|
119
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? VISION_TIMEOUT_MS),
|
|
120
|
+
});
|
|
121
|
+
if (!resp.ok) {
|
|
122
|
+
const t = await resp.text();
|
|
123
|
+
return { ok: false, text: `视觉模型调用失败(HTTP ${resp.status}):${t.slice(0, 200)}` };
|
|
124
|
+
}
|
|
125
|
+
const data = (await resp.json()) as { choices?: Array<{ message?: { content?: unknown } }> };
|
|
126
|
+
const text = String(data?.choices?.[0]?.message?.content ?? '').trim();
|
|
127
|
+
return { ok: !!text, text: text || '(视觉模型返回空内容)' };
|
|
128
|
+
} catch (e) {
|
|
129
|
+
const isTimeout = (e as Error)?.name === 'TimeoutError';
|
|
130
|
+
return {
|
|
131
|
+
ok: false,
|
|
132
|
+
text: isTimeout
|
|
133
|
+
? `视觉模型调用超时(${opts.timeoutMs ?? VISION_TIMEOUT_MS}ms)`
|
|
134
|
+
: `视觉模型调用失败:${String(e).slice(0, 200)}`,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* 解析视觉模型的「凭证 + 模型」。返回 null = 无法识图(调用方应退回 inline:把图直送 brain)。
|
|
141
|
+
* 凭证优先级:config.json 凭证 > 派发注入的 _db_credential > (凭证名与 brain 相同则)复用 brain 凭证。
|
|
142
|
+
*/
|
|
143
|
+
export function resolveVision(
|
|
144
|
+
llmCredentials: Record<string, ResolvedCredential>,
|
|
145
|
+
vcfg: VisionConfig | undefined,
|
|
146
|
+
brainCred: ResolvedCredential | undefined,
|
|
147
|
+
brainCredName: string,
|
|
148
|
+
): { cred: ResolvedCredential; model: string } | null {
|
|
149
|
+
if (!vcfg) return null;
|
|
150
|
+
const credName = String(vcfg.credential ?? brainCredName ?? '');
|
|
151
|
+
const cred =
|
|
152
|
+
(credName && llmCredentials[credName]) ||
|
|
153
|
+
vcfg._db_credential ||
|
|
154
|
+
(credName && credName === brainCredName ? brainCred : undefined);
|
|
155
|
+
if (!cred) return null;
|
|
156
|
+
const model = String(vcfg.model ?? cred.default_model ?? '');
|
|
157
|
+
if (!model) return null;
|
|
158
|
+
return { cred, model };
|
|
159
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { test } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { transcribeAudio } from './speech';
|
|
4
|
+
|
|
5
|
+
async function withFetchImplementation<T>(implementation: typeof fetch, fn: () => Promise<T>): Promise<T> {
|
|
6
|
+
const old = globalThis.fetch;
|
|
7
|
+
globalThis.fetch = implementation;
|
|
8
|
+
try {
|
|
9
|
+
return await fn();
|
|
10
|
+
} finally {
|
|
11
|
+
globalThis.fetch = old;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function audioResponse(): Response {
|
|
16
|
+
return new Response(new Uint8Array([0x49, 0x44, 0x33, 0x04]), {
|
|
17
|
+
status: 200,
|
|
18
|
+
headers: { 'content-type': 'audio/mpeg' },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test('transcribeAudio: transcriptions 协议上传音频文件并读取 text', async () => {
|
|
23
|
+
const requests: Array<{ url: string; init?: RequestInit }> = [];
|
|
24
|
+
const got = await withFetchImplementation((async (input, init) => {
|
|
25
|
+
requests.push({ url: String(input), init });
|
|
26
|
+
if (requests.length === 1) return audioResponse();
|
|
27
|
+
return new Response(JSON.stringify({ text: '请查询订单状态' }), {
|
|
28
|
+
status: 200,
|
|
29
|
+
headers: { 'content-type': 'application/json' },
|
|
30
|
+
});
|
|
31
|
+
}) as typeof fetch, () => transcribeAudio({
|
|
32
|
+
cred: { base_url: 'https://asr.example.com/v1', api_key: 'sk-asr' },
|
|
33
|
+
model: 'whisper-1',
|
|
34
|
+
protocol: 'transcriptions',
|
|
35
|
+
audioUrl: 'https://media.example.com/message.mp3',
|
|
36
|
+
}));
|
|
37
|
+
|
|
38
|
+
assert.equal(got.ok, true);
|
|
39
|
+
assert.equal(got.text, '请查询订单状态');
|
|
40
|
+
assert.equal(requests[1]?.url, 'https://asr.example.com/v1/audio/transcriptions');
|
|
41
|
+
assert.equal(requests[1]?.init?.method, 'POST');
|
|
42
|
+
assert.equal(requests[1]?.init?.body instanceof FormData, true);
|
|
43
|
+
const form = requests[1]?.init?.body as FormData;
|
|
44
|
+
assert.equal(form.get('model'), 'whisper-1');
|
|
45
|
+
assert.equal(form.get('file') instanceof Blob, true);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test('transcribeAudio: chat_input_audio 协议使用 Data URL 并读取对话文本', async () => {
|
|
49
|
+
const requests: Array<{ url: string; init?: RequestInit }> = [];
|
|
50
|
+
const got = await withFetchImplementation((async (input, init) => {
|
|
51
|
+
requests.push({ url: String(input), init });
|
|
52
|
+
if (requests.length === 1) return audioResponse();
|
|
53
|
+
return new Response(JSON.stringify({
|
|
54
|
+
choices: [{ message: { content: '帮我看一下退款进度' } }],
|
|
55
|
+
}), {
|
|
56
|
+
status: 200,
|
|
57
|
+
headers: { 'content-type': 'application/json' },
|
|
58
|
+
});
|
|
59
|
+
}) as typeof fetch, () => transcribeAudio({
|
|
60
|
+
cred: { base_url: 'https://dashscope.example.com/compatible-mode/v1/', api_key: 'sk-asr' },
|
|
61
|
+
model: 'qwen3-asr-flash',
|
|
62
|
+
protocol: 'chat_input_audio',
|
|
63
|
+
audioUrl: 'https://media.example.com/message.mp3',
|
|
64
|
+
}));
|
|
65
|
+
|
|
66
|
+
assert.equal(got.ok, true);
|
|
67
|
+
assert.equal(got.text, '帮我看一下退款进度');
|
|
68
|
+
assert.equal(requests[1]?.url, 'https://dashscope.example.com/compatible-mode/v1/chat/completions');
|
|
69
|
+
const body = JSON.parse(String(requests[1]?.init?.body ?? '{}')) as {
|
|
70
|
+
model?: string;
|
|
71
|
+
messages?: Array<{ content?: Array<{ input_audio?: { data?: string } }> }>;
|
|
72
|
+
};
|
|
73
|
+
assert.equal(body.model, 'qwen3-asr-flash');
|
|
74
|
+
assert.match(String(body.messages?.[0]?.content?.[0]?.input_audio?.data), /^data:audio\/mpeg;base64,/);
|
|
75
|
+
});
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import type { ResolvedCredential } from './perception';
|
|
2
|
+
|
|
3
|
+
export interface AudioConfig {
|
|
4
|
+
/** 语音模型凭证名;留空复用 brain 凭证 */
|
|
5
|
+
credential?: string;
|
|
6
|
+
/** ASR 模型;留空用凭证默认模型 */
|
|
7
|
+
model?: string;
|
|
8
|
+
/** ASR 协议;transcriptions=传统转写端点,chat_input_audio=chat/completions 音频输入 */
|
|
9
|
+
protocol?: AudioProtocol;
|
|
10
|
+
/** transcribe=中枢先转文字;inline=音频直送具备语音理解能力的模型/执行器;off=忽略音频 */
|
|
11
|
+
mode?: 'transcribe' | 'inline' | 'off';
|
|
12
|
+
/** 单音频最大字节数,默认 AUDIO_MAX_BYTES_DEFAULT */
|
|
13
|
+
max_bytes?: number;
|
|
14
|
+
/** 单音频最大秒数(当前用于配置/审计表达,上传端不信任浏览器传值) */
|
|
15
|
+
max_seconds?: number;
|
|
16
|
+
/** 派发时由中枢注入的已解析凭证。 */
|
|
17
|
+
_db_credential?: ResolvedCredential;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type AudioProtocol = 'transcriptions' | 'chat_input_audio';
|
|
21
|
+
|
|
22
|
+
export const AUDIO_MODE_DEFAULT: 'transcribe' = 'transcribe';
|
|
23
|
+
export const AUDIO_PROTOCOL_DEFAULT: AudioProtocol = 'transcriptions';
|
|
24
|
+
export const AUDIO_MAX_BYTES_DEFAULT = 12 * 1024 * 1024;
|
|
25
|
+
export const AUDIO_TIMEOUT_MS = 60000;
|
|
26
|
+
|
|
27
|
+
export interface SpeechResult {
|
|
28
|
+
ok: boolean;
|
|
29
|
+
text: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function audioFilename(url: string, index: number): string {
|
|
33
|
+
const path = (() => { try { return new URL(url).pathname; } catch { return ''; } })();
|
|
34
|
+
const name = path.split('/').pop() || '';
|
|
35
|
+
return /\.[a-z0-9]{2,5}$/i.test(name) ? name : `audio-${index}.webm`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resolveAudio(
|
|
39
|
+
llmCredentials: Record<string, ResolvedCredential>,
|
|
40
|
+
acfg: AudioConfig | undefined,
|
|
41
|
+
brainCred: ResolvedCredential | undefined,
|
|
42
|
+
brainCredName: string,
|
|
43
|
+
): { cred: ResolvedCredential; model: string; protocol: AudioProtocol } | null {
|
|
44
|
+
if (!acfg) return null;
|
|
45
|
+
const credName = String(acfg.credential ?? brainCredName ?? '');
|
|
46
|
+
const cred =
|
|
47
|
+
(credName && llmCredentials[credName]) ||
|
|
48
|
+
acfg._db_credential ||
|
|
49
|
+
(credName && credName === brainCredName ? brainCred : undefined);
|
|
50
|
+
if (!cred) return null;
|
|
51
|
+
const model = String(acfg.model ?? cred.default_model ?? '');
|
|
52
|
+
if (!model) return null;
|
|
53
|
+
const protocol = acfg.protocol === 'chat_input_audio' ? 'chat_input_audio' : AUDIO_PROTOCOL_DEFAULT;
|
|
54
|
+
return { cred, model, protocol };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function fetchAudio(url: string, maxBytes: number): Promise<{ data: ArrayBuffer; blob: Blob; mime: string; bytes: number }> {
|
|
58
|
+
const r = await fetch(url, { signal: AbortSignal.timeout(AUDIO_TIMEOUT_MS) });
|
|
59
|
+
if (!r.ok) throw new Error(`音频下载失败(HTTP ${r.status})`);
|
|
60
|
+
const mime = String(r.headers.get('content-type') ?? 'audio/webm').split(';')[0]!.trim() || 'audio/webm';
|
|
61
|
+
const ab = await r.arrayBuffer();
|
|
62
|
+
if (ab.byteLength > maxBytes) throw new Error(`音频过大(${ab.byteLength} bytes > ${maxBytes} bytes)`);
|
|
63
|
+
return { data: ab, blob: new Blob([ab], { type: mime }), mime, bytes: ab.byteLength };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function readChatCompletionText(data: Record<string, unknown>): string {
|
|
67
|
+
const choices = Array.isArray(data['choices']) ? data['choices'] : [];
|
|
68
|
+
const first = choices[0];
|
|
69
|
+
if (!first || typeof first !== 'object') return '';
|
|
70
|
+
const message = (first as Record<string, unknown>)['message'];
|
|
71
|
+
if (!message || typeof message !== 'object') return '';
|
|
72
|
+
const content = (message as Record<string, unknown>)['content'];
|
|
73
|
+
if (typeof content === 'string') return content.trim();
|
|
74
|
+
if (!Array.isArray(content)) return '';
|
|
75
|
+
return content
|
|
76
|
+
.map((part) => {
|
|
77
|
+
if (typeof part === 'string') return part;
|
|
78
|
+
if (!part || typeof part !== 'object') return '';
|
|
79
|
+
return String((part as Record<string, unknown>)['text'] ?? '');
|
|
80
|
+
})
|
|
81
|
+
.join('')
|
|
82
|
+
.trim();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** OpenAI-compatible ASR。失败不抛给主链路,返回 ok=false + 可回流给模型的文本。 */
|
|
86
|
+
export async function transcribeAudio(opts: {
|
|
87
|
+
cred: ResolvedCredential;
|
|
88
|
+
model: string;
|
|
89
|
+
protocol?: AudioProtocol;
|
|
90
|
+
audioUrl: string;
|
|
91
|
+
index?: number;
|
|
92
|
+
maxBytes?: number;
|
|
93
|
+
timeoutMs?: number;
|
|
94
|
+
}): Promise<SpeechResult & { bytes?: number; mime?: string }> {
|
|
95
|
+
try {
|
|
96
|
+
const maxBytes = Math.max(1024, Math.min(Number(opts.maxBytes ?? AUDIO_MAX_BYTES_DEFAULT) || AUDIO_MAX_BYTES_DEFAULT, 50 * 1024 * 1024));
|
|
97
|
+
const audio = await fetchAudio(opts.audioUrl, maxBytes);
|
|
98
|
+
const protocol = opts.protocol ?? AUDIO_PROTOCOL_DEFAULT;
|
|
99
|
+
const baseUrl = opts.cred.base_url.replace(/\/+$/, '');
|
|
100
|
+
const resp = protocol === 'chat_input_audio'
|
|
101
|
+
? await fetch(baseUrl + '/chat/completions', {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: {
|
|
104
|
+
authorization: `Bearer ${opts.cred.api_key}`,
|
|
105
|
+
'content-type': 'application/json',
|
|
106
|
+
},
|
|
107
|
+
body: JSON.stringify({
|
|
108
|
+
model: opts.model,
|
|
109
|
+
stream: false,
|
|
110
|
+
messages: [{
|
|
111
|
+
role: 'user',
|
|
112
|
+
content: [{
|
|
113
|
+
type: 'input_audio',
|
|
114
|
+
input_audio: {
|
|
115
|
+
data: `data:${audio.mime};base64,${Buffer.from(audio.data).toString('base64')}`,
|
|
116
|
+
},
|
|
117
|
+
}],
|
|
118
|
+
}],
|
|
119
|
+
}),
|
|
120
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? AUDIO_TIMEOUT_MS),
|
|
121
|
+
})
|
|
122
|
+
: await (() => {
|
|
123
|
+
const fd = new FormData();
|
|
124
|
+
fd.set('model', opts.model);
|
|
125
|
+
fd.set('file', audio.blob, audioFilename(opts.audioUrl, opts.index ?? 0));
|
|
126
|
+
return fetch(baseUrl + '/audio/transcriptions', {
|
|
127
|
+
method: 'POST',
|
|
128
|
+
headers: { authorization: `Bearer ${opts.cred.api_key}` },
|
|
129
|
+
body: fd,
|
|
130
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? AUDIO_TIMEOUT_MS),
|
|
131
|
+
});
|
|
132
|
+
})();
|
|
133
|
+
if (!resp.ok) {
|
|
134
|
+
const t = await resp.text().catch(() => '');
|
|
135
|
+
return { ok: false, text: `语音转写失败(HTTP ${resp.status}):${t.slice(0, 200)}`, bytes: audio.bytes, mime: audio.mime };
|
|
136
|
+
}
|
|
137
|
+
const data = await resp.json().catch(() => ({})) as Record<string, unknown>;
|
|
138
|
+
const text = protocol === 'chat_input_audio'
|
|
139
|
+
? readChatCompletionText(data)
|
|
140
|
+
: String(data['text'] ?? '').trim();
|
|
141
|
+
return { ok: !!text, text: text || '(语音模型返回空内容)', bytes: audio.bytes, mime: audio.mime };
|
|
142
|
+
} catch (e) {
|
|
143
|
+
const isTimeout = (e as Error)?.name === 'TimeoutError';
|
|
144
|
+
return { ok: false, text: isTimeout ? `语音转写超时(${opts.timeoutMs ?? AUDIO_TIMEOUT_MS}ms)` : `语音转写失败:${String(e).slice(0, 200)}` };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { localObjectFile, localStorageBucket, objectKey, putObject, storageBucketForRuntime } from './object-storage';
|
|
7
|
+
|
|
8
|
+
test('local media storage: 写入 data/uploads 并返回公开 URL', async () => {
|
|
9
|
+
const root = mkdtempSync(join(tmpdir(), 'bailing-local-upload-'));
|
|
10
|
+
try {
|
|
11
|
+
const bucket = localStorageBucket('https://hub.example.com');
|
|
12
|
+
const key = objectKey(bucket, 'pub_demo', 'image/png');
|
|
13
|
+
const url = await putObject(bucket, key, Buffer.from('png-bytes'), 'image/png', { root });
|
|
14
|
+
assert.equal(url, `https://hub.example.com/uploads/${key}`);
|
|
15
|
+
|
|
16
|
+
const target = localObjectFile(root, key);
|
|
17
|
+
assert.ok(target);
|
|
18
|
+
assert.equal(target.contentType, 'image/png');
|
|
19
|
+
assert.equal(readFileSync(target.file, 'utf8'), 'png-bytes');
|
|
20
|
+
assert.equal(localObjectFile(root, '../secret.txt'), null);
|
|
21
|
+
} finally {
|
|
22
|
+
rmSync(root, { recursive: true, force: true });
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('local media storage: 显式 local 配置在运行期补齐公开 /uploads 地址', async () => {
|
|
27
|
+
const bucket = storageBucketForRuntime({
|
|
28
|
+
...localStorageBucket(''),
|
|
29
|
+
name: 'local-media',
|
|
30
|
+
public_base_url: '',
|
|
31
|
+
path_prefix: 'media',
|
|
32
|
+
}, 'https://hub.example.com/');
|
|
33
|
+
|
|
34
|
+
assert.equal(bucket.name, 'local-media');
|
|
35
|
+
assert.equal(bucket.kind, 'local');
|
|
36
|
+
assert.equal(bucket.public_base_url, 'https://hub.example.com/uploads');
|
|
37
|
+
assert.equal(bucket.path_prefix, 'media');
|
|
38
|
+
});
|