bugx-cli 0.0.0-stage → 0.1.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/LICENSE +55 -0
- package/README.md +280 -2
- package/core/CATALOG.json +141 -0
- package/core/README.md +254 -0
- package/core/adapters/README.md +35 -0
- package/core/adapters/android-interaction.json +81 -0
- package/core/adapters/android.json +24 -0
- package/core/adapters/desktop-macos.json +20 -0
- package/core/adapters/ios-interaction.json +34 -0
- package/core/adapters/ios.json +23 -0
- package/core/adapters/memory-macos.json +24 -0
- package/core/agent/README.md +50 -0
- package/core/agent/__init__.py +146 -0
- package/core/agent/agent_artifacts.py +764 -0
- package/core/agent/agent_eval.py +1073 -0
- package/core/agent/agent_execution.py +552 -0
- package/core/agent/agent_orchestrator.py +1345 -0
- package/core/agent/agent_targets.py +871 -0
- package/core/agent/agent_workspace.py +770 -0
- package/core/assets/README.md +24 -0
- package/core/assets/bugx-avatar-1024.png +0 -0
- package/core/assets/bugx-avatar-512.png +0 -0
- package/core/assets/bugx-avatar-tight.svg +23 -0
- package/core/assets/bugx-avatar.svg +28 -0
- package/core/assets/bugx-hero-cn.png +0 -0
- package/core/assets/bugx-hero-en.png +0 -0
- package/core/assets/project-layout.md +42 -0
- package/core/audit_packs/README.md +37 -0
- package/core/audit_packs/data-audit/manifest.json +94 -0
- package/core/audit_packs/data-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/data-audit/stages/10-schema-inventory.md +14 -0
- package/core/audit_packs/data-audit/stages/20-query-and-integrity.md +14 -0
- package/core/audit_packs/data-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/desktop-audit/manifest.json +123 -0
- package/core/audit_packs/desktop-audit/stages/00-scope.md +15 -0
- package/core/audit_packs/desktop-audit/stages/10-process-model.md +14 -0
- package/core/audit_packs/desktop-audit/stages/20-package-integrity.md +15 -0
- package/core/audit_packs/desktop-audit/stages/30-ui-behavior.md +14 -0
- package/core/audit_packs/desktop-audit/stages/80-evidence-regression.md +15 -0
- package/core/audit_packs/memory-testing.md +227 -0
- package/core/audit_packs/mobile-audit/manifest.json +155 -0
- package/core/audit_packs/mobile-audit/modules/android.md +19 -0
- package/core/audit_packs/mobile-audit/modules/h5.md +18 -0
- package/core/audit_packs/mobile-audit/modules/ios.md +25 -0
- package/core/audit_packs/mobile-audit/modules/miniprogram.md +26 -0
- package/core/audit_packs/mobile-audit/modules/webview.md +18 -0
- package/core/audit_packs/mobile-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/mobile-audit/stages/10-platform-inventory.md +14 -0
- package/core/audit_packs/mobile-audit/stages/20-masvs-static.md +20 -0
- package/core/audit_packs/mobile-audit/stages/30-component-exposure.md +14 -0
- package/core/audit_packs/mobile-audit/stages/40-device-behavior.md +14 -0
- package/core/audit_packs/mobile-audit/stages/80-evidence-regression.md +13 -0
- package/core/audit_packs/native-audit/manifest.json +127 -0
- package/core/audit_packs/native-audit/stages/00-scope.md +14 -0
- package/core/audit_packs/native-audit/stages/10-static-white-box.md +14 -0
- package/core/audit_packs/native-audit/stages/20-memory-concurrency.md +15 -0
- package/core/audit_packs/native-audit/stages/30-behavior-black-box.md +39 -0
- package/core/audit_packs/native-audit/stages/80-evidence-regression.md +14 -0
- package/core/audit_packs/platform-testing.md +174 -0
- package/core/audit_packs/web-audit/manifest.json +191 -0
- package/core/audit_packs/web-audit/modules/graphql.md +5 -0
- package/core/audit_packs/web-audit/modules/h5.md +18 -0
- package/core/audit_packs/web-audit/modules/multi-tenant.md +4 -0
- package/core/audit_packs/web-audit/modules/oauth.md +4 -0
- package/core/audit_packs/web-audit/modules/upload.md +4 -0
- package/core/audit_packs/web-audit/modules/websocket.md +4 -0
- package/core/audit_packs/web-audit/stages/00-scope.md +13 -0
- package/core/audit_packs/web-audit/stages/10-discovery.md +13 -0
- package/core/audit_packs/web-audit/stages/20-auth-session.md +13 -0
- package/core/audit_packs/web-audit/stages/30-authz-business.md +13 -0
- package/core/audit_packs/web-audit/stages/40-input-output.md +13 -0
- package/core/audit_packs/web-audit/stages/50-state-async.md +13 -0
- package/core/audit_packs/web-audit/stages/60-file-ssrf-deser.md +12 -0
- package/core/audit_packs/web-audit/stages/70-config-dependency.md +12 -0
- package/core/audit_packs/web-audit/stages/80-evidence-regression.md +12 -0
- package/core/autonomous_cve/INTERFACE.md +61 -0
- package/core/autonomous_cve/README.md +58 -0
- package/core/autonomous_cve/SPEC.md +25 -0
- package/core/autonomous_cve/__init__.py +109 -0
- package/core/autonomous_cve/attack_graph.py +1096 -0
- package/core/autonomous_cve/attack_graph_store.py +1822 -0
- package/core/autonomous_cve/audit_campaign.py +1232 -0
- package/core/autonomous_cve/behavior_graph.py +459 -0
- package/core/autonomous_cve/ghsa_advisories.py +174 -0
- package/core/autonomous_cve/models.py +93 -0
- package/core/autonomous_cve/mutator.py +87 -0
- package/core/autonomous_cve/patcher.py +126 -0
- package/core/autonomous_cve/scout.py +278 -0
- package/core/autonomous_cve/synthesizer.py +207 -0
- package/core/autonomous_cve/verifier.py +100 -0
- package/core/bugx.md +1299 -0
- package/core/bugx_paths.py +1846 -0
- package/core/cloud_sync/INTERFACE.md +32 -0
- package/core/cloud_sync/README.md +62 -0
- package/core/cloud_sync/SPEC.md +25 -0
- package/core/cloud_sync/__init__.py +23 -0
- package/core/cloud_sync/auto_sync.py +398 -0
- package/core/cloud_sync/cloud_client.py +1199 -0
- package/core/cloud_sync/cloud_onboard.py +702 -0
- package/core/cloud_sync/cloud_schema.py +648 -0
- package/core/cloud_sync/consent.py +81 -0
- package/core/cloud_sync/device_identity.py +307 -0
- package/core/cloud_sync/endpoint_router.py +415 -0
- package/core/cloud_sync/flywheel_client.py +760 -0
- package/core/cloud_sync/network_transport.py +275 -0
- package/core/cloud_sync/onboard_wizard.py +493 -0
- package/core/cloud_sync/sensitive_filter.py +285 -0
- package/core/cloud_sync/sync_pull.py +695 -0
- package/core/cloud_sync/sync_push.py +721 -0
- package/core/contracts/AGENT_GUIDE.md +362 -0
- package/core/contracts/README.md +34 -0
- package/core/contracts/bugx-blackbox.md +541 -0
- package/core/contracts/bugx-opencode.md +469 -0
- package/core/contracts/bugx-quick.md +44 -0
- package/core/contracts/bugx-runtime-contract.md +353 -0
- package/core/contracts/bugx-worker.md +470 -0
- package/core/contracts/engine_gap_contracts.py +390 -0
- package/core/coverage/README.md +70 -0
- package/core/coverage/__init__.py +106 -0
- package/core/coverage/coverage_ai_review.py +185 -0
- package/core/coverage/coverage_backfill.py +54 -0
- package/core/coverage/coverage_bootstrap.py +713 -0
- package/core/coverage/coverage_business.py +36 -0
- package/core/coverage/coverage_cli.py +715 -0
- package/core/coverage/coverage_discovery.py +859 -0
- package/core/coverage/coverage_evidence.py +977 -0
- package/core/coverage/coverage_forensics.py +115 -0
- package/core/coverage/coverage_gate.py +277 -0
- package/core/coverage/coverage_intelligence.py +734 -0
- package/core/coverage/coverage_manifest.py +396 -0
- package/core/coverage/coverage_platform.py +77 -0
- package/core/coverage/coverage_validate.py +236 -0
- package/core/coverage/module_coverage.py +157 -0
- package/core/dev_harness/INTERFACE.md +20 -0
- package/core/dev_harness/README.md +21 -0
- package/core/dev_harness/SPEC.md +25 -0
- package/core/dev_harness/__init__.py +5 -0
- package/core/dev_harness/interaction_preset.py +408 -0
- package/core/engine-integrity.json +2625 -0
- package/core/fuzzing/README.md +49 -0
- package/core/fuzzing/__init__.py +82 -0
- package/core/fuzzing/concurrency_fuzzer.py +382 -0
- package/core/fuzzing/differential_oracle.py +629 -0
- package/core/fuzzing/fuzz_input.py +1188 -0
- package/core/fuzzing/stateful_fuzzer.py +332 -0
- package/core/governance/README.md +61 -0
- package/core/governance/__init__.py +130 -0
- package/core/governance/capacity_planner.py +124 -0
- package/core/governance/dependency_lock.py +317 -0
- package/core/governance/goal_governor.py +754 -0
- package/core/governance/guide_budget.py +458 -0
- package/core/governance/lockdown.sh +50 -0
- package/core/governance/readonly_enforcer.py +154 -0
- package/core/governance/runtime_tool_gate.py +373 -0
- package/core/governance/secret_redactor.py +772 -0
- package/core/governance/token_budget.py +38 -0
- package/core/host_acp/INTERFACE.md +36 -0
- package/core/host_acp/README.md +51 -0
- package/core/host_acp/SPEC.md +25 -0
- package/core/host_acp/__init__.py +121 -0
- package/core/host_acp/base.py +111 -0
- package/core/host_acp/claude.py +41 -0
- package/core/host_acp/cline.py +235 -0
- package/core/host_acp/codex.py +245 -0
- package/core/host_acp/dsh.py +48 -0
- package/core/host_acp/opencode.py +154 -0
- package/core/host_acp/pi.py +36 -0
- package/core/host_acp/zcode.py +41 -0
- package/core/host_runtime/INTERFACE.md +24 -0
- package/core/host_runtime/README.md +62 -0
- package/core/host_runtime/SPEC.md +25 -0
- package/core/host_runtime/__init__.py +21 -0
- package/core/host_runtime/adapters.py +412 -0
- package/core/host_runtime/autonomous_runner.py +1152 -0
- package/core/host_runtime/cline.py +435 -0
- package/core/host_runtime/common.py +103 -0
- package/core/host_runtime/free_models.py +786 -0
- package/core/host_runtime/host_bootstrap.py +389 -0
- package/core/host_runtime/host_evaluators.py +721 -0
- package/core/host_runtime/host_probe.py +41 -0
- package/core/host_runtime/host_provider_arbitrator.py +777 -0
- package/core/host_runtime/host_registry.py +655 -0
- package/core/host_runtime/host_usage.py +127 -0
- package/core/host_runtime/mcp_process_tracker.py +509 -0
- package/core/host_runtime/mcp_registry_gate.py +368 -0
- package/core/hosts/INTERFACE.md +51 -0
- package/core/hosts/README.md +67 -0
- package/core/hosts/SPEC.md +25 -0
- package/core/hosts/__init__.py +136 -0
- package/core/hosts/_base_usage.py +152 -0
- package/core/hosts/_codex_usage.py +297 -0
- package/core/hosts/_dsh_usage.py +184 -0
- package/core/hosts/_mcp_toml.py +365 -0
- package/core/hosts/_zcode_usage.py +269 -0
- package/core/hosts/base.py +451 -0
- package/core/hosts/claude.py +157 -0
- package/core/hosts/cline.py +225 -0
- package/core/hosts/codex.py +948 -0
- package/core/hosts/dsh.py +518 -0
- package/core/hosts/opencode.py +358 -0
- package/core/hosts/pi.py +151 -0
- package/core/hosts/zcode.py +219 -0
- package/core/i18n.py +252 -0
- package/core/infra/README.md +39 -0
- package/core/infra/__init__.py +15 -0
- package/core/infra/build_info.py +86 -0
- package/core/infra/client_metadata.py +185 -0
- package/core/infra/python_runtime.py +540 -0
- package/core/infra/safe_xml.py +221 -0
- package/core/launch_bugx.py +118 -0
- package/core/launch_phases/INTERFACE.md +31 -0
- package/core/launch_phases/README.md +106 -0
- package/core/launch_phases/SPEC.md +25 -0
- package/core/launch_phases/__init__.py +29 -0
- package/core/launch_phases/candidate_revalidation.py +484 -0
- package/core/launch_phases/common.py +1041 -0
- package/core/launch_phases/finding_confirm_phase.py +387 -0
- package/core/launch_phases/finding_settlement.py +1245 -0
- package/core/launch_phases/findings_adjudication.py +666 -0
- package/core/launch_phases/findings_snapshot.py +357 -0
- package/core/launch_phases/judge_phase.py +791 -0
- package/core/launch_phases/lesson_context.py +536 -0
- package/core/launch_phases/lifecycle_reporter.py +627 -0
- package/core/launch_phases/orchestrator_controls.py +682 -0
- package/core/launch_phases/post_commit.py +567 -0
- package/core/launch_phases/post_coverage_sync.py +591 -0
- package/core/launch_phases/post_dry_run.py +817 -0
- package/core/launch_phases/post_observability.py +367 -0
- package/core/launch_phases/post_phase.py +1087 -0
- package/core/launch_phases/post_receipt.py +362 -0
- package/core/launch_phases/post_round_lifecycle.py +786 -0
- package/core/launch_phases/pre_phase.py +1029 -0
- package/core/launch_phases/pre_recon_scout.py +862 -0
- package/core/launch_phases/pre_state_builder.py +1286 -0
- package/core/launch_phases/report_sharing.py +414 -0
- package/core/launch_phases/round_orchestrator.py +1133 -0
- package/core/launch_phases/session_runtime.py +1623 -0
- package/core/launch_phases/startup_gates.py +1022 -0
- package/core/launch_phases/startup_interaction.py +947 -0
- package/core/launch_phases/startup_version_gate.py +873 -0
- package/core/launch_phases/supervisor_bridge.py +1224 -0
- package/core/launch_phases/supervisor_coverage.py +417 -0
- package/core/launch_phases/supervisor_degraded.py +1219 -0
- package/core/launch_phases/worker_barriers.py +414 -0
- package/core/launch_phases/worker_orchestrator.py +1166 -0
- package/core/launch_phases/worker_prior.py +749 -0
- package/core/ledger/INTERFACE.md +35 -0
- package/core/ledger/README.md +160 -0
- package/core/ledger/SPEC.md +25 -0
- package/core/ledger/__init__.py +67 -0
- package/core/ledger/_facade.py +226 -0
- package/core/ledger/archive_ops.py +572 -0
- package/core/ledger/auto_materialization.py +459 -0
- package/core/ledger/bug-log.md +22 -0
- package/core/ledger/cli.py +270 -0
- package/core/ledger/export_ops.py +549 -0
- package/core/ledger/finding_confirmation.py +1274 -0
- package/core/ledger/finding_io.py +299 -0
- package/core/ledger/finding_lifecycle.py +307 -0
- package/core/ledger/finding_verification.py +369 -0
- package/core/ledger/incidents.py +999 -0
- package/core/ledger/lesson-replay-cases.json +20 -0
- package/core/ledger/lesson_ledger.py +241 -0
- package/core/ledger/lesson_replay.py +272 -0
- package/core/ledger/life_ledger.py +668 -0
- package/core/ledger/mistake-book.md +130 -0
- package/core/ledger/patterns.py +681 -0
- package/core/ledger/receipt_contract.py +253 -0
- package/core/ledger/schema.py +1192 -0
- package/core/ledger/sync_ops.py +935 -0
- package/core/ledger/tool_experience.py +682 -0
- package/core/ledger/verify_life.py +1526 -0
- package/core/lesson-ledger.json +275 -0
- package/core/locales/README.md +19 -0
- package/core/locales/en-US.json +462 -0
- package/core/locales/zh-CN.json +462 -0
- package/core/mcp_handlers/INTERFACE.md +75 -0
- package/core/mcp_handlers/README.md +62 -0
- package/core/mcp_handlers/SPEC.md +25 -0
- package/core/mcp_handlers/__init__.py +128 -0
- package/core/mcp_handlers/base.py +697 -0
- package/core/mcp_handlers/channel_lifecycle.py +696 -0
- package/core/mcp_handlers/graph_handlers.py +222 -0
- package/core/mcp_handlers/knowledge_handlers.py +536 -0
- package/core/mcp_handlers/mining_handlers.py +586 -0
- package/core/mcp_handlers/resource_prompt_table.py +116 -0
- package/core/mcp_handlers/retrieval_handlers.py +239 -0
- package/core/mcp_handlers/rpc_server.py +465 -0
- package/core/mcp_handlers/supervisor_handlers.py +1435 -0
- package/core/mcp_handlers/telemetry_handlers.py +227 -0
- package/core/mcp_handlers/tool_table.py +1015 -0
- package/core/mcp_runtime_support/README.md +21 -0
- package/core/mcp_runtime_support/__init__.py +1 -0
- package/core/mcp_runtime_support/common.py +363 -0
- package/core/mcp_runtime_support/environment.py +605 -0
- package/core/mcp_runtime_support/verifier.py +810 -0
- package/core/metadata.txt +5 -0
- package/core/planning/README.md +157 -0
- package/core/planning/__init__.py +242 -0
- package/core/planning/capability_plan.py +187 -0
- package/core/planning/capability_planner.py +195 -0
- package/core/planning/domain_archetype.py +542 -0
- package/core/planning/domain_router.py +267 -0
- package/core/planning/dynamic_flow_analyzer.py +328 -0
- package/core/planning/impact_pruner.py +435 -0
- package/core/planning/intent_adjudicator.py +175 -0
- package/core/planning/judge_pipeline.py +1163 -0
- package/core/planning/logic_analysis.py +419 -0
- package/core/planning/prompt_harness.py +1702 -0
- package/core/planning/source_inspector.py +267 -0
- package/core/planning/spec_harvester.py +449 -0
- package/core/planning/target_sandbox_manager.py +573 -0
- package/core/planning/test_capability_verifier.py +1364 -0
- package/core/planning/tools-kb.md +38 -0
- package/core/planning/unit_kind.py +122 -0
- package/core/probes/INTERFACE.md +73 -0
- package/core/probes/README.md +51 -0
- package/core/probes/SPEC.md +26 -0
- package/core/probes/__init__.py +70 -0
- package/core/probes/android_probe.py +384 -0
- package/core/probes/base.py +147 -0
- package/core/probes/codebase_memory_probe.py +590 -0
- package/core/probes/desktop_probe.py +238 -0
- package/core/probes/differential_probe.py +356 -0
- package/core/probes/efficiency_probe.py +168 -0
- package/core/probes/ios_binary_probe.py +368 -0
- package/core/probes/memory_probe.py +326 -0
- package/core/probes/miniprogram_probe.py +323 -0
- package/core/probes/mobile_probe.py +281 -0
- package/core/probes/native_probe.py +214 -0
- package/core/probes/openwiki_probe.py +193 -0
- package/core/probes/pattern_probe.py +347 -0
- package/core/probes/platform_probe.py +343 -0
- package/core/probes/probe_registry.py +1669 -0
- package/core/probes/sast_probe.py +1009 -0
- package/core/probes/sast_rules.py +841 -0
- package/core/probes/sca_scanner.py +731 -0
- package/core/probes/web_probe.py +359 -0
- package/core/project_profiler/INTERFACE.md +62 -0
- package/core/project_profiler/README.md +53 -0
- package/core/project_profiler/SPEC.md +28 -0
- package/core/project_profiler/__init__.py +201 -0
- package/core/project_profiler/arbitrator.py +311 -0
- package/core/project_profiler/constants.py +247 -0
- package/core/project_profiler/detector.py +392 -0
- package/core/project_profiler/extractors.py +836 -0
- package/core/project_profiler/fingerprint.py +116 -0
- package/core/project_profiler/storage.py +258 -0
- package/core/project_profiler/strategy.py +265 -0
- package/core/prompts/README.md +35 -0
- package/core/prompts/codex_dialog_dispatch.md +9 -0
- package/core/prompts/command_routing_en.md +42 -0
- package/core/prompts/command_routing_zh.md +42 -0
- package/core/prompts/l0_router.md +47 -0
- package/core/prompts/rules/anti_patterns.md +16 -0
- package/core/prompts/rules/concurrency_rules.md +14 -0
- package/core/prompts/rules/memory_leak_rules.md +13 -0
- package/core/prompts/rules/prompt_injection_defense.md +13 -0
- package/core/prompts/stages/stage_explore.md +31 -0
- package/core/prompts/stages/stage_gate.md +43 -0
- package/core/prompts/stages/stage_mutate.md +42 -0
- package/core/prompts/stages/stage_repair.md +85 -0
- package/core/repair/README.md +74 -0
- package/core/repair/__init__.py +169 -0
- package/core/repair/fix_watchlist.py +391 -0
- package/core/repair/l7_dynamic.py +418 -0
- package/core/repair/l7_repair_loop.py +465 -0
- package/core/repair/l7_selfcheck.py +862 -0
- package/core/repair/minimize_repro.py +466 -0
- package/core/repair/patch_synthesizer.py +617 -0
- package/core/repair/regression_pack.py +379 -0
- package/core/repair/rsi_fixer.py +910 -0
- package/core/repair/rsi_loop.py +313 -0
- package/core/repair/rsi_repair.py +348 -0
- package/core/repair/rsi_rounds.py +212 -0
- package/core/repair/rsi_scope.py +262 -0
- package/core/repair/self_heal.py +604 -0
- package/core/repair/test_generator.py +1108 -0
- package/core/repair/test_quality_auditor.py +410 -0
- package/core/repair/test_strategy.py +511 -0
- package/core/report_engine/INTERFACE.md +59 -0
- package/core/report_engine/README.md +69 -0
- package/core/report_engine/SPEC.md +28 -0
- package/core/report_engine/__init__.py +47 -0
- package/core/report_engine/attestation.py +224 -0
- package/core/report_engine/authority.py +255 -0
- package/core/report_engine/finding_report.py +417 -0
- package/core/report_engine/formal_report_builder.py +924 -0
- package/core/report_engine/html_renderers.py +696 -0
- package/core/report_engine/models.py +761 -0
- package/core/report_engine/pdf_exporter.py +231 -0
- package/core/report_engine/projects_assets.py +730 -0
- package/core/report_engine/report_client.py +743 -0
- package/core/report_engine/report_data_builder.py +388 -0
- package/core/report_engine/report_share.py +459 -0
- package/core/report_engine/sast_bridge.py +116 -0
- package/core/report_engine/server.py +822 -0
- package/core/report_engine/visual_report_builder.py +796 -0
- package/core/report_engine/web-conformance.md +63 -0
- package/core/report_engine/web_conformance.py +459 -0
- package/core/report_engine/workbench_assets.py +484 -0
- package/core/retrieval/INTERFACE.md +20 -0
- package/core/retrieval/README.md +161 -0
- package/core/retrieval/SPEC.md +25 -0
- package/core/retrieval/__init__.py +3 -0
- package/core/retrieval/code_analyzer.py +1684 -0
- package/core/retrieval/codebase_memory_bridge.py +337 -0
- package/core/retrieval/context_assembler.py +234 -0
- package/core/retrieval/corpus_fetch.py +369 -0
- package/core/retrieval/graph_ego.py +597 -0
- package/core/retrieval/knowledge_auto.py +662 -0
- package/core/retrieval/knowledge_sources.py +168 -0
- package/core/retrieval/knowledge_sync.py +909 -0
- package/core/retrieval/memory_store.py +480 -0
- package/core/retrieval/query_planner.py +1020 -0
- package/core/retrieval/rrf_engine.py +137 -0
- package/core/retrieval/slice_extractor.py +1209 -0
- package/core/retrieval/slice_normalizer.py +373 -0
- package/core/retrieval/slice_spec.py +357 -0
- package/core/retrieval/symbol_index.py +1132 -0
- package/core/retrieval/universal_code_matcher.py +437 -0
- package/core/retrieval/xerj_bridge.py +476 -0
- package/core/retrieval/xerj_supervisor.py +362 -0
- package/core/rules/README.md +33 -0
- package/core/rules/ios/PROVENANCE.json +30 -0
- package/core/rules/ios/crypto.yaml +36 -0
- package/core/rules/ios/network.yaml +20 -0
- package/core/rules/ios/resilience.yaml +47 -0
- package/core/rules/ios/storage.yaml +48 -0
- package/core/rules/mastg/LICENSE +173 -0
- package/core/rules/mastg/PROVENANCE.json +270 -0
- package/core/rules/mastg/mastg-android-asymmetric-key-pair-used-for-multiple-purposes.yml +13 -0
- package/core/rules/mastg/mastg-android-backup-manifest.yml +24 -0
- package/core/rules/mastg/mastg-android-biometric-event-bound.yml +49 -0
- package/core/rules/mastg/mastg-android-biometric-invalidated-enrollment.yml +11 -0
- package/core/rules/mastg/mastg-android-biometric-no-confirmation-required.yml +10 -0
- package/core/rules/mastg/mastg-android-biometric-validity-duration.yml +24 -0
- package/core/rules/mastg/mastg-android-broken-encryption-algorithms.yaml +9 -0
- package/core/rules/mastg/mastg-android-broken-encryption-modes.yaml +13 -0
- package/core/rules/mastg/mastg-android-content-provider-exported.yml +35 -0
- package/core/rules/mastg/mastg-android-custom-deeplink-scheme.yml +29 -0
- package/core/rules/mastg/mastg-android-dangerous-app-permissions.yaml +65 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-apis.yml +36 -0
- package/core/rules/mastg/mastg-android-data-unencrypted-shared-storage-no-user-interaction-manifest.yml +15 -0
- package/core/rules/mastg/mastg-android-debuggable-flag.yml +10 -0
- package/core/rules/mastg/mastg-android-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-deeplink-autoverify-missing.yml +33 -0
- package/core/rules/mastg/mastg-android-deeplink-unvalidated-parameter.yml +11 -0
- package/core/rules/mastg/mastg-android-device-passcode-present.yml +17 -0
- package/core/rules/mastg/mastg-android-fileprovider-broad-scope.yml +46 -0
- package/core/rules/mastg/mastg-android-hardcoded-crypto-keys-usage.yml +14 -0
- package/core/rules/mastg/mastg-android-hardcoded-security-provider.yaml +18 -0
- package/core/rules/mastg/mastg-android-implicit-intent-internal-communication.yml +30 -0
- package/core/rules/mastg/mastg-android-implicit-intent-leaking-extras.yml +29 -0
- package/core/rules/mastg/mastg-android-input-field-usage.yml +11 -0
- package/core/rules/mastg/mastg-android-key-generation-with-insufficient-key-length.yml +21 -0
- package/core/rules/mastg/mastg-android-keyboard-cache-input-types.yml +10 -0
- package/core/rules/mastg/mastg-android-local-storage-input-validation.yml +48 -0
- package/core/rules/mastg/mastg-android-native-debugger-checks.yml +12 -0
- package/core/rules/mastg/mastg-android-network-checkservertrusted.yml +12 -0
- package/core/rules/mastg/mastg-android-network-hostname-verification.yml +11 -0
- package/core/rules/mastg/mastg-android-network-insecure-trust-anchors.yml +11 -0
- package/core/rules/mastg/mastg-android-network-onreceivedsslerror.yml +12 -0
- package/core/rules/mastg/mastg-android-non-random-use.yml +16 -0
- package/core/rules/mastg/mastg-android-object-deserialization.yml +14 -0
- package/core/rules/mastg/mastg-android-overlay-protection.yml +68 -0
- package/core/rules/mastg/mastg-android-pendingintent-mutable.yml +39 -0
- package/core/rules/mastg/mastg-android-random-apis-insufficient-entropy.yml +17 -0
- package/core/rules/mastg/mastg-android-root-detection.yaml +59 -0
- package/core/rules/mastg/mastg-android-sdk-version.yml +10 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications-manifest.yml +17 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-notifications.yml +11 -0
- package/core/rules/mastg/mastg-android-sensitive-data-in-screenshot.yml +18 -0
- package/core/rules/mastg/mastg-android-sql-injection-contentprovider.yml +17 -0
- package/core/rules/mastg/mastg-android-ssl-socket-hostnameverifier.yml +15 -0
- package/core/rules/mastg/mastg-android-strictmode.yml +10 -0
- package/core/rules/mastg/mastg-android-system-alert-window.yml +9 -0
- package/core/rules/mastg/mastg-android-webview-allow-local-access.yml +15 -0
- package/core/rules/mastg/mastg-android-webview-bridges.yml +28 -0
- package/core/rules/mastg/mastg-android-webview-safebrowsing.yml +20 -0
- package/core/rules/mastg/mastg-android-webview-url-handlers.yml +41 -0
- package/core/rules/miniprogram/PROVENANCE.json +26 -0
- package/core/rules/miniprogram/network.yaml +37 -0
- package/core/rules/miniprogram/platform.yaml +36 -0
- package/core/rules/miniprogram/storage.yaml +48 -0
- package/core/rules/mobsfscan-swift/LICENSE +165 -0
- package/core/rules/mobsfscan-swift/PROVENANCE.json +58 -0
- package/core/rules/mobsfscan-swift/auth.yaml +59 -0
- package/core/rules/mobsfscan-swift/crypto.yaml +66 -0
- package/core/rules/mobsfscan-swift/jailbreak.yaml +14 -0
- package/core/rules/mobsfscan-swift/keyboard.yaml +34 -0
- package/core/rules/mobsfscan-swift/logging.yaml +23 -0
- package/core/rules/mobsfscan-swift/network.yaml +55 -0
- package/core/rules/mobsfscan-swift/resilience.yaml +29 -0
- package/core/rules/mobsfscan-swift/secrets.yaml +33 -0
- package/core/rules/mobsfscan-swift/storage.yaml +29 -0
- package/core/rules/mobsfscan-swift/webview.yaml +32 -0
- package/core/runtime/README.md +198 -0
- package/core/runtime/__init__.py +3 -0
- package/core/runtime/bugx_logging.py +1393 -0
- package/core/runtime/daemon_runner.py +623 -0
- package/core/runtime/fixture_solidify.py +449 -0
- package/core/runtime/global_telemetry.py +549 -0
- package/core/runtime/incident_eval.py +148 -0
- package/core/runtime/interaction.py +605 -0
- package/core/runtime/interaction_store.py +435 -0
- package/core/runtime/interactive_menu.py +95 -0
- package/core/runtime/log_analytics.py +922 -0
- package/core/runtime/mining_quality_framework.py +1387 -0
- package/core/runtime/model_runner.py +769 -0
- package/core/runtime/platform_adapter.py +579 -0
- package/core/runtime/prep_validate.py +476 -0
- package/core/runtime/project_graph.py +827 -0
- package/core/runtime/project_init.py +481 -0
- package/core/runtime/project_profile.py +224 -0
- package/core/runtime/project_settings.py +963 -0
- package/core/runtime/provider_window.py +97 -0
- package/core/runtime/resume_ticket.py +115 -0
- package/core/runtime/scenario_eval.py +814 -0
- package/core/runtime/seed_drill.py +549 -0
- package/core/runtime/self_audit.py +550 -0
- package/core/runtime/session_profile.py +205 -0
- package/core/runtime/setup_ui_env.py +229 -0
- package/core/runtime/startup_environment.py +859 -0
- package/core/runtime/sync_store.py +1421 -0
- package/core/runtime/tool_install_targets.py +18 -0
- package/core/schemas/README.md +35 -0
- package/core/schemas/agent-graph.schema.json +368 -0
- package/core/schemas/attack-graph.schema.json +88 -0
- package/core/schemas/evidence-bundle.schema.json +33 -0
- package/core/schemas/skill-pack.schema.json +230 -0
- package/core/schemas/worker-checkpoint.schema.json +119 -0
- package/core/secure_atomic.py +289 -0
- package/core/seed_corpus/README.md +55 -0
- package/core/seed_corpus/c.txt +29 -0
- package/core/seed_corpus/cpp.txt +32 -0
- package/core/seed_corpus/css.txt +70 -0
- package/core/seed_corpus/go.txt +46 -0
- package/core/seed_corpus/java.txt +30 -0
- package/core/seed_corpus/javascript.txt +55 -0
- package/core/seed_corpus/kotlin.txt +28 -0
- package/core/seed_corpus/python.txt +71 -0
- package/core/seed_corpus/rust.txt +53 -0
- package/core/seed_corpus/swift.txt +29 -0
- package/core/seed_corpus/typescript.txt +29 -0
- package/core/skills/README.md +53 -0
- package/core/skills/__init__.py +189 -0
- package/core/skills/bugx_docs_mcp_server.py +416 -0
- package/core/skills/bugx_mcp_server.py +1134 -0
- package/core/skills/mcp_runtime.py +968 -0
- package/core/skills/mcp_session_proof.py +605 -0
- package/core/skills/mobile_ui_inspector.py +405 -0
- package/core/skills/skill_pack.py +1214 -0
- package/core/skills/skill_synthesizer.py +1153 -0
- package/core/skills/tools_kb.py +313 -0
- package/core/supervisor/INTERFACE.md +121 -0
- package/core/supervisor/README.md +209 -0
- package/core/supervisor/SPEC.md +25 -0
- package/core/supervisor/__init__.py +175 -0
- package/core/supervisor/audit_supervisor.py +1015 -0
- package/core/supervisor/budget_governor.py +760 -0
- package/core/supervisor/checkpoint_handler.py +368 -0
- package/core/supervisor/checkpoint_pipeline.py +1322 -0
- package/core/supervisor/checkpoint_sync.py +640 -0
- package/core/supervisor/claim_events.py +74 -0
- package/core/supervisor/claim_sync.py +590 -0
- package/core/supervisor/cli.py +812 -0
- package/core/supervisor/context_sync.py +55 -0
- package/core/supervisor/coverage_sync.py +115 -0
- package/core/supervisor/finding_commit.py +470 -0
- package/core/supervisor/finding_sync.py +688 -0
- package/core/supervisor/finding_workflow.py +659 -0
- package/core/supervisor/finish_policy.py +224 -0
- package/core/supervisor/finish_sync.py +185 -0
- package/core/supervisor/graph_sync.py +669 -0
- package/core/supervisor/lease_manager.py +788 -0
- package/core/supervisor/lifecycle_blocks.py +124 -0
- package/core/supervisor/next_round_sync.py +126 -0
- package/core/supervisor/observability.py +140 -0
- package/core/supervisor/recovery_sync.py +165 -0
- package/core/supervisor/rejection_remedies.py +308 -0
- package/core/supervisor/round_governor.py +306 -0
- package/core/supervisor/serial_authorization.py +500 -0
- package/core/supervisor/start_sync.py +87 -0
- package/core/supervisor/state_store.py +249 -0
- package/core/supervisor/supervisor_host.py +511 -0
- package/core/supervisor/supervisor_models.py +1143 -0
- package/core/supervisor/systemic_failure.py +104 -0
- package/core/supervisor/task_scheduler.py +1640 -0
- package/core/supervisor/worker_checkpoint.py +223 -0
- package/core/supervisor/worker_execution.py +265 -0
- package/core/supervisor/worker_handoff.py +192 -0
- package/core/supervisor/worker_lifecycle.py +396 -0
- package/core/supervisor/worker_runtime.py +999 -0
- package/core/supervisor/worker_sync.py +89 -0
- package/core/supervisor_types/README.md +36 -0
- package/core/supervisor_types/__init__.py +0 -0
- package/core/supervisor_types/exceptions.py +52 -0
- package/core/supervisor_types/graph_models.py +357 -0
- package/core/supervisor_types/path_containment.py +151 -0
- package/core/supervisor_types/target_fingerprint.py +310 -0
- package/core/supervisor_types/worker_claim.py +402 -0
- package/core/webui/INTERFACE.md +50 -0
- package/core/webui/README.md +57 -0
- package/core/webui/SPEC.md +25 -0
- package/core/webui/__init__.py +11 -0
- package/core/webui/adapters/__init__.py +27 -0
- package/core/webui/adapters/base.py +87 -0
- package/core/webui/adapters/bugx.py +102 -0
- package/core/webui/adapters/claude.py +218 -0
- package/core/webui/adapters/cline.py +399 -0
- package/core/webui/adapters/codex.py +256 -0
- package/core/webui/adapters/dsh.py +173 -0
- package/core/webui/adapters/opencode.py +218 -0
- package/core/webui/adapters/pi.py +272 -0
- package/core/webui/adapters/registry.py +100 -0
- package/core/webui/adapters/zcode.py +312 -0
- package/core/webui/api_routes_post.py +668 -0
- package/core/webui/dispatcher.py +1376 -0
- package/core/webui/docs_session_service.py +473 -0
- package/core/webui/handler.py +674 -0
- package/core/webui/ide_cloud_service.py +526 -0
- package/core/webui/mcp_inspector.py +1743 -0
- package/core/webui/static/assets/index-CXAsl8mr.js +333 -0
- package/core/webui/static/assets/index-DHQUtWtx.css +1 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-B8Z6Jvzv.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-400-normal-C44pakCn.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-Bb4u56_6.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-500-normal-BdVUvljg.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-CWV284fw.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-400-normal-DLkyKLvH.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-8-8HP2PF.woff +0 -0
- package/core/webui/static/assets/source-serif-4-cyrillic-ext-500-normal-DaDZE_Na.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-BccYJ-vZ.woff +0 -0
- package/core/webui/static/assets/source-serif-4-greek-400-normal-Cw5-AHNN.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-By8GFJzz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-greek-500-normal-z-Q6FFuG.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-DJ5YJwmz.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-400-normal-Dn3IlU-Z.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-CUHe9xxf.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-500-normal-DVVamBqs.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-CEpydyUl.woff +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-400-normal-Cp7z-ARB.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-BYjRCDVy.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-latin-ext-500-normal-D-qasQTj.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-BbG3LG1A.woff2 +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-400-normal-DR1UuFon.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-8N8MYVKB.woff +0 -0
- package/core/webui/static/assets/source-serif-4-vietnamese-500-normal-Bi3OSTTW.woff2 +0 -0
- package/core/webui/static/favicon.png +0 -0
- package/core/webui/static/icon-192.png +0 -0
- package/core/webui/static/index.html +42 -0
- package/core/webui/static/manifest.webmanifest +19 -0
- package/core/webui/static/project-settings.css +6458 -0
- package/core/webui/static/project-settings.js +9602 -0
- package/core/webui/static/sw.js +8 -0
- package/core/webui/workspace_service.py +218 -0
- package/docs/07_distribution/01_README_NPM.md +281 -0
- package/docs/07_distribution/README.md +16 -0
- package/docs/README.md +121 -0
- package/ecosystem/README.md +129 -0
- package/ecosystem/integrations/README.md +38 -0
- package/ecosystem/integrations/cline/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/dsh/agents/bugx.md +27 -0
- package/ecosystem/integrations/dsh/dsh-patch.yml +18 -0
- package/ecosystem/integrations/dsh/mcp/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/mcp/index.js +219 -0
- package/ecosystem/integrations/dsh/mcp/package.json +28 -0
- package/ecosystem/integrations/dsh/skills/bugx/SKILL.md +70 -0
- package/ecosystem/integrations/dsh/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/integrations/dsh/ui/client.js +87 -0
- package/ecosystem/integrations/dsh/ui/cordis.patch.yml +4 -0
- package/ecosystem/integrations/dsh/ui/index.js +7 -0
- package/ecosystem/integrations/dsh/ui/package.json +27 -0
- package/ecosystem/integrations/opencode/bugx-mcp-manifest.json +53 -0
- package/ecosystem/integrations/opencode/mcp-lock.json +3067 -0
- package/ecosystem/integrations/opencode/opencode.json +118 -0
- package/ecosystem/integrations/pi/extensions/bugx/README.md +12 -0
- package/ecosystem/integrations/pi/extensions/bugx/index.ts +299 -0
- package/ecosystem/integrations/pi/extensions/bugx/manifest.json +11 -0
- package/ecosystem/integrations/pi/skills/bugx/SKILL.md +69 -0
- package/ecosystem/integrations/qoder/CONNECTORS.md +54 -0
- package/ecosystem/integrations/qoder/connector-meta.json +21 -0
- package/ecosystem/integrations/workbuddy/connector-meta.json +19 -0
- package/ecosystem/integrations/workbuddy/icon.png +0 -0
- package/ecosystem/integrations/workbuddy/skills/bugx/SKILL.md +70 -0
- package/ecosystem/plugins/README.md +37 -0
- package/ecosystem/plugins/bugx/.claude-plugin/marketplace.json +17 -0
- package/ecosystem/plugins/bugx/.claude-plugin/plugin.json +16 -0
- package/ecosystem/plugins/bugx/.codex-plugin/plugin.json +41 -0
- package/ecosystem/plugins/bugx/.zcode-plugin/plugin.json +19 -0
- package/ecosystem/plugins/bugx/agents/bugx-judge.md +71 -0
- package/ecosystem/plugins/bugx/agents/bugx-worker.md +31 -0
- package/ecosystem/plugins/bugx/agents/bugx.md +74 -0
- package/ecosystem/plugins/bugx/assets/bugx-avatar-512.png +0 -0
- package/ecosystem/plugins/bugx/skills/bugx/SKILL.md +118 -0
- package/ecosystem/plugins/bugx/skills/bugx-claude/SKILL.md +326 -0
- package/ecosystem/plugins/bugx/skills/bugx-dsh/SKILL.md +229 -0
- package/ecosystem/plugins/bugx/skills/bugx-opencode/SKILL.md +129 -0
- package/ecosystem/plugins/bugx/skills/bugx-zcode/SKILL.md +459 -0
- package/interfaces/README.md +143 -0
- package/interfaces/bin/README.md +35 -0
- package/interfaces/bin/bugx.js +80 -0
- package/interfaces/cli/README.md +90 -0
- package/interfaces/cli/bugx_cli/__init__.py +4 -0
- package/interfaces/cli/bugx_cli/cli.py +1678 -0
- package/interfaces/cli/bugx_cli/commands/__init__.py +1 -0
- package/interfaces/cli/bugx_cli/commands/advisory.py +94 -0
- package/interfaces/cli/bugx_cli/commands/agent.py +3944 -0
- package/interfaces/cli/bugx_cli/commands/audit.py +632 -0
- package/interfaces/cli/bugx_cli/commands/autonomous.py +260 -0
- package/interfaces/cli/bugx_cli/commands/cloud.py +1370 -0
- package/interfaces/cli/bugx_cli/commands/daemon.py +50 -0
- package/interfaces/cli/bugx_cli/commands/doctor.py +1345 -0
- package/interfaces/cli/bugx_cli/commands/goal.py +107 -0
- package/interfaces/cli/bugx_cli/commands/interaction.py +244 -0
- package/interfaces/cli/bugx_cli/commands/knowledge.py +617 -0
- package/interfaces/cli/bugx_cli/commands/lifecycle.py +2763 -0
- package/interfaces/cli/bugx_cli/commands/patch.py +1014 -0
- package/interfaces/cli/bugx_cli/commands/plugin.py +2714 -0
- package/interfaces/cli/bugx_cli/commands/plugin_claude.py +1446 -0
- package/interfaces/cli/bugx_cli/commands/plugin_cline.py +269 -0
- package/interfaces/cli/bugx_cli/commands/plugin_codex.py +74 -0
- package/interfaces/cli/bugx_cli/commands/plugin_funide.py +728 -0
- package/interfaces/cli/bugx_cli/commands/plugin_qoder.py +216 -0
- package/interfaces/cli/bugx_cli/commands/plugin_zcode.py +710 -0
- package/interfaces/cli/bugx_cli/commands/project.py +670 -0
- package/interfaces/cli/bugx_cli/commands/report.py +260 -0
- package/interfaces/cli/bugx_cli/commands/skill.py +251 -0
- package/interfaces/cli/bugx_cli/commands/stats.py +133 -0
- package/interfaces/cli/bugx_cli/commands/system.py +2567 -0
- package/interfaces/cli/bugx_cli/common.py +898 -0
- package/interfaces/cli/bugx_cli/host_adapters.py +1917 -0
- package/interfaces/cli/bugx_cli/hosts/__init__.py +80 -0
- package/interfaces/cli/bugx_cli/hosts/base.py +99 -0
- package/interfaces/cli/bugx_cli/hosts/registry.py +571 -0
- package/interfaces/cli/bugx_cli/hosts/template_engine.py +188 -0
- package/interfaces/cli/bugx_cli/infra/__init__.py +209 -0
- package/interfaces/cli/bugx_cli/infra/ai_advisor.py +721 -0
- package/interfaces/cli/bugx_cli/infra/engine_installer.py +1937 -0
- package/interfaces/cli/bugx_cli/infra/host_sync.py +545 -0
- package/interfaces/cli/bugx_cli/infra/mcp_advisor.py +755 -0
- package/interfaces/cli/bugx_cli/infra/security.py +332 -0
- package/package.json +98 -4
- package/pyproject.toml +246 -0
- package/scripts/README.md +118 -0
- package/scripts/ensure-python.mjs +97 -0
- package/scripts/isolate-npm-readme.mjs +40 -0
- package/scripts/runtime.lock.json +31 -0
- package/scripts/sync-version.mjs +37 -0
- package/scripts/test-npm-wrapper.mjs +265 -0
|
@@ -0,0 +1,1199 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""bugx 云端同步客户端 —— 对接后端 /api/v1/agent/*(DOC-008 V2-only)。
|
|
3
|
+
|
|
4
|
+
覆盖:device-code 登录(发码+轮询)、api-key、设备登记、project 登记、
|
|
5
|
+
global/project knowledge 的 push/pull、sync/status。复用 report_client 的
|
|
6
|
+
结构化结果(ReportResult)与解析/错误归一。
|
|
7
|
+
|
|
8
|
+
协议口径(DOC-008 §5,V2-only,无任何 V1 fallback):
|
|
9
|
+
wire envelope 严格 schema_version=2;records 五个数组恒在;
|
|
10
|
+
manifest_hash 为 canonical hash(见 core/cloud_schema.py)。
|
|
11
|
+
POST /api/v1/agent/auth/device {device_id, name} -> data{device_code,user_code,verification_uri,expires_in,interval}
|
|
12
|
+
POST /api/v1/agent/auth/device-token {device_code, device_id} -> 成功 data{token,refresh_token,user};pending/denied 用 code=403+error 字段
|
|
13
|
+
POST /api/v1/agent/auth/refresh {refresh_token} -> data{token,refresh_token,user}
|
|
14
|
+
POST /api/v1/agent/devices {device_id, name}(Bearer)
|
|
15
|
+
POST /api/v1/agent/projects {project_key,name,slug,owner}(Bearer)-> data{project_id,project_key,slug,name,owner}
|
|
16
|
+
POST /api/v1/agent/global/knowledge V2 push envelope(Bearer)
|
|
17
|
+
GET /api/v1/agent/global/knowledge ?schema_version=2&cursor=<opaque>&page_size&device_id(query-only,禁止 body)
|
|
18
|
+
POST /api/v1/agent/global/knowledge/ack post-import cursor ACK(Bearer)
|
|
19
|
+
GET /api/v1/agent/sync/status -> data{...}
|
|
20
|
+
旧客户端/旧响应一律明确拒绝(缺 schema、schema=1、legacy lessons/incidents 字段)。
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import base64
|
|
26
|
+
import dataclasses
|
|
27
|
+
import datetime as _datetime
|
|
28
|
+
import hashlib
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import re
|
|
32
|
+
import socket
|
|
33
|
+
import ssl
|
|
34
|
+
import subprocess
|
|
35
|
+
import sys
|
|
36
|
+
import time
|
|
37
|
+
import urllib.error
|
|
38
|
+
import urllib.parse
|
|
39
|
+
import urllib.request
|
|
40
|
+
import uuid
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Any, Callable, Mapping
|
|
43
|
+
|
|
44
|
+
from core.report_engine.report_client import (
|
|
45
|
+
ReportResult,
|
|
46
|
+
atomic_write_nofollow,
|
|
47
|
+
load_installation_secret, # 设备 ID 文件丢失时的同机稳定派生源
|
|
48
|
+
message_from_response,
|
|
49
|
+
parse_response_json,
|
|
50
|
+
)
|
|
51
|
+
from core.infra.client_metadata import client_headers, client_marker, client_user_agent, client_version, tls_context
|
|
52
|
+
from core.secure_atomic import AtomicWriteError, reject_symlink_components
|
|
53
|
+
from core.cloud_sync.cloud_schema import (
|
|
54
|
+
MAX_CURSOR_LENGTH,
|
|
55
|
+
SCHEMA_VERSION,
|
|
56
|
+
SchemaError,
|
|
57
|
+
SyncError,
|
|
58
|
+
build_push_envelope,
|
|
59
|
+
parse_sync_error,
|
|
60
|
+
validate_pull_response,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# 发布包的默认正式云端端点;可由 BUGX_CLOUD_API_BASE 或全局 cloud-config.json 覆盖。
|
|
64
|
+
DEFAULT_BASE = "https://bugx.dev"
|
|
65
|
+
DEFAULT_BASE_CANDIDATES: tuple[str, ...] = ("https://bugx.com.cn", "https://bugx.dev")
|
|
66
|
+
CLOUD_ROUTE_CACHE_PATH = os.environ.get(
|
|
67
|
+
"BUGX_CLOUD_ROUTE_CACHE", str(Path.home() / ".bugx" / "cloud-route-cache.json")
|
|
68
|
+
)
|
|
69
|
+
DEFAULT_ROUTE_TTL = float(os.environ.get("BUGX_CLOUD_ROUTE_TTL", "86400")) # 24 小时
|
|
70
|
+
DEFAULT_PROBE_TIMEOUT = float(os.environ.get("BUGX_PROBE_TIMEOUT", "0.8"))
|
|
71
|
+
_MEMOIZED_BASE_URL: str | None = None
|
|
72
|
+
CRED_PATH = os.environ.get("BUGX_CLOUD_CREDENTIALS", str(Path.home() / ".bugx" / "cloud-credentials.json"))
|
|
73
|
+
DEVICE_ID_PATH = os.environ.get("BUGX_CLOUD_DEVICE_ID", str(Path.home() / ".bugx" / "cloud-device-id"))
|
|
74
|
+
CLOUD_CONFIG_PATH = os.environ.get(
|
|
75
|
+
"BUGX_CLOUD_CONFIG", str(Path.home() / ".bugx" / "cloud-config.json")
|
|
76
|
+
)
|
|
77
|
+
DEFAULT_TIMEOUT = float(os.environ.get("BUGX_CLOUD_TIMEOUT", "8"))
|
|
78
|
+
DEFAULT_RETRIES = int(os.environ.get("BUGX_CLOUD_RETRIES", "1"))
|
|
79
|
+
DEFAULT_PAGE = int(os.environ.get("BUGX_CLOUD_PAGE_SIZE", "100"))
|
|
80
|
+
MAX_PULL_PAGES = int(os.environ.get("BUGX_CLOUD_MAX_PULL_PAGES", "1000"))
|
|
81
|
+
MAX_AGENT_PACKAGE_BYTES = 128 * 1024 * 1024
|
|
82
|
+
AGENT_PACKAGE_READ_CHUNK = 1024 * 1024
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
from core.cloud_sync.network_transport import (
|
|
86
|
+
CurlResponse,
|
|
87
|
+
NoRedirectHandler,
|
|
88
|
+
build_no_redirect_open,
|
|
89
|
+
build_redirect_opener,
|
|
90
|
+
diagnose_network_error,
|
|
91
|
+
is_private_target_host,
|
|
92
|
+
parse_curl_response_headers,
|
|
93
|
+
tls_context,
|
|
94
|
+
trusted_curl_request,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# Compatibility aliases
|
|
98
|
+
_is_private_target_host = is_private_target_host
|
|
99
|
+
_NoRedirectHandler = NoRedirectHandler
|
|
100
|
+
_tls_context = tls_context
|
|
101
|
+
_build_no_redirect_open = build_no_redirect_open
|
|
102
|
+
_build_redirect_opener = build_redirect_opener
|
|
103
|
+
_CurlResponse = CurlResponse
|
|
104
|
+
_parse_curl_response_headers = parse_curl_response_headers
|
|
105
|
+
_trusted_curl_request = trusted_curl_request
|
|
106
|
+
from core.cloud_sync.sensitive_filter import (
|
|
107
|
+
SENSITIVE_POLICIES,
|
|
108
|
+
SYNC_DETAIL_MODES,
|
|
109
|
+
SYNC_POLICY_VOCABS,
|
|
110
|
+
SYNC_SCOPE_DEFAULTS,
|
|
111
|
+
SensitiveSyncError,
|
|
112
|
+
emit_policy_audit,
|
|
113
|
+
iter_record_strings,
|
|
114
|
+
prepare_records_for_sync,
|
|
115
|
+
redact_records_for_sync,
|
|
116
|
+
redact_sensitive_text,
|
|
117
|
+
scan_kind,
|
|
118
|
+
scan_sensitive_text,
|
|
119
|
+
scan_wire_value,
|
|
120
|
+
validate_knowledge_for_sync,
|
|
121
|
+
validate_pull_envelope,
|
|
122
|
+
validate_records_for_sync,
|
|
123
|
+
validate_secret_shapes,
|
|
124
|
+
wire_project_id,
|
|
125
|
+
)
|
|
126
|
+
from core.cloud_sync.endpoint_router import (
|
|
127
|
+
clear_cloud_base_url,
|
|
128
|
+
clear_route_cache,
|
|
129
|
+
cloud_base_url_status,
|
|
130
|
+
cloud_config_path,
|
|
131
|
+
cloud_route_cache_path,
|
|
132
|
+
configured_base_url,
|
|
133
|
+
load_cloud_config,
|
|
134
|
+
load_route_cache,
|
|
135
|
+
probe_candidate_latency,
|
|
136
|
+
read_cloud_config_raw,
|
|
137
|
+
save_route_cache,
|
|
138
|
+
select_lowest_latency_endpoint,
|
|
139
|
+
set_cloud_base_url,
|
|
140
|
+
update_cloud_config,
|
|
141
|
+
validate_base_url,
|
|
142
|
+
)
|
|
143
|
+
from core.cloud_sync.device_identity import (
|
|
144
|
+
CloudCredentials,
|
|
145
|
+
LESSON_FEEDBACK_MAX_ITEMS,
|
|
146
|
+
LESSON_FEEDBACK_OUTCOMES,
|
|
147
|
+
get_device_id,
|
|
148
|
+
get_device_label,
|
|
149
|
+
incident_to_wire,
|
|
150
|
+
lesson_to_wire,
|
|
151
|
+
token_expires_in,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# Compatibility aliases
|
|
155
|
+
_scan_wire_value = scan_wire_value
|
|
156
|
+
_scan_kind = scan_kind
|
|
157
|
+
_iter_record_strings = iter_record_strings
|
|
158
|
+
_validate_secret_shapes = validate_secret_shapes
|
|
159
|
+
_emit_policy_audit = emit_policy_audit
|
|
160
|
+
_wire_project_id = wire_project_id
|
|
161
|
+
_validate_base_url = validate_base_url
|
|
162
|
+
_cloud_config_path = cloud_config_path
|
|
163
|
+
_cloud_route_cache_path = cloud_route_cache_path
|
|
164
|
+
_read_cloud_config_raw = read_cloud_config_raw
|
|
165
|
+
_token_expires_in = token_expires_in
|
|
166
|
+
|
|
167
|
+
AGENT_API_PREFIX = "/api/v1/agent"
|
|
168
|
+
DEVICE_PATH = f"{AGENT_API_PREFIX}/auth/device"
|
|
169
|
+
DEVICE_TOKEN_PATH = f"{AGENT_API_PREFIX}/auth/device-token"
|
|
170
|
+
AUTH_REFRESH_PATH = f"{AGENT_API_PREFIX}/auth/refresh"
|
|
171
|
+
ROUTING_PATH = f"{AGENT_API_PREFIX}/routing"
|
|
172
|
+
DEVICES_PATH = f"{AGENT_API_PREFIX}/devices"
|
|
173
|
+
PROJECTS_PATH = f"{AGENT_API_PREFIX}/projects"
|
|
174
|
+
SYNC_STATUS_PATH = f"{AGENT_API_PREFIX}/sync/status"
|
|
175
|
+
VERSION_CHECK_PATH = f"{AGENT_API_PREFIX}/version"
|
|
176
|
+
DOWNLOAD_PATH = f"{AGENT_API_PREFIX}/download"
|
|
177
|
+
KNOWLEDGE_PREFETCH_PATH = f"{AGENT_API_PREFIX}/knowledge/prefetch"
|
|
178
|
+
VULNERABILITY_QUERY_PATH = f"{AGENT_API_PREFIX}/vulnerabilities/query"
|
|
179
|
+
PATCH_VERIFICATION_PATH = f"{AGENT_API_PREFIX}/patch-verifications"
|
|
180
|
+
PROJECT_PROFILE_MAX_BYTES = 256 * 1024
|
|
181
|
+
VULNERABILITY_QUERY_MAX_COMPONENTS = 100
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
class CloudClient:
|
|
185
|
+
"""带认证的云端客户端(device-code / api-key),网络封装单一入口。"""
|
|
186
|
+
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
base_url: str | None = None,
|
|
190
|
+
credentials: CloudCredentials | None = None,
|
|
191
|
+
cred_path: str | Path | None = None,
|
|
192
|
+
*,
|
|
193
|
+
timeout: float | None = None,
|
|
194
|
+
retries: int | None = None,
|
|
195
|
+
urlopen: Callable[..., Any] | None = None,
|
|
196
|
+
) -> None:
|
|
197
|
+
self.cred_path = cred_path or CRED_PATH
|
|
198
|
+
self.cred = credentials if credentials is not None else CloudCredentials.load(self.cred_path)
|
|
199
|
+
if base_url:
|
|
200
|
+
# An explicit endpoint is authoritative. Do not inspect user sync
|
|
201
|
+
# configuration or device routing before honoring it.
|
|
202
|
+
self._explicit_base = True
|
|
203
|
+
self._server_route_enabled = False
|
|
204
|
+
self.base = _validate_base_url(base_url)
|
|
205
|
+
else:
|
|
206
|
+
configured = cloud_base_url_status()
|
|
207
|
+
self._explicit_base = configured["source"] != "default"
|
|
208
|
+
self._server_route_enabled = not self._explicit_base and client_marker() not in {"dev", "uat"}
|
|
209
|
+
route_base = (
|
|
210
|
+
self.cred.cloud_api_base
|
|
211
|
+
if self._server_route_enabled and self._route_matches_client() else None
|
|
212
|
+
)
|
|
213
|
+
self.base = route_base or configured_base_url()
|
|
214
|
+
self.timeout = timeout if timeout is not None else DEFAULT_TIMEOUT
|
|
215
|
+
self.retries = retries if retries is not None else DEFAULT_RETRIES
|
|
216
|
+
self.max_pull_pages = MAX_PULL_PAGES
|
|
217
|
+
self._custom_urlopen = urlopen is not None
|
|
218
|
+
self._urlopen = urlopen or _build_no_redirect_open(self.base)
|
|
219
|
+
|
|
220
|
+
@staticmethod
|
|
221
|
+
def _expected_environment() -> str:
|
|
222
|
+
return {"dev": "dev", "uat": "uat"}.get(client_marker(), "prod")
|
|
223
|
+
|
|
224
|
+
def _route_matches_client(self) -> bool:
|
|
225
|
+
return bool(self.cred.cloud_api_base and self.cred.cloud_region
|
|
226
|
+
and self.cred.cloud_route_environment == self._expected_environment())
|
|
227
|
+
|
|
228
|
+
def _route_expired(self) -> bool:
|
|
229
|
+
if self._server_route_enabled and self.cred.is_authenticated() and not self._route_matches_client():
|
|
230
|
+
return True
|
|
231
|
+
value = self.cred.cloud_route_expires_at
|
|
232
|
+
if not value:
|
|
233
|
+
return False
|
|
234
|
+
try:
|
|
235
|
+
expires = _datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
236
|
+
except (TypeError, ValueError):
|
|
237
|
+
return True
|
|
238
|
+
if expires.tzinfo is None:
|
|
239
|
+
expires = expires.replace(tzinfo=_datetime.timezone.utc)
|
|
240
|
+
return expires.timestamp() <= time.time()
|
|
241
|
+
|
|
242
|
+
def _store_route(self, route: object) -> bool:
|
|
243
|
+
if not isinstance(route, dict):
|
|
244
|
+
return False
|
|
245
|
+
region = str(route.get("region") or "").strip().lower()
|
|
246
|
+
environment = str(route.get("environment") or "").strip().lower()
|
|
247
|
+
api_base = str(route.get("api_base") or "").strip()
|
|
248
|
+
if region not in {"cn", "global"} or environment != self._expected_environment() or not api_base:
|
|
249
|
+
return False
|
|
250
|
+
try:
|
|
251
|
+
normalized = _validate_base_url(api_base)
|
|
252
|
+
except ValueError:
|
|
253
|
+
return False
|
|
254
|
+
self.cred.cloud_region = region
|
|
255
|
+
self.cred.cloud_api_base = normalized
|
|
256
|
+
self.cred.cloud_route_environment = environment
|
|
257
|
+
self.cred.cloud_route_expires_at = str(route.get("expires_at") or "")
|
|
258
|
+
self.cred.cloud_route_version = str(route.get("config_version") or "")
|
|
259
|
+
if self._server_route_enabled:
|
|
260
|
+
self.base = normalized
|
|
261
|
+
if not self._custom_urlopen:
|
|
262
|
+
self._urlopen = _build_no_redirect_open(self.base)
|
|
263
|
+
return True
|
|
264
|
+
|
|
265
|
+
def _refresh_route(self) -> bool:
|
|
266
|
+
if not self._server_route_enabled or not self.cred.is_authenticated():
|
|
267
|
+
return False
|
|
268
|
+
result = self._request("GET", ROUTING_PATH, auth=True, retry_auth=False)
|
|
269
|
+
if not result.ok:
|
|
270
|
+
return False
|
|
271
|
+
stored = self._store_route(self._data(result))
|
|
272
|
+
if stored:
|
|
273
|
+
self.cred.save(self.cred_path)
|
|
274
|
+
return stored
|
|
275
|
+
|
|
276
|
+
# ---- 内部请求 ----
|
|
277
|
+
def _auth_header(self) -> str | None:
|
|
278
|
+
key = self.cred.api_key or self.cred.token
|
|
279
|
+
return f"Bearer {key}" if key else None
|
|
280
|
+
|
|
281
|
+
def _mark_auth_expired(self) -> None:
|
|
282
|
+
"""Keep a server-confirmed 401 visible to the next CLI process."""
|
|
283
|
+
self.cred.auth_state_override = "expired"
|
|
284
|
+
try:
|
|
285
|
+
self.cred.save(self.cred_path)
|
|
286
|
+
except (OSError, ValueError):
|
|
287
|
+
# An unwritable cache must not hide the authoritative 401 result.
|
|
288
|
+
pass
|
|
289
|
+
|
|
290
|
+
def _open_request(self, req: urllib.request.Request) -> Any:
|
|
291
|
+
try:
|
|
292
|
+
return self._urlopen(req, timeout=self.timeout)
|
|
293
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
|
|
294
|
+
if self._custom_urlopen or not diagnose_network_error(
|
|
295
|
+
exc, req.full_url
|
|
296
|
+
)["is_local_network_blocked"]:
|
|
297
|
+
raise
|
|
298
|
+
try:
|
|
299
|
+
return _trusted_curl_request(req, self.timeout)
|
|
300
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError,
|
|
301
|
+
ValueError) as fallback_error:
|
|
302
|
+
raise fallback_error from exc
|
|
303
|
+
|
|
304
|
+
def _request(self, method: str, path: str, payload: dict | None = None,
|
|
305
|
+
*, auth: bool = True, retry_auth: bool = True,
|
|
306
|
+
params: dict | None = None,
|
|
307
|
+
extra_headers: dict | None = None) -> ReportResult:
|
|
308
|
+
if auth and path not in {ROUTING_PATH, AUTH_REFRESH_PATH} and self._route_expired():
|
|
309
|
+
self._refresh_route()
|
|
310
|
+
url = self.base + path
|
|
311
|
+
if params:
|
|
312
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
313
|
+
headers = {
|
|
314
|
+
"Accept": "application/json",
|
|
315
|
+
**client_headers(),
|
|
316
|
+
}
|
|
317
|
+
if extra_headers:
|
|
318
|
+
headers.update(extra_headers)
|
|
319
|
+
if auth:
|
|
320
|
+
# 客户端到期前 2 天自动静默续期(API Key 为独立体系,不触发 refresh)
|
|
321
|
+
if retry_auth and not self.cred.api_key and self.cred.token and self.cred.refresh_token:
|
|
322
|
+
expires_in = _token_expires_in(self.cred.token)
|
|
323
|
+
if expires_in is not None and expires_in <= 2 * 86400:
|
|
324
|
+
self._refresh()
|
|
325
|
+
header = self._auth_header()
|
|
326
|
+
if header:
|
|
327
|
+
headers["Authorization"] = header
|
|
328
|
+
body = None
|
|
329
|
+
if payload is not None:
|
|
330
|
+
# V2-only:pull 一律 query 参数(DOC-008 §5.2),GET 禁止携带 body。
|
|
331
|
+
headers["Content-Type"] = "application/json"
|
|
332
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
333
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
334
|
+
for attempt in range(self.retries + 1):
|
|
335
|
+
try:
|
|
336
|
+
resp = self._open_request(req)
|
|
337
|
+
try:
|
|
338
|
+
status = getattr(resp, "status", 200)
|
|
339
|
+
raw = resp.read() if hasattr(resp, "read") else b""
|
|
340
|
+
finally:
|
|
341
|
+
resp.close()
|
|
342
|
+
data = parse_response_json(raw)
|
|
343
|
+
# V2 errors use their real HTTP status; older handlers may also
|
|
344
|
+
# return a 200 envelope with code>=400, so handle both forms.
|
|
345
|
+
code_marker = data.get("code") if isinstance(data, dict) else None
|
|
346
|
+
biz_401 = (status == 401) or (code_marker == 401)
|
|
347
|
+
if (biz_401 and auth and retry_auth and self.cred.refresh_token
|
|
348
|
+
and self._refresh()):
|
|
349
|
+
return self._request(method, path, payload, auth=auth, retry_auth=False,
|
|
350
|
+
params=params, extra_headers=extra_headers)
|
|
351
|
+
if biz_401 and auth:
|
|
352
|
+
self._mark_auth_expired()
|
|
353
|
+
retryable = (
|
|
354
|
+
status >= 500
|
|
355
|
+
or (isinstance(code_marker, int) and code_marker in (429, 503))
|
|
356
|
+
)
|
|
357
|
+
if retryable and attempt < self.retries:
|
|
358
|
+
time.sleep(self._retry_delay(data, attempt))
|
|
359
|
+
continue
|
|
360
|
+
biz_bad = isinstance(code_marker, int) and code_marker >= 400
|
|
361
|
+
return ReportResult(ok=200 <= status < 300 and not biz_bad,
|
|
362
|
+
status=status, data=data, error=None,
|
|
363
|
+
)
|
|
364
|
+
except urllib.error.HTTPError as exc:
|
|
365
|
+
# 401 → 用 refresh_token 续期后重试一次(覆盖真实 HTTP 401)
|
|
366
|
+
if (exc.code == 401 and auth and retry_auth and self.cred.refresh_token
|
|
367
|
+
and self._refresh()):
|
|
368
|
+
try:
|
|
369
|
+
exc.close()
|
|
370
|
+
except Exception: # noqa: BLE001
|
|
371
|
+
pass
|
|
372
|
+
return self._request(method, path, payload, auth=auth, retry_auth=False,
|
|
373
|
+
params=params, extra_headers=extra_headers)
|
|
374
|
+
if exc.code == 401 and auth:
|
|
375
|
+
self._mark_auth_expired()
|
|
376
|
+
if exc.code >= 500 and attempt < self.retries:
|
|
377
|
+
try:
|
|
378
|
+
exc.close()
|
|
379
|
+
except Exception: # noqa: BLE001
|
|
380
|
+
pass
|
|
381
|
+
time.sleep(0.5 * (attempt + 1))
|
|
382
|
+
continue
|
|
383
|
+
raw = exc.read()
|
|
384
|
+
try:
|
|
385
|
+
exc.close()
|
|
386
|
+
except Exception: # noqa: BLE001
|
|
387
|
+
pass
|
|
388
|
+
return ReportResult(ok=False, status=exc.code, data=parse_response_json(raw), error=message_from_response(raw, exc))
|
|
389
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
|
|
390
|
+
if attempt < self.retries:
|
|
391
|
+
time.sleep(0.5 * (attempt + 1))
|
|
392
|
+
continue
|
|
393
|
+
diag = diagnose_network_error(exc, url)
|
|
394
|
+
if diag["is_local_network_blocked"]:
|
|
395
|
+
return ReportResult(
|
|
396
|
+
ok=False, status=None,
|
|
397
|
+
data={"code": diag["code"], "message": diag["message"]},
|
|
398
|
+
error=diag["message"],
|
|
399
|
+
)
|
|
400
|
+
message = diag.get("message", str(exc))
|
|
401
|
+
return ReportResult(
|
|
402
|
+
ok=False, status=None,
|
|
403
|
+
data={"code": "SYNC_NETWORK_UNAVAILABLE", "message": message},
|
|
404
|
+
error=message,
|
|
405
|
+
)
|
|
406
|
+
except ValueError as exc:
|
|
407
|
+
return ReportResult(
|
|
408
|
+
ok=False, status=None,
|
|
409
|
+
data={"code": "SYNC_INVALID_RESPONSE", "message": str(exc)},
|
|
410
|
+
error=str(exc),
|
|
411
|
+
)
|
|
412
|
+
return ReportResult(ok=False, status=None, data=None, error="unknown")
|
|
413
|
+
|
|
414
|
+
def _data(self, res: ReportResult) -> dict:
|
|
415
|
+
return (res.data or {}).get("data") if isinstance(res.data, dict) and isinstance(res.data.get("data"), dict) else (res.data or {})
|
|
416
|
+
|
|
417
|
+
def submit_patch_package(self, package: bytes, filename: str, *,
|
|
418
|
+
source_commit: str = "") -> ReportResult:
|
|
419
|
+
"""Submit an opaque patch ZIP; the server owns static verification."""
|
|
420
|
+
if not isinstance(package, (bytes, bytearray)) or not package:
|
|
421
|
+
raise ValueError("补丁包不能为空")
|
|
422
|
+
if not filename or "/" in filename or "\\" in filename:
|
|
423
|
+
raise ValueError("补丁包文件名无效")
|
|
424
|
+
boundary = "----bugx-patch-" + uuid.uuid4().hex
|
|
425
|
+
chunks = [
|
|
426
|
+
f"--{boundary}\r\nContent-Disposition: form-data; name=\"package\"; filename=\"{filename}\"\r\nContent-Type: application/zip\r\n\r\n".encode(),
|
|
427
|
+
bytes(package), b"\r\n",
|
|
428
|
+
f"--{boundary}\r\nContent-Disposition: form-data; name=\"source_commit\"\r\n\r\n{source_commit.strip()}\r\n".encode(),
|
|
429
|
+
f"--{boundary}--\r\n".encode(),
|
|
430
|
+
]
|
|
431
|
+
return self._request_raw(
|
|
432
|
+
"POST", PATCH_VERIFICATION_PATH, b"".join(chunks),
|
|
433
|
+
content_type=f"multipart/form-data; boundary={boundary}",
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
def get_patch_verification(self, verification_id: str) -> ReportResult:
|
|
437
|
+
value = str(verification_id or "").strip()
|
|
438
|
+
if not re.fullmatch(r"[1-9][0-9]*", value):
|
|
439
|
+
raise ValueError("verification_id 必须是正整数")
|
|
440
|
+
return self._request("GET", f"{PATCH_VERIFICATION_PATH}/{value}")
|
|
441
|
+
|
|
442
|
+
def _request_raw(self, method: str, path: str, body: bytes,
|
|
443
|
+
*, content_type: str) -> ReportResult:
|
|
444
|
+
url = self.base + path
|
|
445
|
+
headers = {"Accept": "application/json", **client_headers(),
|
|
446
|
+
"Content-Type": content_type, "Content-Length": str(len(body))}
|
|
447
|
+
auth = self._auth_header()
|
|
448
|
+
if auth:
|
|
449
|
+
headers["Authorization"] = auth
|
|
450
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
451
|
+
try:
|
|
452
|
+
resp = self._open_request(req)
|
|
453
|
+
try:
|
|
454
|
+
status = getattr(resp, "status", 200)
|
|
455
|
+
raw = resp.read() if hasattr(resp, "read") else b""
|
|
456
|
+
finally:
|
|
457
|
+
resp.close()
|
|
458
|
+
data = parse_response_json(raw)
|
|
459
|
+
code = data.get("code") if isinstance(data, dict) else None
|
|
460
|
+
return ReportResult(ok=200 <= status < 300 and not (isinstance(code, int) and code >= 400),
|
|
461
|
+
status=status, data=data, error=None)
|
|
462
|
+
except urllib.error.HTTPError as exc:
|
|
463
|
+
raw = exc.read()
|
|
464
|
+
try:
|
|
465
|
+
exc.close()
|
|
466
|
+
except Exception: # noqa: BLE001
|
|
467
|
+
pass
|
|
468
|
+
return ReportResult(ok=False, status=exc.code, data=parse_response_json(raw), error=message_from_response(raw, exc))
|
|
469
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
|
|
470
|
+
diag = diagnose_network_error(exc, url)
|
|
471
|
+
if diag["is_local_network_blocked"]:
|
|
472
|
+
return ReportResult(
|
|
473
|
+
ok=False, status=None,
|
|
474
|
+
data={"code": diag["code"], "message": diag["message"]},
|
|
475
|
+
error=diag["message"],
|
|
476
|
+
)
|
|
477
|
+
message = diag.get("message", str(exc))
|
|
478
|
+
return ReportResult(ok=False, status=None,
|
|
479
|
+
data={"code": "PATCH_NETWORK_UNAVAILABLE", "message": message},
|
|
480
|
+
error=message)
|
|
481
|
+
except ValueError as exc:
|
|
482
|
+
return ReportResult(ok=False, status=None,
|
|
483
|
+
data={"code": "PATCH_NETWORK_UNAVAILABLE", "message": str(exc)},
|
|
484
|
+
error=str(exc))
|
|
485
|
+
|
|
486
|
+
@staticmethod
|
|
487
|
+
def _retry_delay(data: dict | None, attempt: int) -> float:
|
|
488
|
+
err = parse_sync_error(None, data)
|
|
489
|
+
if err.retry_after_seconds is not None:
|
|
490
|
+
return float(min(err.retry_after_seconds, 30))
|
|
491
|
+
return 0.5 * (attempt + 1)
|
|
492
|
+
|
|
493
|
+
def sync_error(self, res: ReportResult) -> SyncError:
|
|
494
|
+
"""把失败响应解析为结构化同步错误(DOC-008 §5.3)。"""
|
|
495
|
+
status = res.status
|
|
496
|
+
body = res.data if isinstance(res.data, dict) else {}
|
|
497
|
+
wrapped = body.get("code") if isinstance(body, dict) else None
|
|
498
|
+
if isinstance(wrapped, int) and not isinstance(wrapped, bool):
|
|
499
|
+
status = status if (status is not None and status >= 400) else wrapped
|
|
500
|
+
return parse_sync_error(status, body)
|
|
501
|
+
|
|
502
|
+
# ---- 认证 ----
|
|
503
|
+
def start_device(self, name: str = "", device_id: str | None = None) -> dict:
|
|
504
|
+
"""发起 device-code,返回 {device_code, user_code, verification_uri, expires_in, interval}。"""
|
|
505
|
+
did = device_id or get_device_id()
|
|
506
|
+
res = self._request("POST", DEVICE_PATH, {"device_id": did, "name": name}, auth=False, retry_auth=False)
|
|
507
|
+
if not res.ok:
|
|
508
|
+
raise RuntimeError(f"发起设备授权失败: code={res.status} {res.error}")
|
|
509
|
+
return self._data(res)
|
|
510
|
+
|
|
511
|
+
def poll_device_token(self, device_code: str, device_id: str | None = None,
|
|
512
|
+
max_tries: int = 120, interval: int = 5) -> ReportResult:
|
|
513
|
+
"""轮询 device-token:pending/无 token 继续,denied/expired 报错,拿到 token 存凭据。"""
|
|
514
|
+
code_to_msg = {
|
|
515
|
+
"access_denied": "用户已拒绝授权",
|
|
516
|
+
"expired_token": "授权码已过期,请重新登录",
|
|
517
|
+
"expired": "授权码已过期,请重新登录",
|
|
518
|
+
}
|
|
519
|
+
did = device_id or get_device_id()
|
|
520
|
+
backoff = 0.0
|
|
521
|
+
for _ in range(max_tries):
|
|
522
|
+
res = self._request("POST", DEVICE_TOKEN_PATH,
|
|
523
|
+
{"device_code": device_code, "device_id": did},
|
|
524
|
+
auth=False, retry_auth=False)
|
|
525
|
+
data = res.data if isinstance(res.data, dict) else {}
|
|
526
|
+
err = str(data.get("error", "") or "")
|
|
527
|
+
inner = data.get("data") if isinstance(data.get("data"), dict) else {}
|
|
528
|
+
token = inner.get("token") or inner.get("access_token")
|
|
529
|
+
if err in {"access_denied", "expired_token", "expired"}:
|
|
530
|
+
return ReportResult(ok=False, status=getattr(res, "status", None),
|
|
531
|
+
data=res.data, error=code_to_msg.get(err, err))
|
|
532
|
+
if token:
|
|
533
|
+
self.cred = CloudCredentials(
|
|
534
|
+
token=token, refresh_token=inner.get("refresh_token"),
|
|
535
|
+
api_key=inner.get("api_key"), user=inner.get("user"),
|
|
536
|
+
)
|
|
537
|
+
self._store_route(inner.get("route"))
|
|
538
|
+
self.cred.save(self.cred_path)
|
|
539
|
+
return ReportResult(ok=True, status=getattr(res, "status", 200),
|
|
540
|
+
data=res.data, error=None)
|
|
541
|
+
# 限流(联调 I-2):429 不消耗等待授权的轮次(device_code 有效期
|
|
542
|
+
# 远大于 max_tries*interval),按加压退避后重试同一轮询,避免
|
|
543
|
+
# 登录因服务端 RateLimitStrict 凭空失败。
|
|
544
|
+
if getattr(res, "status", None) == 429 or data.get("code") == 429:
|
|
545
|
+
backoff = min(backoff + interval, 30.0)
|
|
546
|
+
time.sleep(backoff)
|
|
547
|
+
continue
|
|
548
|
+
backoff = 0.0
|
|
549
|
+
# 仍在等待授权 -> 继续轮询
|
|
550
|
+
time.sleep(interval)
|
|
551
|
+
return ReportResult(ok=False, status=None, data=None, error="授权超时")
|
|
552
|
+
|
|
553
|
+
def login(self, name: str = "", device_id: str | None = None) -> ReportResult:
|
|
554
|
+
"""完整 device-code 登录:发码→打印 URL→尝试自动打开浏览器→轮询→存凭据。"""
|
|
555
|
+
flow = self.start_device(name=name, device_id=device_id)
|
|
556
|
+
uri = flow.get("verification_uri") or ""
|
|
557
|
+
# 授权页必须是普通 http(s) 地址:被劫持/被替换的服务端可能借
|
|
558
|
+
# file:、自定义 scheme 等把宿主浏览器导向本地文件或钓鱼协议,
|
|
559
|
+
# 这里 fail-closed,绝不打印和打开非 http(s) 链接。
|
|
560
|
+
if uri and not str(uri).lower().startswith(("http://", "https://")):
|
|
561
|
+
return ReportResult(ok=False, status=None, data=None,
|
|
562
|
+
error=f"服务端返回的 verification_uri 不是 http(s) 地址: {uri!r}")
|
|
563
|
+
# flush:stdout 可能是管道(自动化/CI),不刷会卡在缓冲里抓不到 user_code
|
|
564
|
+
print(f"请打开授权页完成登录:{uri}", flush=True)
|
|
565
|
+
print(f"(用户码 {flow.get('user_code')};有效期 {flow.get('expires_in')}s)", flush=True)
|
|
566
|
+
# 后台 device-code 需人工在浏览器确认;有桌面环境时自动拉起,失败仅回退到手动打开
|
|
567
|
+
if uri:
|
|
568
|
+
opened = False
|
|
569
|
+
try:
|
|
570
|
+
import webbrowser
|
|
571
|
+
opened = bool(webbrowser.open(uri, new=2))
|
|
572
|
+
except Exception:
|
|
573
|
+
opened = False
|
|
574
|
+
# macOS 的 TUI/子进程有时没有可用的 webbrowser 注册器;
|
|
575
|
+
# 使用系统 opener 再尝试一次,但仍不把打开失败当成授权成功。
|
|
576
|
+
if not opened and sys.platform == "darwin":
|
|
577
|
+
try:
|
|
578
|
+
opened = subprocess.run(
|
|
579
|
+
["open", uri], check=False,
|
|
580
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
581
|
+
timeout=5,
|
|
582
|
+
).returncode == 0
|
|
583
|
+
except (OSError, subprocess.SubprocessError):
|
|
584
|
+
opened = False
|
|
585
|
+
if opened:
|
|
586
|
+
print(f"已打开浏览器授权页:{uri}", flush=True)
|
|
587
|
+
else:
|
|
588
|
+
print(f"自动打开浏览器失败,请手动打开授权页:{uri}", flush=True)
|
|
589
|
+
# 轮询间隔来自服务端,属不可信输入:限幅到 [1,30] 秒,拒绝 0/负值
|
|
590
|
+
# 造成的忙轮询,也拒绝异常大值把登录挂死。非法类型回退默认 5s。
|
|
591
|
+
try:
|
|
592
|
+
interval = int(flow.get("interval", 5))
|
|
593
|
+
except (TypeError, ValueError):
|
|
594
|
+
interval = 5
|
|
595
|
+
interval = min(30, max(1, interval))
|
|
596
|
+
return self.poll_device_token(flow.get("device_code", ""),
|
|
597
|
+
device_id=device_id, interval=interval)
|
|
598
|
+
|
|
599
|
+
def set_api_key(self, api_key: str) -> None:
|
|
600
|
+
self.cred.api_key = api_key
|
|
601
|
+
self.cred.auth_state_override = None
|
|
602
|
+
self.cred.save(self.cred_path)
|
|
603
|
+
|
|
604
|
+
def logout(self) -> None:
|
|
605
|
+
self.cred.clear(self.cred_path)
|
|
606
|
+
self.cred = CloudCredentials()
|
|
607
|
+
|
|
608
|
+
def _refresh(self) -> bool:
|
|
609
|
+
res = self._request("POST", AUTH_REFRESH_PATH,
|
|
610
|
+
{"refresh_token": self.cred.refresh_token}, auth=False, retry_auth=False)
|
|
611
|
+
data = self._data(res)
|
|
612
|
+
new_tok = data.get("token") or data.get("access_token")
|
|
613
|
+
if res.ok and new_tok:
|
|
614
|
+
self.cred.token = new_tok
|
|
615
|
+
self.cred.refresh_token = data.get("refresh_token", self.cred.refresh_token)
|
|
616
|
+
self._store_route(data.get("route"))
|
|
617
|
+
self.cred.auth_state_override = None
|
|
618
|
+
self.cred.save(self.cred_path)
|
|
619
|
+
return True
|
|
620
|
+
return False
|
|
621
|
+
|
|
622
|
+
def verify_auth(self) -> ReportResult:
|
|
623
|
+
"""用只读同步状态接口验证当前凭据是否被服务端接受。
|
|
624
|
+
|
|
625
|
+
``CloudCredentials.auth_state`` 只能判断本地 JWT 过期或凭据是否
|
|
626
|
+
存在;opaque token 必须由服务端确认。该方法不创建项目、不写知识,
|
|
627
|
+
401 会通过统一请求路径触发 refresh,并在最终失败时标记 expired。
|
|
628
|
+
"""
|
|
629
|
+
if not self.cred.is_authenticated():
|
|
630
|
+
return ReportResult(ok=False, status=None, data=None, error="云端凭据未配置")
|
|
631
|
+
result = self._request("GET", SYNC_STATUS_PATH)
|
|
632
|
+
if result.ok:
|
|
633
|
+
# 成功核验清除曾经持久化的拒绝;不持久化 valid,避免 opaque
|
|
634
|
+
# token 在未来过期后仍被永久视为有效。
|
|
635
|
+
if self.cred.auth_state_override == "expired":
|
|
636
|
+
self.cred.auth_state_override = None
|
|
637
|
+
try:
|
|
638
|
+
self.cred.save(self.cred_path)
|
|
639
|
+
except (OSError, ValueError):
|
|
640
|
+
pass
|
|
641
|
+
elif result.status == 401:
|
|
642
|
+
self._mark_auth_expired()
|
|
643
|
+
return result
|
|
644
|
+
|
|
645
|
+
# ---- 设备 / 项目 ----
|
|
646
|
+
def register_device(self, name: str = "", device_id: str | None = None) -> ReportResult:
|
|
647
|
+
return self._request("POST", DEVICES_PATH,
|
|
648
|
+
{"device_id": device_id or get_device_id(), "name": name})
|
|
649
|
+
|
|
650
|
+
def register_project(self, slug: str, name: str, owner: str = "", *,
|
|
651
|
+
project_key: str | None = None) -> ReportResult:
|
|
652
|
+
"""Resolve/create a project using its stable repository identity."""
|
|
653
|
+
if not isinstance(project_key, str) or not project_key.strip():
|
|
654
|
+
raise ValueError("project_key 必须提供,禁止使用路径或目录名推导项目身份")
|
|
655
|
+
return self._request(
|
|
656
|
+
"POST", PROJECTS_PATH,
|
|
657
|
+
{"project_key": project_key.strip(), "slug": slug, "name": name, "owner": owner},
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
def list_projects(self) -> ReportResult:
|
|
661
|
+
return self._request("GET", PROJECTS_PATH)
|
|
662
|
+
|
|
663
|
+
def project_id(self, res: ReportResult) -> str:
|
|
664
|
+
"""从 register_project 的稳定 DTO 响应提取正整数 project_id。"""
|
|
665
|
+
d = self._data(res)
|
|
666
|
+
value = d.get("project_id")
|
|
667
|
+
if isinstance(value, bool):
|
|
668
|
+
return ""
|
|
669
|
+
if isinstance(value, int) and value > 0:
|
|
670
|
+
return str(value)
|
|
671
|
+
if isinstance(value, str) and re.fullmatch(r"[1-9][0-9]*", value):
|
|
672
|
+
return value
|
|
673
|
+
return ""
|
|
674
|
+
|
|
675
|
+
def project_key(self, res: ReportResult) -> str:
|
|
676
|
+
"""从项目登记 DTO 提取服务端回显的稳定身份。"""
|
|
677
|
+
value = self._data(res).get("project_key")
|
|
678
|
+
return value.strip() if isinstance(value, str) else ""
|
|
679
|
+
|
|
680
|
+
# ---- 项目画像元数据(与知识 V2 通道分离)----
|
|
681
|
+
def get_project_profile(self, project_id: str) -> ReportResult:
|
|
682
|
+
"""读取当前账号项目的 ProjectProfile 元数据。"""
|
|
683
|
+
return self._request("GET", self._profile_path(project_id))
|
|
684
|
+
|
|
685
|
+
def put_project_profile(self, project_id: str, profile: dict[str, Any], *,
|
|
686
|
+
base_revision: int = 0,
|
|
687
|
+
operation_id: str | None = None) -> ReportResult:
|
|
688
|
+
"""幂等写入项目画像;服务端以 revision 做轻量乐观并发控制。"""
|
|
689
|
+
if not isinstance(profile, dict):
|
|
690
|
+
raise ValueError("project_profile 必须是对象")
|
|
691
|
+
if profile.get("schema_version") != 2:
|
|
692
|
+
raise ValueError("project_profile.schema_version 必须为 2")
|
|
693
|
+
if not isinstance(base_revision, int) or isinstance(base_revision, bool) or base_revision < 0:
|
|
694
|
+
raise ValueError("base_revision 必须是非负整数")
|
|
695
|
+
sanitized_profile = dict(profile)
|
|
696
|
+
sanitized_profile.pop("observed_at", None)
|
|
697
|
+
body = {
|
|
698
|
+
"schema_version": 2,
|
|
699
|
+
"profile_revision": int(sanitized_profile.get("revision", 0) or 0),
|
|
700
|
+
"base_revision": base_revision,
|
|
701
|
+
"operation_id": operation_id or f"profile-{uuid.uuid4().hex}",
|
|
702
|
+
"profile": sanitized_profile,
|
|
703
|
+
}
|
|
704
|
+
raw_size = len(json.dumps(body, ensure_ascii=False, sort_keys=True).encode("utf-8"))
|
|
705
|
+
if raw_size > PROJECT_PROFILE_MAX_BYTES:
|
|
706
|
+
raise ValueError("project_profile 超过 256 KiB 限制")
|
|
707
|
+
hits: set[str] = set()
|
|
708
|
+
_scan_wire_value(profile, path="project_profile", hits=hits)
|
|
709
|
+
if hits:
|
|
710
|
+
raise SensitiveSyncError(
|
|
711
|
+
"project_profile 命中敏感信息规则(" + ", ".join(sorted(hits)) + "),拒绝上传"
|
|
712
|
+
)
|
|
713
|
+
return self._request("PUT", self._profile_path(project_id), body)
|
|
714
|
+
|
|
715
|
+
def query_vulnerabilities(self, components: list[dict[str, Any]]) -> ReportResult:
|
|
716
|
+
"""Warm/read the server's public version-specific advisory cache.
|
|
717
|
+
|
|
718
|
+
The response is advisory-only: callers keep local SCA candidates as
|
|
719
|
+
the authoritative offline path and must not mutate ProjectProfile from
|
|
720
|
+
this endpoint.
|
|
721
|
+
"""
|
|
722
|
+
if not isinstance(components, list) or len(components) > VULNERABILITY_QUERY_MAX_COMPONENTS:
|
|
723
|
+
raise ValueError("漏洞查询组件数不能超过 100")
|
|
724
|
+
normalized: list[dict[str, str]] = []
|
|
725
|
+
seen: set[tuple[str, str, str]] = set()
|
|
726
|
+
for item in components:
|
|
727
|
+
if not isinstance(item, dict):
|
|
728
|
+
raise ValueError("漏洞查询组件必须是对象")
|
|
729
|
+
ecosystem = str(item.get("ecosystem") or "").strip().lower()
|
|
730
|
+
name = str(item.get("name") or item.get("package") or "").strip()
|
|
731
|
+
version = str(
|
|
732
|
+
item.get("resolved_version")
|
|
733
|
+
or item.get("declared_version")
|
|
734
|
+
or item.get("observed_version")
|
|
735
|
+
or ""
|
|
736
|
+
).strip()
|
|
737
|
+
if not ecosystem or not name or not version:
|
|
738
|
+
continue
|
|
739
|
+
key = (ecosystem, name, version)
|
|
740
|
+
if key in seen:
|
|
741
|
+
continue
|
|
742
|
+
seen.add(key)
|
|
743
|
+
normalized.append({"ecosystem": ecosystem, "name": name, "version": version})
|
|
744
|
+
return self._request(
|
|
745
|
+
"POST", VULNERABILITY_QUERY_PATH,
|
|
746
|
+
{"schema_version": 1, "components": normalized},
|
|
747
|
+
)
|
|
748
|
+
|
|
749
|
+
# ---- 知识同步(V2-only)----
|
|
750
|
+
def push_knowledge(self, scope: str, project_id: str = "",
|
|
751
|
+
lessons: list[dict] | None = None,
|
|
752
|
+
incidents: list[dict] | None = None, *,
|
|
753
|
+
tool_experience: list[dict] | None = None,
|
|
754
|
+
consumption_events: list[dict] | None = None,
|
|
755
|
+
tombstones: list[dict] | None = None,
|
|
756
|
+
snapshot_id: str | None = None,
|
|
757
|
+
operation_id: str | None = None,
|
|
758
|
+
base_version: int | None = None,
|
|
759
|
+
device_id: str | None = None,
|
|
760
|
+
sensitive_policy: str = "allow") -> ReportResult:
|
|
761
|
+
"""V2 push:完整 envelope(records 四数组恒在,无 legacy 顶层字段)。
|
|
762
|
+
|
|
763
|
+
DOC-211:sensitive_policy=allow 跳过出网敏感扫描(策略应用已在构建侧
|
|
764
|
+
prepare_records_for_sync 完成);block/redact 在此做最终复核。
|
|
765
|
+
"""
|
|
766
|
+
if scope not in {"global", "project"}:
|
|
767
|
+
raise ValueError("scope 必须是 global 或 project")
|
|
768
|
+
if scope == "project" and not str(project_id).strip():
|
|
769
|
+
raise ValueError("project scope 必须显式提供 project_id")
|
|
770
|
+
if base_version is not None and (not isinstance(base_version, int)
|
|
771
|
+
or isinstance(base_version, bool) or base_version < 0):
|
|
772
|
+
raise ValueError("base_version 必须是非负整数")
|
|
773
|
+
filtered_lessons = list(lessons or [])
|
|
774
|
+
filtered_tombstones = list(tombstones or [])
|
|
775
|
+
if scope == "project":
|
|
776
|
+
filtered_lessons = [
|
|
777
|
+
p for p in filtered_lessons
|
|
778
|
+
if not (str(p.get("pattern_id") or p.get("lesson_id") or "").startswith("L-00000000000")
|
|
779
|
+
or ("mistake-book.md" in str(p.get("source_refs") or "")))
|
|
780
|
+
]
|
|
781
|
+
filtered_tombstones = [
|
|
782
|
+
t for t in filtered_tombstones
|
|
783
|
+
if not (str(t.get("record_type") or "") in ("pattern", "patterns")
|
|
784
|
+
and str(t.get("record_id") or "").startswith("L-00000000000"))
|
|
785
|
+
]
|
|
786
|
+
records = {
|
|
787
|
+
"patterns": filtered_lessons,
|
|
788
|
+
"incidents": list(incidents or []),
|
|
789
|
+
"tool_experience": list(tool_experience or []),
|
|
790
|
+
"consumption_events": list(consumption_events or []),
|
|
791
|
+
"tombstones": filtered_tombstones,
|
|
792
|
+
}
|
|
793
|
+
validate_records_for_sync(records, policy=sensitive_policy)
|
|
794
|
+
if sensitive_policy != "allow":
|
|
795
|
+
# DOC-211:与 import 档同源——三正则(16+ 值长门槛)之外的裸凭据
|
|
796
|
+
# 形状(短值赋值/sk-/JWT/DSN)由 secret_redactor 形状扫描兜底。
|
|
797
|
+
_validate_secret_shapes(records, policy=sensitive_policy)
|
|
798
|
+
envelope = build_push_envelope(
|
|
799
|
+
scope, _wire_project_id(project_id), records,
|
|
800
|
+
snapshot_id=snapshot_id or uuid.uuid4().hex,
|
|
801
|
+
operation_id=operation_id or f"op-{uuid.uuid4().hex}",
|
|
802
|
+
base_version=0 if base_version is None else base_version,
|
|
803
|
+
device_id=device_id or get_device_id(),
|
|
804
|
+
client_version=current_version_str(),
|
|
805
|
+
)
|
|
806
|
+
# QUA-05:V2-only 传输(DOC-008 §5)。原先这里保留「base64 容器 ->
|
|
807
|
+
# 裸 envelope -> 去除 client_version 的裸 envelope」三级降级级联,
|
|
808
|
+
# 用于适配旧代服务端。**这是破坏性变更**:降级层已移除,服务端若不
|
|
809
|
+
# 接受容器形态就直接失败并暴露错误,不再静默重试旧形态。
|
|
810
|
+
# 移除理由:降级会掩盖服务端不兼容(表现为偶发成功而非明确报错),
|
|
811
|
+
# 且最坏情况下一次 push 会产生 3 次写请求。
|
|
812
|
+
raw = json.dumps(envelope, ensure_ascii=False, sort_keys=True,
|
|
813
|
+
separators=(",", ":")).encode("utf-8")
|
|
814
|
+
container = {
|
|
815
|
+
"transport": "base64-json",
|
|
816
|
+
"payload_b64": base64.b64encode(raw).decode("ascii"),
|
|
817
|
+
}
|
|
818
|
+
return self._request("POST", self.scope_path(scope, project_id), container)
|
|
819
|
+
|
|
820
|
+
def import_knowledge_bundle(self, bundle: dict[str, Any], *, mode: str = "merge",
|
|
821
|
+
sensitive_policy: str = "allow") -> ReportResult:
|
|
822
|
+
"""Import one validated V2 JSON bundle through the explicit import API.
|
|
823
|
+
|
|
824
|
+
DOC-211:upload 与 sync 同吃一档策略——block 补凭据形状扫描(堵旧
|
|
825
|
+
3 正则弱闸放行 bare sk-/JWT/DSN 的旁路);redact 脱敏后重算并回写
|
|
826
|
+
manifest_hash 再发网;allow 原样放行。
|
|
827
|
+
"""
|
|
828
|
+
if mode not in {"merge", "local_authoritative"}:
|
|
829
|
+
raise ValueError("mode 必须是 merge 或 local_authoritative")
|
|
830
|
+
if sensitive_policy not in SENSITIVE_POLICIES:
|
|
831
|
+
raise ValueError(
|
|
832
|
+
f"未知敏感策略: {sensitive_policy!r}(允许 {'/'.join(SENSITIVE_POLICIES)})")
|
|
833
|
+
from core.cloud_sync.cloud_schema import validate_push_envelope
|
|
834
|
+
validate_push_envelope(bundle)
|
|
835
|
+
payload = dict(bundle)
|
|
836
|
+
payload["mode"] = mode
|
|
837
|
+
scope = str(bundle.get("scope") or "")
|
|
838
|
+
project_id = str(bundle.get("project_id") or "") if scope == "project" else ""
|
|
839
|
+
if sensitive_policy == "allow":
|
|
840
|
+
return self._request("POST", self._import_path(scope, project_id), payload)
|
|
841
|
+
if sensitive_policy == "redact":
|
|
842
|
+
prepared = prepare_records_for_sync(
|
|
843
|
+
bundle["records"], policy="redact")
|
|
844
|
+
payload["records"] = prepared["records"]
|
|
845
|
+
# redact 改内容后 envelope 的 manifest_hash 必须重算回写,
|
|
846
|
+
# 否则服务端按 manifest==hash(records) 直接拒绝(审计#1-1)。
|
|
847
|
+
from core.cloud_sync.cloud_schema import manifest_hash as _manifest_hash
|
|
848
|
+
payload["manifest_hash"] = _manifest_hash(prepared["records"])
|
|
849
|
+
return self._request("POST", self._import_path(scope, project_id), payload)
|
|
850
|
+
validate_records_for_sync(bundle["records"])
|
|
851
|
+
_validate_secret_shapes(bundle["records"])
|
|
852
|
+
return self._request("POST", self._import_path(scope, project_id), payload)
|
|
853
|
+
|
|
854
|
+
# ---- 错题卡质量闭环(联调方案 §2.4)----
|
|
855
|
+
def post_log_report(self, body: dict) -> ReportResult:
|
|
856
|
+
"""内测期诊断日志上报(POST /api/v1/agent/log-reports,登录认证 + 每日限额)。
|
|
857
|
+
|
|
858
|
+
body: {device_id, client_version, kind, payload};payload 为日志文档
|
|
859
|
+
(JSONL 原文或文本)。服务端按账号每日限额(后台可配置)。
|
|
860
|
+
"""
|
|
861
|
+
return self._request("POST", "/api/v1/agent/log-reports", body)
|
|
862
|
+
|
|
863
|
+
def post_lesson_hit_feedback(self, feedbacks: list[dict], *, run_id: str = "",
|
|
864
|
+
project_name: str = "") -> ReportResult:
|
|
865
|
+
"""扫描收尾批量回报错题卡质量计数(POST /api/v1/agent/lessons/hit-feedback)。
|
|
866
|
+
|
|
867
|
+
feedbacks: [{lesson_id, outcome}],outcome ∈ hit|use|false_positive|miss|rejected;
|
|
868
|
+
同一 (lesson_id, outcome) 去重;单请求上限 100 条(分批由调用方负责)。
|
|
869
|
+
鉴权与云同步同会话语义(bxk_ API key / web JWT)。
|
|
870
|
+
"""
|
|
871
|
+
dedup: dict[tuple[str, str], dict] = {}
|
|
872
|
+
for index, item in enumerate(feedbacks or []):
|
|
873
|
+
lesson_id = str((item or {}).get("lesson_id", "")).strip()
|
|
874
|
+
outcome = str((item or {}).get("outcome", "")).strip()
|
|
875
|
+
if not lesson_id or outcome not in LESSON_FEEDBACK_OUTCOMES:
|
|
876
|
+
raise ValueError(
|
|
877
|
+
f"hit-feedback[{index}] 参数无效: lesson_id 必填,outcome ∈ "
|
|
878
|
+
f"{'|'.join(LESSON_FEEDBACK_OUTCOMES)}"
|
|
879
|
+
)
|
|
880
|
+
dedup[(lesson_id, outcome)] = {"lesson_id": lesson_id, "outcome": outcome}
|
|
881
|
+
if not dedup:
|
|
882
|
+
raise ValueError("hit-feedback feedbacks 不能为空")
|
|
883
|
+
if len(dedup) > LESSON_FEEDBACK_MAX_ITEMS:
|
|
884
|
+
raise ValueError(f"hit-feedback 单请求最多 {LESSON_FEEDBACK_MAX_ITEMS} 条")
|
|
885
|
+
payload: dict = {"feedbacks": list(dedup.values())}
|
|
886
|
+
if run_id:
|
|
887
|
+
payload["run_id"] = str(run_id)
|
|
888
|
+
if project_name:
|
|
889
|
+
payload["project_name"] = str(project_name)
|
|
890
|
+
return self._request("POST", "/api/v1/agent/lessons/hit-feedback", payload)
|
|
891
|
+
|
|
892
|
+
def pull_knowledge(self, scope: str, project_id: str = "", cursor: str = "",
|
|
893
|
+
page_size: int = DEFAULT_PAGE, *,
|
|
894
|
+
device_id: str | None = None) -> ReportResult:
|
|
895
|
+
"""V2 pull:参数只走 query;cursor 是服务端 opaque token,原样透传。"""
|
|
896
|
+
if scope not in {"global", "project"}:
|
|
897
|
+
raise ValueError("scope 必须是 global 或 project")
|
|
898
|
+
if scope == "project" and not str(project_id).strip():
|
|
899
|
+
raise ValueError("project scope 必须显式提供 project_id")
|
|
900
|
+
if not isinstance(page_size, int) or isinstance(page_size, bool) or not 1 <= page_size <= 500:
|
|
901
|
+
raise ValueError("page_size 必须在 1..500")
|
|
902
|
+
if not isinstance(cursor, str):
|
|
903
|
+
raise ValueError("cursor 必须是字符串(opaque token 原样透传)")
|
|
904
|
+
if len(cursor) > MAX_CURSOR_LENGTH:
|
|
905
|
+
raise ValueError(f"cursor 长度不能超过 {MAX_CURSOR_LENGTH}")
|
|
906
|
+
requested_device_id = get_device_id() if device_id is None else device_id
|
|
907
|
+
if not isinstance(requested_device_id, str):
|
|
908
|
+
raise ValueError("device_id 必须是字符串")
|
|
909
|
+
params = {
|
|
910
|
+
"schema_version": SCHEMA_VERSION, "cursor": cursor,
|
|
911
|
+
"page_size": page_size,
|
|
912
|
+
}
|
|
913
|
+
if requested_device_id:
|
|
914
|
+
params["device_id"] = requested_device_id
|
|
915
|
+
result = self._request(
|
|
916
|
+
"GET", self.scope_path(scope, project_id), None,
|
|
917
|
+
params=params,
|
|
918
|
+
extra_headers={"X-BugX-Transport": "base64-json"},
|
|
919
|
+
)
|
|
920
|
+
# The device cursor is a server-side resume hint. If a deployment
|
|
921
|
+
# rotated the server signing key, the hint can be invalid even though
|
|
922
|
+
# the client's local cursor is empty. Retry the initial pull without
|
|
923
|
+
# that hint so the server can return a fresh baseline cursor. Explicit
|
|
924
|
+
# cursors remain fail-closed and are never retried this way.
|
|
925
|
+
if not result.ok and not cursor and requested_device_id:
|
|
926
|
+
err = self.sync_error(result)
|
|
927
|
+
if err.code == "SYNC_INVALID_ENVELOPE" and "cursor" in err.message:
|
|
928
|
+
baseline_params = dict(params)
|
|
929
|
+
baseline_params.pop("device_id", None)
|
|
930
|
+
result = self._request(
|
|
931
|
+
"GET", self.scope_path(scope, project_id), None,
|
|
932
|
+
params=baseline_params,
|
|
933
|
+
)
|
|
934
|
+
if result.ok:
|
|
935
|
+
data = self._data(result)
|
|
936
|
+
# 无损容器:payload_b64 = envelope 原文 base64 + sha256 完整性校验。
|
|
937
|
+
if isinstance(data, dict) and data.get("transport") == "base64-json":
|
|
938
|
+
raw = base64.b64decode(data.get("payload_b64") or "")
|
|
939
|
+
payload = json.loads(raw)
|
|
940
|
+
expected = data.get("content_sha256")
|
|
941
|
+
if expected and expected != "sha256:" + hashlib.sha256(raw).hexdigest():
|
|
942
|
+
return ReportResult(ok=False, status=result.status,
|
|
943
|
+
data=result.data, error="pull 容器 sha256 校验失败")
|
|
944
|
+
# ReportResult 是 frozen dataclass:用 replace 派生解码后的结果
|
|
945
|
+
result = dataclasses.replace(result, data=payload)
|
|
946
|
+
try:
|
|
947
|
+
validate_pull_envelope(self._data(result), scope=scope, project_id=project_id)
|
|
948
|
+
except SchemaError as exc:
|
|
949
|
+
return ReportResult(ok=False, status=result.status,
|
|
950
|
+
data=result.data, error=str(exc))
|
|
951
|
+
return result
|
|
952
|
+
|
|
953
|
+
def ack_knowledge(self, scope: str, project_id: str = "", cursor: str = "",
|
|
954
|
+
*, device_id: str | None = None) -> ReportResult:
|
|
955
|
+
"""ACK a durably imported pull cursor so the server may run GC."""
|
|
956
|
+
if scope not in {"global", "project"}:
|
|
957
|
+
raise ValueError("scope 必须是 global 或 project")
|
|
958
|
+
if scope == "project" and not str(project_id).strip():
|
|
959
|
+
raise ValueError("project scope 必须显式提供 project_id")
|
|
960
|
+
if scope == "global" and project_id not in {"", None}:
|
|
961
|
+
raise ValueError("global scope 不得提供 project_id")
|
|
962
|
+
if not isinstance(cursor, str) or not cursor or len(cursor) > MAX_CURSOR_LENGTH:
|
|
963
|
+
raise ValueError("cursor 必须是非空字符串且长度不超过 512")
|
|
964
|
+
requested_device_id = device_id or get_device_id()
|
|
965
|
+
if not isinstance(requested_device_id, str) or not requested_device_id:
|
|
966
|
+
raise ValueError("device_id 必须是非空字符串")
|
|
967
|
+
body = {
|
|
968
|
+
"schema_version": SCHEMA_VERSION,
|
|
969
|
+
"scope": scope,
|
|
970
|
+
"project_id": _wire_project_id(project_id) if scope == "project" else None,
|
|
971
|
+
"cursor": cursor,
|
|
972
|
+
"device_id": requested_device_id,
|
|
973
|
+
}
|
|
974
|
+
return self._request("POST", self._ack_path(scope, project_id), body)
|
|
975
|
+
|
|
976
|
+
def prefetch_knowledge(
|
|
977
|
+
self,
|
|
978
|
+
classification: Mapping[str, Any] | None = None,
|
|
979
|
+
*,
|
|
980
|
+
language: str = "",
|
|
981
|
+
forms: list[str] | None = None,
|
|
982
|
+
surfaces: list[str] | None = None,
|
|
983
|
+
frameworks: list[str] | None = None,
|
|
984
|
+
routing_tags: dict[str, list[str]] | None = None,
|
|
985
|
+
tools: list[str] | None = None,
|
|
986
|
+
tool_names: list[str] | None = None,
|
|
987
|
+
limit: int = 20,
|
|
988
|
+
project_id: int | str | None = None,
|
|
989
|
+
) -> ReportResult:
|
|
990
|
+
"""DOC-041 Phase 2: 定向预拉错题、经验、推荐工具链与预热规则。
|
|
991
|
+
|
|
992
|
+
Agent 在任务启动前按分类画像一次性拉取最相关的错题与经验,
|
|
993
|
+
无需执行全量同步。服务端支持 GET 查询参数与 POST JSON 体。
|
|
994
|
+
"""
|
|
995
|
+
if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= 100:
|
|
996
|
+
raise ValueError("limit 必须在 1..100 之间")
|
|
997
|
+
|
|
998
|
+
payload: dict[str, Any] = {}
|
|
999
|
+
active_tools = tools if tools is not None else tool_names
|
|
1000
|
+
if classification and isinstance(classification, (dict, Mapping)):
|
|
1001
|
+
if not language:
|
|
1002
|
+
language = str(classification.get("primary_language") or classification.get("language") or "")
|
|
1003
|
+
if forms is None and "forms" in classification:
|
|
1004
|
+
forms = classification.get("forms")
|
|
1005
|
+
if surfaces is None and "surfaces" in classification:
|
|
1006
|
+
surfaces = classification.get("surfaces")
|
|
1007
|
+
if frameworks is None and "frameworks" in classification:
|
|
1008
|
+
frameworks = classification.get("frameworks")
|
|
1009
|
+
if routing_tags is None and "routing_tags" in classification:
|
|
1010
|
+
routing_tags = classification.get("routing_tags")
|
|
1011
|
+
if active_tools is None:
|
|
1012
|
+
active_tools = classification.get("tools") or classification.get("tool_names")
|
|
1013
|
+
|
|
1014
|
+
if language and isinstance(language, str) and language.strip() and language.strip() != "unknown":
|
|
1015
|
+
payload["language"] = language.strip()
|
|
1016
|
+
if forms and isinstance(forms, (list, tuple, set)):
|
|
1017
|
+
payload["forms"] = [str(f).strip() for f in forms if str(f).strip()]
|
|
1018
|
+
if surfaces and isinstance(surfaces, (list, tuple, set)):
|
|
1019
|
+
payload["surfaces"] = [str(s).strip() for s in surfaces if str(s).strip()]
|
|
1020
|
+
if frameworks and isinstance(frameworks, (list, tuple, set)):
|
|
1021
|
+
payload["frameworks"] = [str(fw).strip() for fw in frameworks if str(fw).strip()]
|
|
1022
|
+
if active_tools and isinstance(active_tools, (list, tuple, set)):
|
|
1023
|
+
payload["tools"] = [str(t).strip() for t in active_tools if str(t).strip()]
|
|
1024
|
+
if routing_tags and isinstance(routing_tags, dict):
|
|
1025
|
+
payload["routing_tags"] = {
|
|
1026
|
+
str(k).strip(): [str(v).strip() for v in vals if str(v).strip()]
|
|
1027
|
+
for k, vals in routing_tags.items()
|
|
1028
|
+
if isinstance(vals, (list, tuple, set))
|
|
1029
|
+
}
|
|
1030
|
+
payload["limit"] = limit
|
|
1031
|
+
if project_id is not None and str(project_id).strip():
|
|
1032
|
+
try:
|
|
1033
|
+
pid_int = int(project_id)
|
|
1034
|
+
if pid_int > 0:
|
|
1035
|
+
payload["project_id"] = pid_int
|
|
1036
|
+
except (ValueError, TypeError):
|
|
1037
|
+
pass
|
|
1038
|
+
|
|
1039
|
+
return self._request("POST", KNOWLEDGE_PREFETCH_PATH, payload)
|
|
1040
|
+
|
|
1041
|
+
def sync_status(self) -> ReportResult:
|
|
1042
|
+
return self._request("GET", SYNC_STATUS_PATH)
|
|
1043
|
+
|
|
1044
|
+
def scope_path(self, scope: str, project_id: str) -> str:
|
|
1045
|
+
if scope == "global":
|
|
1046
|
+
return f"{AGENT_API_PREFIX}/global/knowledge"
|
|
1047
|
+
value = str(project_id)
|
|
1048
|
+
if not re.fullmatch(r"[1-9][0-9]*", value):
|
|
1049
|
+
raise ValueError("project_id 必须是服务端返回的正整数 ID")
|
|
1050
|
+
return f"{AGENT_API_PREFIX}/projects/{value}/knowledge"
|
|
1051
|
+
|
|
1052
|
+
def _import_path(self, scope: str, project_id: str) -> str:
|
|
1053
|
+
return self.scope_path(scope, project_id) + "/import"
|
|
1054
|
+
|
|
1055
|
+
def _ack_path(self, scope: str, project_id: str) -> str:
|
|
1056
|
+
"""Return the post-import ACK endpoint for one V2 knowledge scope."""
|
|
1057
|
+
return self.scope_path(scope, project_id) + "/ack"
|
|
1058
|
+
|
|
1059
|
+
def _profile_path(self, project_id: str) -> str:
|
|
1060
|
+
value = str(project_id)
|
|
1061
|
+
if not re.fullmatch(r"[1-9][0-9]*", value):
|
|
1062
|
+
raise ValueError("project_id 必须是服务端返回的正整数 ID")
|
|
1063
|
+
return f"{AGENT_API_PREFIX}/projects/{value}/profile"
|
|
1064
|
+
|
|
1065
|
+
# ---- 版本检查与 CLI 包下载(Phase 2 自动更新)----
|
|
1066
|
+
|
|
1067
|
+
def check_version(self, current_version: str = "", channel: str = "") -> ReportResult:
|
|
1068
|
+
"""GET /api/v1/agent/version — 查询最新版本元数据。
|
|
1069
|
+
|
|
1070
|
+
当传入 current_version 时,服务端额外返回 update_available 和
|
|
1071
|
+
update_required 布尔字段。channel 用于选择发布通道(stable /
|
|
1072
|
+
alpha);留空使用服务端默认(stable)通道。此端点公开无需认证,仅限流。
|
|
1073
|
+
"""
|
|
1074
|
+
params = {}
|
|
1075
|
+
if current_version:
|
|
1076
|
+
params["current"] = current_version
|
|
1077
|
+
if channel and channel.strip():
|
|
1078
|
+
params["channel"] = channel.strip()
|
|
1079
|
+
return self._request("GET", VERSION_CHECK_PATH, None,
|
|
1080
|
+
auth=False, retry_auth=False, params=params or None)
|
|
1081
|
+
|
|
1082
|
+
@staticmethod
|
|
1083
|
+
def _is_allowed_agent_download_url(url: str) -> bool:
|
|
1084
|
+
"""升级包最终 URL 白名单:https 任意主机;http 仅限回环地址。
|
|
1085
|
+
|
|
1086
|
+
明文 HTTP 到远端会被中间人篡改升级包,一律拒绝;但回环地址
|
|
1087
|
+
(127.0.0.1/::1/localhost)不出机器,本地镜像与测试夹具依赖它。
|
|
1088
|
+
"""
|
|
1089
|
+
parts = urllib.parse.urlsplit(url)
|
|
1090
|
+
if parts.scheme == "https":
|
|
1091
|
+
return True
|
|
1092
|
+
if parts.scheme == "http":
|
|
1093
|
+
host = (parts.hostname or "").strip("[]").lower()
|
|
1094
|
+
return host in {"127.0.0.1", "::1", "localhost"}
|
|
1095
|
+
return False
|
|
1096
|
+
|
|
1097
|
+
def download_package(self, dest: Path, *, expected_sha256: str = "",
|
|
1098
|
+
expected_version: str = "") -> tuple[bool, str]:
|
|
1099
|
+
"""GET /api/v1/agent/download — 下载 CLI 包到指定路径。
|
|
1100
|
+
|
|
1101
|
+
返回 (success, message)。下载后做 SHA-256 校验(必须提供)。
|
|
1102
|
+
如果 download_url 指向外部地址,服务端会返回 302 重定向,此方法
|
|
1103
|
+
跟随重定向下载,但最终 URL 必须仍是 https://(回环地址例外,
|
|
1104
|
+
见 `_is_allowed_agent_download_url`),否则拒绝。
|
|
1105
|
+
|
|
1106
|
+
dest: 目标文件路径(含文件名)。
|
|
1107
|
+
expected_sha256: 下载后校验哈希(必填,缺失即拒绝下载)。
|
|
1108
|
+
expected_version: 仅用于日志/提示,不影响逻辑。
|
|
1109
|
+
"""
|
|
1110
|
+
expected_sha256 = str(expected_sha256 or "").strip().lower()
|
|
1111
|
+
if not expected_sha256:
|
|
1112
|
+
return False, "缺少 SHA-256 校验值,拒绝下载"
|
|
1113
|
+
if not re.fullmatch(r"[0-9a-f]{64}", expected_sha256):
|
|
1114
|
+
return False, "下载失败: expected_sha256 必须是 64 位 SHA-256 hex"
|
|
1115
|
+
|
|
1116
|
+
url = self.base + DOWNLOAD_PATH
|
|
1117
|
+
# 跟随重定向(版本检查端点可能配置了外部 PyPI 镜像地址)
|
|
1118
|
+
opener = _build_redirect_opener(self.base)
|
|
1119
|
+
headers = {"Accept": "application/octet-stream", **client_headers()}
|
|
1120
|
+
req = urllib.request.Request(url, headers=headers)
|
|
1121
|
+
try:
|
|
1122
|
+
resp = opener.open(req, timeout=self.timeout)
|
|
1123
|
+
try:
|
|
1124
|
+
# 升级包绝不能从明文 HTTP 端点拉取;服务端 302 跳转外部
|
|
1125
|
+
# 镜像时,最终 URL 必须仍是 https://,否则整体拒绝。
|
|
1126
|
+
final_url = ""
|
|
1127
|
+
geturl = getattr(resp, "geturl", None)
|
|
1128
|
+
if callable(geturl):
|
|
1129
|
+
final_url = str(geturl() or "")
|
|
1130
|
+
if not self._is_allowed_agent_download_url(final_url):
|
|
1131
|
+
return False, (
|
|
1132
|
+
f"下载失败: 最终 URL 非 HTTPS,拒绝下载: {final_url}"
|
|
1133
|
+
)
|
|
1134
|
+
headers = getattr(resp, "headers", None)
|
|
1135
|
+
content_length = None
|
|
1136
|
+
if headers is not None:
|
|
1137
|
+
raw_length = headers.get("Content-Length")
|
|
1138
|
+
if raw_length:
|
|
1139
|
+
try:
|
|
1140
|
+
content_length = int(raw_length)
|
|
1141
|
+
except (TypeError, ValueError):
|
|
1142
|
+
return False, "下载失败: Content-Length 无效"
|
|
1143
|
+
if content_length < 0 or content_length > MAX_AGENT_PACKAGE_BYTES:
|
|
1144
|
+
return False, "下载失败: CLI 包超过允许大小"
|
|
1145
|
+
|
|
1146
|
+
chunks: list[bytes] = []
|
|
1147
|
+
total = 0
|
|
1148
|
+
while True:
|
|
1149
|
+
try:
|
|
1150
|
+
chunk = resp.read(AGENT_PACKAGE_READ_CHUNK)
|
|
1151
|
+
except TypeError: # 简化测试响应仍可能只接受无参 read()
|
|
1152
|
+
chunk = resp.read()
|
|
1153
|
+
if not chunk:
|
|
1154
|
+
break
|
|
1155
|
+
total += len(chunk)
|
|
1156
|
+
if total > MAX_AGENT_PACKAGE_BYTES:
|
|
1157
|
+
return False, "下载失败: CLI 包超过允许大小"
|
|
1158
|
+
chunks.append(chunk)
|
|
1159
|
+
if content_length is not None and total != content_length:
|
|
1160
|
+
return False, "下载失败: 响应长度与 Content-Length 不一致"
|
|
1161
|
+
data = b"".join(chunks)
|
|
1162
|
+
finally:
|
|
1163
|
+
resp.close()
|
|
1164
|
+
except urllib.error.HTTPError as exc:
|
|
1165
|
+
raw = b""
|
|
1166
|
+
try:
|
|
1167
|
+
raw = exc.read()
|
|
1168
|
+
finally:
|
|
1169
|
+
try:
|
|
1170
|
+
exc.close()
|
|
1171
|
+
except Exception: # noqa: BLE001
|
|
1172
|
+
pass
|
|
1173
|
+
return False, f"下载失败: HTTP {exc.code} {message_from_response(raw, exc)}"
|
|
1174
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
1175
|
+
return False, f"下载失败: {exc}"
|
|
1176
|
+
|
|
1177
|
+
# SHA-256 校验
|
|
1178
|
+
if expected_sha256:
|
|
1179
|
+
actual = hashlib.sha256(data).hexdigest()
|
|
1180
|
+
if actual != expected_sha256:
|
|
1181
|
+
return False, (
|
|
1182
|
+
f"SHA-256 校验失败: 期望 {expected_sha256},实际 {actual}"
|
|
1183
|
+
)
|
|
1184
|
+
|
|
1185
|
+
# 写入目标文件
|
|
1186
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
1187
|
+
try:
|
|
1188
|
+
atomic_write_nofollow(dest, data)
|
|
1189
|
+
except (OSError, ValueError) as exc:
|
|
1190
|
+
return False, f"写入文件失败: {exc}"
|
|
1191
|
+
|
|
1192
|
+
version_note = f" (v{expected_version})" if expected_version else ""
|
|
1193
|
+
return True, f"CLI 包已下载到 {dest}{version_note}"
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def current_version_str() -> str:
|
|
1197
|
+
"""返回当前引擎/CLI 版本号,用于 User-Agent(自包含零反向导入)。"""
|
|
1198
|
+
return client_version()
|
|
1199
|
+
|