diff --git a/.github/scripts/reuse.mjs b/.github/scripts/reuse.mjs new file mode 100644 index 000000000..388060a70 --- /dev/null +++ b/.github/scripts/reuse.mjs @@ -0,0 +1,80 @@ +/** 只复用相同工作流对相同合并代码的完整成功检查;证据不足时执行全量门禁。 */ +export async function reuse({ github, context, core }) { + core.setOutput('reuse', 'false') + if ( + context.eventName !== 'push' || + context.payload.forced || + !context.payload.before?.match(/^[a-f0-9]{40}$/) || + /^0+$/.test(context.payload.before) + ) + return + + try { + const repo = context.repo + const { data: current } = await github.rest.actions.getWorkflowRun({ ...repo, run_id: context.runId }) + const { data: pushed } = await github.rest.git.getCommit({ ...repo, commit_sha: context.sha }) + const pulls = await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + ...repo, + commit_sha: context.sha, + per_page: 100, + }) + for (const pull of pulls) { + if ( + !pull.merged_at || + pull.merge_commit_sha !== context.sha || + pull.base?.ref !== context.ref.replace('refs/heads/', '') || + pull.base?.repo?.full_name !== `${repo.owner}/${repo.repo}` + ) + continue + + // 不过滤 success:同一 PR 最新执行失败或仍在运行时,不能退回旧的绿灯。 + const { data } = await github.rest.actions.listWorkflowRuns({ + ...repo, + workflow_id: current.workflow_id, + event: 'pull_request', + head_sha: pull.head.sha, + per_page: 100, + }) + const run = data.workflow_runs + .filter( + candidate => candidate.head_sha === pull.head.sha && candidate.head_repository?.id === pull.head.repo?.id, + ) + .sort((left, right) => right.id - left.id)[0] + if (!run || run.status !== 'completed' || run.conclusion !== 'success') continue + + const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRun, { + ...repo, + run_id: run.id, + filter: 'latest', + per_page: 100, + }) + const proofs = jobs.filter( + job => + job.status === 'completed' && job.conclusion === 'success' && /^CI proof \([a-f0-9]{40}\)$/.test(job.name), + ) + if (proofs.length !== 1) continue + const testedSha = proofs[0].name.slice(10, -1) + const { data: tested } = await github.rest.git.getCommit({ ...repo, commit_sha: testedSha }) + // run.head_sha 是 PR 分支头;只有 proof 记录的 github.sha 才是实际测试的模拟合并提交。 + if ( + tested.parents.length !== 2 || + tested.parents[0].sha !== context.payload.before || + tested.parents[1].sha !== pull.head.sha || + tested.tree.sha !== pushed.tree.sha + ) + continue + + // 查询证明期间可能有人重新运行 CI,不能复用已经失效的运行快照。 + const { data: latest } = await github.rest.actions.getWorkflowRun({ ...repo, run_id: run.id }) + if (latest.status !== 'completed' || latest.conclusion !== 'success' || latest.run_attempt !== run.run_attempt) + continue + + core.setOutput('reuse', 'true') + core.notice(`复用 PR #${pull.number} 的完整检查:${run.html_url};代码树 ${tested.tree.sha}`) + return + } + core.info('没有匹配的完整 PR 检查,执行全量门禁。') + } catch (error) { + core.warning(`无法确认 PR 检查,执行全量门禁:${error.message}`) + } +} diff --git a/.github/scripts/reuse.test.mjs b/.github/scripts/reuse.test.mjs new file mode 100644 index 000000000..8d113f25d --- /dev/null +++ b/.github/scripts/reuse.test.mjs @@ -0,0 +1,171 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { reuse } from './reuse.mjs' + +/** 构造带真实 GitHub 字段形状的离线 API 替身。 */ +function fixture() { + const head = 'a'.repeat(40), + base = 'b'.repeat(40), + sha = 'c'.repeat(40), + merge = 'd'.repeat(40) + const state = { + context: { + eventName: 'push', + repo: { owner: 'owner', repo: 'repo' }, + ref: 'refs/heads/v3', + sha, + runId: 20, + payload: { before: base }, + }, + pull: { + number: 7, + merged_at: '2026-09-09T00:00:00Z', + merge_commit_sha: sha, + head: { sha: head, repo: { id: 2 } }, + base: { ref: 'v3', repo: { full_name: 'owner/repo' } }, + }, + runs: [ + { + id: 10, + run_attempt: 1, + status: 'completed', + conclusion: 'success', + head_sha: head, + head_repository: { id: 2 }, + html_url: 'https://github.com/owner/repo/actions/runs/10', + }, + ], + jobs: [{ name: `CI proof (${merge})`, status: 'completed', conclusion: 'success' }], + tested: { parents: [{ sha: base }, { sha: head }], tree: { sha: 'tree' } }, + outputs: {}, + calls: [], + warnings: [], + } + /** 保留 API 参数供测试验证,避免错误地过滤历史失败记录。 */ + const api = name => async args => { + state.calls.push({ name, args }) + if (state.error) throw new Error('API unavailable') + if (name === 'getWorkflowRun') + return { data: args.run_id === 20 ? { workflow_id: 100 } : { ...state.runs[0], ...state.refreshed } } + if (name === 'getCommit') return { data: args.commit_sha === sha ? { tree: { sha: 'tree' } } : state.tested } + if (name === 'listPullRequestsAssociatedWithCommit') return [state.pull] + if (name === 'listWorkflowRuns') return { data: { workflow_runs: state.runs } } + if (name === 'listJobsForWorkflowRun') return state.jobs + throw new Error(name) + } + state.github = { + rest: { + actions: { + getWorkflowRun: api('getWorkflowRun'), + listWorkflowRuns: api('listWorkflowRuns'), + listJobsForWorkflowRun: api('listJobsForWorkflowRun'), + }, + git: { getCommit: api('getCommit') }, + repos: { listPullRequestsAssociatedWithCommit: api('listPullRequestsAssociatedWithCommit') }, + }, + paginate: (method, args) => method(args), + } + state.core = { + setOutput: (key, value) => { + state.outputs[key] = value + }, + notice: () => {}, + info: () => {}, + warning: message => state.warnings.push(message), + } + return state +} + +test('相同合并代码且完整成功时复用,即使 fork run 没有 pull_requests 字段', async () => { + const state = fixture() + await reuse(state) + assert.equal(state.outputs.reuse, 'true') + const query = state.calls.find(call => call.name === 'listWorkflowRuns').args + assert.equal(query.workflow_id, 100) + assert.equal(query.event, 'pull_request') + assert.equal(query.status, undefined) + assert.equal(state.calls.find(call => call.name === 'listJobsForWorkflowRun').args.filter, 'latest') +}) + +const cases = { + 'PR 必须完整执行': state => { + state.context.eventName = 'pull_request' + }, + '手工触发必须完整执行': state => { + state.context.eventName = 'workflow_dispatch' + }, + 'force push 必须完整执行': state => { + state.context.payload.forced = true + }, + '新建分支必须完整执行': state => { + state.context.payload.before = '0'.repeat(40) + }, + '直接 push 没有对应合并': state => { + state.pull.merge_commit_sha = 'other' + }, + '未合并 PR 不可复用': state => { + state.pull.merged_at = null + }, + '目标分支不同': state => { + state.pull.base.ref = 'other' + }, + '目标仓库不同': state => { + state.pull.base.repo.full_name = 'other/repo' + }, + 'PR head 已改变': state => { + state.pull.head.sha = 'e'.repeat(40) + }, + 'PR 来源仓库不同': state => { + state.pull.head.repo.id = 9 + }, + '旧工作流没有 proof': state => { + state.jobs = [] + }, + 'proof 被跳过': state => { + state.jobs[0].conclusion = 'skipped' + }, + 'proof 尚未完成': state => { + state.jobs[0].status = 'in_progress' + }, + 'proof 重复': state => { + state.jobs.push({ ...state.jobs[0] }) + }, + '工作流有失败': state => { + state.runs[0].conclusion = 'failure' + }, + '工作流尚未完成': state => { + state.runs[0].status = 'in_progress' + }, + '最新执行失败不可退回旧成功': state => { + state.runs.push({ ...state.runs[0], id: 11, conclusion: 'failure' }) + }, + '查询期间开始重跑': state => { + state.refreshed = { status: 'in_progress', conclusion: null } + }, + '查询期间运行轮次变化': state => { + state.refreshed = { run_attempt: 2 } + }, + '目标分支已经前进': state => { + state.tested.parents[0].sha = 'e'.repeat(40) + }, + '证明不是 PR 模拟合并': state => { + state.tested.parents.pop() + }, + '模拟合并来自其他 PR head': state => { + state.tested.parents[1].sha = 'e'.repeat(40) + }, + '合入代码树有变化': state => { + state.tested.tree.sha = 'different' + }, + 'API 异常回退全量': state => { + state.error = true + }, +} +for (const [name, mutate] of Object.entries(cases)) { + test(name, async () => { + const state = fixture() + mutate(state) + await reuse(state) + assert.equal(state.outputs.reuse, 'false') + }) +} diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml index fb77b623d..9d77face9 100644 --- a/.github/workflows/pylint.yml +++ b/.github/workflows/pylint.yml @@ -17,7 +17,32 @@ concurrency: cancel-in-progress: true jobs: + reuse: + name: Check reusable PR verification + runs-on: ubuntu-latest + timeout-minutes: 3 + permissions: + contents: read + actions: read + pull-requests: read + outputs: + reused: ${{ steps.check.outputs.reuse }} + steps: + - name: Checkout code + uses: actions/checkout@v7 + - name: Test reuse decision + run: node --test .github/scripts/reuse.test.mjs + - name: Check successful PR merge tree + id: check + uses: actions/github-script@v9 + with: + script: | + const { reuse } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/reuse.mjs`); + await reuse({ github, context, core }); + pylint: + needs: reuse + if: needs.reuse.outputs.reused != 'true' runs-on: ubuntu-latest name: Pylint Code Quality Check @@ -105,3 +130,13 @@ jobs: echo "🎉 Pylint 检查完成!" echo "✅ 改动 Python 文件没有新增语法错误或严重问题" echo "📊 全仓建议性报告已保存为构建工件" + + proof: + name: CI proof (${{ github.sha }}) + needs: [pylint] + if: github.event_name == 'pull_request' && needs.pylint.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 1 + steps: + - name: Record fully verified merge commit + run: echo 'All required checks passed for this PR merge commit.' diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d12e9cac4..0f58be451 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,7 @@ name: Unit Tests on: - # 指向 v3 的 PR 与推送都跑全量单测,作为合并门禁 + # PR 完整验证;合并推送仅在代码树和成功证明匹配时复用 pull_request: branches: - v3 @@ -19,7 +19,32 @@ concurrency: cancel-in-progress: true jobs: + reuse: + name: Check reusable PR verification + runs-on: ubuntu-latest + timeout-minutes: 3 + permissions: + contents: read + actions: read + pull-requests: read + outputs: + reused: ${{ steps.check.outputs.reuse }} + steps: + - name: Checkout code + uses: actions/checkout@v7 + - name: Test reuse decision + run: node --test .github/scripts/reuse.test.mjs + - name: Check successful PR merge tree + id: check + uses: actions/github-script@v9 + with: + script: | + const { reuse } = await import(`${process.env.GITHUB_WORKSPACE}/.github/scripts/reuse.mjs`); + await reuse({ github, context, core }); + architecture: + needs: reuse + if: needs.reuse.outputs.reused != 'true' runs-on: ubuntu-latest name: Architecture Contract Gate timeout-minutes: 10 @@ -90,42 +115,11 @@ jobs: uv run --locked --no-sync python scripts/startup/performance.py --check --repeat 3 - pytest: - runs-on: ubuntu-latest - name: Unit Tests (${{ matrix.shard }}) - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - include: - - shard: '1/4' - - shard: '2/4' - - shard: '3/4' - - shard: '4/4' - - steps: - - name: Checkout code - uses: actions/checkout@v7 - - - name: Set up uv - uses: astral-sh/setup-uv@v10.0.1 - with: - python-version: '3.14' - enable-cache: true - cache-dependency-glob: | - pyproject.toml - uv.lock - - - name: Install dependencies - run: uv sync --locked - - - name: Run tests - timeout-minutes: 10 - run: uv run --locked --no-sync python tests/run.py --shard "${{ matrix.shard }}" - coverage-shard: + needs: reuse + if: needs.reuse.outputs.reused != 'true' runs-on: ubuntu-latest - name: Coverage Shard (${{ matrix.shard }}) + name: Unit Tests with Coverage (${{ matrix.shard }}) timeout-minutes: 15 strategy: fail-fast: false @@ -222,3 +216,13 @@ jobs: coverage.xml coverage.json retention-days: 7 + + proof: + name: CI proof (${{ github.sha }}) + needs: [architecture, coverage-shard, coverage-report] + if: github.event_name == 'pull_request' && needs.architecture.result == 'success' && needs.coverage-shard.result == 'success' && needs.coverage-report.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 1 + steps: + - name: Record fully verified merge commit + run: echo 'All required checks passed for this PR merge commit.' diff --git a/.trivyignore.yaml b/.trivyignore.yaml index b46d614fa..26ab62c21 100644 --- a/.trivyignore.yaml +++ b/.trivyignore.yaml @@ -1,4 +1,11 @@ vulnerabilities: + - id: CVE-2026-84445 + paths: + - usr/bin/rclone + purls: + - pkg:golang/google.golang.org/grpc@v1.84.0-dev.0.20260723093437-b6eac429d7b6 + expired_at: 2026-10-09 + statement: The pinned rclone image d6f5448594ecefefcf09cfeaf85cb7a21a866328032576ce2c1813e7b59c66dc has no google.golang.org/grpc/xds functions in either its amd64 or arm64 Go function table. GHSA-2v4p-qf9q-27wj requires xds.NewGRPCServer, so the affected interceptor is not linked. Reassess this exception when upgrading rclone or before expiry; see docs/development-setup.md. - id: GHSA-6v7p-g79w-8964 paths: - Python diff --git a/AGENTS.md b/AGENTS.md index faf4eea20..af23d6f9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,6 +4,16 @@ This file is the primary instruction set for all AI agents and LLMs working in t --- +## Shared Contract and Execution Authority + +Architecture, business correctness, SDK/Compat compatibility, test isolation, useful contract documentation, and truthful verification reports apply to everyone. Maintainer discretion over execution does not waive these engineering contracts or permit baseline laundering. + +Submission preparation and checklists in this file and the linked rules are **contributor defaults**. A confirmed maintainer may explicitly adjust applicable verification scope, timing, evidence reuse, and delivery order, including saving a local anchor before remaining checks. Record the decision, supporting evidence, unverified items, and follow-up; an anchor is a recoverable state, not a claim of validation or acceptance. + +Maintainer execution authority comes from the current user or established project context that confirms their maintainer role and authorization. GitHub `WRITE` proves platform capability only; a contributor's self-declared role does not grant an exception. Without confirmed maintainer authorization, follow the contributor defaults. Reuse an existing scoped authorization without requesting it again; an explicit current restriction takes precedence. CI failure decisions follow `docs/rules/12-collaboration-and-distribution.md` and cannot bypass platform protection. + +--- + ## Task-to-Documentation Mapping For work that changes or reviews repository behavior, identify the domains actually touched and load only the applicable documents. Simple factual checks and unrelated domains do not require preloading rule files. @@ -38,11 +48,11 @@ For work that changes or reviews repository behavior, identify the domains actua ### Quality and Security * **Primary Reference:** `docs/rules/11-quality-and-security.md` -* **Required Constraints:** All code changes must pass the relevant pytest tests and pylint checks. Dependency changes require a current `uv.lock`, locked environment verification, and a passing locked dependency vulnerability audit. +* **Required Constraints:** Preserve the quality contracts below and run applicable pytest, changed-file pylint, and architecture checks under the contributor preparation defaults or a documented maintainer arrangement. Dependency changes require a current `uv.lock`, locked environment verification, and the locked dependency vulnerability audit; execution discretion does not waive dependency or release policy. ### Testing * **Primary Reference:** `docs/testing.md` -* **Required Constraints:** pytest is the only runner; `tests/conftest.py` isolates each run to a temporary `CONFIG_DIR`. Tests must not touch the real database, network, or external services (TMDB, LLM catalogs, downloaders, media servers, MP server) — mock at the boundary or replay recorded responses; the bar is zero real outbound traffic. Tests must restore any process-level state they stub (`sys.modules`, singletons, caches, settings). New tests must be pytest-native (function + `assert` + fixtures); do not add new `unittest.TestCase`. Convert existing `TestCase` files to pytest-native opportunistically when you modify them. Before opening a PR to `v3`, run the affected tests and applicable local checks. Run the full local suite (`uv run --locked --no-sync python tests/run.py`) for dependency or lock changes, shared test infrastructure, database or startup paths, cross-module lifecycle, compatibility layers, broad behavior changes, or an explicit maintainer requirement. The changed path must pass; any unrelated failure must be reported and reproduced against the current `upstream/v3` baseline instead of silently expanding the PR. Documentation-only changes use applicable text and structure checks; the `.github/workflows/test.yml` gate remains the final full-suite check on every PR/push to `v3`. +* **Required Constraints:** pytest is the only runner; `tests/conftest.py` isolates each run to a temporary `CONFIG_DIR`. Tests must not touch the real database, network, or external services (TMDB, LLM catalogs, downloaders, media servers, MP server); mock at the boundary or replay recorded responses for zero real outbound traffic. Restore any process-level state stubbed by tests (`sys.modules`, singletons, caches, settings). New tests must be pytest-native (function + `assert` + fixtures); do not add new `unittest.TestCase`. When modifying an existing `TestCase` file, convert the entire file to pytest-native and verify equivalent behavior. The contributor verification scope and maintainer arrangements are defined in `docs/testing.md`. Documentation-only changes use applicable text and structure checks. GitHub Actions reuse remains subject to the exact tested merge tree and base contract in that document. ### Commands and Development Workflow * **Primary Reference:** `docs/rules/03-commands.md` @@ -66,8 +76,8 @@ The legacy roots have no physical directories in the source tree. Current images | `app/adapters/cache/` | Redis 与文件缓存等具体持久化实现 | 缓存协议、装饰器和进程内缓存策略 | `backends.py`, `redis.py` | | `app/adapters/system/` | 操作系统、文件、进程、标准流、包/资源安装、显示和 Rust 加速适配 | 业务规则、进程重启决策 | `host.py`, `display/`, `stdio.py`, `package.py`, `resource.py`, `rust.py`, `fsproxy.py` | | `app/adapters/external/` | CookieCloud、插件市场、OCR、IP 归属和 MoviePilot Server 等命名外部生态 | 通用 HTTP/DNS/文件机制或可复用领域语义 | `market.py`, `server.py`, `cookiecloud.py`, `ocr.py`, `location.py`, `wechat.py` | -| `app/application/` | 聚焦应用服务、用例命令,以及由用例拥有的持久化/技术能力 Port/Protocol | SQLAlchemy、Session、Oper 等具体 DB 实现,具体 Adapter 静态依赖,多领域 Chain 编排、底层通用机制、通用传输协议 | `recognition.py`, `filter.py`, `outbox.py`, `subscription/write.py`, `workflow.py` | -| `app/application/messaging/` | 消息渲染/路由、交互和 Agent 到消息桥接:`ingress.py` 统一渠道回环入口;`interaction.py` 通用交互契约和视图工具;`router.py` 统一交互优先级和回调分发;`site.py`/`subscribe.py`/`skill.py` 对应命令的会话、输入解析和视图;`media.py` 媒体交互状态(业务工作流仍由 `MediaInteractionChain` 执行);`plugin.py` 插件输入接管和插件按钮回调;`agent.py` Agent 选择状态、回调协议和 WebAgent 消息桥接;`message.py` 通知渲染、模板和队列。不作为推荐给插件直接使用的公开 SDK | 认证策略、通用 HTTP、服务发现、仅端点使用的 Web Push 行为 | `ingress.py`, `message.py`, `interaction.py`, `router.py`, `agent.py` | +| `app/application/` | 聚焦应用服务、用例命令,以及由用例拥有的持久化/技术能力 Port/Protocol;同一模块的多文件实现进入单词命名子目录 | SQLAlchemy、Session、Oper 等具体 DB 实现,具体 Adapter 静态依赖,多领域 Chain 编排、底层通用机制、通用传输协议 | `recognition.py`, `filter.py`, `outbox.py`, `subscription/write.py`, `workflow.py` | +| `app/application/messaging/` | 消息渲染/路由、交互和 Agent 到消息桥接:`ingress.py` 统一渠道回环入口;`interaction/` 承载通用状态和 Agent 选择契约;`channel/admin.py` 承载渠道管理员解析;`router.py` 统一交互优先级和回调分发;`site.py`/`subscribe.py`/`skill.py` 对应命令的会话、输入解析和视图;`media.py` 媒体交互状态(业务工作流仍由 `MediaInteractionChain` 执行);`plugin.py` 插件输入接管和插件按钮回调;`webagent/` 承载 WebAgent 事件和流编排;`agent.py` 保留 WebAgent 应用编排。不作为推荐给插件直接使用的公开 SDK | 认证策略、通用 HTTP、服务发现、仅端点使用的 Web Push 行为 | `ingress.py`, `message.py`, `interaction/`, `channel/`, `webagent/`, `router.py`, `agent.py` | | `app/application/security/` | 认证、授权、Cookie、Passkey、OTP/二次认证、路径/URL 安全、SSRF 和签名策略 | 通用 URL 解析、进程运行策略、普通业务校验 | `access.py`, `auth.py`, `cookie.py`, `passkey.py`, `otp.py`, `twofactor.py`, `url.py` | | `app/chain/` | Reusable use-case orchestration across modules, Application services, injected ports, events, and caches; chains reach modules only through `run_module` dispatch on method-name contracts | Transport schemas, backend-specific protocol details, concrete Adapter imports, generic primitives, direct Oper/DB imports, direct imports of module internals (classes, exceptions, constants) | `media/`, `download/`, `subscribe/`, `transfer/` | | `app/db/oper/` | 面向表和持久化值的 SQLAlchemy 数据访问;接收调用方 Session,只查询、暂存或 flush | Application 业务规则、隐式事务所有权、外部副作用 | `subscribe.py`, `site.py`, `workflow.py` | @@ -132,6 +142,61 @@ Architecture, persistence, security, external protocols, cross-module lifecycle, * **Minimal Change Principle:** Prefer the smallest correct change. Do not perform unrelated refactors, mass renames, or formatting-only cleanup. * **Output Language:** Summaries, validation results, and risk notes default to Chinese unless the user requests otherwise. +### Contributor Preparation Defaults + +For contributors, inspect the final diff and complete applicable local checks before committing host code, tests, dependencies, architecture fixtures, or CI changes. A request to commit or push alone does not waive that preparation. Confirmed maintainers may use the documented execution arrangements above, including a local anchor followed by remaining validation. `.github/workflows/test.yml` and `.github/workflows/pylint.yml` remain the CI source of truth; re-read them when they change. + +Select checks by affected contracts: architecture policy and snapshots for ownership/import/contract changes, relevant ratchets for governed Python changes, and startup performance for startup changes. Run focused behavior tests and changed-file pylint for affected Python files. The following is a command reference, not a requirement to execute every command for every task. When both apply, run architecture policy tests before snapshot checks, in the same order as CI. Shared test environments map these commands as described in `docs/development-setup.md`. + +```bash +uv run --locked --no-sync pytest \ + tests/test_architecture_dependencies.py \ + tests/test_architecture_adapter_imports.py \ + tests/test_architecture_egress.py \ + tests/test_architecture_event_facts.py \ + tests/test_architecture_event_policy.py -q +uv run --locked --no-sync python scripts/architecture/event_policy.py +uv run --locked --no-sync pytest \ + tests/test_architecture_contract_baseline.py \ + tests/test_architecture_baseline_cli.py -q +uv run --locked --no-sync python scripts/architecture/baseline.py --check-host +uv run --locked --no-sync mypy --config-file mypy.ini +uv run --locked --no-sync python scripts/architecture/complexity.py +uv run --locked --no-sync python scripts/architecture/complexity.py --v2 +uv run --locked --no-sync python scripts/architecture/concurrency.py +uv run --locked --no-sync python scripts/architecture/async_blocking.py +uv run --locked --no-sync python scripts/architecture/task_ownership.py +uv run --locked --no-sync python scripts/architecture/service_locator.py +uv run --locked --no-sync python scripts/architecture/ruff_ratchet.py +uv run --locked --no-sync python scripts/architecture/mypy_ratchet.py +uv run --locked --no-sync python scripts/startup/performance.py --check --repeat 3 +``` + +Apply the following acceptance rules: + +* **No baseline laundering:** A failed baseline or ratchet is evidence to inspect, not permission to regenerate fixtures. Never use `--write-host`, `--write-plugins`, or any ratchet `--write` merely to make a gate pass. Fix added dependencies, cycles, layer violations, direct egress, service locators, blocking calls, unmanaged tasks, type/lint growth, complexity growth, or concurrency growth in the implementation. +* **Reviewed baseline updates only:** Update a fixture only when the task intentionally changes the governed contract or the tool reports a genuine lower debt watermark. First prove the change complies with architecture policy, inspect the semantic diff, update coupled documentation/tests, run the non-writing check again, and include the fixture diff in the same commit. Complexity, concurrency, async-blocking, and host snapshot writers can overwrite regressions mechanically, so their ability to write is not approval to do so. +* **Diagnose snapshot failures:** When `baseline.py --check-host` fails unexpectedly, rerun it with `--diagnostics` and inspect the affected JSON under `tests/fixtures/architecture/`. Do not infer that a changed snapshot is acceptable from test success alone. +* **Test the behavior:** Run focused pytest coverage for every changed behavior. Run `uv run --locked --no-sync python tests/run.py` before commit for dependency/lock changes, shared test infrastructure, database or startup paths, cross-module lifecycle, compatibility layers, or broad behavior changes. Do not weaken, skip, or delete tests to satisfy a gate without proving equivalent coverage. +* **Check changed Python files:** For PR preparation, take the deduplicated union of `git diff --name-only --diff-filter=ACMRT ...HEAD -- '*.py'`, `git diff --cached --name-only --diff-filter=ACMRT -- '*.py'`, and `git diff --name-only --diff-filter=ACMRT -- '*.py'`, plus intended new files from `git ls-files --others --exclude-standard -- '*.py'`. Resolve `` to the actual target base ref (normally `upstream/v3`). Keep staged and unstaged comparisons separate: they can cancel against HEAD while the index still contains a broken change. Exclude unrelated local files from the planned commit. + + Before commit validation, confirm the index contains exactly the authorized changes: ordinary `git commit` writes the index, not the working tree. Stage only the selected paths/hunks and record `git write-tree` before exporting or linting. Use the working-tree shortcut only when all tracked files match the index (`git diff --quiet` succeeds) and no extra configuration or import inputs can alter lint behavior. Then run `uv run --locked --no-sync pylint ` on the non-empty selection. Code, project configuration, and project-local lint dependencies must come from the same planned tree. Filter candidates by existence in the planned index tree, so staged deletions/renames are excluded but unstaged deletions do not hide content that would still be committed. + + Otherwise, including partial staging, validate a temporary checkout of the index instead of linting the working-tree version or staging unrelated hunks. This selects the inputs for the existing lint check, not an additional gate. From the repository root, export the index into a fresh temporary directory: + + ```bash + INDEX_CHECKOUT="$(mktemp -d)" + git checkout-index --all --prefix="${INDEX_CHECKOUT}/" + ``` + + Run pylint from that directory on the selected Python paths present there, using the original absolute test-environment interpreter (`/bin/python -m pylint `), with project configuration and project-local lint dependencies resolved from the export, not the original working tree or extra local inputs. The export copies indexed files only; it does not stage anything or change the working tree. Confirm `git write-tree` still matches the recorded tree immediately before committing. Commit that verified index without `-a`, path arguments, or another staging step that changes the tree; any index change invalidates the affected evidence. CI PRs compare base to HEAD; CI pushes use the workflow's before/current SHA range. For broad Python changes, also check `app/` in the same validated tree. +* **Verify dependency changes:** If `pyproject.toml` or `uv.lock` changed, run `uv lock --check`, `uv sync --locked --offline --inexact --no-dev --check`, the full `uv run --locked --no-sync python tests/run.py`, and the locked `pip-audit` commands in `docs/rules/03-commands.md`. Do not commit an out-of-date or locally generated alternative lock file. +* **Protect coverage:** Changes in `app/application/` or `app/domain/` must preserve the CI line-coverage floor. Add focused tests for new branches. Local macOS coverage is diagnostic only; never write or commit the canonical coverage baseline from it. +* **Verify the final tree:** Re-run affected gates after all fixes and generated fixture updates, then inspect `git diff --check`, `git status --short`, and the complete diff. Report the exact commands and outcomes; never claim a gate was run if it was skipped or failed. +* **Close the remote loop:** After an authorized push or PR creation, inspect GitHub checks for the exact pushed commit and the actual required checks/Ruleset. Diagnose failures from logs and fix unresolved substantive issues caused, worsened, or newly exposed by this change. Handle unrelated failures under the documented maintainer decision in `docs/rules/12-collaboration-and-distribution.md`; ordinary optional or pending automation does not automatically block delivery. Do not weaken workflows or ratchets, bypass platform protection, or claim unfinished required verification passed. + +Documentation-only changes, including documentation contract tests, use applicable text, link, structure, focused test, and diff checks instead of the product suite; state that scope explicitly. Contributors report a blocked applicable check and obtain a maintainer decision before proceeding beyond the affected boundary. A documented maintainer arrangement may already cover that limitation; reuse it within scope and report what remains unverified. + ### Conflict Resolution If existing code appears to contradict the documentation, identify the exact contradiction and decide which current-task gate it affects. Stop and ask only when it blocks acceptance, creates a security or data-safety ambiguity, or cannot be resolved from current source and maintained documentation. Otherwise preserve the evidence, continue unaffected work, and report the discrepancy without silently expanding scope. @@ -160,4 +225,4 @@ For the full documentation map and cross-references, refer to: **[Documentation Hub Index](./docs/rules/README.md)** -*Last Updated: 2026-08-19* +*Last Updated: 2026-09-06* diff --git a/app/adapters/cache/redis.py b/app/adapters/cache/redis.py index 115c7397e..2166fd130 100644 --- a/app/adapters/cache/redis.py +++ b/app/adapters/cache/redis.py @@ -91,6 +91,7 @@ class RedisHelper(ConfigReloadMixin, metaclass=Singleton): "CACHE_REDIS_MAXMEMORY", "CACHE_REDIS_MAX_CONNECTIONS", "CACHE_REDIS_POOL_TIMEOUT", + "BIG_MEMORY_MODE", } def __init__(self): @@ -370,6 +371,7 @@ class AsyncRedisHelper(ConfigReloadMixin, metaclass=Singleton): "CACHE_REDIS_MAXMEMORY", "CACHE_REDIS_MAX_CONNECTIONS", "CACHE_REDIS_POOL_TIMEOUT", + "BIG_MEMORY_MODE", } def __init__(self): diff --git a/app/adapters/external/ocr.py b/app/adapters/external/ocr.py index 366c145fe..d709979dd 100644 --- a/app/adapters/external/ocr.py +++ b/app/adapters/external/ocr.py @@ -1,4 +1,5 @@ import base64 +import binascii from typing import Optional from app.adapters.network.http import RequestUtils @@ -14,7 +15,9 @@ class OcrHelper: """初始化 OCR 服务地址,优先使用组合根设置快照。""" if ocr_base_url is None: ocr_base_url = get_runtime_setting('OCR_HOST') - self._ocr_b64_url = f"{str(ocr_base_url).rstrip('/')}/captcha/base64" + base_url = str(ocr_base_url).rstrip('/') + self._ocr_b64_url = f"{base_url}/captcha/base64" + self._ocr_image_url = f"{base_url}/captcha/image" def get_captcha_text( self, @@ -22,33 +25,48 @@ class OcrHelper: image_b64: Optional[str] = None, cookie: Optional[str] = None, ua: Optional[str] = None, + image_data: Optional[bytes] = None, ) -> str: """ - 根据图片地址,获取验证码图片,并识别内容 + 获取验证码图片并识别内容,优先使用原始图片字节接口。 :param image_url: 图片地址 :param image_b64: 图片base64,跳过图片地址下载 :param cookie: 下载图片使用的cookie :param ua: 下载图片使用的ua + :param image_data: 已取得的原始图片字节,跳过下载和 Base64 编码 :return: 验证码识别结果,失败时返回空字符串 """ - image_b64 = self._normalize_image_base64(image_b64) - if image_url: + raw_image = image_data or b"" + if not raw_image and image_url: data_url_b64 = self._extract_data_url_base64(image_url) if data_url_b64: - image_b64 = self._normalize_image_base64(data_url_b64) + try: + raw_image = base64.b64decode( + self._normalize_image_base64(data_url_b64), + validate=True, + ) + except (ValueError, binascii.Error): + return "" else: ret = RequestUtils(ua=ua, cookies=cookie).get_res(image_url) if ret is not None: - image_bin = ret.content - if not image_bin: + raw_image = ret.content or b"" + if not raw_image: return "" - image_b64 = base64.b64encode(image_bin).decode() - if not image_b64: - return "" - ret = RequestUtils(content_type="application/json").post_res( - url=self._ocr_b64_url, - json={"base64_img": image_b64}) + if raw_image: + ret = RequestUtils(content_type="application/octet-stream").post_res( + url=self._ocr_image_url, + data=raw_image, + ) + else: + image_b64 = self._normalize_image_base64(image_b64) + if not image_b64: + return "" + ret = RequestUtils(content_type="application/json").post_res( + url=self._ocr_b64_url, + json={"base64_img": image_b64}, + ) if ret: return ret.json().get("result") or "" return "" diff --git a/app/adapters/external/plugin/client.py b/app/adapters/external/plugin/client.py index aba9f53ba..d7450bf92 100644 --- a/app/adapters/external/plugin/client.py +++ b/app/adapters/external/plugin/client.py @@ -9,9 +9,10 @@ import threading import time import traceback from collections import Counter +from concurrent.futures import Future from pathlib import Path from typing import Any, Dict, Iterator, List, Optional, cast -from urllib.parse import urlparse, urlsplit +from urllib.parse import urlsplit import httpx2 from packaging.specifiers import InvalidSpecifier, SpecifierSet @@ -29,6 +30,12 @@ from app.domain.plugin import ( parse_local_plugin_path, parse_local_plugin_reference, ) +from app.domain.plugin import ( + normalize_plugin_market_repo_url as _normalize_plugin_market_repo_url, +) +from app.domain.plugin import ( + split_plugin_market_repo_urls as _split_plugin_market_repo_urls, +) from app.foundation.environment import is_free_threaded_runtime from app.foundation.singleton import WeakSingleton from app.foundation.url import UrlUtils @@ -50,6 +57,8 @@ PLUGIN_INDEX_MAX_ENTRIES = 4096 PLUGIN_INDEX_MAX_HISTORY_ENTRIES = 512 PLUGIN_INDEX_MAX_NESTING = 64 PLUGIN_INDEX_READ_CHUNK_SIZE = 64 * 1024 +PLUGIN_INDEX_REQUEST_TIMEOUT = 15 +DEFAULT_PLUGIN_INDEX_FETCH_CONCURRENCY = 5 PLUGIN_INDEX_COMPATIBILITY_FLAG_PATTERN = re.compile(r"^v\d+t?$") PLUGIN_INDEX_TEXT_LIMITS = { "name": 256, @@ -63,11 +72,23 @@ PLUGIN_INDEX_TEXT_LIMITS = { "repo_url": 2048, } +# 目录服务和来源库存可能在同一进程内同时刷新;调用方各自创建的信号量 +# 只能限制单次刷新,不能限制真实出站请求总量。索引传输层统一持有闸门。 +_PLUGIN_INDEX_FETCH_GATE = threading.BoundedSemaphore( + DEFAULT_PLUGIN_INDEX_FETCH_CONCURRENCY +) + class _PluginIndexTooLargeError(RuntimeError): """插件索引的声明长度或实际读取字节超过资源边界。""" +def _format_request_error(error: Exception) -> str: + """保留异常类型,避免无消息异常在运行日志中显示为空白。""" + detail = str(error).strip() + return f"{type(error).__name__}: {detail}" if detail else type(error).__name__ + + def build_local_repo_url( plugin_id: str, *, @@ -132,34 +153,9 @@ VERSION_BACKWARD_COMPATIBLE_FLAGS: Dict[str, List[str]] = { "v3": ["v2"], } -def normalize_plugin_market_repo_url(repo_url: str) -> Optional[str]: - """规范化插件仓库地址,便于跨来源合并去重。""" - repo_url = (repo_url or "").strip().rstrip("/") - if not repo_url: - return None - repo_url = repo_url.removesuffix(".git") - parsed_url = urlparse(repo_url) - if parsed_url.scheme not in {"http", "https"}: - return None - if (parsed_url.hostname or "").lower() != "github.com": - return None - paths = [item for item in parsed_url.path.split("/") if item] - if len(paths) < 2: - return None - return f"https://github.com/{paths[0]}/{paths[1]}" - - -def split_plugin_market_repo_urls(value: Optional[str]) -> list[str]: - """拆分插件市场仓库配置并保持原有顺序去重。""" - repos: list[str] = [] - seen_repos = set() - for item in re.split(r"[\n,,]+", value or ""): - normalized_repo = normalize_plugin_market_repo_url(item) - if not normalized_repo or normalized_repo.lower() in seen_repos: - continue - repos.append(normalized_repo) - seen_repos.add(normalized_repo.lower()) - return repos +# 保留历史兼容模块的导出路径;规范化规则的唯一实现位于纯领域模块。 +normalize_plugin_market_repo_url = _normalize_plugin_market_repo_url +split_plugin_market_repo_urls = _split_plugin_market_repo_urls def extract_plugin_market_repos_from_wiki( @@ -209,10 +205,18 @@ def merge_plugin_market_repos( seen_repos.add(normalized_repo.lower()) return merged_repos + class PluginMarketTransport(metaclass=WeakSingleton): """负责插件市场、本地仓库和 GitHub 元数据读取。""" _base_url = "https://raw.githubusercontent.com/{user}/{repo}/main/" + _index_future_lock = threading.Lock() + _index_futures: dict[tuple[str, str], Future[Optional[PluginIndex]]] = {} + _index_task_lock = threading.Lock() + _index_tasks: dict[ + tuple[asyncio.AbstractEventLoop, str, str], + asyncio.Task[Optional[PluginIndex]], + ] = {} _release_task_lock = threading.Lock() _release_tasks: dict[ tuple[asyncio.AbstractEventLoop, str, bool], @@ -487,13 +491,12 @@ class PluginMarketTransport(metaclass=WeakSingleton): candidates: PluginIndex = {} for repo_order, repo_path in enumerate(self.get_local_repo_paths()): if not repo_path.exists() or not repo_path.is_dir(): - logger.warn(f"本地插件仓库目录不存在或不可读:{repo_path}") - continue + raise RuntimeError(f"本地插件仓库目录不存在或不可读:{repo_path}") package_candidates = [] if get_runtime_setting('VERSION_FLAG'): package_candidates.append((get_runtime_setting('VERSION_FLAG'), self.__get_local_package(repo_path, - get_runtime_setting('VERSION_FLAG')))) + get_runtime_setting('VERSION_FLAG')))) # 向后兼容:补充扫描更低版本的 package 文件,便于本地仓库复用历史版本插件。 for backward_flag in VERSION_BACKWARD_COMPATIBLE_FLAGS.get(get_runtime_setting('VERSION_FLAG'), []): package_candidates.append((backward_flag, self.__get_local_package(repo_path, backward_flag))) @@ -884,6 +887,8 @@ class PluginMarketTransport(metaclass=WeakSingleton): if not repo_url: return None + repo_url = normalize_plugin_market_repo_url(repo_url) or repo_url + user, repo = cls.get_repo_info(repo_url) if not user or not repo: return None @@ -903,7 +908,7 @@ class PluginMarketTransport(metaclass=WeakSingleton): cls, url: str, headers: Optional[dict[str, str]] = None, - timeout: Optional[int] = 60, + timeout: Optional[int] = PLUGIN_INDEX_REQUEST_TIMEOUT, ) -> Optional[tuple[int, str]]: """按 GitHub 降级顺序流式读取同步插件索引,并限制解压后字节数。""" strategies = cls._build_github_request_strategies( @@ -929,7 +934,7 @@ class PluginMarketTransport(metaclass=WeakSingleton): except Exception as error: # noqa: BLE001 - 失败后尝试下一传输策略 logger.error( f"[GitHub] 插件索引请求失败,策略:{strategy_name}," - f"URL:{target_url},错误:{error}" + f"URL:{target_url},错误:{_format_request_error(error)}" ) logger.error(f"[GitHub] 所有策略均无法读取插件索引,URL:{url}") return None @@ -939,7 +944,7 @@ class PluginMarketTransport(metaclass=WeakSingleton): cls, url: str, headers: Optional[dict[str, str]] = None, - timeout: Optional[int] = 60, + timeout: Optional[int] = PLUGIN_INDEX_REQUEST_TIMEOUT, ) -> Optional[tuple[int, str]]: """按 GitHub 降级顺序流式读取异步插件索引,并限制解压后字节数。""" strategies = cls._build_github_request_strategies( @@ -965,7 +970,7 @@ class PluginMarketTransport(metaclass=WeakSingleton): except Exception as error: # noqa: BLE001 - 失败后尝试下一传输策略 logger.error( f"[GitHub] 插件索引请求失败,策略:{strategy_name}," - f"URL:{target_url},错误:{error}" + f"URL:{target_url},错误:{_format_request_error(error)}" ) logger.error(f"[GitHub] 所有策略均无法读取插件索引,URL:{url}") return None @@ -1130,6 +1135,81 @@ class PluginMarketTransport(metaclass=WeakSingleton): releases.extend(cls.__normalize_plugin_release_response(payload)) return len(payload) >= 100 + @staticmethod + def _plugin_index_key( + repo_url: str, + package_version: Optional[str], + ) -> tuple[str, str]: + """生成跨 URL 表示形式稳定的插件索引请求键。""" + normalized_repo = normalize_plugin_market_repo_url(repo_url) + return ( + (normalized_repo or str(repo_url).strip().rstrip("/")).lower(), + package_version or "", + ) + + @classmethod + def _remove_index_future( + cls, + key: tuple[str, str], + future: Future[Optional[PluginIndex]], + ) -> None: + """同步索引请求结束后释放 single-flight 占位。""" + with cls._index_future_lock: + if cls._index_futures.get(key) is future: + cls._index_futures.pop(key, None) + + @classmethod + def _remove_index_task( + cls, + key: tuple[asyncio.AbstractEventLoop, str, str], + task: asyncio.Future[Optional[PluginIndex]], + ) -> None: + """异步索引请求结束后释放事件循环和仓库引用。""" + with cls._index_task_lock: + if cls._index_tasks.get(key) is task: + cls._index_tasks.pop(key, None) + # 调用方可能在请求完成前取消等待;主动读取异常避免事件循环告警, + # 不影响其他仍在等待同一个任务的调用方取得原始异常。 + try: + task.exception() + except BaseException: # noqa: BLE001 - 仅消费已完成任务的异常 + pass + + @staticmethod + async def _acquire_index_fetch_slot() -> None: + """以可取消方式等待跨同步/异步调用共享的索引请求闸门。""" + while not _PLUGIN_INDEX_FETCH_GATE.acquire(blocking=False): + await asyncio.sleep(0.01) + + def _fetch_plugin_index_sync( + self, + package_url: str, + headers: Optional[dict[str, str]], + ) -> Optional[PluginIndex]: + """在共享进程级闸门内完成一次同步索引读取。""" + with _PLUGIN_INDEX_FETCH_GATE: + response = self.__request_plugin_index_with_fallback( + package_url, + headers=headers, + ) + return self._resolve_plugin_index_result(response) + + async def _fetch_plugin_index_async( + self, + package_url: str, + headers: Optional[dict[str, str]], + ) -> Optional[PluginIndex]: + """在共享进程级闸门内完成一次异步索引读取。""" + await self._acquire_index_fetch_slot() + try: + response = await self.__async_request_plugin_index_with_fallback( + package_url, + headers=headers, + ) + finally: + _PLUGIN_INDEX_FETCH_GATE.release() + return self._resolve_plugin_index_result(response) + @cached(maxsize=1024, ttl=1800, skip_none=False) # type: ignore[misc] def get_plugin_index_result( self, @@ -1141,11 +1221,32 @@ class PluginMarketTransport(metaclass=WeakSingleton): if request is None: raise ValueError("插件仓库地址无效") package_url, headers = request - response = self.__request_plugin_index_with_fallback( - package_url, - headers=headers, - ) - return self._resolve_plugin_index_result(response) + key = self._plugin_index_key(repo_url, package_version) + with self._index_future_lock: + future = self._index_futures.get(key) + if future is None: + future = Future[Optional[PluginIndex]]() + self._index_futures[key] = future + owner = True + else: + owner = False + + assert future is not None + + if not owner: + return future.result() + + try: + result = self._fetch_plugin_index_sync(package_url, headers) + except BaseException as error: # noqa: BLE001 - 共享结果必须传播原始异常 + future.set_exception(error) + future.exception() + raise + else: + future.set_result(result) + return result + finally: + self._remove_index_future(key, future) def get_plugins(self, repo_url: str, package_version: Optional[str] = None) -> Optional[PluginIndex]: @@ -1251,7 +1352,7 @@ class PluginMarketTransport(metaclass=WeakSingleton): timeout: Optional[int] = 60, is_api: bool = False, ) -> list[tuple[str, str, PluginRequestOptions]]: - """构造同步与异步 GitHub 请求共用的镜像、代理和直连顺序。""" + """构造同步与异步 GitHub 请求共用的镜像和单一出口顺序。""" strategies: list[tuple[str, str, PluginRequestOptions]] = [] if not is_api and get_runtime_setting('GITHUB_PROXY'): proxy_url = ( @@ -1272,9 +1373,10 @@ class PluginMarketTransport(metaclass=WeakSingleton): }, ) ) - strategies.append( - ("直连", url, {"headers": headers, "timeout": timeout}) - ) + else: + strategies.append( + ("直连", url, {"headers": headers, "timeout": timeout}) + ) return strategies @staticmethod @@ -1283,7 +1385,8 @@ class PluginMarketTransport(metaclass=WeakSingleton): timeout: Optional[int] = 60, is_api: bool = False) -> Optional[Response]: """ - 使用自动降级策略,请求资源,优先级依次为镜像站、代理、直连 + 使用自动降级策略,请求资源:可选镜像站后只使用一个出口; + 显式配置代理时不再追加无效直连。 :param url: 目标URL :param headers: 请求头信息 :param timeout: 请求超时时间 @@ -1306,7 +1409,10 @@ class PluginMarketTransport(metaclass=WeakSingleton): logger.debug(f"[GitHub] 请求成功,策略:{strategy_name}, URL: {target_url}") return res except Exception as e: - logger.error(f"[GitHub] 请求失败,策略:{strategy_name}, URL: {target_url},错误:{str(e)}") + logger.error( + f"[GitHub] 请求失败,策略:{strategy_name}, URL: {target_url}," + f"错误:{_format_request_error(e)}" + ) logger.error(f"[GitHub] 所有策略均请求失败,URL: {url},请检查网络连接或 GitHub 配置") return None @@ -1404,7 +1510,8 @@ class PluginMarketTransport(metaclass=WeakSingleton): timeout: Optional[int] = 60, is_api: bool = False) -> Optional[httpx2.Response]: """ - 使用自动降级策略,异步请求资源,优先级依次为镜像站、代理、直连 + 使用自动降级策略,异步请求资源:可选镜像站后只使用一个出口; + 显式配置代理时不再追加无效直连。 :param url: 目标URL :param headers: 请求头信息 :param timeout: 请求超时时间 @@ -1427,7 +1534,10 @@ class PluginMarketTransport(metaclass=WeakSingleton): logger.debug(f"[GitHub] 请求成功,策略:{strategy_name}, URL: {target_url}") return res except Exception as e: - logger.error(f"[GitHub] 请求失败,策略:{strategy_name}, URL: {target_url},错误:{str(e)}") + logger.error( + f"[GitHub] 请求失败,策略:{strategy_name}, URL: {target_url}," + f"错误:{_format_request_error(e)}" + ) logger.error(f"[GitHub] 所有策略均请求失败,URL: {url},请检查网络连接或 GitHub 配置") return None @@ -1470,11 +1580,33 @@ class PluginMarketTransport(metaclass=WeakSingleton): if request is None: raise ValueError("插件仓库地址无效") package_url, headers = request - response = await self.__async_request_plugin_index_with_fallback( - package_url, - headers=headers, + repo_key, generation_key = self._plugin_index_key( + repo_url, + package_version, ) - return self._resolve_plugin_index_result(response) + loop = asyncio.get_running_loop() + task_key = (loop, repo_key, generation_key) + with self._index_task_lock: + task = self._index_tasks.get(task_key) + if task is None: + task = cast( + asyncio.Task[Optional[PluginIndex]], + get_task_registry().create( + self._fetch_plugin_index_async(package_url, headers), + owner="plugin.market.index", + ), + ) + self._index_tasks[task_key] = task + + def on_index_task_done( + completed_task: asyncio.Future[Optional[PluginIndex]], + ) -> None: + self._remove_index_task(task_key, completed_task) + + task.add_done_callback(on_index_task_done) + + # 单个调用方取消等待时不能连带取消共享请求。 + return await asyncio.shield(task) async def async_get_plugins(self, repo_url: str, package_version: Optional[str] = None) -> Optional[PluginIndex]: diff --git a/app/adapters/external/server.py b/app/adapters/external/server.py index 7e8798755..5baed205c 100644 --- a/app/adapters/external/server.py +++ b/app/adapters/external/server.py @@ -54,6 +54,8 @@ def reset_server_application_services() -> None: class MoviePilotServerHelper: """ MoviePilot 服务端请求辅助工具。 + + 中心服务请求统一使用 HTTP/1.1,用于对照验证间歇性请求失败是否与 HTTP/2 链路有关。 """ USER_UID_HEADER = "X-MoviePilot-User-Uid" @@ -2012,6 +2014,7 @@ class MoviePilotServerHelper: 异步发送服务端 GET 请求,默认携带安装用户 ID。 """ return await AsyncRequestUtils( + http2=False, proxies=get_runtime_setting('PROXY'), timeout=timeout, headers=cls.build_headers(url) if include_user_uid else {}, @@ -2034,6 +2037,7 @@ class MoviePilotServerHelper: 异步发送携带安装用户 ID 的服务端 JSON POST 请求。 """ return await AsyncRequestUtils( + http2=False, proxies=get_runtime_setting('PROXY'), timeout=timeout, headers=cls.build_headers(url, content_type="application/json"), @@ -2056,6 +2060,7 @@ class MoviePilotServerHelper: 异步发送携带安装用户 ID 的服务端 DELETE 请求。 """ return await AsyncRequestUtils( + http2=False, proxies=get_runtime_setting('PROXY'), timeout=timeout, headers=cls.build_headers(url), diff --git a/app/adapters/network/browser.py b/app/adapters/network/browser.py index aae633c65..7271ef7c2 100644 --- a/app/adapters/network/browser.py +++ b/app/adapters/network/browser.py @@ -173,6 +173,7 @@ class _BrowserSessionState: active_index: int = 0 user_agent: Optional[str] = None cookies: Optional[str] = None + owner: Optional[Any] = field(default=None, repr=False) created_at: float = field(default_factory=time.monotonic) last_used_at: float = field(default_factory=time.monotonic) lock: threading.RLock = field(default_factory=threading.RLock) @@ -198,6 +199,7 @@ class BrowserSessionHelper: _sessions: dict[str, _BrowserSessionState] = {} _session_executors: dict[str, ThreadPoolExecutor] = {} + _session_executor_owners: dict[str, Any] = {} _session_thread_ids: dict[str, int] = {} _sessions_lock = threading.RLock() @@ -264,26 +266,28 @@ class BrowserSessionHelper: 关闭所有 Agent 浏览器会话。 """ with cls._sessions_lock: - session_keys = list( - set(cls._sessions.keys()) | set(cls._session_executors.keys()) - ) + session_keys = set(cls._sessions) | set(cls._session_executors) for session_key in session_keys: - cls.close_session(session_key) + with cls._sessions_lock: + session = cls._sessions.get(session_key) + owner = session.owner if session else cls._session_executor_owners.get(session_key) + cls.close_session(session_key, owner=owner) @classmethod - def close_session(cls, session_key: str) -> bool: + def close_session(cls, session_key: str, owner: Optional[Any] = None) -> bool: """ 关闭指定 Agent 浏览器会话。 :param session_key: 会话标识 + :param owner: 可选宿主作用域;提供时只允许关闭该作用域拥有的会话 :return: 找到并关闭会话时返回 True """ if cls._is_current_session_thread(session_key): - closed = cls._close_session_in_thread(session_key) + closed = cls._close_session_in_thread(session_key, owner=owner) cls._shutdown_session_executor(session_key, wait=False) return closed - executor = cls._get_existing_session_executor(session_key) + executor = cls._get_existing_session_executor(session_key, owner=owner) if executor: context = copy_context() # 会话线程保持空底层上下文,每次操作只使用当前调用快照。 @@ -294,16 +298,39 @@ class BrowserSessionHelper: session_key, cls._close_session_in_thread, session_key, + owner=owner, ) try: return future.result() finally: cls._shutdown_session_executor(session_key) - closed = cls._close_session_in_thread(session_key) + closed = cls._close_session_in_thread(session_key, owner=owner) cls._shutdown_session_executor(session_key) return closed + @classmethod + def close_owner(cls, owner: Any) -> bool: + """关闭宿主作用域创建的全部浏览器会话和其专属执行线程。""" + with cls._sessions_lock: + session_keys = { + key for key, session in cls._sessions.items() if session.owner is owner + } + session_keys.update( + key for key, session_owner in cls._session_executor_owners.items() + if session_owner is owner + ) + for session_key in session_keys: + cls.close_session(session_key, owner=owner) + with cls._sessions_lock: + return not any( + session.owner is owner + for session in cls._sessions.values() + ) and not any( + session_owner is owner + for session_owner in cls._session_executor_owners.values() + ) + def with_session( self, session_key: str, @@ -311,6 +338,7 @@ class BrowserSessionHelper: user_agent: Optional[str] = None, cookies: Optional[str] = None, timeout: Optional[int] = 30, + owner: Optional[Any] = None, ) -> Any: """ 获取或创建浏览器会话,并在持有会话锁时执行回调。 @@ -320,6 +348,7 @@ class BrowserSessionHelper: :param user_agent: 新建会话时使用的 User-Agent :param cookies: 本次操作要注入的 Cookie 请求头 :param timeout: 默认操作超时时间,单位秒 + :param owner: 可选宿主作用域;提供时会隔离并校验会话归属 :return: 回调函数返回值 """ self._prune_sessions() @@ -331,6 +360,7 @@ class BrowserSessionHelper: user_agent=user_agent, cookies=cookies, timeout=timeout, + owner=owner, ) def _with_session_in_thread( @@ -340,6 +370,7 @@ class BrowserSessionHelper: user_agent: Optional[str] = None, cookies: Optional[str] = None, timeout: Optional[int] = 30, + owner: Optional[Any] = None, ) -> Any: """ 在会话专属线程内获取浏览器会话并执行回调。 @@ -355,6 +386,7 @@ class BrowserSessionHelper: session_key=session_key, user_agent=user_agent, cookies=cookies, + owner=owner, ) with session.lock: session.last_used_at = time.monotonic() @@ -371,6 +403,7 @@ class BrowserSessionHelper: session_key: str, callback: Callable[..., Any], *args: Any, + owner: Optional[Any] = None, **kwargs: Any, ) -> Any: """ @@ -383,10 +416,10 @@ class BrowserSessionHelper: :return: 回调返回值 """ if cls._is_current_session_thread(session_key): - return callback(*args, **kwargs) + return callback(*args, owner=owner, **kwargs) for _ in range(2): - executor = cls._get_session_executor(session_key) + executor = cls._get_session_executor(session_key, owner=owner) try: context = copy_context() # 会话线程保持空底层上下文,每次操作只使用当前调用快照。 @@ -397,6 +430,7 @@ class BrowserSessionHelper: session_key, callback, *args, + owner=owner, **kwargs, ) except RuntimeError: @@ -447,7 +481,7 @@ class BrowserSessionHelper: return thread_id == threading.get_ident() @classmethod - def _get_session_executor(cls, session_key: str) -> ThreadPoolExecutor: + def _get_session_executor(cls, session_key: str, owner: Optional[Any] = None) -> ThreadPoolExecutor: """ 获取或创建指定会话的单线程执行器。 @@ -457,17 +491,21 @@ class BrowserSessionHelper: with cls._sessions_lock: executor = cls._session_executors.get(session_key) if executor: + existing_owner = cls._session_executor_owners.get(session_key) + if existing_owner is not owner: + raise PermissionError("浏览器会话不属于当前任务") return executor executor = ThreadPoolExecutor( max_workers=1, thread_name_prefix=cls.SESSION_WORKER_NAME_PREFIX, ) cls._session_executors[session_key] = executor + cls._session_executor_owners[session_key] = owner return executor @classmethod def _get_existing_session_executor( - cls, session_key: str + cls, session_key: str, owner: Optional[Any] = None ) -> Optional[ThreadPoolExecutor]: """ 获取指定会话已存在的执行器。 @@ -476,7 +514,10 @@ class BrowserSessionHelper: :return: 已存在的执行器,不存在时返回 None """ with cls._sessions_lock: - return cls._session_executors.get(session_key) + executor = cls._session_executors.get(session_key) + if executor and cls._session_executor_owners.get(session_key) is not owner: + raise PermissionError("浏览器会话不属于当前任务") + return executor @classmethod def _discard_session_executor( @@ -493,6 +534,7 @@ class BrowserSessionHelper: with cls._sessions_lock: if cls._session_executors.get(session_key) is executor: cls._session_executors.pop(session_key, None) + cls._session_executor_owners.pop(session_key, None) @classmethod def _shutdown_session_executor( @@ -508,19 +550,24 @@ class BrowserSessionHelper: """ with cls._sessions_lock: executor = cls._session_executors.pop(session_key, None) + cls._session_executor_owners.pop(session_key, None) cls._session_thread_ids.pop(session_key, None) if executor: executor.shutdown(wait=wait, cancel_futures=True) @classmethod - def _close_session_in_thread(cls, session_key: str) -> bool: + def _close_session_in_thread(cls, session_key: str, owner: Optional[Any] = None) -> bool: """ 在会话固定线程内关闭并移除浏览器会话。 :param session_key: 会话标识 + :param owner: 可选宿主作用域;提供时校验会话归属 :return: 找到并关闭会话时返回 True """ with cls._sessions_lock: + session = cls._sessions.get(session_key) + if session and session.owner is not owner: + raise PermissionError("浏览器会话不属于当前任务") session = cls._sessions.pop(session_key, None) if not session: return False @@ -604,16 +651,69 @@ class BrowserSessionHelper: """ if tab_index < 0 or tab_index >= len(session.pages): raise ValueError(f"标签页索引不存在: {tab_index}") + active_index = session.active_index page = session.pages.pop(tab_index) + close_error: Exception | None = None try: page.close() except Exception as err: + close_error = err logger.warning(f"关闭浏览器标签页失败: {str(err)}") if not session.pages: session.pages.append(session.context.new_page()) - session.active_index = min(session.active_index, len(session.pages) - 1) + elif tab_index < active_index: + active_index -= 1 + session.active_index = min(active_index, len(session.pages) - 1) + if close_error is not None: + raise RuntimeError("关闭浏览器标签页失败") from close_error return BrowserSessionHelper.list_tabs(session) + @staticmethod + def get_cookies( + session: _BrowserSessionState, + page: Optional[BrowserPage] = None, + ) -> dict[str, Any]: + """读取活动页面所属域名的 Cookie、User-Agent 和页面地址。""" + active_page = page or session.active_page + current_url = getattr(active_page, "url", "") or "" + current_host = (urlparse(current_url).hostname or "").lower().rstrip(".") + values: dict[str, str] = {} + if session.cookies: + injected = cookie_parse(session.cookies) + if isinstance(injected, dict): + values.update({str(key): str(value) for key, value in injected.items()}) + + for cookie in session.context.cookies() or []: + if not isinstance(cookie, dict): + continue + name = cookie.get("name") + value = cookie.get("value") + if name is None or value is None: + continue + domain = str(cookie.get("domain") or "").lower().lstrip(".").rstrip(".") + if current_host and domain and current_host != domain and not current_host.endswith(f".{domain}"): + continue + values[str(name)] = str(value) + + user_agent = session.user_agent + if not user_agent: + try: + user_agent = str( + active_page.evaluate("() => window.navigator.userAgent") or "" + ) + except Exception: + user_agent = "" + cookie_header = "; ".join(f"{name}={value}" for name, value in values.items()) + return { + "url": current_url, + "user_agent": user_agent or "", + "cookie": cookie_header, + "cookies": [ + {"name": name, "value": value} + for name, value in values.items() + ], + } + def goto( self, page: BrowserPage, @@ -731,10 +831,14 @@ class BrowserSessionHelper: session_key: str, user_agent: Optional[str] = None, cookies: Optional[str] = None, + owner: Optional[Any] = None, ) -> _BrowserSessionState: """复用匹配会话,或为新的会话键创建上下文。""" + self._validate_owner(owner) with self._sessions_lock: session = self._sessions.get(session_key) + if session and session.owner is not owner: + raise PermissionError("浏览器会话不属于当前任务") if session and user_agent and session.user_agent != user_agent: self._sessions.pop(session_key, None) self._close_session_state(session) @@ -756,16 +860,26 @@ class BrowserSessionHelper: pages=[page], user_agent=user_agent, cookies=cookies, + owner=owner, ) with self._sessions_lock: existing_session = self._sessions.get(session_key) if existing_session: + if existing_session.owner is not owner: + self._close_session_state(session) + raise PermissionError("浏览器会话不属于当前任务") self._close_session_state(session) return existing_session self._sessions[session_key] = session self._enforce_session_limit(protect_session_key=session_key) return session + @staticmethod + def _validate_owner(owner: Optional[Any]) -> None: + """拒绝已封口作用域创建或复用浏览器会话。""" + if owner is not None and bool(getattr(owner, "closed", False)): + raise PermissionError("浏览器会话所属任务已停止") + @classmethod def _prune_sessions(cls) -> None: """关闭超过空闲时限的浏览器会话。""" @@ -777,7 +891,10 @@ class BrowserSessionHelper: if now - session.last_used_at > cls.SESSION_TTL_SECONDS ] for session_key in expired_keys: - cls.close_session(session_key) + with cls._sessions_lock: + session = cls._sessions.get(session_key) + owner = session.owner if session else None + cls.close_session(session_key, owner=owner) @classmethod def _enforce_session_limit(cls, protect_session_key: Optional[str] = None) -> None: @@ -801,7 +918,8 @@ class BrowserSessionHelper: candidate_keys, key=lambda key: cls._sessions[key].last_used_at, ) - if not cls.close_session(oldest_key): + oldest_owner = cls._sessions[oldest_key].owner + if not cls.close_session(oldest_key, owner=oldest_owner): return @staticmethod @@ -851,6 +969,8 @@ class BrowserSessionHelper: script = f""" () => {{ const limit = {int(max_elements)}; + document.querySelectorAll('[{cls.REF_ATTRIBUTE}]').forEach((el) => + el.removeAttribute('{cls.REF_ATTRIBUTE}')); const selector = [ 'a[href]', 'button', diff --git a/app/adapters/network/http.py b/app/adapters/network/http.py index deec5b1bd..4a87b6389 100644 --- a/app/adapters/network/http.py +++ b/app/adapters/network/http.py @@ -23,6 +23,7 @@ urllib3.disable_warnings(InsecureRequestWarning) # 业务模块只依赖网络适配器暴露的异常边界,不直接导入具体 transport。 HttpRequestError = requests.exceptions.RequestException +AsyncHttpRequestError = httpx2.RequestError _default_user_agent: Optional[str] = None diff --git a/app/adapters/system/backup/files.py b/app/adapters/system/backup/files.py index 6711251cf..cb3c23a45 100644 --- a/app/adapters/system/backup/files.py +++ b/app/adapters/system/backup/files.py @@ -11,7 +11,8 @@ from pathlib import Path from app.runtime.version import get_app_version _BACKUP_NAME = re.compile( - r"^(?:moviepilot_(?Pv\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)_)?" + r"^(?:(?P[0-9A-Za-z][0-9A-Za-z_-]*)" + r"(?:_(?Pv\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?))?_)?" r"(?Psqlite|postgresql)_" r"(?P\d{8}_\d{6})" r"(?:_(?P\d+))?" @@ -81,13 +82,24 @@ class BackupFiles: db_type: str, created_at: datetime, suffix: str, + target: str = "moviepilot", + version: str | None = None, ) -> str: - """生成包含数据库类型和秒级时间的简短可读文件名。""" + """生成包含目标、可选版本、数据库类型和时间的可读文件名。""" timestamp = created_at.strftime("%Y%m%d_%H%M%S") - version = get_app_version().strip() - if _RELEASE_VERSION.fullmatch(version) is None: - raise ValueError("程序版本号无法用于数据库备份命名") - base = f"moviepilot_{version}_{db_type}_{timestamp}" + if not re.fullmatch(r"[0-9A-Za-z][0-9A-Za-z_-]*", target): + raise ValueError("数据库备份目标或版本号无法用于文件命名") + normalized_version = version.strip() if version else None + if normalized_version is None and target == "moviepilot": + normalized_version = get_app_version().strip() + if normalized_version: + if not normalized_version.startswith("v"): + normalized_version = f"v{normalized_version}" + if _RELEASE_VERSION.fullmatch(normalized_version) is None: + raise ValueError("数据库备份目标或版本号无法用于文件命名") + base = f"{target}_{normalized_version}_{db_type}_{timestamp}" + else: + base = f"{target}_{db_type}_{timestamp}" candidate = f"{base}{suffix}" sequence = 1 while (self.root / candidate).exists(): @@ -102,6 +114,11 @@ class BackupFiles: """从受管文件名读取数据库类型。""" return BackupFiles._match(name).group("db_type") + @staticmethod + def target(name: str) -> str: + """从受管文件名读取备份目标,旧格式归属于 MoviePilot。""" + return BackupFiles._match(name).group("target") or "moviepilot" + @staticmethod def created_at(name: str) -> datetime: """从受管文件名读取本地创建时间。""" diff --git a/app/adapters/system/host.py b/app/adapters/system/host.py index d2d394a17..de574dfa1 100644 --- a/app/adapters/system/host.py +++ b/app/adapters/system/host.py @@ -561,7 +561,7 @@ class SystemUtils: if entry.is_file(follow_symlinks=False): entry_path = Path(entry.path) if (pattern.match(entry.name) and - (min_filesize <= 0 or entry.stat().st_size >= min_filesize * 1024 * 1024)): + (min_filesize <= 0 or entry.stat().st_size >= min_filesize * 1024 * 1024)): files.append(entry_path) elif entry.is_dir() and is_recursive: _scan_directory(Path(entry.path), is_recursive) @@ -688,7 +688,7 @@ class SystemUtils: if entry.is_file(follow_symlinks=False): # 检查文件是否符合条件 if (pattern.match(entry.name) and - (min_filesize <= 0 or entry.stat().st_size >= min_filesize * 1024 * 1024)): + (min_filesize <= 0 or entry.stat().st_size >= min_filesize * 1024 * 1024)): return True elif entry.is_dir() and is_recursive: # 递归搜索子目录 @@ -1108,9 +1108,9 @@ class SystemUtils: if result.returncode == 0: output = result.stdout.lower() return ( - 'nfs' in output - or 'smbfs' in output - or (include_local_fuse and 'fuse' in output) + 'nfs' in output + or 'smbfs' in output + or (include_local_fuse and 'fuse' in output) ) elif system == 'Windows': # Windows 检查网络驱动器 diff --git a/app/adapters/system/plugin/package.py b/app/adapters/system/plugin/package.py index 90d4730aa..b13ba50de 100644 --- a/app/adapters/system/plugin/package.py +++ b/app/adapters/system/plugin/package.py @@ -1,11 +1,11 @@ -"""插件包文件安装、快照恢复和分身处理适配器。""" +"""插件包文件安装和快照恢复适配器。""" from __future__ import annotations import asyncio +import errno import hashlib import io -import re import shutil import stat import uuid @@ -44,6 +44,25 @@ from app.runtime.settings import get_runtime_setting from app.runtime.version import get_app_version +class PluginContentSwapError(OSError): + """插件内容换入失败,并随异常携带运行目录的实际恢复结论。 + + 上层能观察到的只有运行目录还在不在,而被删到一半的运行目录同样"存在"; + 只凭存在与否判断就会把残骸当成完好的旧插件,进而把本次的临时备份当作多余 + 材料删掉,结果是安装报失败、运行目录却只剩半份旧文件且无处可取。因此把 + "运行目录是否仍是换入前那一份"由换入方作为事实上报,不让上层去猜。 + """ + + def __init__(self, cause: BaseException, *, runtime_intact: bool) -> None: + """按原始失败构造换入异常,并记录运行目录的恢复结论。 + + :param cause: 触发换入失败的原始异常,消息原样透传给上层展示 + :param runtime_intact: 运行目录是否仍是换入前那一份(未触碰或已回滚到位) + """ + super().__init__(str(cause)) + self.runtime_intact = runtime_intact + + class PluginPackageSourcePort(Protocol): """声明包 owner 读取市场元数据和远端制品所需的外部端口。""" @@ -447,32 +466,63 @@ class PluginPackageManager: existed: bool, label: str, ) -> None: - """用同级 staging 替换目录,失败时保留替换前的当前目录。""" + """用同级 staging 替换目录,并兼容 overlayfs 的跨设备替换。""" if existed and not snapshot.is_dir(): raise FileNotFoundError(f"{label}补偿快照不存在:{snapshot}") target.parent.mkdir(parents=True, exist_ok=True) staging = target.parent / f".{target.name}.restore-{uuid.uuid4().hex}" previous = target.parent / f".{target.name}.previous-{uuid.uuid4().hex}" + previous_available = False + published = False try: if existed: shutil.copytree(snapshot, staging) if target.exists(): - target.replace(previous) + try: + target.replace(previous) + except OSError as error: + if error.errno != errno.EXDEV: + raise + # overlayfs 可能拒绝把镜像层目录直接 rename 到可写层, + # 先复制旧目标保留回滚材料,再删除旧目录继续发布快照。 + if target.is_dir(): + shutil.copytree(target, previous, symlinks=True) + else: + shutil.copy2(target, previous, follow_symlinks=False) + previous_available = True + PluginPackageManager.__remove_snapshot_path(target) + else: + previous_available = True if existed: staging.replace(target) - if previous.exists(): - shutil.rmtree(previous) + published = True except Exception: - if not target.exists() and previous.exists(): - previous.replace(target) + if previous_available and not published: + try: + PluginPackageManager.__remove_snapshot_path(target) + previous.replace(target) + previous_available = False + except Exception as rollback_error: + logger.error( + f"恢复{label}旧目录失败,已保留恢复材料 {previous}: " + f"{rollback_error}" + ) raise finally: if staging.exists(): shutil.rmtree(staging, ignore_errors=True) - if target.exists() and previous.exists(): + if published and previous.exists(): shutil.rmtree(previous, ignore_errors=True) + @staticmethod + def __remove_snapshot_path(path: Path) -> None: + """删除待替换的当前路径,保留快照材料供失败回滚。""" + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + elif path.exists() or path.is_symlink(): + path.unlink() + @classmethod def stage_persistent_backup(cls, checkpoint: PluginPackageCheckpoint) -> None: """把新载荷复制到持久配置目录的独立 staging,不覆盖现有备份。""" @@ -912,8 +962,8 @@ class PluginPackageManager: logger.warning("记录插件原生依赖安装前状态失败:%s", error) def install_raw(self, pid: str, repo_url: str, package_version: Optional[str] = None, - release_version: Optional[str] = None, force_install: bool = False, - before_dependency_install: Optional[Callable[[], None]] = None) \ + release_version: Optional[str] = None, force_install: bool = False, + before_dependency_install: Optional[Callable[[], None]] = None) \ -> tuple[bool, str]: """执行已通过来源准入的同步包安装,不负责身份或运行态提交。""" if self.is_local_repo_url(repo_url): @@ -961,11 +1011,12 @@ class PluginPackageManager: release_tag = selection.release_tag if release_tag and not selection.fallback_to_filelist: - def prepare_selected_release() -> tuple[bool, str]: + def prepare_selected_release(staging_dir: Path) -> tuple[bool, str]: return self.__install_from_release( pid, selection.user_repo, release_tag, + staging_dir, ) return self.__install_flow_sync( @@ -978,20 +1029,24 @@ class PluginPackageManager: if release_tag: # 当前索引 Release 失败时回退文件列表,避免发布产物短暂滞后阻断安装。 - def prepare_release() -> tuple[bool, str]: + def prepare_release(staging_dir: Path) -> tuple[bool, str]: ok, msg = self.__install_from_release( pid, selection.user_repo, release_tag, + staging_dir, ) if ok: return True, msg logger.warning(f"{pid} Release 安装失败,回退文件列表安装:{msg}") - self.__remove_old_plugin(pid) + # 回退前只清理本次暂存的半份 Release 产物;已安装的运行目录 + # 此刻还没有被触碰,清理它会让一次可恢复的回退变成数据丢失。 + shutil.rmtree(staging_dir, ignore_errors=True) return self.__prepare_content_via_filelist_sync( pid, selection.user_repo, selection.package_version, + staging_dir, ) return self.__install_flow_sync( @@ -1002,11 +1057,13 @@ class PluginPackageManager: before_dependency_install, ) # 未声明 release 打包的插件继续使用文件列表方式安装。 - def prepare_filelist() -> tuple[bool, str]: + + def prepare_filelist(staging_dir: Path) -> tuple[bool, str]: return self.__prepare_content_via_filelist_sync( pid, selection.user_repo, selection.package_version, + staging_dir, ) return self.__install_flow_sync( @@ -1093,11 +1150,11 @@ class PluginPackageManager: except Exception: return False, "本地插件来源路径无效" - def prepare_local() -> tuple[bool, str]: + def prepare_local(staging_dir: Path) -> tuple[bool, str]: try: shutil.copytree( source_dir, - dest_dir, + staging_dir, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".DS_Store", "node_modules") ) @@ -1156,7 +1213,7 @@ class PluginPackageManager: return None, "插件源码目录不存在" elif res.status_code != 200: return None, f"连接仓库失败:{res.status_code} - " \ - f"{'超出速率限制,请设置Github Token或稍后重试' if res.status_code == 403 else res.reason}" + f"{'超出速率限制,请设置Github Token或稍后重试' if res.status_code == 403 else res.reason}" try: ret = res.json() @@ -1173,8 +1230,9 @@ class PluginPackageManager: pid: str, remote_path: object, package_version: Optional[str], + dest_root: Path, ) -> Path: - """把市场文件路径限定到当前插件目录,拒绝绝对路径和目录穿越。""" + """把市场文件路径限定到给定落盘根目录之内,拒绝绝对路径和目录穿越。""" if not isinstance(remote_path, str) or not remote_path or "\\" in remote_path: raise ValueError("插件文件路径无效") pure_path = PurePosixPath(remote_path) @@ -1189,24 +1247,30 @@ class PluginPackageManager: or any(part in {"", ".", ".."} for part in parts[2:]) ): raise ValueError("插件文件路径无效") - plugin_dir = (self._plugins_root() / pid.lower()).resolve() - file_path = (plugin_dir / Path(*parts[2:])).resolve() - if not file_path.is_relative_to(plugin_dir): + resolved_root = dest_root.resolve() + file_path = (resolved_root / Path(*parts[2:])).resolve() + if not file_path.is_relative_to(resolved_root): raise ValueError("插件文件路径无效") return file_path def __download_files(self, pid: str, file_list: list[dict[str, Any]], user_repo: str, - package_version: Optional[str] = None) -> tuple[bool, str]: + package_version: Optional[str] = None, + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 下载插件文件 :param pid: 插件 ID :param file_list: 要下载的文件列表,包含文件的元数据(包括下载链接) :param user_repo: GitHub 仓库的 user/repo 路径 + :param dest_root: 文件落盘的根目录,未指定时直接写入插件运行目录 :return: (是否成功, 错误信息) """ if not file_list: return False, "文件列表为空" + download_root = ( + dest_root if dest_root is not None + else self._plugins_root() / pid.lower() + ) # 使用栈结构来替代递归调用,避免递归深度过大问题 stack = [(pid, file_list)] @@ -1221,6 +1285,7 @@ class PluginPackageManager: pid, item.get("path"), package_version, + download_root, ) except ValueError as error: return False, str(error) @@ -1232,10 +1297,10 @@ class PluginPackageManager: elif res.status_code != 200: return False, f"下载文件 {item.get('path')} 失败:{res.status_code}" - # 创建插件文件夹并写入文件 + # GitHub 文件列表同时承载 Python 源码和 wheel 等二进制制品,统一按原始字节写入 file_path.parent.mkdir(parents=True, exist_ok=True) - with open(file_path, "w", encoding="utf-8") as f: - f.write(res.text) + with open(file_path, "wb") as f: + f.write(res.content) logger.debug(f"文件 {item.get('path')} 下载成功,保存路径:{file_path}") else: # 如果是子目录,则将子目录内容加入栈中继续处理 @@ -1384,65 +1449,221 @@ class PluginPackageManager: """读取远端插件元数据,并把异常收敛为空映射。""" try: plugins = ( - self.get_plugins(repo_url) if not package_version - else self.get_plugins(repo_url, package_version) - ) or {} + self.get_plugins(repo_url) if not package_version + else self.get_plugins(repo_url, package_version) + ) or {} meta = plugins.get(pid) return meta if isinstance(meta, dict) else {} except Exception as e: logger.error(f"获取插件 {pid} 元数据失败:{e}") return {} + def __new_install_staging_dir(self, pid: str) -> Path: + """分配一个全新的安装暂存目录,让新内容在触碰运行目录前先完整就位。""" + return ( + Path(get_runtime_setting('TEMP_PATH')) + / "plugin_install_staging" + / f"{pid.lower()}-{uuid.uuid4().hex}" + ) + + @staticmethod + def __swap_staged_plugin_content(staging_dir: Path, final_dir: Path) -> None: + """把已就位的暂存内容换入插件运行目录,失败时运行目录保持换入前的内容。 + + 手法与运行目录补偿替换一致(见 __restore_tree):先把旧目录改名挪到同级 + 隐藏位置留作回滚材料,再把暂存目录改名落位,确认落位后才删除旧目录。同一 + 文件系统内两次改名都是原子的,因此进程在任意时刻被杀,磁盘上要么是旧内容 + 要么是新内容,唯一的中间态是"运行目录短暂缺失、旧内容完整躺在 previous + 目录里",仍可人工恢复,不会出现任何一份内容被删到无处可取的时点。 + + 两个改名都可能因跨文件系统失败:overlayfs 会拒绝把镜像层的插件目录直接改 + 名到可写层,暂存目录又常落在独立的临时分区。两处都退化为复制,代价是复制 + 期间可能中途失败留下半份目录,因此复制失败一律先删掉半成品再把旧目录换 + 回;换回本身也失败时只记录旧目录的保留位置,原始失败原样挂在异常链上不被 + 吞掉,避免出现"看起来只是安装失败"实则运行目录已空的假象。 + + 旧目录退化为复制后还得逐个删掉原目录,这一步同样可能删到一半才失败。删除 + 一旦开始运行目录就不再完整,因此把"可回滚"状态提前到删除之前置位:只要运 + 行目录有被改动的可能就必须走回滚,绝不能因为删除没跑完就跳过回滚。回滚到 + 底有没有把旧内容放回,由抛出的异常如实上报,供上层决定要不要动用备份。 + + :param staging_dir: 已就位的待安装内容目录 + :param final_dir: 插件运行目录,可能已存在旧内容 + :raise PluginContentSwapError: 换入失败,异常携带运行目录的实际恢复结论 + """ + final_dir.parent.mkdir(parents=True, exist_ok=True) + previous = final_dir.parent / f".{final_dir.name}.previous-{uuid.uuid4().hex}" + previous_available = False + runtime_dirty = False + published = False + try: + if final_dir.exists(): + try: + final_dir.replace(previous) + except OSError as error: + if error.errno != errno.EXDEV: + raise + shutil.copytree(final_dir, previous, symlinks=True) + previous_available = True + # 删除从这一刻起就可能只删一半,先认账再动手 + runtime_dirty = True + PluginPackageManager.__remove_snapshot_path(final_dir) + else: + previous_available = True + # 旧内容已挪开或本来就不存在,此后才允许重建运行目录 + runtime_dirty = True + try: + staging_dir.replace(final_dir) + except OSError as error: + if error.errno != errno.EXDEV: + raise + logger.debug( + f"插件安装内容跨文件系统无法改名换入,退化为复制:{staging_dir}" + ) + shutil.copytree(staging_dir, final_dir, symlinks=True) + published = True + except Exception as error: + # 运行目录从未被触碰时无需回滚,它本身就还是换入前那一份 + runtime_intact = not runtime_dirty + if runtime_dirty and not published: + try: + PluginPackageManager.__remove_snapshot_path(final_dir) + if previous_available: + previous.replace(final_dir) + previous_available = False + runtime_intact = True + except Exception as rollback_error: + logger.error( + f"插件安装换入失败后恢复旧目录失败,已保留恢复材料 {previous}: " + f"{rollback_error}" + ) + raise PluginContentSwapError( + error, runtime_intact=runtime_intact + ) from error + finally: + if previous.exists() and (published or not previous_available): + shutil.rmtree(previous, ignore_errors=True) + + async def __async_swap_staged_plugin_content( + self, staging_dir: Path, final_dir: Path + ) -> None: + """在线程中执行换入,避免目录改名与复制阻塞事件循环,语义与同步换入一致。""" + await _await_thread_operation( + self.__swap_staged_plugin_content, staging_dir, final_dir + ) + + @staticmethod + def __swap_left_runtime_intact(error: OSError) -> bool: + """判断换入失败后运行目录是否确定仍是换入前那一份。 + + 只认换入方随异常带出的回滚结论:运行目录存在与否区分不了"完整旧内容"和 + "删到一半的残骸"。拿不到结论的异常按最坏情况处理,宁可多走一次备份兜底。 + + :param error: 换入阶段抛出的异常 + :return: 运行目录是否确定保持换入前内容 + """ + return isinstance(error, PluginContentSwapError) and error.runtime_intact + + def __recover_after_swap_failure( + self, pid: str, error: OSError, backup_dir: Optional[str] + ) -> None: + """换入失败后按实际回滚结论处置本次临时备份。 + + :param pid: 插件 ID + :param error: 换入阶段抛出的异常 + :param backup_dir: 本次安装前留下的临时备份目录,强制安装时为空 + """ + if self.__swap_left_runtime_intact(error): + if backup_dir: + shutil.rmtree(backup_dir, ignore_errors=True) + return + if backup_dir: + self.__restore_plugin(pid, backup_dir) + logger.warn(f"{pid} 插件安装失败,已还原备份插件") + return + logger.error( + f"{pid} 换入失败且运行目录未能恢复,本次未留临时备份," + f"请按上一条日志保留的恢复材料人工处理" + ) + + async def __async_recover_after_swap_failure( + self, pid: str, error: OSError, backup_dir: Optional[str] + ) -> None: + """异步流程的备份处置,判据与同步一致;备份清理由统一 finally 负责。 + + :param pid: 插件 ID + :param error: 换入阶段抛出的异常 + :param backup_dir: 本次安装前留下的临时备份目录,强制安装时为空 + """ + if self.__swap_left_runtime_intact(error): + return + if backup_dir: + await self.__async_restore_plugin(pid, backup_dir) + logger.warning(f"{pid} 插件安装失败,已还原备份插件") + return + logger.error( + f"{pid} 换入失败且运行目录未能恢复,本次未留临时备份," + f"请按上一条日志保留的恢复材料人工处理" + ) + def __install_flow_sync( self, pid: str, force_install: bool, - prepare_content: Callable[[], tuple[bool, str]], + prepare_content: Callable[[Path], tuple[bool, str]], repo_url: Optional[str] = None, before_dependency_install: Optional[Callable[[], None]] = None, ) -> tuple[bool, str]: """ - 同步安装统一流程:备份→清理→准备内容→安装依赖→上报 - prepare_content 负责把插件文件放到 app/plugins/{pid} + 同步安装统一流程:暂存内容→备份→换入→安装依赖→上报 + prepare_content 负责把插件文件放到调用时给定的暂存目录;只有新内容在暂存 + 目录里完整就位后才会触碰运行目录,因此下载或解压失败时已装插件原样保留。 """ - backup_dir = None - if not force_install: - backup_dir = self.__backup_plugin(pid) + plugin_dir = self.__plugin_dir(pid) + staging_dir = self.__new_install_staging_dir(pid) + try: + success, message = prepare_content(staging_dir) + if not success: + # 运行目录此刻尚未被触碰,已装插件天然完整,无需还原也无需清理 + logger.error(f"{pid} 准备插件内容失败:{message}") + return False, message - self.__remove_old_plugin(pid) + backup_dir = None + if not force_install: + backup_dir = self.__backup_plugin(pid) - success, message = prepare_content() - if not success: - logger.error(f"{pid} 准备插件内容失败:{message}") - if backup_dir: - self.__restore_plugin(pid, backup_dir) - logger.warn(f"{pid} 插件安装失败,已还原备份插件") - else: - self.__remove_old_plugin(pid) - logger.warn(f"{pid} 已清理对应插件目录,请尝试重新安装") - return False, message + try: + self.__swap_staged_plugin_content(staging_dir, plugin_dir) + except OSError as error: + message = f"写入插件内容失败:{error}" + logger.error(f"{pid} {message}") + self.__recover_after_swap_failure(pid, error, backup_dir) + return False, message - dependencies_exist, dep_ok, dep_msg = ( - self.__install_dependencies_if_required( - pid, - before_dependency_install, + dependencies_exist, dep_ok, dep_msg = ( + self.__install_dependencies_if_required( + pid, + before_dependency_install, + ) + if before_dependency_install is not None + else self.__install_dependencies_if_required(pid) ) - if before_dependency_install is not None - else self.__install_dependencies_if_required(pid) - ) - if dependencies_exist and not dep_ok: - logger.error(f"{pid} 依赖安装失败:{dep_msg}") - if backup_dir: - self.__restore_plugin(pid, backup_dir) - logger.warn(f"{pid} 插件安装失败,已还原备份插件") - else: - self.__remove_old_plugin(pid) - logger.warn(f"{pid} 已清理对应插件目录,请尝试重新安装") - return False, dep_msg + if dependencies_exist and not dep_ok: + logger.error(f"{pid} 依赖安装失败:{dep_msg}") + if backup_dir: + self.__restore_plugin(pid, backup_dir) + logger.warn(f"{pid} 插件安装失败,已还原备份插件") + else: + self.__remove_old_plugin(pid) + logger.warn(f"{pid} 已清理对应插件目录,请尝试重新安装") + return False, dep_msg - if backup_dir: - shutil.rmtree(backup_dir, ignore_errors=True) - return True, "" + if backup_dir: + shutil.rmtree(backup_dir, ignore_errors=True) + return True, "" + finally: + if staging_dir.exists(): + shutil.rmtree(staging_dir, ignore_errors=True) @staticmethod def __validate_release_zip_name(name: str) -> None: @@ -1533,11 +1754,12 @@ class PluginPackageManager: targets.append((info, dest_path, info.is_dir())) return targets - def __install_from_release(self, pid: str, user_repo: str, release_tag: str) -> tuple[bool, str]: + def __install_from_release(self, pid: str, user_repo: str, release_tag: str, + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 通过 GitHub Release 资产文件安装插件。 规范:release 中存在名为 "{pid}_v{version}.zip" 的资产,zip 根即插件文件; - 将其全部解压到 app/plugins/{pid} + 将其全部解压到 dest_root,未指定时直接解压到插件运行目录。 """ # 拼接资产文件名 asset_name = f"{release_tag.lower()}.zip" @@ -1583,7 +1805,10 @@ class PluginPackageManager: infos = zf.infolist() if not infos: return False, "压缩包内容为空" - dest_base = self._plugins_root() / pid.lower() + dest_base = ( + dest_root if dest_root is not None + else self._plugins_root() / pid.lower() + ) targets = self.__iter_release_zip_targets(zf, dest_base) wrote_any = False for info, dest_path, is_dir in targets: @@ -1625,7 +1850,7 @@ class PluginPackageManager: return None, "插件源码目录不存在" elif res.status_code != 200: return None, f"连接仓库失败:{res.status_code} - " \ - f"{'超出速率限制,请设置Github Token或稍后重试' if res.status_code == 403 else res.text}" + f"{'超出速率限制,请设置Github Token或稍后重试' if res.status_code == 403 else res.text}" try: ret = res.json() @@ -1638,17 +1863,23 @@ class PluginPackageManager: return None, "插件数据解析失败" async def __async_download_files(self, pid: str, file_list: list[dict[str, Any]], user_repo: str, - package_version: Optional[str] = None) -> tuple[bool, str]: + package_version: Optional[str] = None, + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 异步下载插件文件 :param pid: 插件 ID :param file_list: 要下载的文件列表,包含文件的元数据(包括下载链接) :param user_repo: GitHub 仓库的 user/repo 路径 + :param dest_root: 文件落盘的根目录,未指定时直接写入插件运行目录 :return: (是否成功, 错误信息) """ if not file_list: return False, "文件列表为空" + download_root = ( + dest_root if dest_root is not None + else self._plugins_root() / pid.lower() + ) # 使用栈结构来替代递归调用,避免递归深度过大问题 stack = [(pid, file_list)] @@ -1663,6 +1894,7 @@ class PluginPackageManager: pid, item.get("path"), package_version, + download_root, ) except ValueError as error: return False, str(error) @@ -1674,11 +1906,11 @@ class PluginPackageManager: elif res.status_code != 200: return False, f"下载文件 {item.get('path')} 失败:{res.status_code}" - # 创建插件文件夹并写入文件 + # GitHub 文件列表同时承载 Python 源码和 wheel 等二进制制品,统一按原始字节写入 file_path = AsyncPath(resolved_path) await file_path.parent.mkdir(parents=True, exist_ok=True) - async with aiofiles.open(file_path, "w", encoding="utf-8") as f: - await f.write(res.text) + async with aiofiles.open(file_path, "wb") as f: + await f.write(res.content) logger.debug(f"文件 {item.get('path')} 下载成功,保存路径:{file_path}") else: # 如果是子目录,则将子目录内容加入栈中继续处理 @@ -1861,11 +2093,12 @@ class PluginPackageManager: release_tag = selection.release_tag if release_tag and not selection.fallback_to_filelist: - async def prepare_selected_release() -> tuple[bool, str]: + async def prepare_selected_release(staging_dir: Path) -> tuple[bool, str]: return await self.__async_install_from_release( pid, selection.user_repo, release_tag, + staging_dir, ) return await self.__install_flow_async( @@ -1878,20 +2111,24 @@ class PluginPackageManager: if release_tag: # 当前索引 Release 失败时回退文件列表,保持同步与异步安装一致。 - async def prepare_release() -> tuple[bool, str]: + async def prepare_release(staging_dir: Path) -> tuple[bool, str]: ok, msg = await self.__async_install_from_release( pid, selection.user_repo, release_tag, + staging_dir, ) if ok: return True, msg logger.warning(f"{pid} Release 安装失败,回退文件列表安装:{msg}") - await self.__async_remove_old_plugin(pid) + # 回退前只清理本次暂存的半份 Release 产物;已安装的运行目录 + # 此刻还没有被触碰,清理它会让一次可恢复的回退变成数据丢失。 + await aioshutil.rmtree(staging_dir, ignore_errors=True) return await self.__prepare_content_via_filelist_async( pid, selection.user_repo, selection.package_version, + staging_dir, ) return await self.__install_flow_async( @@ -1902,11 +2139,13 @@ class PluginPackageManager: before_dependency_install, ) # 未声明 release 打包的插件继续使用文件列表方式安装。 - async def prepare_filelist() -> tuple[bool, str]: + + async def prepare_filelist(staging_dir: Path) -> tuple[bool, str]: return await self.__prepare_content_via_filelist_async( pid, selection.user_repo, selection.package_version, + staging_dir, ) return await self.__install_flow_async( @@ -1959,9 +2198,9 @@ class PluginPackageManager: """异步读取远端插件元数据,并把异常收敛为空映射。""" try: plugins = ( - await self.async_get_plugins(repo_url) if not package_version - else await self.async_get_plugins(repo_url, package_version) - ) or {} + await self.async_get_plugins(repo_url) if not package_version + else await self.async_get_plugins(repo_url, package_version) + ) or {} meta = plugins.get(pid) return meta if isinstance(meta, dict) else {} except Exception as e: @@ -1972,29 +2211,34 @@ class PluginPackageManager: self, pid: str, force_install: bool, - prepare_content: Callable[[], Awaitable[tuple[bool, str]]], + prepare_content: Callable[[Path], Awaitable[tuple[bool, str]]], repo_url: Optional[str] = None, before_dependency_install: Optional[Callable[[], None]] = None, ) -> tuple[bool, str]: """ - 异步安装流程,处理插件内容准备、依赖安装和注册 + 异步安装统一流程:暂存内容→备份→换入→安装依赖→上报 + prepare_content 负责把插件文件放到调用时给定的暂存目录;只有新内容在暂存 + 目录里完整就位后才会触碰运行目录,中断语义与同步流程一致。 """ + plugin_dir = self.__plugin_dir(pid) + staging_dir = self.__new_install_staging_dir(pid) backup_dir = None try: + success, message = await prepare_content(staging_dir) + if not success: + # 运行目录此刻尚未被触碰,已装插件天然完整,无需还原也无需清理 + logger.error(f"{pid} 准备插件内容失败:{message}") + return False, message + if not force_install: backup_dir = await self.__async_backup_plugin(pid) - await self.__async_remove_old_plugin(pid) - - success, message = await prepare_content() - if not success: - logger.error(f"{pid} 准备插件内容失败:{message}") - if backup_dir: - await self.__async_restore_plugin(pid, backup_dir) - logger.warning(f"{pid} 插件安装失败,已还原备份插件") - else: - await self.__async_remove_old_plugin(pid) - logger.warning(f"{pid} 已清理对应插件目录,请尝试重新安装") + try: + await self.__async_swap_staged_plugin_content(staging_dir, plugin_dir) + except OSError as error: + message = f"写入插件内容失败:{error}" + logger.error(f"{pid} {message}") + await self.__async_recover_after_swap_failure(pid, error, backup_dir) return False, message dependencies_exist, dep_ok, dep_msg = ( @@ -2024,11 +2268,15 @@ class PluginPackageManager: finally: if backup_dir: await aioshutil.rmtree(backup_dir, ignore_errors=True) + if await AsyncPath(staging_dir).exists(): + await aioshutil.rmtree(staging_dir, ignore_errors=True) def __prepare_content_via_filelist_sync(self, pid: str, user_repo: str, - package_version: Optional[str]) -> tuple[bool, str]: + package_version: Optional[str], + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 同步准备插件内容,通过文件列表获取插件文件和依赖 + :param dest_root: 文件落盘的根目录,未指定时直接写入插件运行目录 """ runtime_pid = pid.lower() file_list, msg = self.__get_file_list(runtime_pid, user_repo, package_version) @@ -2036,15 +2284,19 @@ class PluginPackageManager: if msg == "插件源码目录不存在": return False, f"{pid} {msg}" return False, msg or "插件文件列表读取失败" - ok, m = self.__download_files(runtime_pid, file_list, user_repo, package_version) + ok, m = self.__download_files( + runtime_pid, file_list, user_repo, package_version, dest_root + ) if not ok: return False, m return True, "" async def __prepare_content_via_filelist_async(self, pid: str, user_repo: str, - package_version: Optional[str]) -> tuple[bool, str]: + package_version: Optional[str], + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 异步准备插件内容,通过文件列表获取插件文件和依赖 + :param dest_root: 文件落盘的根目录,未指定时直接写入插件运行目录 """ runtime_pid = pid.lower() file_list, msg = await self.__async_get_file_list( @@ -2061,16 +2313,18 @@ class PluginPackageManager: file_list, user_repo, package_version, + dest_root, ) if not ok: return False, m return True, "" - async def __async_install_from_release(self, pid: str, user_repo: str, release_tag: str) -> tuple[bool, str]: + async def __async_install_from_release(self, pid: str, user_repo: str, release_tag: str, + dest_root: Optional[Path] = None) -> tuple[bool, str]: """ 通过 GitHub Release 资产文件安装插件(异步)。 规范:release 中存在名为 "{pid}_v{version}.zip" 的资产,zip 根即插件文件; - 将其全部解压到 app/plugins/{pid} + 将其全部解压到 dest_root,未指定时直接解压到插件运行目录。 """ # 拼接资产文件名 asset_name = f"{release_tag.lower()}.zip" @@ -2118,7 +2372,10 @@ class PluginPackageManager: infos = zf.infolist() if not infos: return False, "压缩包内容为空" - dest_base = self._plugins_root() / pid.lower() + dest_base = ( + dest_root if dest_root is not None + else self._plugins_root() / pid.lower() + ) targets = self.__iter_release_zip_targets(zf, dest_base) wrote_any = False for info, dest_path, is_dir in targets: @@ -2175,217 +2432,3 @@ class PluginPackageManager: exc_info=True, ) return False - - def clone( - self, - *, - plugin_id: str, - clone_id: str, - original_class_name: str, - suffix: str, - name: str, - description: str, - version: Optional[str] = None, - icon: Optional[str] = None, - ) -> tuple[bool, str]: - """复制并改写插件分身文件,任一步失败都删除不完整目标。""" - original_dir = self.__plugin_dir(plugin_id) - clone_dir = self.__plugin_dir(clone_id) - if not original_dir.is_dir(): - return False, f"原插件目录 {original_dir} 不存在" - if clone_dir.exists(): - return False, f"分身插件 {clone_id} 已存在" - - checkpoint = self.checkpoint(clone_id) - try: - shutil.copytree(original_dir, clone_dir) - success, message = self._modify_plugin_files( - plugin_dir=clone_dir, - original_class_name=original_class_name, - suffix=suffix, - name=name, - description=description, - version=version, - icon=icon, - ) - if not success: - self.rollback(checkpoint) - return False, message - self.commit(checkpoint) - logger.info(f"已复制插件目录:{original_dir} -> {clone_dir}") - return True, "文件修改成功" - except Exception as err: - try: - self.rollback(checkpoint) - except Exception as rollback_err: - logger.error( - f"清理插件分身 {clone_id} 失败:{rollback_err}", - exc_info=True, - ) - return False, f"创建插件分身文件失败:{err}" - - def _modify_plugin_files( - self, - *, - plugin_dir: Path, - original_class_name: str, - suffix: str, - name: str, - description: str, - version: Optional[str], - icon: Optional[str], - ) -> tuple[bool, str]: - """改写分身的 Python 元数据和联邦前端资源。""" - clone_class_name = f"{original_class_name}{suffix}" - init_file = plugin_dir / "__init__.py" - if init_file.exists(): - success, message = self._modify_python_file( - file_path=init_file, - original_class_name=original_class_name, - clone_class_name=clone_class_name, - name=name, - description=description, - version=version, - icon=icon, - ) - if not success: - return False, message - - dist_dir = plugin_dir / "dist" - if dist_dir.exists(): - success, message = self._modify_federation_files( - dist_dir=dist_dir, - original_class_name=original_class_name, - clone_class_name=clone_class_name, - ) - if not success: - return False, message - return True, "文件修改成功" - - @staticmethod - def _modify_python_file( - *, - file_path: Path, - original_class_name: str, - clone_class_name: str, - name: str, - description: str, - version: Optional[str], - icon: Optional[str], - ) -> tuple[bool, str]: - """改写插件主类名称、展示元数据和独立配置前缀。""" - try: - content = file_path.read_text(encoding="utf-8", errors="replace") - content = content.replace( - f"class {original_class_name}", - f"class {clone_class_name}", - ) - if name: - content = re.sub( - r'plugin_name\s*=\s*["\'][^"\']*["\']', - f'plugin_name = "{name}"', - content, - ) - if description: - content = re.sub( - r'plugin_desc\s*=\s*["\'][^"\']*["\']', - f'plugin_desc = "{description}"', - content, - ) - content = re.sub( - r'plugin_config_prefix\s*=\s*["\'][^"\']*["\']', - f'plugin_config_prefix = "{clone_class_name.lower()}_"', - content, - ) - if version: - content = re.sub( - r'plugin_version\s*=\s*["\'][^"\']*["\']', - f'plugin_version = "{version}"', - content, - ) - if icon and icon.strip(): - content = re.sub( - r'plugin_icon\s*=\s*["\'][^"\']*["\']', - f'plugin_icon = "{icon}"', - content, - ) - if "def init_plugin(self" in content: - init_index = content.index("def init_plugin(self") - content = ( - content[:init_index] - + "is_clone = True\n\n " - + content[init_index:] - ) - file_path.write_text(content, encoding="utf-8") - return True, "Python文件修改成功" - except Exception as err: - logger.error(f"修改Python文件失败:{err}") - return False, f"修改Python文件失败:{err}" - - def _modify_federation_files( - self, - *, - dist_dir: Path, - original_class_name: str, - clone_class_name: str, - ) -> tuple[bool, str]: - """改写联邦构建产物中的插件类名和样式命名空间。""" - try: - for file_path in dist_dir.rglob("*"): - if not file_path.is_file() or file_path.suffix not in {".js", ".css"}: - continue - try: - content = file_path.read_text(encoding="utf-8", errors="replace") - if file_path.suffix == ".js": - content = content.replace(original_class_name, clone_class_name) - content = content.replace( - f'"{original_class_name}"', - f'"{clone_class_name}"', - ) - content = content.replace( - f"'{original_class_name}'", - f"'{clone_class_name}'", - ) - content = content.replace( - f"css__{original_class_name}__", - f"css__{clone_class_name}__", - ) - content = content.replace( - original_class_name.lower(), - clone_class_name.lower(), - ) - file_path.write_text(content, encoding="utf-8") - except Exception as err: - logger.warning(f"修改联邦插件文件 {file_path} 失败:{err}") - self._rename_federation_assets( - dist_dir, - original_class_name, - clone_class_name, - ) - return True, "联邦插件文件修改完成" - except Exception as err: - logger.error(f"修改联邦插件文件失败:{err}") - return False, f"修改联邦插件文件失败:{err}" - - @staticmethod - def _rename_federation_assets( - dist_dir: Path, - original_class_name: str, - clone_class_name: str, - ) -> None: - """重命名包含原类名的顶层联邦资源,避免分身资源冲突。""" - try: - for file_path in dist_dir.glob("*"): - if not file_path.is_file(): - continue - if original_class_name.lower() not in file_path.name.lower(): - continue - new_name = file_path.name.replace( - original_class_name.lower(), - clone_class_name.lower(), - ) - new_path = file_path.parent / new_name - if not new_path.exists(): - file_path.rename(new_path) - except Exception as err: - logger.warning(f"重命名联邦插件资源文件失败:{err}") diff --git a/app/adapters/system/rust.py b/app/adapters/system/rust.py index fb7c856e9..8c69e749b 100644 --- a/app/adapters/system/rust.py +++ b/app/adapters/system/rust.py @@ -117,6 +117,7 @@ def is_debug_log_enabled() -> bool: return True return getattr(logging, log_settings.LOG_LEVEL.upper(), logging.INFO) <= logging.DEBUG + def parse_indexer_torrents( html_text: str, domain: str, diff --git a/app/adapters/system/update.py b/app/adapters/system/update.py index f816f7938..3f2b565fc 100644 --- a/app/adapters/system/update.py +++ b/app/adapters/system/update.py @@ -4,20 +4,24 @@ from __future__ import annotations import hashlib import json +import os import re +import shutil import stat import subprocess import threading import zipfile from datetime import datetime, timezone from pathlib import Path, PurePosixPath +from tempfile import TemporaryDirectory from typing import Any, cast from app.adapters.network.http import RequestUtils from app.adapters.system.resource import ResourceHelper, get_resource_versions -from app.foundation.environment import is_docker +from app.foundation.environment import is_docker, is_exe from app.foundation.singleton import SingletonClass from app.foundation.version import compare_version +from app.runtime.dependencies.profile import runtime_sync_arguments from app.runtime.log import logger from app.runtime.settings import get_runtime_setting from app.runtime.thread import ThreadHelper @@ -79,7 +83,7 @@ class SystemUpdateManager(metaclass=SingletonClass): @property def _install_file(self) -> Path: - """返回启动器消费的安装意图文件路径。""" + """返回 Docker root worker 或本地 CLI 消费的安装意图文件路径。""" return self._root / "install.json" @property @@ -97,6 +101,33 @@ class SystemUpdateManager(metaclass=SingletonClass): """返回站点资源包暂存目录。""" return self._root / "resources" + @property + def _docker_app_dir(self) -> Path: + """返回 Docker 当前后端源码目录。""" + return Path(get_runtime_setting("ROOT_PATH")) + + @property + def _docker_public_dir(self) -> Path: + """返回 Docker 当前前端静态文件目录。""" + return Path(get_runtime_setting("FRONTEND_PATH")) + + @property + def _docker_pending_file(self) -> Path: + """返回 Docker 载荷切换事务标记路径。""" + return Path(get_runtime_setting("TEMP_PATH")) / "__update_pending__" + + @property + def _docker_previous_app_dir(self) -> Path: + """返回 Docker 更新前后端源码备份目录。""" + app_dir = self._docker_app_dir + return app_dir.with_name(f"{app_dir.name}.__update_previous__") + + @property + def _docker_previous_public_dir(self) -> Path: + """返回 Docker 更新前前端静态文件备份目录。""" + public_dir = self._docker_public_dir + return public_dir.with_name(f"{public_dir.name}.__update_previous__") + @staticmethod def _now() -> str: """返回 UTC ISO 时间戳。""" @@ -204,12 +235,14 @@ class SystemUpdateManager(metaclass=SingletonClass): return next(item for item in state["updates"] if item["type"] == target) def _sync_aggregate(self, state: dict[str, Any]) -> dict[str, Any]: - """从两类明细重新计算旧版顶层字段和汇总进度。""" + """从两类明细重新计算旧版顶层字段、当前版本和汇总进度。""" application = self._get_item(state, _APPLICATION) + current_version = get_app_version() + application["current_version"] = current_version state.update( { "state": application.get("state", "idle"), - "current_version": get_app_version(), + "current_version": current_version, "version": application.get("version"), "frontend_version": application.get("frontend_version"), "release_name": application.get("release_name"), @@ -261,7 +294,7 @@ class SystemUpdateManager(metaclass=SingletonClass): return min(100, int(downloaded_value * 100 / total_value)) def get_status(self) -> SystemUpdateStatus: - """返回状态快照,并在新进程中收敛已完成的安装状态。""" + """收敛安装状态并返回快照;提醒开关实时读取,避免缓存绕过关闭设置。""" with self._lock: state = self._read_state() changed = False @@ -286,6 +319,15 @@ class SystemUpdateManager(metaclass=SingletonClass): elif item.get("state") == "installing" and self._is_install_applied(item, target): self._reset_item_after_install(item) changed = True + elif ( + target == _RESOURCES + and item.get("state") == "ready" + and self._is_install_applied(item, target) + ): + # 容器替换或手工安装可能先让运行资源达到目标版本,需丢弃残留待安装包。 + self._discard_prepared_target(target) + self._reset_item_after_install(item) + changed = True resources_changed = ( previous_auth_version != auth_version or previous_indexer_version != indexer_version @@ -294,6 +336,8 @@ class SystemUpdateManager(metaclass=SingletonClass): state = self._persist_state(self._sync_aggregate(state)) else: state = self._sync_aggregate(state) + state["auto_update"] = get_runtime_setting("MOVIEPILOT_AUTO_UPDATE") is True + state["auto_update_resource"] = get_runtime_setting("AUTO_UPDATE_RESOURCE") is True return cast(SystemUpdateStatus, SystemUpdateStatus.model_validate(state)) def _is_install_applied(self, item: dict[str, Any], target: SystemUpdateType) -> bool: @@ -334,6 +378,16 @@ class SystemUpdateManager(metaclass=SingletonClass): } ) + def check_scheduled(self) -> SystemUpdateStatus: + """按实时开关分别检查主程序和资源,避免热重载前的排队任务越过关闭设置。""" + for target, setting in ( + (_APPLICATION, "MOVIEPILOT_AUTO_UPDATE"), + (_RESOURCES, "AUTO_UPDATE_RESOURCE"), + ): + if get_runtime_setting(setting) is True: + self.check(target) + return self.get_status() + def check(self, target: SystemUpdateType | None = None) -> SystemUpdateStatus: """检查主程序和站点资源更新,定时检查失败只记录在对应明细中。""" targets = (target,) if target else _TARGETS @@ -495,10 +549,11 @@ class SystemUpdateManager(metaclass=SingletonClass): return self.get_status() def request_install(self, target: SystemUpdateType = _APPLICATION) -> tuple[bool, str]: - """校验指定待安装制品,并写入启动阶段消费的安装意图。""" + """校验指定待安装制品,并写入 Docker worker 消费的安装意图。""" if target not in _TARGETS: return False, f"未知升级类型:{target}" with self._lock: + temporary: Path | None = None state = self.get_status() item = self._get_item(state.model_dump(), target) if item["state"] != "ready": @@ -506,7 +561,8 @@ class SystemUpdateManager(metaclass=SingletonClass): try: prepared = self._read_prepared_manifest() if target == _APPLICATION: - self._validate_application_manifest(prepared) + if not is_exe(): + self._validate_application_manifest(prepared) message = "主程序更新包已就绪,正在重启安装" else: self._validate_resource_manifest(prepared) @@ -520,15 +576,524 @@ class SystemUpdateManager(metaclass=SingletonClass): if target not in targets: targets.append(target) prepared["targets"] = targets - self._install_file.write_text( + self._install_file.parent.mkdir(parents=True, exist_ok=True) + temporary = self._install_file.with_suffix(f".tmp.{os.getpid()}") + temporary.write_text( json.dumps(prepared, ensure_ascii=False, indent=2), encoding="utf-8" ) + temporary.replace(self._install_file) self._write_item(target, state="installing", can_install=False, error=None) return True, message except (OSError, RuntimeError, json.JSONDecodeError) as error: + if temporary is not None: + temporary.unlink(missing_ok=True) self._write_item(target, state="failed", error=str(error), can_install=False) return False, str(error) + def apply_prepared_update(self) -> tuple[bool, str]: + """由 Docker root 更新 worker 将已确认制品替换到当前运行目录。""" + if not is_docker(): + return False, "当前运行环境不是 Docker" + + targets: set[SystemUpdateType] = set() + with self._lock: + try: + prepared = self._read_install_manifest() + targets = self._prepared_targets(prepared) + if not targets: + raise RuntimeError("更新清单缺少可安装目标") + if _APPLICATION in targets: + self._validate_application_manifest(prepared) + version = str(prepared.get("version") or "") + frontend_version = str(prepared.get("frontend_version") or "") + if self._validate_backend_archive(version) != frontend_version: + raise RuntimeError("后端更新包声明的前端版本不匹配") + self._validate_frontend_archive(frontend_version) + if _RESOURCES in targets: + self._validate_resource_manifest(prepared) + + if _APPLICATION in targets: + self._apply_docker_application( + prepared, + include_resources=_RESOURCES in targets, + ) + elif _RESOURCES in targets: + self._apply_docker_resources(prepared) + + try: + for target in (_APPLICATION, _RESOURCES): + if target in targets: + self._consume_prepared_target(target) + except (OSError, RuntimeError, ValueError) as error: + # 载荷已经替换成功,清单清理失败不能阻止 worker 通知入口重启。 + logger.warning(f"更新载荷已替换,但清理下载清单失败:{error}") + try: + self._install_file.unlink(missing_ok=True) + except OSError as error: + logger.warning(f"清理 Docker 更新安装清单失败:{error}") + return True, "已下载的更新已替换到 Docker 程序目录" + except (OSError, RuntimeError, ValueError, zipfile.BadZipFile) as error: + message = f"Docker 更新包替换失败:{error}" + self._mark_install_failed(targets, message) + logger.error(message) + return False, message + + def _read_install_manifest(self) -> dict[str, Any]: + """读取必须存在的 Docker 更新安装清单。""" + payload = json.loads(self._install_file.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + raise RuntimeError("更新安装清单格式无效") + return payload + + @staticmethod + def _prepared_targets(prepared: dict[str, Any]) -> set[SystemUpdateType]: + """解析更新清单中的主程序和站点资源安装目标。""" + raw_targets = prepared.get("targets") + if raw_targets is not None and not isinstance(raw_targets, list): + raise RuntimeError("更新清单目标格式无效") + if isinstance(raw_targets, list) and any( + not isinstance(target, str) or target not in _TARGETS + for target in raw_targets + ): + raise RuntimeError("更新清单包含未知安装目标") + targets = { + cast(SystemUpdateType, target) + for target in raw_targets or [] + } + if not targets and prepared.get("backend_archive"): + targets.add(_APPLICATION) + return targets + + def _mark_install_failed( + self, targets: set[SystemUpdateType], message: str + ) -> None: + """记录 Docker 更新失败并撤销本次安装意图,保留下载包供重试。""" + try: + self._install_file.unlink(missing_ok=True) + except OSError as error: + logger.warning(f"清理 Docker 更新安装清单失败:{error}") + if not targets: + try: + state = self._read_state() + targets = { + cast(SystemUpdateType, item["type"]) + for item in state.get("updates", []) + if item.get("state") == "installing" and item.get("type") in _TARGETS + } + except Exception as error: # noqa: BLE001 失败路径只记录,不能遮蔽原始错误 + logger.warning(f"读取待安装更新状态失败:{error}") + for target in targets: + try: + self._write_item( + target, + state="failed", + error=message, + can_update=True, + can_install=False, + ) + except Exception as error: # noqa: BLE001 失败路径不得遮蔽原始安装错误 + logger.error(f"记录 {target} 更新失败状态失败:{error}") + + def _consume_prepared_target(self, target: SystemUpdateType) -> None: + """从持久化下载清单移除已替换目标,保留另一类下载制品。""" + prepared = self._read_prepared_manifest_optional() + if target == _APPLICATION: + for key in ( + "version", + "frontend_version", + "backend_archive", + "frontend_archive", + "backend_sha256", + "frontend_sha256", + ): + prepared.pop(key, None) + elif target == _RESOURCES: + for key in ("resource_package_version", "resource_files"): + prepared.pop(key, None) + else: + raise ValueError(f"未知升级类型:{target}") + + targets = [ + value + for value in prepared.get("targets", []) + if value in _TARGETS and value != target + ] + if targets: + prepared["targets"] = targets + else: + prepared.pop("targets", None) + + prepared_file = self._root / "prepared.json" + if prepared.get("backend_archive") or prepared.get("resource_files"): + temporary = prepared_file.with_suffix(f".tmp.{os.getpid()}") + temporary.write_text( + json.dumps(prepared, ensure_ascii=False, indent=2), encoding="utf-8" + ) + temporary.replace(prepared_file) + else: + prepared_file.unlink(missing_ok=True) + + def _set_docker_pending(self, state: str) -> None: + """原子写入 Docker 载荷切换状态,供入口脚本在异常重启时恢复。""" + self._docker_pending_file.parent.mkdir(parents=True, exist_ok=True) + temporary = self._docker_pending_file.with_suffix(f".tmp.{os.getpid()}") + temporary.write_text(f"{state}\n", encoding="utf-8") + temporary.replace(self._docker_pending_file) + + def _clear_docker_pending(self) -> None: + """清除已经提交完成的 Docker 载荷切换状态。""" + self._docker_pending_file.unlink(missing_ok=True) + + @staticmethod + def _setting_text(key: str, default: str = "") -> str: + """读取更新 worker 所需的运行配置,并兼容独立 root 子进程环境。""" + try: + value = get_runtime_setting(key) + except AttributeError: + value = None + return str(value or os.getenv(key, default) or default).strip() + + def _sync_docker_dependencies(self, project_dir: Path, *, force: bool = False) -> bool: + """按新后端清单同步 Docker 共享虚拟环境依赖。""" + current_dir = self._docker_app_dir + if not force and all( + (current_dir / name).read_bytes() == (project_dir / name).read_bytes() + for name in ("pyproject.toml", "uv.lock") + ): + return False + + venv_path = self._setting_text("VENV_PATH", "/opt/venv") + uv_bin = self._setting_text("UV_BIN", "/usr/local/bin/uv") + command = [ + uv_bin, + "sync", + "--project", + str(project_dir), + "--locked", + "--inexact", + "--no-dev", + "--no-install-project", + "--python", + f"{venv_path}/bin/python3", + *runtime_sync_arguments(), + ] + package_index = self._setting_text("PIP_PROXY") + if package_index: + command.extend(("--default-index", package_index)) + environment = os.environ.copy() + proxy = self._setting_text("PROXY_HOST") + if proxy: + for key in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"): + environment[key] = proxy + environment.update( + { + "UV_PROJECT_ENVIRONMENT": venv_path, + "UV_LINK_MODE": "copy", + } + ) + try: + result = subprocess.run( + command, + cwd=str(project_dir), + env=environment, + capture_output=True, + text=True, + check=False, + ) + except OSError as error: + raise RuntimeError(f"依赖同步执行失败:{error}") from error + if result.returncode != 0: + raise RuntimeError(f"依赖同步失败,退出码:{result.returncode}") + return True + + def _extract_backend_archive(self, archive_path: Path, destination: Path) -> Path: + """安全解压后端 Release,并返回唯一的源码根目录。""" + with zipfile.ZipFile(archive_path) as archive: + self._validate_zip_members(archive) + roots = { + PurePosixPath(name).parts[0] + for name in archive.namelist() + if PurePosixPath(name).parts + } + if len(roots) != 1: + raise RuntimeError("后端更新包源码根目录无效") + archive.extractall(destination) + source_root = destination / next(iter(roots)) + if not source_root.is_dir(): + raise RuntimeError("后端更新包源码目录不存在") + return source_root + + def _extract_frontend_archive(self, archive_path: Path, destination: Path) -> Path: + """安全解压前端 dist.zip,并返回静态文件目录。""" + with zipfile.ZipFile(archive_path) as archive: + self._validate_zip_members(archive) + archive.extractall(destination) + frontend_dir = destination / "dist" + if not frontend_dir.is_dir(): + raise RuntimeError("前端更新包缺少 dist 目录") + return frontend_dir + + @staticmethod + def _remove_path(path: Path) -> None: + """删除 Docker 更新事务中的文件或目录。""" + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(path) + elif path.exists() or path.is_symlink(): + path.unlink() + + @staticmethod + def _preserve_tree_ownership(source: Path, destination: Path) -> None: + """复制运行时目录后恢复原目录的所有者,避免插件变成 root 不可写。""" + source_paths = (source, *source.rglob("*")) + for source_path in source_paths: + destination_path = destination / source_path.relative_to(source) + source_stat = source_path.lstat() + os.chown( + destination_path, + source_stat.st_uid, + source_stat.st_gid, + follow_symlinks=False, + ) + + def _copy_plugin_runtime_payload(self, source: Path, destination: Path) -> None: + """ + 迁移插件运行时内容,但保留新版宿主的包根入口。 + + ``app/plugins/__init__.py`` 属于后端源码提供的兼容入口,不属于持久化插件; + 旧版本该文件包含宿主实现,随插件目录迁移会遮蔽新版 SDK 的兼容符号。 + """ + destination.mkdir(parents=True, exist_ok=True) + for destination_path in destination.iterdir(): + if destination_path.name != "__init__.py": + self._remove_path(destination_path) + + for source_path in source.iterdir(): + if source_path.name == "__init__.py": + continue + destination_path = destination / source_path.name + if source_path.is_dir() and not source_path.is_symlink(): + shutil.copytree(source_path, destination_path, symlinks=True) + else: + shutil.copy2(source_path, destination_path, follow_symlinks=False) + self._preserve_tree_ownership(source_path, destination_path) + + @staticmethod + def _clear_staged_native_resources(resource_dir: Path) -> None: + """清除暂存目录中的旧平台原生站点资源。""" + if not resource_dir.is_dir(): + return + for path in resource_dir.iterdir(): + if path.is_file() and path.name.startswith("sites.") and path.suffix in { + ".so", + ".pyd", + ".dylib", + }: + path.unlink() + + def _resource_source_dir(self, app_dir: Path) -> Path: + """定位当前后端携带的站点资源目录,并兼容历史目录。""" + resource_dir = app_dir / "app" / "application" / "site" + for legacy_dir in ( + app_dir / "app" / "infrastructure", + app_dir / "app" / "adapters" / "network", + app_dir / "app" / "helper", + ): + if not resource_dir.is_dir() and legacy_dir.is_dir(): + resource_dir = legacy_dir + return resource_dir + + @staticmethod + def _is_site_runtime_resource(path: Path) -> bool: + """判断文件是否属于需要跨 Docker 应用升级继承的站点运行时资源。""" + return path.is_file() and ( + (path.name.startswith("user.sites.") and path.suffix == ".bin") + or ( + path.name.startswith("sites.") + and path.suffix in {".so", ".pyd", ".dylib"} + ) + ) + + def _copy_site_runtime_resources( + self, source_dir: Path, destination_dir: Path + ) -> None: + """只把旧版本的站点索引和原生资源叠加到新版源码目录。""" + if not source_dir.is_dir(): + return + destination_dir.mkdir(parents=True, exist_ok=True) + for path in source_dir.iterdir(): + if self._is_site_runtime_resource(path): + shutil.copy2(path, destination_dir / path.name) + + def _copy_prepared_resources( + self, prepared: dict[str, Any], resource_dir: Path + ) -> None: + """把已校验的完整站点资源包复制到指定源码目录。""" + self._clear_staged_native_resources(resource_dir) + for item in prepared.get("resource_files", []): + name = Path(str(item.get("name") or "")) + if name.name != str(name): + raise RuntimeError("站点资源文件名不安全") + shutil.copy2(str(item["path"]), resource_dir / name) + + def _prepare_docker_application( + self, + prepared: dict[str, Any], + temporary_root: Path, + *, + include_resources: bool, + ) -> tuple[Path, Path]: + """ + 解压并组装待切换的 Docker 后端、前端和插件资源载荷。 + + 新版本归档是 Python 源码的唯一来源,旧版本目录只迁移插件和站点运行时内容, + 不覆盖新版的插件包根兼容入口或新增应用模块。 + """ + backend_extract = temporary_root / "backend" + frontend_extract = temporary_root / "frontend" + backend_extract.mkdir() + frontend_extract.mkdir() + source_app = self._extract_backend_archive( + Path(str(prepared["backend_archive"])), backend_extract + ) + source_public = self._extract_frontend_archive( + Path(str(prepared["frontend_archive"])), frontend_extract + ) + stage_app = temporary_root / "App" + stage_public = temporary_root / "public" + source_app.replace(stage_app) + source_public.replace(stage_public) + + current_app = self._docker_app_dir + current_plugins = current_app / "app" / "plugins" + stage_plugins = stage_app / "app" / "plugins" + if stage_plugins.is_symlink(): + self._remove_path(stage_plugins) + if stage_plugins.exists() and not stage_plugins.is_dir(): + raise RuntimeError("插件运行目录不是目录") + stage_plugins.mkdir(parents=True, exist_ok=True) + if current_plugins.is_dir(): + self._copy_plugin_runtime_payload(current_plugins, stage_plugins) + if not (stage_plugins / "__init__.py").is_file(): + raise RuntimeError("插件运行目录缺少 app.plugins 兼容入口") + + stage_resources = stage_app / "app" / "application" / "site" + current_resources = self._resource_source_dir(current_app) + self._copy_site_runtime_resources(current_resources, stage_resources) + if include_resources: + self._copy_prepared_resources(prepared, stage_resources) + return stage_app, stage_public + + def _restore_docker_payload(self) -> None: + """在 Docker 载荷切换失败时恢复更新前的源码和前端目录。""" + for current, previous in ( + (self._docker_app_dir, self._docker_previous_app_dir), + (self._docker_public_dir, self._docker_previous_public_dir), + ): + if not previous.exists(): + continue + if current.exists() or current.is_symlink(): + self._remove_path(current) + previous.replace(current) + + def _apply_docker_application( + self, prepared: dict[str, Any], *, include_resources: bool + ) -> None: + """原子替换 Docker 后端源码和前端静态目录,并同步依赖。""" + app_dir = self._docker_app_dir + public_dir = self._docker_public_dir + previous_app = self._docker_previous_app_dir + previous_public = self._docker_previous_public_dir + if not app_dir.is_dir() or not public_dir.is_dir(): + raise RuntimeError("Docker 当前程序目录不完整") + if previous_app.exists() or previous_public.exists(): + raise RuntimeError("存在未完成的 Docker 更新事务") + + with TemporaryDirectory(prefix=".moviepilot-update-", dir=str(app_dir.parent)) as temp: + temporary_root = Path(temp) + stage_app, stage_public = self._prepare_docker_application( + prepared, + temporary_root, + include_resources=include_resources, + ) + dependencies_changed = any( + (app_dir / name).read_bytes() != (stage_app / name).read_bytes() + for name in ("pyproject.toml", "uv.lock") + ) + dependency_sync_started = False + self._set_docker_pending("prepared") + try: + if dependencies_changed: + self._set_docker_pending("dependencies") + dependency_sync_started = True + self._sync_docker_dependencies(stage_app) + self._set_docker_pending("prepared") + app_dir.replace(previous_app) + try: + public_dir.replace(previous_public) + stage_app.replace(app_dir) + stage_public.replace(public_dir) + except OSError: + self._restore_docker_payload() + raise + self._set_docker_pending("committed") + except Exception: + rollback_failed = False + try: + self._restore_docker_payload() + except OSError as error: + logger.error(f"Docker 更新回滚失败:{error}") + rollback_failed = True + if dependency_sync_started: + try: + self._set_docker_pending("dependencies") + self._sync_docker_dependencies(app_dir, force=True) + except (OSError, RuntimeError) as error: + logger.error(f"Docker 更新依赖回滚失败:{error}") + rollback_failed = True + if rollback_failed: + raise + try: + self._clear_docker_pending() + except OSError as error: + logger.error(f"清理 Docker 更新事务标记失败:{error}") + raise + raise + + try: + self._remove_path(previous_app) + self._remove_path(previous_public) + self._clear_docker_pending() + except OSError as error: + logger.warning(f"Docker 更新已完成但旧载荷清理失败:{error}") + + def _apply_docker_resources(self, prepared: dict[str, Any]) -> None: + """备份并替换 Docker 站点资源,失败时恢复旧目录。""" + resource_dir = self._resource_source_dir(self._docker_app_dir) + resource_dir.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory( + prefix=".moviepilot-resource-update-", dir=str(resource_dir.parent) + ) as temp: + stage_dir = Path(temp) / "site" + if resource_dir.is_dir(): + shutil.copytree(resource_dir, stage_dir, symlinks=True) + else: + stage_dir.mkdir() + self._copy_prepared_resources(prepared, stage_dir) + backup_dir = resource_dir.with_name(f"{resource_dir.name}.__prepared_previous__") + self._remove_path(backup_dir) + if resource_dir.exists() or resource_dir.is_symlink(): + # OverlayFS 下镜像层目录不能直接重命名,先复制完整备份再移除。 + shutil.copytree(resource_dir, backup_dir, symlinks=True) + try: + self._remove_path(resource_dir) + stage_dir.replace(resource_dir) + except OSError: + if backup_dir.exists(): + self._remove_path(resource_dir) + backup_dir.replace(resource_dir) + raise + self._remove_path(backup_dir) + def cancel_install(self, reason: str) -> None: """重启请求失败时撤销全部已选安装意图,避免下次普通启动意外安装。""" with self._lock: @@ -557,7 +1122,10 @@ class SystemUpdateManager(metaclass=SingletonClass): """在后台线程中下载并校验指定升级类型的制品。""" try: if target == _APPLICATION: - self._download_application() + if is_exe(): + self._simulate_application_download() + else: + self._download_application() else: self._download_resources() except Exception as error: # noqa: BLE001 后台线程必须沉淀为可查询失败 @@ -568,6 +1136,35 @@ class SystemUpdateManager(metaclass=SingletonClass): self._download_active = False self._active_target = None + def _simulate_application_download(self) -> None: + """exe 部署下模拟主程序下载,直接写入准备清单并反馈完成。""" + if get_runtime_setting("MOVIEPILOT_AUTO_UPDATE") is not True: + raise RuntimeError("请先在高级设置里启用自动检查版本更新") + target_item = self._get_item(self._read_state(), _APPLICATION) + version = str(target_item.get("version") or "") + if not version: + raise RuntimeError("主程序更新缺少目标版本") + self._merge_prepared_manifest( + { + "version": version, + "frontend_version": version, + "backend_archive": str(self._backend_archive), + "frontend_archive": str(self._frontend_archive), + "backend_sha256": "", + "frontend_sha256": "", + "prepared_at": self._now(), + }, + ) + self._write_item( + _APPLICATION, + state="ready", + downloaded_bytes=100, + total_bytes=100, + error=None, + can_update=False, + can_install=True, + ) + def _download_application(self) -> None: """下载后端 Release 和其 version.py 声明的前端 dist.zip。""" target = self._get_item(self._read_state(), _APPLICATION) @@ -762,6 +1359,12 @@ class SystemUpdateManager(metaclass=SingletonClass): frontend_archive = Path(str(prepared.get("frontend_archive") or "")) if not prepared.get("version") or not prepared.get("frontend_version"): raise RuntimeError("主程序更新清单缺少版本信息") + for archive, expected in ( + (backend_archive, self._backend_archive), + (frontend_archive, self._frontend_archive), + ): + if archive.resolve() != expected.resolve(): + raise RuntimeError("主程序更新包路径不安全") if not backend_archive.is_file() or self._sha256(backend_archive) != prepared.get("backend_sha256"): raise RuntimeError("后端更新包校验失败") if not frontend_archive.is_file() or self._sha256(frontend_archive) != prepared.get("frontend_sha256"): @@ -776,7 +1379,7 @@ class SystemUpdateManager(metaclass=SingletonClass): actual_names = { str(item.get("name") or "") for item in files if isinstance(item, dict) } - if actual_names != expected_names: + if len(files) != len(expected_names) or actual_names != expected_names: raise RuntimeError("站点资源更新清单不是当前平台的完整资源包") root = self._root.resolve() for item in files: @@ -791,20 +1394,27 @@ class SystemUpdateManager(metaclass=SingletonClass): raise RuntimeError(f"站点资源文件校验失败:{item.get('name')}") def _request(self) -> RequestUtils: - """创建访问 GitHub Release 的请求客户端。""" + """创建访问 GitHub Release API 的认证请求客户端。""" return RequestUtils( proxies=get_runtime_setting("PROXY"), headers=get_runtime_setting("GITHUB_HEADERS"), timeout=60, ) + def _download_request(self) -> RequestUtils: + """创建公开 GitHub 归档下载客户端,避免认证头传递到 codeload。""" + return RequestUtils( + proxies=get_runtime_setting("PROXY"), + timeout=60, + ) + def _download_file( self, url: str, destination: Path, downloaded_before: int, total_hint: int ) -> tuple[int, int]: - """流式下载文件并把进度写入当前升级类型。""" + """使用公开下载客户端流式下载文件并把进度写入当前升级类型。""" temporary = destination.with_suffix(".part") temporary.unlink(missing_ok=True) - with self._request().get_stream(url) as response: + with self._download_request().get_stream(url) as response: if response is None or response.status_code != 200: raise RuntimeError( f"下载更新包失败:HTTP {getattr(response, 'status_code', '无响应')}" diff --git a/app/agent/api/arguments.py b/app/agent/api/arguments.py new file mode 100644 index 000000000..56e78551f --- /dev/null +++ b/app/agent/api/arguments.py @@ -0,0 +1,239 @@ +"""按已生成的 API 输入合同规范实际请求,使相同写入使用稳定参数身份。""" + +from copy import deepcopy +from typing import Any + +from pydantic import TypeAdapter, ValidationError + +from app.agent.policy.api import resolve_api_route + +_SCALAR_ADAPTERS = { + "boolean": TypeAdapter(bool), + "integer": TypeAdapter(int), + "number": TypeAdapter(float), + "string": TypeAdapter(str), +} +_MISSING = object() +_CONTRACT_DESCRIPTION_MAX_CHARS = 180 + + +def _resolve_schema(schema: dict[str, Any], definitions: dict[str, Any]) -> dict[str, Any]: + """只展开缓存合同的本地引用,拒绝循环引用和任何远程 schema。""" + seen = set() + while "$ref" in schema: + reference = schema["$ref"] + if not isinstance(reference, str) or not reference.startswith("#/$defs/") or reference in seen: + raise ValueError("API 参数合同引用无效") + seen.add(reference) + name = reference.removeprefix("#/$defs/").replace("~1", "/").replace("~0", "~") + target = definitions.get(name) + if not isinstance(target, dict): + raise ValueError("API 参数合同引用缺失") + schema = {**target, **{key: value for key, value in schema.items() if key != "$ref"}} + return schema + + +def _contract_description(value: Any) -> str | None: + """为错误回执保留有界字段说明,避免把原始请求值带回模型。""" + if not isinstance(value, str) or not value.strip(): + return None + text = " ".join(value.split()) + if len(text) <= _CONTRACT_DESCRIPTION_MAX_CHARS: + return text + return text[: _CONTRACT_DESCRIPTION_MAX_CHARS - 1].rstrip() + "…" + + +def _contract_node( + schema: dict[str, Any], + definitions: dict[str, Any], + *, + depth: int = 0, +) -> dict[str, Any]: + """把单个 JSON Schema 节点压缩成可直接纠错的输入提示。""" + try: + resolved = _resolve_schema(schema, definitions) + except ValueError: + return {"type": "unknown"} + + result: dict[str, Any] = {} + description = _contract_description(resolved.get("description")) + if description: + result["description"] = description + if "const" in resolved: + result["const"] = resolved["const"] + if isinstance(resolved.get("enum"), list): + result["enum"] = deepcopy(resolved["enum"]) + if "default" in resolved: + result["default"] = deepcopy(resolved["default"]) + if isinstance(resolved.get("type"), str): + result["type"] = resolved["type"] + for key in ("minimum", "maximum", "minItems", "maxItems", "minLength", "maxLength"): + if key in resolved: + result[key] = resolved[key] + + alternatives = resolved.get("oneOf", resolved.get("anyOf")) + if isinstance(alternatives, list): + result["one_of"] = [ + _contract_node(item, definitions, depth=depth + 1) + for item in alternatives + if isinstance(item, dict) + ] + + properties = resolved.get("properties") + if isinstance(properties, dict): + required = resolved.get("required") + if isinstance(required, list) and required: + result["required"] = [item for item in required if isinstance(item, str)] + if depth < 4: + result["fields"] = { + name: _contract_node(value, definitions, depth=depth + 1) + for name, value in properties.items() + if isinstance(name, str) and isinstance(value, dict) + } + else: + result["fields"] = sorted(name for name in properties if isinstance(name, str)) + if resolved.get("additionalProperties") is False: + result["additional_properties"] = False + elif isinstance(resolved.get("items"), dict) and depth < 4: + result["items"] = _contract_node(resolved["items"], definitions, depth=depth + 1) + return result + + +def api_input_contract(operation_id: str, schema: dict[str, Any]) -> dict[str, Any]: + """返回一个 operation 的有界输入合同,供调用失败时指导模型纠正参数。""" + branch = next( + ( + item + for item in schema.get("oneOf", []) + if isinstance(item, dict) + and item.get("properties", {}).get("operation_id", {}).get("const") == operation_id + ), + None, + ) + if not isinstance(branch, dict): + return {"operation_id": operation_id, "available": False} + properties = branch.get("properties", {}) + contract: dict[str, Any] = { + "operation_id": operation_id, + "allowed_arguments": [ + name for name in properties if isinstance(name, str) and name != "operation_id" + ], + } + required = branch.get("required") + if isinstance(required, list): + contract["required_arguments"] = [ + name for name in required if isinstance(name, str) and name != "operation_id" + ] + definitions = schema.get("$defs", {}) + for name in ("path_params", "query", "body"): + node = properties.get(name) + if isinstance(node, dict): + contract[name] = _contract_node(node, definitions) + return contract + + +def _value_type(value: Any) -> str: + """按 JSON 原始类型选择联合分支,布尔值不能误当成整数。""" + return { + type(None): "null", bool: "boolean", int: "integer", float: "number", + str: "string", dict: "object", list: "array", + }.get(type(value), "") + + +def _normalize_union(value: Any, schema: dict[str, Any], definitions: dict[str, Any], depth: int) -> Any: + """优先选择原始类型匹配的联合,歧义时不猜测不同分支的默认值。""" + alternatives = [_resolve_schema(item, definitions) for item in schema.get("oneOf", schema.get("anyOf", []))] + exact = [item for item in alternatives if item.get("type") == _value_type(value)] + candidates = [] + for option in exact or alternatives: + try: + candidates.append(_normalize_value(value, option, definitions, depth + 1)) + except (TypeError, ValueError): + continue + if not candidates: + raise ValueError("API 参数不符合联合类型合同") + if all(candidate == candidates[0] for candidate in candidates): + return candidates[0] + # 同一输入可合法落入多个不同对象分支时保留原值,避免合并不同业务意图。 + return deepcopy(value) + + +def _normalize_object(value: dict[str, Any], schema: dict[str, Any], definitions: dict[str, Any], depth: int) -> dict[str, Any]: + """按模型字段补明确默认值;自由字典保留原内容,forbid 额外字段明确拒绝。""" + properties = schema.get("properties") + if not isinstance(properties, dict): + return deepcopy(value) + extra = schema.get("additionalProperties") + unknown = set(value) - set(properties) + if unknown and extra is False: + raise ValueError("API 参数包含合同未声明的字段") + normalized = {key: deepcopy(value[key]) for key in unknown} if extra is True or isinstance(extra, dict) else {} + required = schema.get("required", []) + for key, declaration in properties.items(): + field_schema = _resolve_schema(declaration, definitions) + current = value.get(key, field_schema.get("default", _MISSING)) + if current is _MISSING: + if key in required: + raise ValueError("API 参数缺少必需字段") + continue + normalized[key] = _normalize_value(current, field_schema, definitions, depth + 1) + return normalized + + +def _normalize_value(value: Any, declaration: dict[str, Any], definitions: dict[str, Any], depth: int = 0) -> Any: + """递归规范有限深度的 JSON 值,类型转换与实际请求共用同一份参数。""" + if depth > 32: + raise ValueError("API 参数嵌套过深") + schema = _resolve_schema(declaration, definitions) + if "anyOf" in schema or "oneOf" in schema: + return _normalize_union(value, schema, definitions, depth) + kind = schema.get("type") + # JSON 布尔值不是数字;尤其不能把路径中的 true 改成 ID 1 后执行写入。 + if kind in {"integer", "number"} and isinstance(value, bool): + raise ValueError("API 数值参数不能使用布尔值") + if kind == "object": + if not isinstance(value, dict): + raise ValueError("API 参数必须是对象") + return _normalize_object(value, schema, definitions, depth) + if kind == "array": + if not isinstance(value, list): + raise ValueError("API 参数必须是数组") + return [_normalize_value(item, schema.get("items", {}), definitions, depth + 1) for item in value] + if kind == "null" and value is not None: + raise ValueError("API 参数必须为空值") + adapter = _SCALAR_ADAPTERS.get(kind) if isinstance(kind, str) else None + if adapter is not None: + value = adapter.validate_python(value) + if "const" in schema and value != schema["const"]: + raise ValueError("API 参数常量不匹配") + if "enum" in schema and value not in schema["enum"]: + raise ValueError("API 参数枚举值无效") + return deepcopy(value) + + +def canonical_api_arguments(arguments: dict[str, Any], schema: dict[str, Any]) -> dict[str, Any]: + """先采用执行器真实 GET 参数投影,再按唯一 operation 合同规范请求。""" + operation_id = arguments.get("operation_id") + branch = next((item for item in schema.get("oneOf", []) + if item.get("properties", {}).get("operation_id", {}).get("const") == operation_id), None) + route = resolve_api_route(str(operation_id or "")) + if branch is None or route is None: + raise ValueError("API 操作没有规范参数合同") + values = deepcopy(arguments) + if route.method == "GET" and isinstance(values.get("body"), dict): + values["query"] = {**(values.get("query") or {}), **values.pop("body")} + properties = branch.get("properties", {}) + # 网关公共 schema 的空容器只代表没有参数,不应被 operation 分支当作额外字段。 + for field in ("path_params", "query", "body"): + if field not in properties and values.get(field) in (None, {}): + values.pop(field, None) + elif field in {"path_params", "query"} and field in properties: + values.setdefault(field, {}) + try: + normalized = _normalize_object(values, branch, schema.get("$defs", {}), 0) + except ValidationError as error: + raise ValueError("API 参数类型不符合输入合同") from error + # ToolNode 会按网关公共 schema 注入这些缺省字段,指纹与 handler 实参保持相同。 + for key, default in (("path_params", {}), ("query", {}), ("body", None)): + normalized.setdefault(key, default) + return normalized diff --git a/app/agent/api/executor.py b/app/agent/api/executor.py index aee56cfc0..cc8096b1a 100644 --- a/app/agent/api/executor.py +++ b/app/agent/api/executor.py @@ -7,8 +7,10 @@ from dataclasses import dataclass from typing import Any, Mapping from urllib.parse import quote -from app.adapters.network.http import AsyncRequestUtils -from app.agent.policy.api import ApiOperationRoute, resolve_api_route +from app.adapters.network.http import AsyncHttpRequestError, AsyncRequestUtils +from app.agent.policy.api import ApiOperationRoute, resolve_api_operation, resolve_api_route +from app.agent.policy.contracts import ActionEffect +from app.agent.policy.sanitizer import stable_type_name from app.application.security.token import create_access_token from app.runtime.log import logger from app.runtime.settings import get_runtime_setting @@ -17,6 +19,11 @@ from app.runtime.settings import get_runtime_setting class ApiExecutionError(RuntimeError): """固定 API 路由无法构造或请求失败。""" + def __init__(self, message: str, *, external_may_continue: bool = False) -> None: + """区分调用前拒绝和请求发出后无法确认的外部副作用。""" + super().__init__(message) + self.external_may_continue = external_may_continue + @dataclass(frozen=True) class ApiExecutionContext: @@ -175,6 +182,9 @@ class MoviePilotApiExecutor: verify=False, trust_env=False, ) + spec = resolve_api_operation(operation_id) + may_change_state = spec is None or spec.effect not in {ActionEffect.SAFE_READ, ActionEffect.SENSITIVE_READ} + status_code: int | None = None try: response = await request.request( method=route.method, @@ -184,18 +194,23 @@ class MoviePilotApiExecutor: raise_exception=True, ) if response is None: - raise ApiExecutionError("MoviePilot API 没有返回响应") + raise ApiExecutionError("MoviePilot API 没有返回响应", external_may_continue=may_change_state) try: - payload = response.json() status_code = response.status_code + payload = response.json() response_headers = dict(response.headers) finally: await response.aclose() except ApiExecutionError: raise except Exception as error: - logger.warning(f"Agent API 请求失败: operation={operation_id} error={error}") - raise ApiExecutionError(f"MoviePilot API 请求失败: {operation_id}") from error + logger.warning(f"Agent API 请求失败: operation={operation_id} error_type={stable_type_name(error)}") + transport_failed = isinstance(error, (AsyncHttpRequestError, ConnectionError, TimeoutError)) + response_unreadable = status_code is not None and status_code < 400 + raise ApiExecutionError( + f"MoviePilot API 请求失败: {operation_id}", + external_may_continue=may_change_state and (transport_failed or response_unreadable), + ) from error if status_code >= 400: return json.dumps( {"success": False, "error": "api_error", "status_code": status_code, "data": payload}, diff --git a/app/agent/callback/__init__.py b/app/agent/callback/__init__.py index d4119dae0..8669792a0 100644 --- a/app/agent/callback/__init__.py +++ b/app/agent/callback/__init__.py @@ -42,7 +42,7 @@ class StreamingHandler: - 后续有新内容时编辑同一条消息(通过 edit_message) - 当消息长度接近渠道限制时,冻结当前消息并发送新消息继续输出 4. 工具调用时: - - 流式渠道:工具消息直接 emit() 追加到 buffer,与 Agent 文字合并为同一条流式消息 + - 可编辑渠道:工具摘要实时写入 buffer;同一批次的后续调用会原地更新摘要块 - 非流式渠道:调用 take() 取出已积累的文字,与工具消息合并独立发送 5. Agent最终完成时调用 stop_streaming():执行最后一次刷新, 返回是否已通过流式发送完所有内容(调用方据此决定是否还需额外发送) @@ -75,8 +75,13 @@ class StreamingHandler: self._original_chat_id: Optional[str] = None self._title: str = "" self._allow_dispatch_without_context = False - # 非啰嗦模式下的待输出工具统计,等下一段文本到来时再统一补一句摘要 + # 非啰嗦模式下尚未写入展示的工具统计。 self._pending_tool_stats: dict[str, dict[str, Any]] = {} + # 当前正在实时更新的工具摘要块:(起始偏移, 完整块, 摘要行)。 + # 正文到来后清空,使下一次工具调用开启新的统计批次。 + self._live_tool_summary: Optional[tuple[int, str, str]] = None + # 当前实时摘要批次的累计统计,不能随着每次渲染摘要被消费掉。 + self._live_tool_stats: dict[str, dict[str, Any]] = {} # 本轮已写入缓冲区的工具展示行,供 Telegram 富文本渲染时做区分样式 self._tool_summaries: set[str] = set() @@ -96,8 +101,16 @@ class StreamingHandler: emitted = token or "" if self._pending_tool_stats: - summary = self._consume_pending_tool_summary_locked() + if self._live_tool_summary: + # 实时摘要已经直接更新了 buffer,正文只需继续追加,避免把 + # 本次替换后的摘要块再次拼接到缓冲区末尾。 + self._flush_live_tool_summary_locked() + summary = "" + else: + summary = self._consume_pending_tool_summary_locked() if summary: + self._live_tool_summary = None + self._live_tool_stats = {} if emitted: emitted = f"{summary}{emitted.lstrip(chr(10))}" else: @@ -107,6 +120,9 @@ class StreamingHandler: if self._buffer.endswith("\n\n") and emitted.startswith("\n"): emitted = emitted.lstrip("\n") self._buffer += emitted + if emitted: + self._live_tool_summary = None + self._live_tool_stats = {} return emitted def emit_tool_message(self, message: str) -> str: @@ -127,6 +143,10 @@ class StreamingHandler: ) return self.emit(f"\n\n{tool_message}\n\n") + def _is_verbose_mode(self) -> bool: + """判断当前是否启用逐条工具调用展示。""" + return bool(get_runtime_setting("AI_AGENT_VERBOSE")) + def report_tool_call( self, tool_name: str, @@ -140,7 +160,7 @@ class StreamingHandler: 相同的详细模式语义,避免无条件调用 ``record_tool_call`` 后只显示汇总。 """ safe_message = sanitize_for_host(tool_message) if tool_message else tool_message - if get_runtime_setting("AI_AGENT_VERBOSE") and safe_message: + if self._is_verbose_mode() and safe_message: return self.emit_tool_message(str(safe_message)) self.record_tool_call( tool_name=tool_name, @@ -149,6 +169,19 @@ class StreamingHandler: ) return "" + def tool_call_started( + self, + tool_name: str, + tool_message: Optional[str] = None, + ) -> str: + """为支持结构化生命周期的宿主预留工具调用 ID。""" + del tool_name, tool_message + return "" + + def tool_call_finished(self, tool_id: str, status: str = "done") -> None: + """收口真实工具执行;普通通知渠道无需额外输出生命周期事件。""" + del tool_id, status + async def take(self) -> str: """ 获取当前已积累的消息内容,获取后清空缓冲区。 @@ -162,10 +195,14 @@ class StreamingHandler: with self._lock: if not self._buffer: + self._live_tool_summary = None + self._live_tool_stats = {} return "" message = self._buffer logger.info(f"Agent消息: {message}") self._buffer = "" + self._live_tool_summary = None + self._live_tool_stats = {} return message def clear(self): @@ -179,6 +216,8 @@ class StreamingHandler: self._msg_start_offset = 0 self._pending_tool_stats = {} self._tool_summaries = set() + self._live_tool_summary = None + self._live_tool_stats = {} def reset(self): """ @@ -194,6 +233,8 @@ class StreamingHandler: self._msg_start_offset = 0 self._pending_tool_stats = {} self._tool_summaries = set() + self._live_tool_summary = None + self._live_tool_stats = {} async def start_streaming( self, @@ -257,6 +298,8 @@ class StreamingHandler: self._msg_start_offset = 0 self._pending_tool_stats = {} self._tool_summaries = set() + self._live_tool_summary = None + self._live_tool_stats = {} # 检查渠道是否支持消息编辑,不支持则仅收集 token 到 buffer,不实时推送 if not self._can_stream(): @@ -321,6 +364,8 @@ class StreamingHandler: self._msg_start_offset = 0 self._pending_tool_stats = {} self._tool_summaries = set() + self._live_tool_summary = None + self._live_tool_stats = {} if all_sent: # 所有内容已通过流式发送,清空缓冲区 self._buffer = "" @@ -365,22 +410,30 @@ class StreamingHandler: for target_value in target_values: bucket["targets"].add(str(target_value)) + self._on_tool_stats_recorded() + + def _on_tool_stats_recorded(self) -> None: + """工具统计新增后,在支持编辑的流式渠道中立即刷新当前摘要块。""" + if not self._streaming_enabled or not self._can_stream(): + return + with self._lock: + self._flush_live_tool_summary_locked() + @staticmethod def _extract_subagent_targets(tool_kwargs: dict[str, Any]) -> list[str]: - """提取子代理工具请求中的目标子代理类型。""" + """按实际委派条目数量生成通用子代理统计目标。""" tasks = tool_kwargs.get("tasks") if not isinstance(tasks, list): - subagent_type = tool_kwargs.get("subagent_type") - return [str(subagent_type)] if subagent_type else [] + return ["general-purpose"] if tool_kwargs.get("description") else [] targets = [] for task in tasks: if isinstance(task, dict): - subagent_type = task.get("subagent_type") + description = task.get("description") else: - subagent_type = getattr(task, "subagent_type", None) - if subagent_type: - targets.append(str(subagent_type)) + description = getattr(task, "description", None) + if description: + targets.append("general-purpose") return targets def flush_pending_tool_summary(self) -> str: @@ -388,11 +441,58 @@ class StreamingHandler: 将待输出的工具统计摘要补入缓冲区,并返回本次新增的摘要文本。 """ with self._lock: + if self._live_tool_summary and self._pending_tool_stats: + return self._flush_live_tool_summary_locked() summary = self._consume_pending_tool_summary_locked() if summary: self._buffer += summary + self._live_tool_summary = None + self._live_tool_stats = {} return summary + def _flush_live_tool_summary_locked(self) -> str: + """在缓冲区末尾追加或原地替换当前工具批次摘要。""" + live_summary = self._live_tool_summary + visible_buffer = self._buffer + live_start = len(self._buffer) + old_summary = None + + if live_summary and self._buffer[live_summary[0] :] == live_summary[1]: + live_start, _old_block, old_summary = live_summary + visible_buffer = self._buffer[:live_start] + + if self._pending_tool_stats: + self._merge_tool_stats_locked(self._live_tool_stats, self._pending_tool_stats) + self._pending_tool_stats = {} + pending_summary = self._build_tool_summary_locked(self._live_tool_stats, visible_buffer) + if not pending_summary: + return "" + + summary, summary_block = pending_summary + if old_summary: + self._tool_summaries.discard(old_summary) + self._tool_summaries.add(summary) + self._buffer = visible_buffer + summary_block + self._live_tool_summary = (len(visible_buffer), summary_block, summary) + return summary_block + + @staticmethod + def _merge_tool_stats_locked( + accumulated_stats: dict[str, dict[str, Any]], + new_stats: dict[str, dict[str, Any]], + ) -> None: + """将新一轮工具统计并入当前实时摘要批次。""" + for category, bucket in new_stats.items(): + accumulated_bucket = accumulated_stats.setdefault( + category, + { + "count": 0, + "targets": set(), + }, + ) + accumulated_bucket["count"] += bucket["count"] + accumulated_bucket["targets"].update(bucket["targets"]) + @staticmethod def _classify_tool_call( tool_name: str, @@ -405,12 +505,12 @@ class StreamingHandler: if tool_name in {"read_skill", "skill"}: return "skill", tool_kwargs.get("name") - if tool_name == "query_activity_log": - return "activity_log", tool_kwargs.get("keyword") or tool_kwargs.get("date") + if tool_name == "search_memory": + return "memory", tool_kwargs.get("query") or tool_kwargs.get("category") if tool_name == "subagent_task": return "subagent", StreamingHandler._extract_subagent_targets(tool_kwargs) if tool_name == "task": - return "subagent", tool_kwargs.get("subagent_type") + return "subagent", "general-purpose" if tool_kwargs.get("description") else None if tool_name == "read_file": return "file_read", tool_kwargs.get("file_path") if tool_name in {"write_file", "edit_file"}: @@ -500,11 +600,36 @@ class StreamingHandler: return "tool", None def _consume_pending_tool_summary_locked(self) -> str: - if not self._pending_tool_stats: + pending_summary = self._build_pending_tool_summary_locked(self._buffer) + if not pending_summary: return "" + summary, summary_block = pending_summary + self._tool_summaries.add(summary) + return summary_block + + def _build_pending_tool_summary_locked( + self, + visible_buffer: str, + ) -> Optional[tuple[str, str]]: + """消费待统计数据,并按给定可见文本计算摘要块的段落边界。""" + if not self._pending_tool_stats: + return None + + pending_stats = self._pending_tool_stats + self._pending_tool_stats = {} + return self._build_tool_summary_locked(pending_stats, visible_buffer) + + def _build_tool_summary_locked( + self, + tool_stats: dict[str, dict[str, Any]], + visible_buffer: str, + ) -> Optional[tuple[str, str]]: + """按给定工具统计和可见文本生成摘要行及其段落块。""" + if not tool_stats: + return None parts = [] - for category, bucket in self._pending_tool_stats.items(): + for category, bucket in tool_stats.items(): value = bucket["count"] if category in {"file_read", "file_write", "directory", "web_browse", "skill"} and bucket["targets"]: value = len(bucket["targets"]) @@ -512,20 +637,18 @@ class StreamingHandler: if part: parts.append(part) - self._pending_tool_stats = {} if not parts: - return "" + return None summary = f"({','.join(parts)})" - self._tool_summaries.add(summary) # 摘要前始终保证一个空行,让工具执行信息与正文分属不同段落, # 避免 Markdown 富文本把单个换行折叠成同一段落内的软换行 - visible_buffer = self._buffer.rstrip(" \t") + visible_buffer = visible_buffer.rstrip(" \t") trailing_newlines = len(visible_buffer) - len(visible_buffer.rstrip("\n")) prefix = "" if visible_buffer.strip(): prefix = "\n" * max(2 - trailing_newlines, 0) - return f"{prefix}{summary}\n\n" + return summary, f"{prefix}{summary}\n\n" @staticmethod def _format_tool_stat(category: str, count: int) -> str: @@ -548,8 +671,8 @@ class StreamingHandler: return f"查询了 {count} 次数据" if category == "skill": return f"查询了 {count} 个技能说明" - if category == "activity_log": - return f"查询了 {count} 次活动日志" + if category == "memory": + return f"检索了 {count} 次记忆" if category == "action": return f"执行了 {count} 次操作" if category == "interaction": @@ -584,10 +707,14 @@ class StreamingHandler: 富文本会把普通段落间的空行折叠成紧凑排版,引用块作为独立 block 类型 渲染,保证工具执行信息在 Telegram 上始终与正文有可辨识的视觉分隔。 + 匹配与登记均按 splitlines 识别换行,同时保留原换行符,兼容 CRLF 续行参数。 """ if not self._tool_summaries or not text: return text - return "\n".join(f"> {line}" if line in self._tool_summaries else line for line in text.split("\n")) + return "".join( + f"> {line}" if line.splitlines()[0] in self._tool_summaries else line + for line in text.splitlines(keepends=True) + ) async def _flush_loop(self): """ diff --git a/app/agent/defaults/CURRENT_PERSONA.md b/app/agent/defaults/CURRENT_PERSONA.md index 55ecb9654..54cf7a35b 100644 --- a/app/agent/defaults/CURRENT_PERSONA.md +++ b/app/agent/defaults/CURRENT_PERSONA.md @@ -13,7 +13,7 @@ deprecated_phrases: [] 1. 核心系统提示词(程序内置,不可运行时覆盖) 2. `personas//PERSONA.md` 3. `extra_context_files` -4. `memory/*.md` -5. `activity/*.md` +4. `memory/MEMORY.md`(默认注入) +5. `memory/.md` 与 `memory/activity/*.md`(通过 search_memory 按需检索) `memory` 中的长期偏好可以细化回复方式,但不应覆盖系统核心身份、目标和安全边界。 diff --git a/app/agent/defaults/subagents/download-diagnostician/SUBAGENT.md b/app/agent/defaults/subagents/download-diagnostician/SUBAGENT.md deleted file mode 100644 index b7cab82b2..000000000 --- a/app/agent/defaults/subagents/download-diagnostician/SUBAGENT.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -version: 1 -subagent_id: download-diagnostician -label: 下载诊断 -description: Download and transfer diagnosis subagent for downloaders, download tasks, transfer history, and library status. -include_tags: - - download - - transfer - - library - - directory - - file - - media -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in downloaders, download tasks, transfer history, directory settings, and library ingestion state. diff --git a/app/agent/defaults/subagents/media-researcher/SUBAGENT.md b/app/agent/defaults/subagents/media-researcher/SUBAGENT.md deleted file mode 100644 index 95c668984..000000000 --- a/app/agent/defaults/subagents/media-researcher/SUBAGENT.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -version: 1 -subagent_id: media-researcher -label: 媒体研究 -description: Media research subagent for title recognition, people, episodes, metadata, and library existence checks. -include_tags: - - media - - library - - recommendation - - metadata - - web -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in media identity resolution, metadata validation, person credits, and library status analysis. diff --git a/app/agent/defaults/subagents/moviepilot-explorer/SUBAGENT.md b/app/agent/defaults/subagents/moviepilot-explorer/SUBAGENT.md deleted file mode 100644 index 5c527ff46..000000000 --- a/app/agent/defaults/subagents/moviepilot-explorer/SUBAGENT.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -version: 1 -subagent_id: moviepilot-explorer -label: 代码探索 -description: MoviePilot exploration subagent for source-code inspection, configuration structure analysis, logs, and code-level troubleshooting clues. -include_tags: - - system - - settings - - file - - directory - - command -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in MoviePilot source-code structure, local configuration files, directory layout, logs or read-only command output, and code-level root-cause troubleshooting. Prefer reading relevant code paths before judging behavior, and distinguish code/config evidence from runtime system state. diff --git a/app/agent/defaults/subagents/resource-searcher/SUBAGENT.md b/app/agent/defaults/subagents/resource-searcher/SUBAGENT.md deleted file mode 100644 index 680eb5779..000000000 --- a/app/agent/defaults/subagents/resource-searcher/SUBAGENT.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -version: 1 -subagent_id: resource-searcher -label: 资源搜索 -description: Site and resource search subagent for site checks, torrent search, and resource quality analysis. -include_tags: - - resource - - site - - web - - media -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in site status, site user data, torrent search results, and resource quality judgment. diff --git a/app/agent/defaults/subagents/subscription-analyst/SUBAGENT.md b/app/agent/defaults/subagents/subscription-analyst/SUBAGENT.md deleted file mode 100644 index 80f0bae3a..000000000 --- a/app/agent/defaults/subagents/subscription-analyst/SUBAGENT.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -version: 1 -subagent_id: subscription-analyst -label: 订阅分析 -description: Subscription analysis subagent for subscriptions, history, filter rules, and custom identifiers. -include_tags: - - subscription - - filter_rule - - settings - - media -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in current subscription state, subscription history, filter rules, and subscription optimization suggestions. diff --git a/app/agent/defaults/subagents/system-diagnostician/SUBAGENT.md b/app/agent/defaults/subagents/system-diagnostician/SUBAGENT.md deleted file mode 100644 index 12580ee77..000000000 --- a/app/agent/defaults/subagents/system-diagnostician/SUBAGENT.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -version: 1 -subagent_id: system-diagnostician -label: 系统诊断 -description: System diagnosis subagent for read-only inspection of settings, schedulers, workflows, plugins, directories, and command output. -include_tags: - - system - - settings - - plugin - - workflow - - scheduler - - file - - directory - - web - - command - - persona - - slash_command -exclude_tags: - - write - - message - - user_interaction ---- -# SUBAGENT - -You specialize in settings, plugins, scheduled tasks, workflows, directories, and read-only command diagnostics. diff --git a/app/agent/llm/discovery.py b/app/agent/llm/discovery.py index f65435667..0b1050fab 100644 --- a/app/agent/llm/discovery.py +++ b/app/agent/llm/discovery.py @@ -397,9 +397,15 @@ class _ProviderDiscovery: connect_timeout=10, trust_env=False, ) + # google-genai 的 aiohttp 请求已经显式传入 timeout,不能再从 + # async_client_args 透传同名参数,否则会触发重复关键字异常。 + async_client_args = { + key: value for key, value in client_args.items() if key != "timeout" + } http_options = HttpOptions( + timeout=15_000, client_args=client_args, - async_client_args=client_args, + async_client_args=async_client_args, ) client = genai.Client(api_key=api_key, http_options=http_options) diff --git a/app/agent/llm/helper.py b/app/agent/llm/helper.py index 3fd0d1c18..3894ff660 100644 --- a/app/agent/llm/helper.py +++ b/app/agent/llm/helper.py @@ -7,6 +7,7 @@ import time from functools import wraps from typing import TYPE_CHECKING, Any, List, Optional from urllib.parse import urlsplit +from uuid import uuid4 from langchain_core.messages import AIMessage, AIMessageChunk @@ -403,7 +404,7 @@ def _patch_openai_responses_instructions_support(): # 处理 ChatGPT 官方 Responses API (Codex) 端点兼容性 is_codex = "chatgpt.com/backend-api/codex" in base_url - + if is_codex and (getattr(self, "use_responses_api", False) or "input" in payload): instructions = payload.get("instructions", "") inputs = payload.get("input", []) @@ -423,10 +424,10 @@ def _patch_openai_responses_instructions_support(): payload["input"] = new_inputs payload["instructions"] = instructions or "You are a helpful assistant." payload["store"] = False - + # Codex 端点不支持的部分常见补全参数,统一清理避免 400 报错 unsupported_keys = [ - "presence_penalty", "frequency_penalty", "top_p", "n", "user", + "presence_penalty", "frequency_penalty", "top_p", "n", "user", "stop", "metadata", "logit_bias", "logprobs", "top_logprobs", "stream_options", "temperature" ] @@ -841,6 +842,50 @@ class LLMHelper: return image_support return True + @classmethod + def supports_model_image_input(cls, model: Any) -> bool: + """按本次实际模型的 profile 和目录判断图像输入,每次请求重新读取用户总开关。""" + if not get_runtime_setting('LLM_SUPPORT_IMAGE_INPUT'): + return False + profile = getattr(model, "profile", None) + profile = profile if isinstance(profile, dict) else {} + supported = profile.get("image_inputs") + if isinstance(supported, bool): + return supported + provider = getattr(model, "_moviepilot_llm_provider_id", None) or profile.get("moviepilot_provider_id") + model_name = next((value for name in ("model_name", "model", "model_id") + if isinstance(value := getattr(model, name, None), str) and value), None) + if not provider or not model_name: + # 未知自定义模型沿用用户图片开关,不能套用另一个全局默认模型的能力。 + return True + base_url = getattr(model, "_moviepilot_llm_base_url", None) or profile.get("moviepilot_base_url") or "" + supported = cls._resolve_catalog_image_input_support( + provider=str(provider), model=model_name, base_url=str(base_url), base_url_preset="", + ) + return supported is not False + + @staticmethod + def is_unsupported_image_input_error(error: BaseException) -> bool: + """仅识别图片能力拒绝,不把认证、限流或普通请求故障降级为图片问题。""" + status = getattr(error, "status_code", None) + if isinstance(status, int) and status not in {400, 404, 422}: + return False + parts = [str(error)] + for name in ("message", "code", "body"): + value = getattr(error, name, None) + if value is not None: + parts.append(str(value)) + detail = " ".join(parts).lower() + if "no endpoints found that support image input" in detail: + return True + if "not a vlm" in detail or "text-only prompts" in detail: + return True + if "unknown variant" in detail and "image_url" in detail: + return True + return ("image input" in detail or "images" in detail) and any( + marker in detail for marker in ("does not support", "do not support", "not support", "unsupported", "no endpoint") + ) + @staticmethod def _build_openai_default_headers( default_headers: dict[str, str] | None = None, @@ -881,11 +926,17 @@ class LLMHelper: default_headers: dict[str, str] | None, model_kwargs: dict[str, Any], ) -> tuple[dict[str, str] | None, dict[str, Any]]: - """为 OpenAI 与 xAI 官方端点构造稳定提示词缓存路由参数。""" + """为官方端点构造稳定会话及提示词缓存路由参数。""" cache_key = str(prompt_cache_key or "").strip() headers = dict(default_headers or {}) kwargs = dict(model_kwargs) provider_name = str(provider or "").strip().lower() + if cls._matches_endpoint_host(base_url, "opencode.ai"): + # 主对话沿用脱敏缓存键;独立测试、摘要调用的标识在模型实例内复用。 + headers["x-opencode-session"] = cache_key or f"moviepilot-{uuid4().hex}" + if not any(key.lower() == "user-agent" for key in headers): + headers["User-Agent"] = "MoviePilot" + return headers, kwargs if not cache_key: return headers or None, kwargs @@ -1335,7 +1386,7 @@ class LLMHelper: from langchain_openai import ChatOpenAI _patch_openai_responses_instructions_support() - + # ChatGPT Codex 端点强制要求 stream: True if runtime.get("use_responses_api") and "chatgpt.com/backend-api/codex" in str(runtime.get("base_url") or ""): streaming = True diff --git a/app/agent/loader.py b/app/agent/loader.py index 4e0d66864..2adf30760 100644 --- a/app/agent/loader.py +++ b/app/agent/loader.py @@ -23,7 +23,6 @@ from app.agent.capabilities.adapter import ( from app.runtime.capabilities.model import CapabilityMaterializationState from app.runtime.capabilities.runtime import CapabilityRuntime - _runtime_lock = threading.RLock() _agent_runtime: CapabilityRuntime | None = None @@ -135,7 +134,7 @@ def is_tool_factory_materialized() -> bool: async def close_materialized_terminal_sessions() -> None: """关闭已物化的终端会话管理器,不触发新的 Agent 工具导入。""" - module = sys.modules.get("app.agent.tools.impl._terminal_session") + module = sys.modules.get("app.agent.terminal.manager") manager = getattr(module, "terminal_session_manager", None) if module else None close = getattr(manager, "close", None) if callable(close): diff --git a/app/agent/memory/__init__.py b/app/agent/memory/__init__.py index 1f8dc4366..c230fb944 100644 --- a/app/agent/memory/__init__.py +++ b/app/agent/memory/__init__.py @@ -6,6 +6,7 @@ from typing import Dict, List, Optional from langchain_core.messages import BaseMessage, messages_from_dict, messages_to_dict +from app.agent.tools.result import messages_for_persistence from app.application.messaging.chat import ( AgentChatPersistenceService, AgentChatRecord, @@ -115,11 +116,11 @@ class MemoryManager: user_id: str, chat: Optional[AgentChatRecord], ) -> List[BaseMessage]: - """统一校验持久化快照、反序列化消息并回填内存缓存。""" + """反序列化后清理历史工具图像并回填缓存,真实用户附件保持原样。""" if not chat or not chat.agent_messages: return [] try: - messages = messages_from_dict(chat.agent_messages) + messages = messages_for_persistence(messages_from_dict(chat.agent_messages)) except Exception as e: logger.debug(f"恢复持久化Agent消息失败: {e}") return [] @@ -202,7 +203,7 @@ class MemoryManager: self, session_id: str, user_id: str, messages: List[BaseMessage] ) -> None: """ - 保存Agent消息到内存缓存与持久化会话表。 + 当前会话在缓存保留原图,持久化副本只保存工具图片的失效说明。 """ self._update_agent_messages( session_id=session_id, @@ -213,7 +214,7 @@ class MemoryManager: self._chat_service().save_agent_messages( session_id=session_id, user_id=user_id, - messages=messages_to_dict(messages), + messages=messages_to_dict(messages_for_persistence(messages)), ) except Exception as e: logger.debug(f"持久化Agent消息失败: {e}") @@ -221,7 +222,7 @@ class MemoryManager: async def async_save_agent_messages( self, session_id: str, user_id: str, messages: List[BaseMessage] ) -> None: - """异步保存 Agent 消息,持久化写入经有界数据库 worker 承接。""" + """缓存保留原图,去除工具图片的副本经有界数据库 worker 持久化。""" self._update_agent_messages( session_id=session_id, user_id=user_id, @@ -232,7 +233,7 @@ class MemoryManager: await persistence.async_save_agent_messages( session_id=session_id, user_id=user_id, - messages=messages_to_dict(messages), + messages=messages_to_dict(messages_for_persistence(messages)), ) except Exception as e: logger.debug(f"持久化Agent消息失败: {e}") diff --git a/app/agent/middleware/activity.py b/app/agent/middleware/activity.py deleted file mode 100644 index b47b202cf..000000000 --- a/app/agent/middleware/activity.py +++ /dev/null @@ -1,762 +0,0 @@ -""" -活动日志中间件 - 自动记录 Agent 每次交互的操作摘要。 - -按日期存储在 CONFIG_PATH/agent/activity/YYYY-MM-DD.md 中, -每次 Agent 执行完毕后自动调用 LLM 对本轮对话生成简洁的活动摘要, -系统提示词只注入稳定的检索规则,完整日志由工具按需查询。 -""" - -import asyncio -import json -import os -import re -from collections.abc import Awaitable, Callable -from datetime import datetime, timedelta -from pathlib import Path -from typing import Annotated, Any, NotRequired, Optional, TypedDict - -import anyio -from anyio import Path as AsyncPath -from langchain.agents.middleware.types import ( - AgentMiddleware, - AgentState, - ContextT, - ModelRequest, - ModelResponse, - PrivateStateAttr, # noqa - ResponseT, - ToolCallRequest, -) -from langchain_core.messages import AIMessage, HumanMessage, ToolMessage -from langchain_core.tools import StructuredTool -from langgraph.runtime import Runtime -from pydantic import BaseModel, Field - -from app.agent.middleware.utils import append_to_system_message -from app.agent.policy.sanitizer import ( - sanitize_for_host, - summarize_error, - summarize_result, -) -from app.agent.tools.tags import ToolTag -from app.runtime.log import logger -from app.runtime.tasks import TaskRegistry, get_task_registry - -# 活动日志保留天数 -DEFAULT_RETENTION_DAYS = 7 - -# 注入系统提示词时索引的天数 -PROMPT_LOAD_DAYS = 3 - -# 工具默认查询的天数 -DEFAULT_QUERY_DAYS = 7 - -# 工具单次返回的最大条数 -DEFAULT_QUERY_LIMIT = 20 -MAX_QUERY_LIMIT = 50 - -# 每日日志文件最大大小 (256KB) -MAX_LOG_FILE_SIZE = 256 * 1024 - -# 提取本轮对话上下文的最大字符数(避免过长的对话消耗太多 token) -MAX_CONTEXT_FOR_SUMMARY = 4000 - -SUMMARY_SKIP_MARKER = "SKIP" -QUERY_ACTIVITY_LOG_TOOL_NAME = "query_activity_log" -QUERY_ACTIVITY_LOG_TOOL_DESCRIPTION = ( - "Query recent MoviePilot Agent activity logs on demand. Use this when the user asks what was done before, " - "asks to continue a previous task, or explicitly references recent agent activity. Supports keyword, date, " - "recent-day window, limit, and optional regex filters. If a keyword search returns no results, retry with " - "a shorter keyword, a larger days window, or no keyword to inspect recent entries." -) - -# LLM 总结的提示词 -SUMMARY_PROMPT = """请判断以下 AI 助手与用户的对话是否值得写入 MoviePilot 活动日志。 - -如果本轮只是问候、寒暄、感谢、确认、闲聊、没有实际任务、没有工具动作、任务没有推进、纯粹的格式纠正或无意义空转,请只输出:SKIP - -如果值得记录,请输出一条中文单行活动摘要,要求: -- 40 到 160 个汉字左右,信息密度高,不要写成泛泛一句话。 -- 只输出摘要正文,不要标题、编号、Markdown、JSON 或解释。 -- 尽量包含:用户目标、关键对象(影片/剧集/站点/路径/任务/设置)、助手采取的关键动作或工具、结果状态、失败原因或下一步。 -- 如果有明确 ID、路径、站点名、任务状态、成功/失败数量,请保留关键值。 -- 不要记录 API Key、Cookie、Token、密码等敏感信息;如出现请写成“敏感信息已省略”。 - -推荐格式示例: -用户要求整理 `/downloads/Show`,助手识别为《示例剧》TMDB 12345,并提交 transfer_file 整理,结果成功。 -用户排查下载失败,助手查询 qBittorrent 任务和站点状态,发现 tracker 超时,建议更换站点或重试。 - -对话记录: -{conversation}""" - -ACTIVITY_ENTRY_PATTERN = re.compile(r"^-\s+\*\*(?P